branch_name
stringclasses 22
values | content
stringlengths 18
81.8M
| directory_id
stringlengths 40
40
| languages
sequence | num_files
int64 1
7.38k
| repo_language
stringlengths 1
23
| repo_name
stringlengths 7
101
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>weichunchang/1031<file_sep>/src/page/home/Home.vue
<template>
<div>
<app-header/>
<swiper-content/>
<Category/>
<Activity/>
<hot-recommend/>
<weekendsgo-content/>
</div>
</template>
<script>
import HeaderComponent from "./Header";
import WeekendsgoComponent from "./Weekendsgo";
import SwiperComponent from "./Swiper";
import Activity from "./Activity";
import HotRecommend from "./Recommend";
import Category from "./Category";
export default {
components:{
"app-header":HeaderComponent,
"weekendsgo-content": WeekendsgoComponent,
"swiper-content":SwiperComponent,
"hot-recommend":HotRecommend,
"Category":Category,
"Activity":Activity
}
}
</script>
<style>
</style>
<file_sep>/src/page/home/Swiper.vue
<template>
<swiper :options="swiperOption" ref="mySwiper">
<swiper-slide>
<div class = "swiper-img-con">
<img class="swipe-img"
src="http://img1.qunarzz.com/piao/fusion/1710/f5/57137c621d75ba02.jpg_640x200_b984ddf7.jpg"
alt="去哪儿门票" style="opacity: 1;"/>
</div>
</swiper-slide>
<swiper-slide>
<div class = "swiper-img-con">
<img class="swipe-img"
src="http://img1.qunarzz.com/piao/fusion/1609/15/630b82d932a3c402.jpg_640x200_862e836b.jpg"
alt="去哪儿门票" style="opacity: 1;"/>
</div>
</swiper-slide>
<swiper-slide>
<div class = "swiper-img-con">
<img class="swipe-img"
src="http://img1.qunarzz.com/piao/fusion/1609/f3/52a119dbed871902.jpg_640x200_b4573df8.jpg"
alt="去哪儿门票" style="opacity: 1;"/>
</div>
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</template>
<script>
import { swiper, swiperSlide } from 'vue-awesome-swiper';
export default {
data() {
return {
swiperOption: {
// swiper options 所有的配置同swiper官方api配置
autoplay: 3000,
direction: 'horizontal',
autoHeight: true,
pagination: '.swiper-pagination',
observeParents: true,
}
}
},
components: {
swiper,
swiperSlide
},
computed: {
swiper() {
return this.$refs.mySwiper.swiper
}
}
}
</script>
<style>
.swiper-img-con{
overflow: hidden;
width:100%;
height:0;
padding-bottom:31.25%;
}
.swipe-img{
width:100%
}
</style>
<file_sep>/src/page/home/Recommend.vue
<template>
<div class = "HotRecommend-con">
<p class = "hot-title">热销推荐</p>
<ul class = "hotlist">
<li class = "listElem">
<div class = "hot-img-con">
<img src="http://img1.qunarzz.com/sight/p0/1409/19/adca619faaab0898245dc4ec482b5722.jpg_140x140_80f63803.jpg" alt="故宫">
</div>
<div class = "hot-ticket-desc">
<p class = "hot-ticket-title">故宫</p>
<p class = "attraction-desc">东方宫殿建筑代表,世界宫殿建筑代表</p>
<p class = "hot-ticket-price"><span class = "price-symbol">¥</span><span class = "price-num">20</span>起</p>
</div>
</li>
<li class = "listElem">
<div class = "hot-img-con">
<img src="http://img1.qunarzz.com/sight/p0/1708/2b/2b3b94de99c0a425a3.img.jpg_140x140_97813766.jpg" alt="八达岭长城">
</div>
<div class = "hot-ticket-desc">
<p class = "hot-ticket-title">八达岭长城</p>
<p class = "attraction-desc">不到长城非好汉</p>
<p class = "hot-ticket-price"><span class = "price-symbol">¥</span><span class = "price-num">25</span>起</p>
</div>
</li>
<li class = "listElem">
<div class = "hot-img-con">
<img src="http://img1.qunarzz.com/sight/p0/1505/d2/d274c92de14c93da.water.jpg_140x140_e20be8e0.jpg" alt="颐和园">
</div>
<div class = "hot-ticket-desc">
<p class = "hot-ticket-title">颐和园</p>
<p class = "attraction-desc">保存完整的一座皇家行宫御苑</p>
<p class = "hot-ticket-price"><span class = "price-symbol">¥</span><span class = "price-num">23.2</span>起</p>
</div>
</li>
<li class = "listElem">
<div class = "hot-img-con">
<img src="http://img1.qunarzz.com/sight/p0/1508/a5/4003f9dd7bebf61eccbf64046e26d487.water.jpg_140x140_b05eb1df.jpg" alt="北京欢乐谷">
</div>
<div class = "hot-ticket-desc">
<p class = "hot-ticket-title">北京欢乐谷</p>
<p class = "attraction-desc">七大主题园区带你畅想北京欢乐谷</p>
<p class = "hot-ticket-price"><span class = "price-symbol">¥</span><span class = "price-num">20</span>起</p>
</div>
</li>
<li class = "listElem">
<div class = "hot-img-con">
<img src="http://img1.qunarzz.com/sight/p0/1708/2b/2b6378fd3b2e1d86a3.img.jpg_140x140_eae81520.jpg" alt="慕田峪长城">
</div>
<div class = "hot-ticket-desc">
<p class = "hot-ticket-title">慕田峪长城</p>
<p class = "attraction-desc">秀美长城,关键是人少</p>
<p class = "hot-ticket-price"><span class = "price-symbol">¥</span><span class = "price-num">20</span>起</p>
</div>
</li>
</ul>
</div>
</template>
<script>
</script>
<style scoped>
.HotRecommend-con{
clear: both;
width:100%;
background:#eee;
}
.hot-title{
height:.8rem;
padding-left: .26rem;
line-height:.8rem;
color:#212121;
}
.hotlist{
/*width:6.4rem;*/
height:9.4rem;
}
.listElem{
/*width:5.92rem;*/
height:1.4rem;
padding:12px;
background:#fff;
border-bottom:1px solid #CCCCCC
}
.hot-img-con{
float:left;
}
.hot-img-con img{
width:1.4rem;
height:1.4rem;
}
.hot-ticket-desc{
float:left;
margin-left:10px;
}
.hot-ticket-title{
font-size:0.32rem;
line-height: 0.36rem;
}
.attraction-desc{
overflow: hidden;
width:4.32rem;
white-space: nowrap;
text-overflow: ellipsis;
line-height:.6rem;
font-size:0.28rem;
color:#CACACA
}
.hot-ticket-price{
line-height:0.44rem;
color:#CACACA;
}
.price-symbol{
color:#FB6700;
}
.price-num{
font-size:.44rem;
color:#FB6700;
}
</style><file_sep>/src/page/home/Category.vue
<template>
<swiper :options="swiperOption" ref="mySwiper">
<swiper-slide>
<div id="category-container">
<ul class="category-img-container">
<li class="category-img-con">
<img src="../img/index/category-img1.png" class="category-img" />
<p class="keywords">景点门票</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img2.png" class="category-img" />
<p class="keywords">动植物园</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img3.png" class="category-img" />
<p class="keywords">故宫</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img4.png" class="category-img" />
<p class="keywords">一日游</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img5.png" class="category-img" />
<p class="keywords">必游榜单</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img6.png" class="category-img" />
<p class="keywords">秋色美</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img7.png" class="category-img" />
<p class="keywords">游乐场</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img8.png" class="category-img" />
<p class="keywords">泡温泉</p>
</li>
</ul>
</div>
</swiper-slide>
<swiper-slide>
<div id="category-container">
<ul class="category-img-container">
<li class="category-img-con">
<img src="../img/index/category-img9.png" class="category-img" />
<p class="keywords">城市观光</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img10.png" class="category-img" />
<p class="keywords">玻璃栈道</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img11.png" class="category-img" />
<p class="keywords">名胜古迹</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img12.png" class="category-img" />
<p class="keywords">周边游</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img13.png" class="category-img" />
<p class="keywords">自然风光</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img14.png" class="category-img" />
<p class="keywords">古水北镇</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img15.png" class="category-img" />
<p class="keywords">景点讲解</p>
</li>
<li class="category-img-con">
<img src="../img/index/category-img16.png" class="category-img" />
<p class="keywords">全部</p>
</li>
</ul>
</div>
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</template>
<script>
import { swiper, swiperSlide } from 'vue-awesome-swiper'
export default {
data() {
return {
swiperOption: {
direction: 'horizontal',
autoHeight: true,
pagination: '.swiper-pagination',
observeParents: true
}
}
},
components: {
swiper,
swiperSlide
}
}
</script>
<style scoped>
#category-container {
/*让高度自动变为宽度的31.25%,只能用padding实现*/
overflow: hidden;
width: 100%;
height: 0;
padding-bottom:3.8rem;
}
.category-img-con {
float: left;
width: 25%;
padding-top: .3rem;
text-align: center;
}
.category-img {
width: .66rem;
height: .66rem;
}
.keywords {
padding: .2rem 0;
}
</style> | e118027c34c3d351228e5868d62ec26009c98389 | [
"Vue"
] | 4 | Vue | weichunchang/1031 | ffd148ffb3b200d1cda4d15e58f9ccd4b6ad429e | c3b745f3675a897e8b28f3dbf1269238cf96a46d |
refs/heads/master | <file_sep>copyright_msg: Copyrighted_By_Rem
redhat_apache: httpd
debian_apache: apache2
<file_sep># we collect here all info specific to an account.
{
"dovah-kin".uid = 5555;
"dovah-kin".group = "hellonix";
"dovah-kin".mapping = ["nagato.pain" "lin.greed" "psyanticy"];
# mapping: a list of users that are allowed to switch to the programmatic user.
# same for each user you gonna add.
# ...
# ...
}
<file_sep>--- # set_facts example
- hosts: appserver
user: test
sudo: yes
connection: ssh
gather_facts: no
vars:
playbok_version: 0.1
tasks:
- name: Local variable display
set_fact:
singlefact: Somthing
- debug: msg={{ playbook_version}}
- debug: msg={{ singlefact }}
<file_sep>--- # local action demo
- host: apapcheweb
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: Ping application server before we run our install
local_action: command ping -c 4 tcox5
- name: Install Lynx on remote server
yum: pkg=lynx state=latest
<file_sep># Compiling open source Software manually:
#### Compiling from source is done for various reason
To compile Stuff you need `make` `c++` ...
These can be installed via:
* Debian/Ubuntu: apt-get install build-essential
* RHEL : yum groupinstall "development tools"
After downloading and extracting the tar/gz file, Always check if there is any INSTALL file where you can find instruction on how to compile the program
Always pay attention to choose a `--prefix` when running the configuration step or something similar to that. The prefix allow us to specify where to install the binaries, doc, etc
Sometimes the configuration/something similar fail and it is usually due to a missing configuration library/program
When using `make all` or something similar we can specify `-j 32` to allow the compiling process to use your 32 cores instead of a single one.
`make install` generally take all the folders and files and put them in their proper location.
Shutout to the creator of [this video](https://www.youtube.com/watch?v=G4lHVdGX6LI).
<file_sep>- name: Restart HTTPD
service: name={{ redhat_apache}} state=restarted
when: "ansible_os_family='Redhat'"
ignore_errors: yes
- name: Restart apache2
service: name={{ debian_apache}} state=restarted
when: "ansiblel_os_family == debian"
ignore_errors: yes
<file_sep>--- # seboolean example
- hosts: apachweb
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: Change boolean for anonymous writes on the web server
seboolean: name=httpd_aron_write state=yes
<file_sep>--- # Testing the J2 template Module
- hosts: apacheweb:debian
connection: ssh
user: test
sudo: yes
gather_facts: yes
vars:
userName: test
userPassword: <PASSWORD>
connectionType: SFTP
tasks:
- name: Install the configuration file customized for the system
template: src=test.conf.j2 dest=/home/test/test.conf owner=test group=test mode=750
<file_sep>--- # notify exampel
- hosts: all
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
-name:
<file_sep># Python packaging in NixOS
For more in-depth stuff check: [nixpkgs/doc/languages-frameworks/python.section.md](https://github.com/NixOS/nixpkgs/blob/master/doc/languages-frameworks/python.section.md)
## Installing Python and packages
The Nix and NixOS manuals explain how packages are generally installed. In the case of Python and Nix, it is important to make a distinction between whether the package is considered an application or a library.
Applications on Nix are typically installed into your user profile imperatively using nix-env -i, and on NixOS declaratively by adding the package name to environment.systemPackages in /etc/nixos/configuration.nix. Dependencies such as libraries are automatically installed and should not be installed explicitly.
## Environment defined in separate .nix file
Create a file, e.g. build.nix, with the following expression
```
with import <nixpkgs> {};
python35.withPackages (ps: with ps; [ numpy toolz ])
```
and install it in your profile with
```
nix-env -if build.nix
```
If you prefer to, you could also add the environment as a package override to the Nixpkgs set, e.g. using config.nix
```nix
{ # ...
packageOverrides = pkgs: with pkgs; {
myEnv = python35.withPackages (ps: with ps; [ numpy toolz ]);
};
}
```
and install it in your profile with
```shell
nix-env -iA nixpkgs.myEnv
```
here's another example how to install the environment system-wide
```nix
{ # ...
environment.systemPackages = with pkgs; [
(python35.withPackages(ps: with ps; [ numpy toolz ]))
];
}
```
## Temporary Python environment with nix-shell
nix-shell gives the possibility to temporarily load another environment, akin to virtualenv.
The first and recommended method is to create an environment with `python.buildEnv` or `python.withPackages`:
```bash
$ nix-shell -p 'python35.withPackages(ps: with ps; [ numpy toolz ])'
```
The other method, which is not recommended, does not create an environment and requires you to list the packages directly,
```bash
$ nix-shell -p python35.pkgs.numpy python35.pkgs.toolz
```
nix-shell can also load an expression from a .nix file.
```nix
with import <nixpkgs> {};
(python35.withPackages (ps: [ps.numpy ps.toolz])).env
```
`with` statement brings all attributes of `nixpkgs` in the local scope. we create a Python 3.5 environment with the `withPackages` function.
The `withPackages` function expects us to provide a function as an argument that takes the set of all python packages and returns a list of packages to include in the environment. Here, we select the packages `numpy` and `toolz` from the package set.
Execute command with `--run`
A convenient option with `nix-shell` is the `--run` option, with which you can execute a command in the nix-shell. We can e.g. directly open a Python shell
```bash
$ nix-shell -p python35Packages.numpy python35Packages.toolz --run "python3"
```
## Developing with Python
The function buildPythonPackage is called and as argument it accepts a set. In this case the set is a recursive set, rec. One of the arguments is the name of the package, which consists of a basename (generally following the name on PyPi) and a version. Another argument, src specifies the source, which in this case is fetched from PyPI using the helper function fetchPypi.The output of the function is a derivation.
If something is exclusively a build-time dependency, then the dependency should be included as a `buildInput`, but if it is (also) a runtime dependency, then it should be added to `propagatedBuildInputs`. Test dependencies are considered build-time dependencies.
Occasionally you have also system libraries to consider (alongside python packages). E.g., lxml provides Python bindings to libxml2 and libxslt. These libraries are only required when building the bindings and are therefore added as `buildInputs`.
## Building packages and applications
Python libraries and applications that use setuptools or distutils are typically build with respectively the buildPythonPackage and buildPythonApplication functions. These two functions also support installing a wheel.
## `buildPythonPackage` function
* The `buildPythonPackage` function is implemented in `pkgs/development/interpreters/python/build-python-package.nix`
* The `buildPythonPackage` mainly does four things:
* In the `buildPhase`, it calls ${python.interpreter} setup.py bdist_wheel to build a wheel binary zipfile.
* In the `installPhase`, it installs the wheel file using pip install `*.whl`.
* In the `postFixup` phase, the `wrapPythonPrograms` bash function is called to wrap all programs in the `$out/bin/*` directory to include `$PATH` environment variable and add dependent libraries to script's `sys.path`.
* In the `installCheck` phase, `${python.interpreter} setup.py test` is ran.
## `buildPythonPackage` parameters
* `namePrefix`: Prepended text to ${name} parameter.
* `disabled`: If true, package is not build for particular python interpreter version.
* `setupPyBuildFlags`: List of flags passed to setup.py build_ext command
* `pythonPath`: List of packages to be added into $PYTHONPATH. Packages in `pythonPath` are not propagated (contrary to `propagatedBuildInputs`).
* `preShellHook`: Hook to execute commands before shellHook
* `postShellHook`: Hook to execute commands after shellHook
* `makeWrapperArgs`: A list of strings. Arguments to be passed to makeWrapper, which wraps generated binaries. By default, the arguments to makeWrapper set PATH and PYTHONPATH environment variables before calling the binary. Additional arguments here can allow a developer to set environment variables which will be available when the binary is run. For example, `makeWrapperArgs = ["--set FOO BAR" "--set BAZ QUX"]`. (real example: `makeWrapperArgs = ["--prefix" "PATH" ":" "${stdenv.lib.makeBinPath [ imagemagick xpdf tesseract ]}" ];` ) other example : ``makeWrapperArgs = ["--prefix" "PATH" ":" "${openssl}/bin" "--set" "PYTHONPATH" ":"];``
* `installFlags`: A list of strings. Arguments to be passed to pip install. To pass options to python setup.py install, use --install-option. E.g., installFlags=["--install-option='--cpp_implementation'"].
* `format`: Format of the source. Valid options are setuptools (default), flit, wheel, and other
* `catchConflicts` If true, abort package build if a package name appears more than once in dependency tree. Default is true
* `checkInputs` Dependencies needed for running the checkPhase. These are added to `buildInputs` when `doCheck = true`.
# Automatic tests
By default the command python setup.py test is run as part of the `checkPhase`, but often it is necessary to pass a custom checkPhase. An example of such a situation is when py.test is used.
Most python modules follows the standard test protocol where the pytest runner can be used instead. `py.test` supports a -k parameter to ignore test methods or classes:
```nix
buildPythonPackage {
# ...
# assumes the tests are located in tests
checkInputs = [ pytest ];
checkPhase = ''
py.test -k 'not function_name and not other_function' tests
'';
}
```
## Notes
Unicode issues can typically be fixed by including glibcLocales in buildInputs and exporting `LC_ALL=en_US.utf-8`.
Tests that attempt to access $HOME can be fixed by using the following work-around before running tests (e.g. preCheck): export HOME=$(mktemp -d)
<file_sep>- name: install the apache web server
yum: pkg=httpd state=latest
notify: Restart httpd
- name: install lynx
yum: pkg=lynx state=latest
<file_sep>--- # apt example
- host: apapcheweb
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: Install apache web server
apt: name=apache2 state=present # absent
- name: equivalant of apt-get update
apt: update_cache=yes
- name: equivalant of apt-get upgrade
apt: upgrade=dist
<file_sep>--- # package module exampel
- hosts: all
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: Install Apache web server
package: name=present state=latest
<file_sep>--- # jinja2 module example ( extention of python that allows to templatize our configuration)
- host: apapcheweb:debian
user: test
sudo: yes
connection: ssh
gather_facts: yes
vars:
userName: test
userPassword: <PASSWORD>
connectionType: SFTP
tasks:
- name: Install the configuration file customized for the system
template: src=jinja2_configuration_file.conf.j2 dest=/home/test/jinja2_configuration_file.conf owner=test group=test mode=750
<file_sep>--- # My first YAML Playbook for ansible
- hosts: all
user: test
sudo: yes
connection: ssh
gather_facts: no
vars:
playbook_version: 0.1b
vars_files:
- copyright.yml
- webdefaults.yml
vars_prompt:
- name: web_domain
prompt: Web Domain
# - name: pkg_name
# prompt: Install which package ?
tasks:
# - name: Install Lynx web browser
# action: yum name=lynx state=installed
# - name: Check for telent client
# action: yum name=telnet state=absent
# - name: Install provided package
# action: yum name= {{ pkg_name}} state=installed
- name: Install apache web server
action: yum name=httpd state=installed
async: 300
poll: 3
notify: Restart HTTPD
- name: Install the lynx web browser
action: yum name= {{ pkg_lynx}} state=installed
handlers:
- name: Restart the pache web server
action: service name=httpd state=restarted
<file_sep>{ deploymentName ? "deployment"
, title ? "deployment Timeboard"
, description ? "deployment timeboard to visualize different mertics"
, ...
}:
let
apiKey = builtins.readFile ./datadog-api.key;
appKey = builtins.readFile ./datadog-app.key;
# This can be further improved or maybe passed as args.
deviceNames = ["xvdf" "xvda"];
DiskStorageMetrics = ["system.disk.free" "system.disk.used"];
diskStoragePercentage = ["system.disk.in_use" "system.disk.total"];
DiskIOMetrics = ["system.io.r_s" "system.io.w_s"];
systemMetrics = ["system.cpu.iowait" "system.cpu.idle" "system.swap.used" "system.swap.free" "system.mem.free" "system.mem.used"]; # CPU RAM and SWAP
totalMemoryUsage = ["system.mem.total" "system.swap.total"];
listOfPossibleDevices = [ "xvdf" "xvdg" "xvdh" "xvdi" "xvdj" "xvdk" "xvdl" "xvdm" "xvdn" "xvdo" "xvdp" "xvdq"];
# this assumes that any disk other than the root one is encrypted.
diskMetricQuery = {device, metric}:
{
# this is kinda of crappy but yeah
q= if builtins.any (ac: device == ac) (listOfPossibleDevices)
then "avg:${metric}{$Deployment,device:/dev/mapper/${device}} by {host}"
else "avg:${metric}{$Deployment,device:/dev/disk/by-label/nixos} by {host}";
aggregator="avg";
type="line";
};
diskUsage = {devices, metric}:
{
title = "${metric}";#for ${map (x: (x + " ")) device}"; FIXME
definition = builtins.toJSON {
requests = map (device: (diskMetricQuery { inherit metric device; }) ) devices;
viz= "timeseries";
};
};
diskIOMetrics = {device, metric}:
{
q= "avg:${metric}{$Deployment,device:${device}} by {host}";
aggregator="avg";
type="line";
};
diskIOUsage = {devices, metric}:
{
title = "${metric}";#for ${map (x: (x + " ")) device}"; FIXME
definition = builtins.toJSON {
requests = map (device: (diskIOMetrics { inherit metric device; }) ) devices;
viz= "timeseries";
};
};
diskStorage = {device, metric}:
{
title = "${metric} for the ${device} device";#for ${map (x: (x + " ")) device}"; FIXME
definition = builtins.toJSON {
requests = [{
q = if builtins.any (ac: device == ac) (listOfPossibleDevices)
then "top(max:${metric}{$Deployment,device:/dev/mapper/${device}} by {host}, 10, 'max', 'desc')"
else "top(max:${metric}{$Deployment,device:/dev/disk/by-label/nixos} by {host}, 10, 'max', 'desc')";
}];
viz= "toplist";
};
};
systemHardwareUsage = {metric}:
{
title = "${metric}";
definition = builtins.toJSON {
requests = [{
aggregator="avg";
type="line";
q = "avg:${metric}{$Deployment} by {host}";
}];
viz= "timeseries";
};
};
memroyTotalUsage = {metric}:
{
title = "${metric}";
definition = builtins.toJSON {
requests = [{
q = "top(max:${metric}{$Deployment} by {host}, 10, 'max', 'desc')";
}];
viz= "toplist";
};
};
in
{
resources.datadogTimeboards.deployment-timeboard =
{ config, lib, ...}:
{
inherit title description appKey apiKey;
readOnly = true;
templateVariables = [
{
name = "Deployment";
prefix = "deployment";
default = deployment;
}
];
graphs = (lib.flatten ( map (metric: (diskUsage {devices=deviceNames; inherit metric;})) (DiskStorageMetrics)))
++ (lib.flatten ( map (metric: (diskIOUsage {devices=deviceNames; inherit metric;})) (DiskIOMetrics)))
++ (lib.flatten (map (metric: (map (device: (diskStorage {inherit metric device;})) (deviceNames)))(diskStoragePercentage)))
++ (lib.flatten (map (metric: ( systemHardwareUsage {inherit metric;})) systemMetrics ))
++ (lib.flatten (map (metric: (memroyTotalUsage {inherit metric;})) totalMemoryUsage ));
};
}
<file_sep>--- # Variables command line passing example
- hosts: '{{ hosts }}'
user: '{{ user }}'
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: install soem software
yum: pkg={{ pkg }} state=latest
<file_sep># Systemd
### systemd and journald, how these works
#### systemd essentials
`systemd` is a suite of tools that provides a fast and flexible init model for managing linux systems.
The basic object that systemd manages and acts upon is a "unit". the most common type of unit is a service ( a unit file ending in .service)
systemd services are managed using the systemctl command.
systemctl start/stop/status/restart service_name.
By default, most systemd unit files aren't started automatically at boot. To configure this functionality, we need to "enable" to unit.
This hooks it up to a certain boot "target", causing it to be triggered when that target is started:
`systemctl enable nginx.service`
`systemctl disable nginx.service`
To show all active systemd units:
`systemctl list-units`
`systemctl list-unit-files`
__Using Targets (Runlevels)__
In systemd, "targets" are used instead of runlevels. Targets are basically synchronization points that the server can use to bring the server into a specific state.
to view the default that systemd tries to reach at boot : `systemctl get-default`
To see all of the targets available on your system, type : `systemctl list-unit-files --type=target`
To change the default target that will be used at boot: `systemctl set-default multi-user.target`
To see what units are tied to a target: `list-dependencies multi-user.target`
You can modify the system state to transition between targets with the isolate option. This will stop any units that are not tied to the specified target. Be sure that the target you are isolating does not stop any essential services: `sudo systemctl isolate multi-user.target`
For some of the major states that a system can transition to, shortcuts are available:
- To power off your server: `systemctl poweroff`
- Reboot the system: `systemctl reboot`
- Boot into rescue mode: `systemctl rescue`
#### systemd in depth
Systemd Units: Units are the objects that systemd knows how to manage. These are basically a standardized representation of system resources that can be managed by the suite of daemons and manipulated by the provided utilities.
_Types of Units_:
- `.service`: is the main one used, service unit describes how to manage a service or application on the server.
- `.target`: A target unit is used to provide synchronization points for other units when booting up or changing states.
- `.timer`: A .timer unit defines a timer that will be managed by systemd, similar to a cron job for delayed or scheduled activation.
________________________________________________________________________________
_[Unit] Section Directives_:
- `Description=`: This directive can be used to describe the name and basic functionality of the unit. It is returned by various systemd tools, so it is good to set this to something short, specific, and informative.
- `Documentation=`: This directive provides a location for a list of URIs for documentation. These can be either internally available man pages or web accessible URLs. The systemctl status command will expose this information, allowing for easy discoverability.
- `Requires=`: This directive lists any units upon which this unit essentially depends. If the current unit is activated, the units listed here must successfully activate as well, else this unit will fail. These units are started in parallel with the current unit by default.
- `Wants=`: This directive is similar to Requires=, but less strict.
- `BindsTo=`: This directive is similar to Requires=, but also causes the current unit to stop when the associated unit terminates.
- `Before=`: The units listed in this directive will not be started until the current unit is marked as started if they are activated at the same time. This does not imply a dependency relationship and must be used in conjunction with one of the above directives if this is desired.
- `After=`: The units listed in this directive will be started before starting the current unit.
- `Conflicts=`: This can be used to list units that cannot be run at the same time as the current unit. Starting a unit with this relationship will cause the other units to be stopped.
- `Condition...=`: There are a number of directives that start with Condition which allow the administrator to test certain conditions prior to starting the unit. This can be used to provide a generic unit file that will only be run when on appropriate systems. If the condition is not met, the unit is gracefully skipped.
- `Assert...=`: Similar to the directives that start with Condition, these directives check for different aspects of the running environment to decide whether the unit should activate. However, unlike the Condition directives, a negative result causes a failure with this directive.
________________________________________________________________________________
_[Install] Section Directives_: This section is optional and is used to define the behavior or a unit if it is enabled or disabled.
- `WantedBy=`: The WantedBy= directive is the most common way to specify how a unit should be enabled. This directive allows you to specify a dependency relationship in a similar way to the Wants= directive does in the [Unit] section.
- `RequiredBy=`: This directive is very similar to the WantedBy= directive, but instead specifies a required dependency that will cause the activation to fail if not met. When enabled, a unit with this directive will create a directory ending with .requires.
- `Alias=`: This directive allows the unit to be enabled under another name as well. Among other uses, this allows multiple providers of a function to be available, so that related units can look for any provider of the common aliased name.
- `Also=`: This directive allows units to be enabled or disabled as a set. Supporting units that should always be available when this unit is active can be listed here. They will be managed as a group for installation tasks.
- `DefaultInstance=`: For template units (covered later) which can produce unit instances with unpredictable names, this can be used as a fallback value for the name if an appropriate name is not provided.
________________________________________________________________________________
Unit-Specific Section Directives: Unit type-specific sections. Most unit types offer directives that only apply to their specific type.
The device, target, snapshot, and scope unit types have no unit-specific directives, and thus have no associated sections for their type.
The [Service] section is used to provide configuration that is only applicable for services.
the Type= of the service need to be specified. This categorizes services by their process and daemonizing behavior. This is important because it tells systemd how to correctly manage the servie and find out its state.
The Type= directive can be one of the following:
simple: The main process of the service is specified in the start line. This is the default if the Type= and Busname= directives are not set, but the ExecStart= is set.
forking: This service type is used when the service forks a child process, exiting the parent process almost immediately. This tells systemd that the process is still running even though the parent exited.
oneshot: This type indicates that the process will be short-lived and that systemd should wait for the process to exit before continuing on with other units. This is the default Type= and ExecStart= are not set. It is used for one-off tasks.
dbus: This indicates that unit will take a name on the D-Bus bus. When this happens, systemd will continue to process the next unit.
notify: This indicates that the service will issue a notification when it has finished starting up. The systemd process will wait for this to happen before proceeding to other units.
idle: This indicates that the service will not be run until all jobs are dispatched.
Some additional directives may be needed when using certain service types. For instance:
RemainAfterExit=: This directive is commonly used with the oneshot type. It indicates that the service should be considered active even after the process exits.
PIDFile=: If the service type is marked as "forking", this directive is used to set the path of the file that should contain the process ID number of the main child that should be monitored.
BusName=: This directive should be set to the D-Bus bus name that the service will attempt to acquire when using the "dbus" service type.
NotifyAccess=: This specifies access to the socket that should be used to listen for notifications when the "notify" service type is selected This can be "none", "main", or "all. The default, "none", ignores all status messages. The "main" option will listen to messages from the main process and the "all" option will cause all members of the service's control group to be processed.
How to manage our services. The directives to do this are:
ExecStart=: This specifies the full path and the arguments of the command to be executed to start the process. This may only be specified once (except for "oneshot" services). If the path to the command is preceded by a dash "-" character, non-zero exit statuses will be accepted without marking the unit activation as failed.
ExecStartPre=: This can be used to provide additional commands that should be executed before the main process is started. This can be used multiple times. Again, commands must specify a full path and they can be preceded by "-" to indicate that the failure of the command will be tolerated.
ExecStartPost=: This has the same exact qualities as ExecStartPre= except that it specifies commands that will be run after the main process is started.
ExecReload=: This optional directive indicates the command necessary to reload the configuration of the service if available.
ExecStop=: This indicates the command needed to stop the service. If this is not given, the process will be killed immediately when the service is stopped.
ExecStopPost=: This can be used to specify commands to execute following the stop command.
RestartSec=: If automatically restarting the service is enabled, this specifies the amount of time to wait before attempting to restart the service.
Restart=: This indicates the circumstances under which systemd will attempt to automatically restart the service. This can be set to values like "always", "on-success", "on-failure", "on-abnormal", "on-abort", or "on-watchdog". These will trigger a restart according to the way that the service was stopped.
TimeoutSec=: This configures the amount of time that systemd will wait when starting or stopping the service before marking it as failed or forcefully killing it. You can set separate timeouts with TimeoutStartSec= and TimeoutStopSec= as well.
The [Socket] Section: Socket units are very common in systemd configurations because many services implement socket-based activation to provide better parallelization and flexibility. Each socket unit must have a matching service unit that will be activated when the socket receives activity.
ListenStream=: This defines an address for a stream socket which supports sequential, reliable communication. Services that use TCP should use this socket type.
ListenDatagram=: This defines an address for a datagram socket which supports fast, unreliable communication packets. Services that use UDP should set this socket type.
ListenSequentialPacket=: This defines an address for sequential, reliable communication with max length datagrams that preserves message boundaries. This is found most often for Unix sockets.
ListenFIFO: Along with the other listening types, you can also specify a FIFO buffer instead of a socket.
...
Accept=: This determines whether an additional instance of the service will be started for each connection. If set to false (the default), one instance will handle all connections.
SocketUser=: With a Unix socket, specifies the owner of the socket. This will be the root user if left unset.
SocketGroup=: With a Unix socket, specifies the group owner of the socket. This will be the root group if neither this or the above are set. If only the SocketUser= is set, systemd will try to find a matching group.
SocketMode=: For Unix sockets or FIFO buffers, this sets the permissions on the created entity.
Service=: If the service name does not match the .socket name, the service can be specified with this directive.
The [Mount] Section: Mount units allow for mount point management from within systemd. Mount points are named after the directory that they control, with a translation algorithm applied.
What=: The absolute path to the resource that needs to be mounted.
Where=: The absolute path of the mount point where the resource should be mounted. This should be the same as the unit file name, except using conventional filesystem notation.
Type=: The filesystem type of the mount.
Options=: Any mount options that need to be applied. This is a comma-separated list.
SloppyOptions=: A boolean that determines whether the mount will fail if there is an unrecognized mount option.
DirectoryMode=: If parent directories need to be created for the mount point, this determines the permission mode of these directories.
TimeoutSec=: Configures the amount of time the system will wait until the mount operation is marked as failed.
The [Automount] Section: This unit allows an associated .mount unit to be automatically mounted at boot. As with the .mount unit, these units must be named after the translated mount point's path.
Where=: The absolute path of the automount point on the filesystem. This will match the filename except that it uses conventional path notation instead of the translation.
DirectoryMode=: If the automount point or any parent directories need to be created, this will determine the permissions settings of those path components.
The [Swap] Section: Swap units are used to configure swap space on the system. The units must be named after the swap file or the swap device, using the same filesystem translation that was discussed above.
Like the mount options, the swap units can be automatically created from /etc/fstab entries, or can be configured through a dedicated unit file.
What=: The absolute path to the location of the swap space, whether this is a file or a device.
Priority=: This takes an integer that indicates the priority of the swap being configured.
Options=: Any options that are typically set in the /etc/fstab file can be set with this directive instead. A comma-separated list is used.
TimeoutSec=: The amount of time that systemd waits for the swap to be activated before marking the operation as a failure.
The [Path] Section: A path unit defines a filesystem path that systmed can monitor for changes. Another unit must exist that will be be activated when certain activity is detected at the path location. Path activity is determined thorugh inotify events.
PathExists=: This directive is used to check whether the path in question exists. If it does, the associated unit is activated.
PathExistsGlob=: This is the same as the above, but supports file glob expressions for determining path existence.
PathChanged=: This watches the path location for changes. The associated unit is activated if a change is detected when the watched file is closed.
PathModified=: This watches for changes like the above directive, but it activates on file writes as well as when the file is closed.
DirectoryNotEmpty=: This directive allows systemd to activate the associated unit when the directory is no longer empty.
Unit=: This specifies the unit to activate when the path conditions specified above are met. If this is omitted, systemd will look for a .service file that shares the same base unit name as this unit.
MakeDirectory=: This determines if systemd will create the directory structure of the path in question prior to watching.
DirectoryMode=: If the above is enabled, this will set the permission mode of any path components that must be created.
The [Timer] Section: Timer units are used to schedule tasks to operate at a specific time or after a certain delay. This unit type replaces or supplements some of the functionality of the cron and at daemons. An associated unit must be provided which will be activated when the timer is reached.
OnActiveSec=: This directive allows the associated unit to be activated relative to the .timer unit's activation.
OnBootSec=: This directive is used to specify the amount of time after the system is booted when the associated unit should be activated.
OnStartupSec=: This directive is similar to the above timer, but in relation to when the systemd process itself was started.
OnUnitActiveSec=: This sets a timer according to when the associated unit was last activated.
OnUnitInactiveSec=: This sets the timer in relation to when the associated unit was last marked as inactive.
OnCalendar=: This allows you to activate the associated unit by specifying an absolute instead of relative to an event.
AccuracySec=: This unit is used to set the level of accuracy with which the timer should be adhered to. By default, the associated unit will be activated within one minute of the timer being reached. The value of this directive will determine the upper bounds on the window in which systemd schedules the activation to occur.
Unit=: This directive is used to specify the unit that should be activated when the timer elapses. If unset, systemd will look for a .service unit with a name that matches this unit.
Persistent=: If this is set, systemd will trigger the associated unit when the timer becomes active if it would have been triggered during the period in which the timer was inactive.
WakeSystem=: Setting this directive allows you to wake a system from suspend if the timer is reached when in that state.
_The [Slice] Section_: The [Slice] section of a unit file actually does not have any .slice unit specific configuration. Instead, it can contain some resource management directives that are actually available to a number of the units listed above.
________________________________________________________________________________
_Creating Instance Units from Template Unit Files_: Template unit files are, in most ways, no different than regular unit files. However, these provide flexibility in configuring units by allowing certain parts of the file to utilize dynamic information that will be available at runtime.
Template and Instance Unit Names: Template unit files can be identified because they contain an @ symbol after the base unit name and before the unit type suffix. A template unit file name may look like this: `example@.service`
When an instance is created from a template, an instance identifier is placed between the @ symbol and the period signifying the start of the unit type. For example, the above template unit file could be used to create an instance unit that looks like this: `example@instance1.service`
Template Specifiers: The power of template unit files is mainly seen through its ability to dynamically substitute appropriate information within the unit definition according to the operating environment. This is done by setting the directives in the template file as normal, but replacing certain values or parts of values with variable specifiers.
The following are some of the more common specifiers will be replaced when an instance unit is interpreted with the relevant information:
- `%n`: Anywhere where this appears in a template file, the full resulting unit name will be inserted.
- `%N`: This is the same as the above, but any escaping, such as those present in file path patterns, will be reversed.
- `%p`: This references the unit name prefix. This is the portion of the unit name that comes before the @ symbol.
- `%P`: This is the same as above, but with any escaping reversed.
- `%i`: This references the instance name, which is the identifier following the @ in the instance unit. This is one of the most commonly used specifiers because it will be guaranteed to be dynamic. The use of this identifier encourages the use of configuration significant identifiers. For example, the port that the service will be run at can be used as the instance identifier and the template can use this specifier to set up the port specification.
- `%I`: This specifier is the same as the above, but with any escaping reversed.
- `%f`: This will be replaced with the unescaped instance name or the prefix name, prepended with a /.
- `%c`: This will indicate the control group of the unit, with the standard parent hierarchy of /sys/fs/cgroup/ssytemd/ removed.
- `%u`: The name of the user configured to run the unit.
- `%U`: The same as above, but as a numeric UID instead of name.
- `%H`: The host name of the system that is running the unit.
- `%%`: This is used to insert a literal percentage sign.
#### Journald
_Viewing Basic Log Information_: A systemd component called journald collects and manages journal entries from all parts of the system. This is basically log information from applications and the kernel.
- `journalctl`
- `journalctl -b`: only from the current boot
- `journalctl -k`:only kernel messages
- `journalctl -u nginx.service`: To see all of the journal entries for the unit in question
- `systemctl cat nginx.service`: To see the full contents of a unit file
- `systemctl list-dependencies nginx.service`: To see the dependency tree of a unit (which units systemd will attempt to activate when starting the unit)
- `systemctl list-dependencies --all nginx.service`: recursive dependencies
- `systemctl show nginx.service`: the low-level details of the unit's settings on the system
Systemd-journald can be configured to grow its files up to a percentage of the size of the volume it’s hosted in.
The daemon would then automatically delete old journal entries to keep the size below that threshold.
Journald.conf:
- `SystemKeepFree`: This is one of the several parameters that control how large the journal can grow up to. This parameter applies if systemd is saving journals under the /var/log/journal directory. It specifies how much disk space the systemd-journald daemon will leave for other applications in the file system where the journal is hosted. The default is 15%.
- `SystemMaxuse`: This parameter controls the maximum disk space the journal can consume when it’s persistent. This defaults to 10% of the disk space.
- `SystemMaxFileSize`: This specifies the maximum size of a journal file for persistent storage. This defaults to one-eighth of the size of the SystemMaxUse parameter.
- `MaxRetentionSec`: The maximum time to store entries in the journal. Journal files containing records which are older than this period will be deleted automatically.
- `MaxLevelStore`: This parameter can take any of the following values: ... All messages equal or below the level specified will be stored on disk. The default value is “debug” which means all log messages from “emerg” to “debug”.
- `SystemMaxFiles` and `RuntimeMaxFiles`: control how many individual journal files to keep at most. Note that only archived files are deleted to reduce the number of files until this limit is reached; active files will stay around. This means that, in effect, there might still be more journal files around in total than this limit after a vacuuming operation is complete. This setting defaults to 100.
- `MaxRetentionSec`: The maximum time to store journal entries. This controls whether journal files containing entries older then the specified time span are deleted. Normally, time-based deletion of old journal files should not be required as size-based deletion with options such as SystemMaxUse= should be sufficient to ensure that journal files do not grow without bounds. However, to enforce data retention policies, it might make sense to change this value from the default of 0 (which turns off this feature). This setting also takes time values which may be suffixed with the units "year", "month", "week", "day", "h" or " m" to override the default time unit of seconds.
Check journald disk usage: `journalctl --disk-usage`
So we basically have the following limits on journald log size:
limit by size
limit by number of files
limit by date
default size limit: 4GB.
default file number limit: 100 files max.
#### Resources:
[Systemd essential](https://www.digitalocean.com/community/tutorials/systemd-essentials-working-with-services-units-and-the-journal)
To get more in depth look for these in the above web site bottom page:
* [How To Use Systemctl to Manage Systemd Services and Units](https://www.digitalocean.com/community/tutorials/how-to-use-systemctl-to-manage-systemd-services-and-units)
* [How To Use Journalctl to View and Manipulate Systemd Logs](https://www.digitalocean.com/community/tutorials/how-to-use-journalctl-to-view-and-manipulate-systemd-logs)
* [Understanding Systemd Units and Unit Files](https://www.digitalocean.com/community/tutorials/understanding-systemd-units-and-unit-files)
<file_sep>--- # git example
- host: apapcheweb
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: Checking out a git repo on the remote server
git: repo=ssh://test@tcox1/home/test/testrepo dest=/home/test/gitrepo version='somthing'
<file_sep># Hashicorp Packer
Packer is an open source tool for creating identical machine images for multiple platforms from a single source configuration.
### Use Cases
- Continuous Delivery
- Dev/Prod Parity
- Appliance/Demo Creation
### Installation
- Using nix: `nix-env -i packer`
- Using other linux distor: use `yum` or `apt`
- Install from source
### Packer terminology
- `Artifacts` are the results of a single build, and are usually a set of IDs or files to represent a machine image.
- `Builds` are a single task that eventually produces an image for a single platform.
- `Builders` are components of Packer that are able to create a machine image for a single platform. Builders read in some configuration and use that to run and generate a machine image.
- `Commands` are sub-commands for the packer program that perform some job.
- `Post-processors` are components of Packer that take the result of a builder or another post-processor and process that to create a new artifact.
- `Provisioners` are components of Packer that install and configure software within a running machine prior to that machine being turned into a static image. They perform the major work of making the image contain useful software.
- `Templates` are JSON files which define one or more builds by configuring the various components of Packer.
### Packer Commands (CLI)
Enabling Machine-Readable Output: The machine-readable output format can be enabled by passing the -machine-readable flag to any Packer command.
Format for Machine-Readable Output: `timestamp,target,type,data...`
- `timestamp` is a Unix timestamp in UTC of when the message was printed.
- `target` When you call packer build this can be either empty or individual build names
- `type` is the type of machine-readable message being outputted. The two most common types are ui and artifact
- `data` is zero or more comma-separated values associated with the prior type.
- Build Command: The `packer build` command takes a template and runs all the builds within it in order to generate a set of artifacts.
- Fix Command: The `packer fix` command takes a template and finds backwards incompatible parts of it and brings it up to date so it can be used with the latest version of Packer. After you update to a new Packer release, you should run the fix command to make sure your templates work with the new release.
example: `packer fix old.json > new.json`
- Inspect Command: the `packer inspect` command takes a template and outputs the various components a template defines. This can help you quickly learn about a template without having to dive into the JSON itself.
- Validate Command: The `packer validate` command is used to validate the syntax and configuration of a template.
### Template Structure
The configuration file used to define what image we want built and how is called a template in Packer terminology. The format of a template is simple JSON
- `builders` (required) is an array of one or more objects that defines the builders that will be used to create machine images for this template, and configures each of those builders.
- `description` (optional) is a string providing a description of what the template does. This output is used only in the inspect command.
- `min_packer_version` (optional) is a string that has a minimum Packer version that is required to parse the template. This can be used to ensure that proper versions of Packer are used with the template. A max version can't be specified because Packer retains backwards compatibility with packer fix.
- `post-processors` (optional) is an array of one or more objects that defines the various post-processing steps to take with the built images.
- `provisioners` (optional) is an array of one or more objects that defines the provisioners that will be used to install and configure software for the machines created by each of the builders. Provisioners use builtin and third-party software to install and configure the machine image after booting. Provisioners prepare the system for use, so common use cases for provisioners include:
* installing packages
* patching the kernel
* creating users
* downloading application code
- `variables` (optional) is an object of one or more key/value strings that defines user variables contained in the template. If it is not specified, then no variables are defined.
An example of a predefined provisioner :
The file provisioner can upload both single files and complete directories.
```json
"provisioners": [
{
"type": "shell-local",
"command": "tar cf toupload/files.tar files"
},
{
"destination": "/tmp/",
"source": "./toupload",
"type": "file"
},
{
"inline": [
"cd /tmp && tar xf toupload/files.tar",
"rm toupload/files.tar"
],
"type": "shell"
}
]
}
```
There is a wide range of provisioner types: check them [here](https://www.packer.io/docs/provisioners/index.html).
To pass the access and secret keys to the template we can use the following piece of code to make packer prompt us for the access keys:
```json
"variables": {
"aws_access_key": "",
"aws_secret_key": ""
},
```
We can also use env variables:
```json
{
"variables": {
"my_secret": "{{env `MY_SECRET`}}",
}
}
```
Use `packer validate example.json` to validate the template
#### Build an Image
```bash
$ packer build \
-var 'aws_access_key=YOUR ACCESS KEY' \
-var 'aws_secret_key=YOUR SECRET KEY' \
example.json
```
--> At the end of running packer build, Packer outputs the artifacts that were created as part of the build. Artifacts are the results of a build, and typically represent an ID (such as in the case of an AMI) or a set of files (such as for a VMware virtual machine).
If we have multiple builders (involving multiple cloud provider) and we want to restrick the build to a given we can use: `packer build -only=amazon-ebs example.json`
## Provision
Packer fully supports automated provisioning in order to install software onto the machines prior to turning them into images.
We can use `-on-error=ask` when running `packer build` to debug issues.
### Configuring Provisioners
Provisioners are configured as part of the template. We'll use the built-in shell provisioner that comes with Packer to install Redis.
```json
{
"variables": ["..."],
"builders": ["..."],
"provisioners": [{
"type": "shell",
"inline": [
"sleep 30",
"sudo apt-get update",
"sudo apt-get install -y redis-server"
]
}]
}
```
To configure the provisioners, we add a new section provisioners to the template, alongside the builders configuration. The provisioners section is an array of provisioners to run. If multiple provisioners are specified, they are run in the order given.
By default, each provisioner is run for every builder defined. So if we had two builders defined in our template, such as both Amazon and DigitalOcean, then the shell script would run as part of both builds. There are ways to restrict provisioners to certain build
Packer is able to make an AMI and a VMware virtual machine in parallel provisioned with the same scripts
The one provisioner we defined has a type of shell. This provisioner ships with Packer and runs shell scripts on the running machine.
## Vagrant Boxes as post-processors
Packer also has the ability to take the results of a builder and turn it into a Vagrant box.
Post-processors are added in the post-processors section of a template, which we haven't created yet
```json
{
"builders": ["..."],
"provisioners": ["..."],
"post-processors": ["vagrant"]
}
```
<file_sep>- name: Install the telnet client
yum: pkg=telnet state=latest
- name: Install the lynx web browser
yum: pkg=lynx state=latest
<file_sep>--- # geturl exampel
- hosts: all
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: Get and download the INI file from the web sever
get_url: url=http://tcox1.labserver.com/mytest.ini dest=/home/test/mytest.ini mode=0444
<file_sep>- name: Install Apache Web Server
yum: pkg={{redhat_apache}} state=latest
when: "ansible_os_family == 'Redhat'"
ignore_errors: yes
notify: Restart HTTPD
- name: Install (Debian/Ubuntu ) Apache Web Server
apt: pkg={{debian_apache}} state=latest
when: "ansible_os_family == 'Debian'"
notify: restart Apache2
ignore_errors: yes
- debug: Need to install telnet
when: "ansible_os_family == 'RedHat'"
notify: InstallTelnet
<file_sep># SConfiguration file for our custom widget
<Connectivity>
ConnectionType {{ connectionType }}
<Connectivity>
<Account Information>
Usernale {{ userName }}
password {{ <PASSWORD>}}
<Account Information>
<system Information>
DistributionType {{ ansible_os_family }}
<system Information>
<file_sep>{ enableEscalation ? false
, alertedUsers ? [] # peoples that will receive the alerts
, escalateToUsers ? [] # when enableEscalation is set, people to escalate to.
, datadogProcesses ? [] # list of processes that datadog will be monitoring (sshd or zabbix_agentd for example :p)
, ...
}:
with import <nixpkgs/lib>;
{
defaults =
{config, pkgs, lib, ...}:
{
# this Should be updated for datadog agent v6 on 18.09.
services.dd-agent.processConfig = lib.mkOverride 10 ( if datadogProcesses!=[] then ''
init_config:
instances:
${concatMapStrings (x: " - name: "+x +"\n"+ " search_string: ['" + x +"']\n") datadogProcesses}
'' else "");
};
resources.datadogMonitors =
let
apiKey = builtins.readFile ./datadog-api.key;
appKey = builtins.readFile ./datadog-app.key;
systemServices = service:
{ config, lib, resources, ...}:
let
deployment = "${toLower config.deployment.name}";
in
{
inherit apiKey appKey;
name = "[${deployment}]: ${service} on {{host.name}} not working";
type = "service check";
query = ''
"process.up".over("deployment:${deployment}","process:${service}").last(2).count_by_status()
'';
message = ''
The systemd unit ${service} failed or not running please run `systemctl status` UNIT_NAME for more information.
${concatMapStrings (x: " @"+x) alertedUsers}
'';
monitorOptions = builtins.toJSON ({
no_data_timeframe = 3;
new_host_delay = 300;
# test this for when a service is oneshot
notify_no_data = true;
thresholds.critical = 1;
} // (
escalation "${service} has been in a failed state/not running for over an hour"
)
);
};
escalation = msg:(if enableEscalation then
{
escalation_message = ''
${msg}
${if escalateToUsers!=[] then concatMapStrings (x: " @"+x) escalateToUsers else ""}
'';
renotify_interval = 60;
}
else {});
in
{
no-data-monitor =
{ config, ...}:
{
inherit apiKey appKey;
name = "[${config.deployment.name}] {{host.name}} no data is being collected";
type = "service check";
query = ''"datadog.agent.up".over("deployment:${toLower config.deployment.name}").by("host").last(1).count_by_status()'';
message = ''
No data is being collected from {{host.name}}, this generally indicates that the host is no longer reachable,
please investigate
${concatMapStrings (x: " @"+x) alertedUsers}
'';
monitorOptions = builtins.toJSON ({
no_data_timeframe = 30;
new_host_delay = 300;
notify_no_data = true;
thresholds.critical = 1;
} // (
escalation "No data has been collected from {{host.name}} for over an hour"
)
);
};
memory-monitor =
{ config, ...}:
{
inherit apiKey appKey;
name = "[${config.deployment.name}] Usable memory in {{host.name}} is under 3Gb";
type = "metric alert";
query = "avg(last_10m):avg:system.mem.usable{deployment:${toLower config.deployment.name}} by {host} < 3221225472";
message = ''
The usable memory in {{host.name}} is very low, this can impact the system performance.
${concatMapStrings (x: " @"+x) alertedUsers}
'';
monitorOptions = builtins.toJSON ({
no_data_timeframe = 30;
new_host_delay = 300;
thresholds.critical = 3221225472;
} // (
escalation "The usable memory is above the critical threshold for over an hour"
)
);
};
cpu-idle-monitor =
{ config, ...}:
{
inherit apiKey appKey;
name = "[${config.deployment.name}] Idle CPU percentage in {{host.name}} is under 10% for the last 10 min";
type = "metric alert";
query = "avg(last_10m):avg:system.cpu.idle{deployment:${toLower config.deployment.name}} by {host} < 10";
message = ''
The Idle CPU in {{host.name}} is very low, this can impact the system performance.
${concatMapStrings (x: " @"+x) alertedUsers}
'';
monitorOptions = builtins.toJSON ({
no_data_timeframe = 30;
new_host_delay = 300;
thresholds.critical = 10;
} // (
escalation "The Idle CPU is below the critical threshold for over an hour"
)
);
};
inode-free-monitor =
{ config, ...}:
{
inherit apiKey appKey;
name = "[${config.deployment.name}] Free Inode in {{host.name}} are under 1000";
type = "metric alert";
query = "avg(last_10m):avg:system.fs.inodes.free{deployment:${toLower config.deployment.name}} by {host} < 1000";
message = ''
Free Inode in {{host.name}} is very low, this can impact the system performance.
${concatMapStrings (x: " @"+x) alertedUsers}
'';
monitorOptions = builtins.toJSON ({
no_data_timeframe = 30;
new_host_delay = 300;
thresholds.critical = 1000;
} // (
escalation "Free Inode is below the critical threshold for over an hour"
)
);
};
swap-memory-monitor =
{ config, ...}:
{
inherit apiKey appKey;
name = "[${config.deployment.name}] SWAP memory in {{host.name}} is under 1 GB";
type = "metric alert";
query = "avg(last_10m):avg:system.swap.free{deployment:${toLower config.deployment.name}} by {host} < 1070000000";
message = ''
SWAP in {{host.name}} is very low, this can impact the system performance.
${concatMapStrings (x: " @"+x) alertedUsers}
'';
monitorOptions = builtins.toJSON ({
no_data_timeframe = 30;
new_host_delay = 300;
thresholds.critical = 1070000000;
} // (
escalation "SWAP memory is below the critical threshold for over an hour"
)
);
};
system-uptime-monitor =
{ config, ...}:
{
inherit apiKey appKey;
name = "[${config.deployment.name}] {{host.name}} recently rebooted";
type = "metric alert";
query = "max(last_5m):avg:system.uptime{deployment:${toLower config.deployment.name}} by {host} < 1800";
message = ''
{{host.name}} recently rebooted, please investigte.
${concatMapStrings (x: " @"+x) alertedUsers}
'';
monitorOptions = builtins.toJSON ({
no_data_timeframe = 30;
new_host_delay = 1800;
thresholds.critical = 1800;
}
);
};
cpu-iowait-monitor =
{ config, ...}:
{
inherit apiKey appKey;
name = "[${config.deployment.name}] CPU IO wait in {{host.name}} is above 90%";
type = "metric alert";
query = "avg(last_10m):avg:system.cpu.iowait{deployment:${toLower config.deployment.name}} by {host} > 90";
message = ''
CPU IO wait in {{host.name}} is very high, this can impact the system performance.
${concatMapStrings (x: " @"+x) alertedUsers}
'';
monitorOptions = builtins.toJSON ({
no_data_timeframe = 30;
new_host_delay = 300;
thresholds.critical = 90;
} // (
escalation "CPU IO wait is above the critical threshold for over an hour"
)
);
};
disk-usage-monitor =
{ config, ...}:
{
inherit apiKey appKey;
name = "[${config.deployment.name}] disk space on {{host.name}}:{{device.name}} is under 10%";
type = "metric alert";
query = "max(last_15m):"+
"( 100 * max:system.disk.free{deployment:${toLower config.deployment.name},!device:devtmpfs,!device:tmpfs} by {device,host} ) /"+
" max:system.disk.total{deployment:${toLower config.deployment.name},!device:devtmpfs,!device:tmpfs} by {device,host} <= 10";
message = ''
Available disk space on {{host.name}}, {{device.name}} is under 10%. Please run `df -h` for more informations.
${concatMapStrings (x: " @"+x) alertedUsers}
'';
monitorOptions = builtins.toJSON ({
no_data_timeframe = 30;
new_host_delay = 300;
thresholds.critical = 10;
} // (
escalation "Low available disk space on {{host.name}}/{{device.name}} for over an hour"
)
);
};
} // (
builtins.listToAttrs (map (s: nameValuePair "${s}-monitor" (systemServices s) ) datadogProcesses)
);
}
/* sshd-monitor =
{ config, ...}:
{
inherit apiKey appKey;
name = "[${config.deployment.name}] sshd service on {{host.name}} is not working";
type = "service check";
query = ''"process.up".over("deployment:nixos-hardened-image","process:sshd").last(2).count_by_status()'';
message = ''
The sshd service on {{host.name}} is not working.
${concatMapStrings (x: " @"+x) alertedUsers}
'';
monitorOptions = builtins.toJSON ({
no_data_timeframe = 3;
new_host_delay = 300;
thresholds.critical = 2;
notify_no_data = true;
} // (
escalation "SSHD is not working on {{host.name}} for more than an hour"
)
);
}; */<file_sep>--- # Local action playbook
- hosts: 192.168.3.11
connections: local
tasks:
- name install Telnet client
yum: pkg=telnet ensure=latest
<file_sep>--- # Service module example
- hosts: apacheweb
user: test
sudo: yes
connection: ssh
tasks:
- name: Install web server
action: yum name=httpd state=installed
- name: Start the web Service
service: name=httpd state=started
- name: Enable httpd after reboot
service: name=httpd enabled=yes
<file_sep>--- # script example
- hosts: webserver
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- script: ~/machin/playbook/system_uptime.syh > uptime.log --some-argument 11234
<file_sep># VIM
* Remove all comments and space:
g/\v^(#|$)/d
* Copy and Cut:
http://vim.wikia.com/wiki/Cut/copy_and_paste_using_visual_selection
* Comment and uncomment things:
To comment:
if the line has no tab/space at the beginning:
ctrl + V then jjj then shift + I (cappital i) then //then esc esc
if the line has tab/space at the beginning you still can do the above or swap for c:
ctrl + V then jjj then c then //then esc esc
To uncomment:
if the lines have no tab/space at the beginning:
ctrl + V then jjj then ll (lower cap L) then c
if the lines have tab/space at the beginning, then you space one over and esc
ctrl + V then jjj then ll (lower cap L) then c then space then esc
* Visual mode:
v + y to copy
v + c to cut
v + d to cut
v + p to paste
V to highlight a block
<file_sep># t5adhrit
_t5adhrit_
<file_sep>--- # htpasswd exampel
- hosts: all
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: install the python dependencies
apt: pkg=python-passlib state=latest
- name: adding a user to web site authentication
htpasswd: path=/etc/apache2/.htpasswd name=test2 password=<PASSWORD> owner=test2 group=test2 mode=064
- name: remove a user from web site authentication
htpasswd: path=/etc/apache2/.htpasswd name=test2 state=abscent
<file_sep>--- # outline to playbook translation
- hosts: apacheweb
user: test
sudo: yes
gathering_facts: no
tasks:
- name: date/time stamp for when the playbook start
command: /usr/bin/date
register: timestamp_start
- debug: var=timestamp_start
- name: install the apache web server
yum: pkg=httpd state= latest
notify: Start HTTPD
- name: start the web service
service: name=httpd state=restarted
- name: verify that the web service is running
command: systemctl status httpd
register: result
- debug: var=result
- name: install client software - telnet
yum: pkg=telnet state=latest
- name: install client software - lynx
yum: pkg=lynx state=latest
- name: log all the packages installed on the system
command: yum list installed
register: installed_result
- debug: var=installed_result
- name: /date/time stamp for when the playbook ends
command: /usr/bin/date
register: timestamp_end
- debug: var=timestamp_end
handlers:
- name: start HTTPD
service: name=httpd state= restarted
<file_sep># Packaging with nix.
*notes taken from nixpkgs manual: https://nixos.org/nixpkgs/manual/*
### Phases
Using stdenv:
To build a package with the standard environment, you use the function stdenv.mkDerivation
Specifying a name and a src is the absolute minimum you need to do.
Many packages have dependencies that are not provided in the standard environment. It’s usually sufficient to specify those dependencies in the buildInputs:
This attribute ensures that the bin subdirectories of these packages appear in the PATH environment variable during the build, that their include subdirectories are searched by the C compiler, and so on
Often it is necessary to override or modify some aspect of the build. To make this easier, the standard environment breaks the package build into a number of phases,all of which can be overridden or modified individually, the main phases are:
* unpacking the sources
* applying patches
* configuring
* building
* installing
__controlling Phases__
There are a number of variables that control what phases are executed and in what order:
Variables affecting phase control:
phases: can change the order in which phases are executed, or add new phases. default phases:
...* prePhases
...* unpackPhase
...* patchPhase
...* preConfigurePhases
...* configurePhase
...* preBuildPhases
...* buildPhase
...* checkPhase
...* preInstallPhases
...* installPhase
...* fixupPhase
...* preDistPhases
...* distPhase
...* postPhases
* prePhases: Additional phases executed before any of the default phases.
* preConfigurePhases: Additional phases executed just before the configure phase.
* preBuildPhases: Additional phases executed just before the build phase.
* preInstallPhases: Additional phases executed just before the install phase.
* preFixupPhases: Additional phases executed just before the fixup phase.
* preDistPhases: Additional phases executed just before the distribution phase.
* postPhases: Additional phases executed after any of the default phases.
--- The unpack phase ---
Variables controlling the unpack phase:
* srcs / src
* sourceRoot
* setSourceRoot
* preUnpack
* postUnpack
* dontMakeSourcesWritable
* unpackCmd
--- The patch phase ---
Variables controlling the patch phase:
* patches: The list of patches. They must be in the format accepted by the patch command.
* patchFlags
* prePatch
* postPatch
--- The configure phase ---
The configure phase prepares the source tree for building. The default configurePhase runs ./configure
Variables controlling the configure phase:
* configureScript: The name of the configure script. It defaults to ./configure if it exists; otherwise, the configure phase is skipped. (it can also be a command)
* configureFlags
* configureFlagsArray
* dontAddPrefix: By default, the flag --prefix=$prefix is added to the configure flags. If this is undesirable, set this variable to true.
* prefix: The prefix under which the package must be installed, passed via the --prefix option to the configure script. It defaults to $out.
* dontAddDisableDepTrack
* dontFixLibtool: By default, the configure phase applies some special hackery to all files called ltmain.sh before running the configure script in order to improve the purity of Libtool-based packages . If this is undesirable, set this variable to true.
* dontDisableStatic
* configurePlatforms
* preConfigure: Hook executed at the start of the configure phase.
* postConfigure: Hook executed at the end of the configure phase.
--- The build phase ---
The build phase is responsible for actually building the package (e.g. compiling it). The default buildPhase simply calls make if a file named Makefile, makefile or GNUmakefile exists in the current directory
Variables controlling the build phase:
* dontBuild: Set to true to skip the build phase.
* makefile: The file name of the Makefile.
* makeFlags: A list of strings passed as additional flags to make. These flags are also used by the default install and check phase. For setting make flags specific to the build phase, use buildFlags
* makeFlagsArray
* buildFlags / buildFlagsArray
* preBuild
* postBuild
--- The check phase ---
The check phase checks whether the package was built correctly by running its test suite.
Variables controlling the check phase
* doCheck: Controls whether the check phase is executed. By default it is skipped
* makeFlags / makeFlagsArray / makefile
* checkTarget: The make target that runs the tests. Defaults to check.
* checkFlags / checkFlagsArray
* preCheck and postCheck
--- The install phase ---
The install phase is responsible for installing the package in the Nix store under out. The default installPhase creates the directory $out and calls make install.
Variables controlling the install phase:
* makeFlags / makeFlagsArray / makefile
* installTargets: The make targets that perform the installation. Defaults to install.
* installFlags / installFlagsArray
* preInstall / postInstall
--- The fixup phase ---
The fixup phase performs some (Nix-specific) post-processing actions on the files installed under $out by the install phase. The default fixupPhase does the following:
* It moves the man/, doc/ and info/ subdirectories of $out to share/.
* It strips libraries and executables of debug information.
* On Linux, it applies the patchelf command to ELF executables and libraries to remove unused directories from the RPATH in order to prevent unnecessary runtime dependencies.
* It rewrites the interpreter paths of shell scripts to paths found in PATH. E.g., /usr/bin/perl will be rewritten to /nix/store/some-perl/bin/perl found in PATH.
__Variables controlling the fixup phase:__
* dontStrip
* dontStripHost
* dontStripTarget
* dontMoveSbin: If set, files in $out/sbin are not moved to $out/bin. By default, they are.
* stripAllList
* stripAllFlags
* stripDebugList List of directories to search for libraries and executables from which only debugging-related symbols should be stripped. It defaults to lib bin sbin.
* stripDebugFlags
* dontPatchELF: If set, the patchelf command is not used to remove unnecessary RPATH entries. Only applies to Linux.
* dontPatchShebangs: If set, scripts starting with #! do not have their interpreter paths rewritten to paths in the Nix store.
* forceShare
* setupHook
* preFixup and postFixup
* separateDebugInfo
--- The installCheck phase ---
The installCheck phase checks whether the package was installed correctly by running its test suite against the installed directories. The default installCheck calls make installcheck.
Variables controlling the installCheck phase
* doInstallCheck: Controls whether the installCheck phase is executed. By default it is skipped
* preInstallCheck and postInstallCheck
--- The distribution phase ---
The distribution phase is intended to produce a source distribution of the package. The default distPhase first calls make dist, then it copies the resulting source tarballs to $out/tarballs/. This phase is only executed if the attribute doDist is set.
Variables controlling the distribution phase
* distTarget: The make target that produces the distribution. Defaults to dist.
* distFlags / distFlagsArray
* tarballs:The names of the source distribution files to be copied to $out/tarballs/. It can contain shell wildcards. The default is `*.tar.gz`.
* dontCopyDist: If set, no files are copied to $out/tarballs/.
* preDist; Hook executed at the start of the distribution phase.
* postDist: Hook executed at the end of the distribution phase.
### Shell functions
substituteinfileoutfilesubs: Performs string substitution on the contents of infile, writing the result to outfile. The substitutions in subs are of the following form:
--replaces1s2
Replace every occurrence of the string s1 by s2.
--subst-varvarName
Replace every occurrence of @varName@ by the contents of the environment variable varName. This is useful for generating files from templates, using @...@ in the template as placeholders.
--subst-var-byvarNames
Replace every occurrence of @varName@ by the string s.
Example:
substitute ./foo.in ./foo.out \
--replace /usr/bin/bar $bar/bin/bar \
--replace "a string containing spaces" "some other text" \
--subst-var someVar
substituteInPlacefilesubs: Like substitute, but performs the substitutions in place on the file file.
substituteAllinfileoutfile: Replaces every occurrence of @varName@, where varName is any environment variable, in infile, writing the result to outfile.
substituteAllInPlacefile: Like substituteAll, but performs the substitutions in place on the file file.
stripHashpath: Strips the directory and hash part of a store path, outputting the name part to stdout
### Package setup hooks
--------------------------------------------
some stuff i didn't understand:
--------------------------------------------
Python: Adds the lib/${python.libPrefix}/site-packages subdirectory of each build input to the PYTHONPATH environment variable.
pkg-config: Adds the lib/pkgconfig and share/pkgconfig subdirectories of each build input to the PKG_CONFIG_PATH environment variable.
paxctl: Defines the paxmark helper for setting per-executable PaX flags on Linux (where it is available by default; on all other platforms, paxmark is a no-op). For example, to disable secure memory protections on the executable foo:
postFixup = ''
paxmark m $out/bin/foo
'';
The m flag is the most common flag and is typically required for applications that employ JIT compilation or otherwise need to execute code generated at run-time. Disabling PaX protections should be considered a last resort: if possible, problematic features should be disabled or patched to work with PaX.
### Hardening in Nixpkgs
There are flags available to harden packages at compile or link-time. These can be toggled using the stdenv.mkDerivation parameters hardeningDisable and hardeningEnable.
-------------------------------
someother stuff that i didnt get a clue off.
-------------------------------
## Multiple-output packages
----------------------
didnt understand that much !!!
-----------------------
The Nix language allows a derivation to produce multiple outputs, which is similar to what is utilized by other Linux distribution packaging systems. The outputs reside in separate nix store paths, so they can be mostly handled independently of each other, including passing to build inputs, garbage collection or binary substitution. The exception is that building from source always produces all the outputs.
The main motivation is to save disk space by reducing runtime closure sizes; consequently also sizes of substituted binaries get reduced. Splitting can be used to have more granular runtime dependencies, for example the typical reduction is to split away development-only files, as those are typically not needed during runtime. As a result, closure sizes of many packages can get reduced to a half or even much less.
Installing a split package: When installing a package via systemPackages or nix-env you have several options: ...
# [WIP]
Chapter 5. ..................
-----------------------------------------------------------------------------------------------------------------------------------
///// others
patchs : variable in the pkgs definitions looks for a file that has the patch file. something that looks like git diff
<file_sep># Packaging from source:
## RPM:
https://rpm-guide.readthedocs.io/en/latest/rpm-guide.html
<file_sep># Ansible
various Ansible playbook for different operations.
<file_sep>--- # users example
- hosts: apacheweb
user: test
sudo: yes
gather_facts: no
connection: ssh
tasks:
- name: Add the user called apacheee to the apache web client
user: name=apacheee comment="Test Apache" uid=3030 group=wheel shell=/bin/bash
- name: remove a user
user: name=apacheee state=abscent remove=yes
<file_sep># when attached, destroying the security group fails,
# when adding a rule we need to add --check
{ vpcId ? "vpc-xxxxxx"
, accessKeyId ? "dovah"
, region ? "us-east-1"
, description? "know true pain"
, akinRules ? false
, toPort ? null
, fromPort ? null
, rulesFile ? ./rules.nix
, ...
}:
{
network.description = description;
resources.ec2SecurityGroups = with (import ../generic.nix { akinRules = akinRules; toPort = toPort; fromPort = fromPort; region = region; accessKeyId = accessKeyId;});
let
rules = import rulesFile;
in
{
group1 = createSecurityGroups "sg1" "desc1" vpcId rules.set1;
group2 = createSecurityGroups "sg1" "desc2" vpcId rules.set2;
};
}
#rules.nix
{
set1 = [
{ fromPort = 22; toPort = 22; protocol = "tcp"; sourceIp = "11.11.11.11/32"; }
{ fromPort = 80; toPort = 80; protocol = "tcp"; sourceIp = "11.11.22.33/32"; }
];
set2 = [
{ fromPort = 22; toPort = 22; protocol = "tcp"; sourceIp = "11.11.11.11/32"; }
{ fromPort = 80; toPort = 80; protocol = "tcp"; sourceIp = "11.11.22.33/32"; }
];
}
# generic.nix
{ accessKeyId ? "dovah"
, region ? "us-east-1"
, fromPort ? null
, toPort ? null
, akinRules ? false
, ...
}:
let
mapping = ip:
{
fromPort = fromPort; toPort = toPort; sourceIp = "${ip}";
};
in
{
createSecurityGroups = name: description: vpc: rules:
{
inherit accessKeyId region;
vpcId = vpc;
description = description;
name = name;
rules = if akinRules then (map mapping rules) else rules;
};
}
<file_sep>ansible-playbook myfirstplaybook.yml --check (this is a dry run)
ansible all --list-hosts
ansible-playbook local.yml --connection=local
ansible-vault create secure.yml
ansible-vault edit secure.yml ( to open and edit)
ansible-vault rekey secure.yml (change the password)
ansible-playbook tags.yml --tags "verification"
ansible-playbook tags.yml --skip-tags "verification"
ansible-playbook startat.yml --start-at-task="Install Lynx"
ansible-playbook startat.yml --step
ansible-playbook from-command-line.yml --extra-vars "hosts=apacheweb user=test pkg=telent"
ansible apacheweb -m setup -a 'filter=ansible_distribution'
ansible apacheweb -m file -a 'path=/etc/fstab' /// get the info of the file fstab
ansible apacheweb -s -m file -a 'path=/tmp/etc state=directory mode=700 owner=root'
<file_sep>#!/bin/python
from datadog import initialize, api
import argparse
options = {
'api_key': '<KEY>',
'app_key': '<KEY>'
}
initialize(**options)
parser = argparse.ArgumentParser(description="Add description to security groups")
parser.add_argument("-u", "--username", dest="username", required=True, help='the username you want to delete')
parser.add_argument("-m", "--mail-extention", dest="mail", required=True, help='organization mail extention')
args = parser.parse_args()
username = str(args.username)
mail = str(args.mail)
full_username = username + '@' + mail
# Disable user
r = api.User.delete(full_username)
message = str(r.items()[0][1])
print full_username + " " + message
<file_sep>--- # when playbook Example
- hosts: apacheweb
user: test
sudo: yes
connection: ssh
vars:
playbook_type: conditionalexample
vars_files:
- conf/copyright.yml
- conf/webdefaults.yml
tasks:
- name: install apache to the appropriate distribution type (debian)
command: apt-get -y install apache2
when: ansible_os_family == "Debian"
- name: Install apache to the appropriate distribuition type (redhat)
command: yum -y install httpd
when: ansible_os_family == "Redhat"
<file_sep>--- # Debug example
- hosts: apacheweb
user: test
sudo: yes
gather_facts: no
connection: ssh
tasks:
- name: install web server
yum: name=httpd state=installed
- debug: msg="Equivilant of sudo yum install httpd"
- name: how long has the system been up
shell: /usr/bin/uptime
register: result
- debug: var=result
<file_sep># GPG Stuff
Get my gpg key:
gpg --armor --export <EMAIL>
Decrypt:
gpg --output aws-creds.txt --decrypt credentials.csv.gpg
Encrypt:
gpg --encrypt --armor --recipient <EMAIL> --recipient <EMAIL> doc.txt
List gpg keys :
gpg --list-keys
Import a key:
gpg --import name
<file_sep>#!/bin/bash
while getopts ":c:h:a" o; do
case "${o}" in
c)
conf_file=${OPTARG};;
a)
Backup_ID_from_CLI=${OPTARG};;
h)
echo -e 'Usage: -c $conf_file_path -a $snapshot_id. \nSample of the config file:
some bla bla help
'
exit 0;;
esac
done
if [ -z $conf_file ]; then
echo 'ERROR: Config file path is missing. Usage: -c $conf_file_path. Use -h option for help'
exit 1
fi
<file_sep># Makefile
#### Source: ftp://ftp.gnu.org/old-gnu/Manuals/make-3.79.1/html_chapter/make_4.html
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
The makefile tells make how to compile and link a program.
A simple makefile consists of "rules" with the following shape:
```
target ... : prerequisites ...
command
...
...
```
A target is usually the name of a file that is generated by a program; examples of targets are executable or object files. A target can also be the name of an action to carry out, such as `clean`.
A prerequisite is a file that is used as input to create the target. A target often depends on several files.
A command is an action that make carries out. A rule may have more than one command, each on its own line. Please note: you need to put a tab character at the beginning of every command line! This is an obscurity that catches the unwary.
A rule explains how and when to remake certain files which are the targets of the particular rule. make carries out the commands on the prerequisites to create or update the target. A rule can also explain how and when to carry out an action.
## Examples:
In this example, all the C files include `defs.h`, but only those defining editing commands include `command.h`, and only low level files that change the editor buffer include `buffer.h`.
```
edit : main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o
cc -o edit main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o
main.o : main.c defs.h
cc -c main.c
kbd.o : kbd.c defs.h command.h
cc -c kbd.c
command.o : command.c defs.h command.h
cc -c command.c
display.o : display.c defs.h buffer.h
cc -c display.c
insert.o : insert.c defs.h buffer.h
cc -c insert.c
search.o : search.c defs.h buffer.h
cc -c search.c
files.o : files.c defs.h buffer.h command.h
cc -c files.c
utils.o : utils.c defs.h
cc -c utils.c
clean :
rm edit main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o
```
To use this makefile to create the executable file called `edit`, type:`make`.
To use this makefile to delete the executable file and all the object files from the directory, type: `make clean`.
## How make Processes a Makefile:
By default, make starts with the first target (not targets whose names start with `.`). This is called the default goal.
`make` reads the `makefile` in the current directory and begins by processing the first rule. In the example, this rule is for relinking `edit`; but before make can fully process this rule, it must process the rules for the files that `edit` depends on, which in this case are the object files. Each of these files is processed according to its own rule. These rules say to update each `.o` file by compiling its source file. The recompilation must be done if the source file, or any of the header files named as prerequisites, is more recent than the object file, or if the object file does not exist.
We can use variable with makefiles.
It is not necessary to spell out the commands for compiling the individual C source files, because make can figure them out: it has an implicit rule for updating a `.o` file from a correspondingly named `.c` file using a `cc -c` command. For example, it will use the command `cc -c main.c -o main.o` to compile `main.c` into `main.o`. We can therefore omit the commands from the rules for the object files.
When a `.c` file is used automatically in this way, it is also automatically added to the list of prerequisites. We can therefore omit the `.c` files from the prerequisites, provided we omit the commands.
Here is the entire example, with both of these changes, and a variable objects as suggested above:
```
objects = main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o
edit : $(objects)
cc -o edit $(objects)
main.o : defs.h
kbd.o : defs.h command.h
command.o : defs.h command.h
display.o : defs.h buffer.h
insert.o : defs.h buffer.h
search.o : defs.h buffer.h
files.o : defs.h buffer.h command.h
utils.o : defs.h
.PHONY : clean
clean :
-rm edit $(objects)
```
This is how we would write the makefile in actual practice.
When the objects of a makefile are created only by implicit rules, an alternative style of makefile is possible. In this style of makefile, you group entries by their prerequisites instead of by their targets. Here is what one looks like:
```
objects = main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o
edit : $(objects)
cc -o edit $(objects)
$(objects) : defs.h
kbd.o command.o files.o : command.h
display.o insert.o search.o files.o : buffer.h
```
Makefiles contain five kinds of things: explicit rules, implicit rules, variable definitions, directives, and comments:
- An explicit rule says when and how to remake one or more files, called the rule's targets. It lists the other files that the targets depend on, call the prerequisites of the target, and may also give commands to use to create or update the targets.
- An implicit rule says when and how to remake a class of files based on their names. It describes how a target may depend on a file with a name similar to the target and gives commands to create or update such a target.
- A variable definition is a line that specifies a text string value for a variable that can be substituted into the text later.
- A directive is a command for make to do something special while reading the makefile. These include:
* Reading another makefile.
* Deciding (based on the values of variables) whether to use or ignore a part of the makefile
* Defining a variable from a verbatim string containing multiple lines.
- `#` in a line of a makefile starts a comment. It and the rest of the line are ignored, except that a trailing backslash not escaped by another backslash will continue the comment across multiple lines.
By default, when make looks for the makefile, it tries the following names, in order: `GNUmakefile`, `makefile` and `Makefile`. If you do not specify any makefiles to be read with `-f` or `--file` options, make will try the default makefile names.
The include directive tells make to suspend reading the current makefile and read one or more other makefiles before continuing. The directive is a line in the makefile that looks like this: `include filenames...`.
Filenames can contain shell file name patterns.
If you want make to simply ignore a makefile which does not exist and cannot be remade, with no error message, use the `-include` directive instead of `include`, like this:
```
-include filenames...
sinclude is another name for -include.
```
GNU make does its work in two distinct phases. During the first phase it reads all the makefiles, included makefiles, etc. and internalizes all the variables and their values, implicit and explicit rules, and constructs a dependency graph of all the targets and their prerequisites. During the second phase, make uses these internal structures to determine what targets will need to be rebuilt and to invoke the rules necessary to do so.
<file_sep>#!bin/bash
/usr/bin/uptime
<file_sep>- name: Make sure lynx is installed and then log it
raw: yum list installed | grep > /home/test/install.log
<file_sep>--- # lookup playbook example
- hosts: apacheweb
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
# - debug: msg="Lookup the Superhero for bruce WAYNE {{ lookup ('csvfile','Bruce wayne file=lookup.csv delimiter=, default=NOMATCH')}}"
- debug: msg="{{ lookup('env', 'HOME')}} is the value listed"
<file_sep># Quick tip sand tricks
## Nix
- Build a package: `nix-build -A pipreqs --option sandbox true`.
- Build a python package: `nix-build -A pythonPackages.mail-parser`.
-> We usually want to build with sandboxing enabled.
- Delete a store path: `nix-store --delete /nix/store/dovahbalblaremismylovekagatoo-somepackagename.tar.gz --ignore-liveness`.
- To query available packages: `nix-env -qaP`.
- List installed packages: `nix-env -q`.
- To install: `nix-env -i pcre-8.41`.
- To remove: `nix-env -e pcre-8.41`.
- To update all stuff: `nix-env -u`.
- To update a package and it's dependencies run: `nix-env -uA pcre-8.41`.
- The A means install with the package name with a pkgs. prefix.
- To remove uninstalled packages: `nix-collect-garbage`.
- Completely delete all cache, unused store: `nix-collect-garbage -d`.
- To start a repl: `nix repl '/path/to/nixpkgs'`
## NixOps
- Get device mapping to deploy from snaps: `nixoos show-physical -d nagatoPain --backup xxxxxxxxxxxx`.
- Take a backup: `nixops backup -d nagatoPain`.
- Take backup with freeze (works only for xfs) `nixops backup -d nagatoPain --freeze`.
- Show backup status: `nixops backup-status -d nagatoPain`
- Show latest backup status: `nixops backup-status -d nagatoPain --latest`.
- Get status of a given backupid: `nixops backup-status -d nagatoPain --backupid`
- Start a nixops dev-shell: `./dev-shell -I channel:nixos-18.09` (use the channnel you want ofc).
<file_sep># NixOps
### What is NixOps
Nixops is the best provisioning tool out there. It can nonetheless improve a lot. it's only handicap is that is only used for NixOS systems. Hitherto, NixOps is something that is advertised as the "NixOS-based cloud deployment tool". It basically expands NixOS' approach of deploying a complete system configuration from a declarative specification to networks of machines and instantiates and provisions the required machines (e.g. in an IaaS cloud environment, such as Amazon EC2) automatically if requested.
In this [paper](https://nixos.org/~eelco/pubs/charon-releng2013-final.pdf) NixOps was introduced as a tool for automated provisioning and deployment of machines. NixOps has several important characteristics:
• It is declarative
• It performs provisioning
• It allows abstracting over the target environment
• It uses a single configuration formalism (Nix’s purely functional language)
--------------------------------------------------------------------------------
NixOps is a tool for deploying sets of NixOS Linux machines, either to real hardware or to virtual machines.
It extends NixOS’s declarative approach to system configuration management to networks and adds provisioning.
A NixOps deployment process is driven by one or more network models that encapsulate multiple (partial) NixOS configurations. In a standard NixOps workflow, network models are typically split into a logical network model capturing settings that are machine independent and a physical network model capturing machine specific properties.
For example, here is a NixOps specification of a network consisting of two machines — one running Apache httpd,
the other serving a file system via NFS:
--------------------------------------------------------------------------------
```
{
webserver =
{ deployment.targetEnv = "virtualbox";
services.httpd.enable = true;
services.httpd.documentRoot = "/data";
fileSystems."/data" =
{ fsType = "nfs4";
device = "fileserver:/"; };
};
fileserver =
{ deployment.targetEnv = "virtualbox";
services.nfs.server.enable = true;
services.nfs.server.exports = "...";
};
}
```
-------------------------------------------------------------------------------
The values of the webserver and fileserver attributes are regular NixOS system specifications, except for the deployment.* options, which tell NixOps how each machine should be instantiated (in this case, as VirtualBox virtual machines running on your desktop).
=> This following commands will download and install NixOps (you should have the nix package manager installed ), create the instances, build, upload and activate the NixOS configurations you specified. To change something to the configuration, you just edit the specification and run `nixops deploy` again.
```
$ nix-env -i nixops
$ nixops create -d simple network.nix
$ nixops deploy -d simple
```
What the above command does is invoking the Nix package manager to build all the machine configurations, then it transfers their corresponding package closures to the target machines and finally activates the NixOS configurations. The end result is a collection of machines running the new configuration, if all previous steps have succeeded.
If we adapt any of the network models, and run the deploy command again, the system is upgraded. In case of an upgrade, only the packages that have been changed are built and transferred, making this phase as efficient as possible.
NixOps makes it easy to abstract over target environments, allowing you to use the same “logical” specification for both testing and production deployments. For instance, to deploy to Amazon EC2, you would just change the deployment.* options to:
```
deployment.targetEnv = "ec2";
deployment.region = "eu-west-1";
```
In addition to deploying system configurations, NixOps can be used to perform many other kinds of system administration tasks that work on machine level( Deploy to the `None` backend (such a drag!)).
---------------------------------------------------------------------------
Here is the config of a simple machine running NGINX
```
{pkgs, ...}:
{
# Describe your "deployment"
network.description = "NGINX web server";
# A single machine description.
server = {
deployment.targetEnv = "virtualbox";
deployment.virtualbox.memorySize = 1024; # megabytes
services.nginx.enable = true;
services.nginx.config = ''
http {
include ${pkgs.nginx}/conf/mime.types;
default_type application/octet-stream;
server {
listen 80 default_server;
server_name _;
root "/var/nginx/html.html"; # or something more relevant
}
}
'';
};
}
```
This example builds a VM but if you want to deploy over SSH just change the deployment.* lines to the following, filling in your IP and hostname.
```
deployment.targetEnv = "none";
deployment.targetHost = "10.2.2.5";
networking.hostName = "my-kobay-machine";
fileSystems."/" = {
device = "/dev/disk/by-label/nixos";
fsType = "ext4";
};
boot.loader.grub = {
enable = true;
version = 2;
device = "/dev/sda";
};
```
When you are writing a configuration you are creating a nested set (that's what Nix calls it but I would consider it a dictionary).
The Nix language has a lot of convenience syntax around sets for this reason. The most important thing to realize is that nested sets are automatically created.
```
a.b.c.d = 5
# Is the same as
a = { b = { c = { d = 5; }; }; }
```
## Modules
It is a good practice to keep services in modules. In this setup, module are divided into a number of modules based on how they are used.
For example:
* `base/`: Configuration that is used by all machines. Each machine will include base/default.nix and nothing else out of this directory.
* `services/`: Configuration for services that I can enable on my machines. These will be included by the machine configurations themselves to deploy services to those machines.
* `lib/`: Modules used by other services and modules but not useful to be included into server configs directly (for example my SSL certificates).
* `pkg/`: out-of-tree programs for peculiar use. These are generally personal projects.
* `users/`: Descriptions of human users, this includes their SSH keys and preferred shells, aliases and other personal configs. Some users are present in every machine (they are included in base/users.nix) others are pulled in by services.
So to fit into this structure we'll extract the NGINX config into services/nginx.nix.
```
{pkgs, ...}: let
# Extract the config into a binding.
config = ''
http {
include ${pkgs.nginx}/conf/mime.types;
default_type application/octet-stream;
server {
listen 80 default_server;
server_name _;
root "/var/nginx/html.html"; # or something more relevant
}
}
'';
in {
services.nginx = {
enable = true;
config = config;
};
}
```
And modify the existing config file to:
```
{pkgs, ...}:
{
# Describe your "deployment"
network.description = "NGINX web server";
# A single machine description.
server = {
imports = [
services/nginx.nix
];
deployment = {
targetEnv = "virtualbox";
virtualbox.memorySize = 1024; # megabytes
};
};
}
```
The way imports work is Nix is very nice, the file gets loaded and if it is a function it gets passed the global argument set (this is where we get the pkgs variable from). Then the result is merged into the importing module. This means that you don't have to worry about where in the tree your code gets included,
it is always the root. Now by commenting out or deleting the NGINX import and deploying you can simply remove the service from your system. This is the primary benefit of how I structure the code. Selecting what services should be on a machine (other then the base services which are always present) is as simple as adding or removing imports from the services/ directory.
## Use of arguments
Generally we create a nix file that contains things that can change from on env to another `dev` to `prod` ...
To ease alot of work we can use arguments to parameterize that.
Arguments are declared as follow in the top of the nixops config file.
For example we can have an `ec2.nix` as follow:
```
{ account
, accountId
, region ? "us-east-1"
, instanceType ? "r3.xlarge"
# Tagging arguments
, client ? "PDX"
, project ? "UNKNOWN"
, category ? "DEV"
, owner ? "<EMAIL>"
, approver ? "<EMAIL>"
, keep ? false
, description ? ""
, ...
}:
{
network.description = description;
defaults =
{ resources, lib, ... }:
deployment.targetEnv = "ec2";
deployment.ec2 = {
inherit region zone;
instanceType = lib.mkDefault instanceType;
spotInstancePrice = lib.mkDefault spotInstancePrice;
...
...
...
tags = {
Client = client;
Project = project;
Category = category;
Owner = owner;
};
};
}
```
The arguments can have default values if not specified in the deployment: `instanceType ? "r3.xlarge"`.
The `?` is for requiring an argument, the "r3.xlarge" is the default argument (or value) given to the variable if no argument is given.
Assigning arguments a value use set-args: `nixops set-args -d deployment-name --argstr argument1 "DovahAssassins" --argstr argument2 "FeelPain" --arg isTrue true --unset argument3`
`arg` is for boolean and `argstr` for string `unset` is to remove an argument.
### General notes
is using `users.mutableUsers = false;` with no defined user with passowrd or ssh key we will get an error as follow:
```bash
Failed assertions:
- Neither the root account nor any wheel user has a password or SSH authorized key.
You must set one to prevent being locked out of your system.
```
-> Nixops is protecting us cause we won't be able to log in the server as users are not mutable( no ssh-keys /password can be added)
<file_sep>--- # Loop playbook Example
- hosts: apacheweb
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: Add a list of users
user: name ={{ item}} state=present
with_items:
- user1
- user2
- user3
<file_sep># Disk formatting and encryption
### Encrypting filesystem:
* Create a file system (ext4 in this case):
`mkfs.ext4 /dev/sdf`
* Encrypted the newly formatted disk:
`cryptsetup -y luksFormat /dev/sdf`: Enter the encryption password in this step
* Open/Unlock the encrypted device and give it a name (`data`):
`cryptsetup luksOpen /dev/sdf data`
* Format the encrypted device:
`mkfs.ext4 /dev/mapper/data`
* Finally mounted Volume:
`mount /dev/mapper/data /data`
__Whenever w need to close the encrypted device we can use:__
`cryptsetup luksClose /dev/mapper/data`
__Whenever we need to resize the encrypted volume__
```bash
cryptsetup resize /dev/mapper/data
xfs_growfs /disk/mounted/path
```
### Other usefull stuff:
To check if our system support encryption to disks:
`grep -i config_dm_crypt /boot/config-$(uname -r)`.
To make sure we have the cryptsetup utility:
```
$ lsmod | grep dm_crypt
$ modprobe dm_crypt
$ lsmod | grep dm_crypt
```
To install it, Run: `yum/apt-get install cryptsetup`
* check filesystem type: `lsblk -f`
* fix xfs filesystem (make sure it is not mounted) : `xfs_repair /dev/xvdg`
### Mount NFS filesystem:
```shell
yum install nfs-utils nfs-utils-lib
mount nfsserverIPAdress:/home/ /home/nfs_home
```
### Resizing disk with parted
[Expanding a Linux Partition](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/expand-linux-partition.html)
[Extending a Linux File System after Resizing the Volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/recognize-expanded-volume-linux.html)
First make sure parted is installed
_This is to make sure the root volume is MBR (msdos) and not GPT_
```
parted /dev/xvda print
Model: Xen Virtual Block Device (xvd)
Disk /dev/xvda: 17.2GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1 1049kB 8590MB 8589MB primary ext4 boot```
```
```
parted /dev/xvda
GNU Parted 2.1
Using /dev/xvda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) unit s
(parted) print
Model: Xen Virtual Block Device (xvd)
Disk /dev/xvda: 33554432s
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1 2048s 16777215s 16775168s primary ext4 boot
(parted) rm 1
(parted) mkpart primary 2048s 100%
(parted) print
Model: Xen Virtual Block Device (xvd)
Disk /dev/xvda: 33554432s
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1 2048s 33554431s 33552384s primary ext4
(parted) set 1 boot on
(parted) print
Model: Xen Virtual Block Device (xvd)
Disk /dev/xvda: 33554432s
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1 2048s 33554431s 33552384s primary ext4 boot
(parted) quit
Information: You may need to update /etc/fstab.
```
```
e2fsck -f /dev/xvda1
e2fsck 1.41.12 (17-May-2010)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
/dev/xvda1: 18680/524288 files (0.2% non-contiguous), 258010/2096896 blocks
```
_now we extend the volume_
```
resize2fs /dev/xvda1
resize2fs 1.41.12 (17-May-2010)
Resizing the filesystem on /dev/xvda1 to 4194048 (4k) blocks.
The filesystem on /dev/xvda1 is now 4194048 blocks long.
```
<file_sep>git_user: git_user
git_pwd: <PASSWORD>
admin_user: admin
admin_pwd: <PASSWORD>
<file_sep>--- # Tag functionalities example
- hosts: apacheweb
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: Install telnet and lynx packages
yum: pkg={{Item}} state=latest
with_items:
- telnet
- lynx
tags:
- packages
- name: Verify that telnet was installed
raw: yum list installed | grep telnet > /home/test/pkg.log
tags:
- verification
<file_sep>--- # Start at playbook example
- hosts: apacheweb
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: Install telent
yum: pkg=telnet state=latest
- name: Install lynx
yum: pkg=lynx state=latest
- name: List home
command: ls -al /home/test
register: result
- debug: var=result
<file_sep># Some retarded mysqld commands.
Good tutorials: [1](https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-centos-7), [2](https://www.digitalocean.com/community/tutorials/a-basic-mysql-tutorial).
--------------------------------------------------------------------------------
```
SHOW DATABASES;
CREATE DATABASE database-name;
DROP DATABASE database-name;
USE database-name;
SHOW tables;
DESCRIBE potluck;
SELECT * FROM potluck;
DELETE FROM on_search WHERE search_date < NOW() - INTERVAL N DAY
```
*InnoDB is a storage engine for the database management system MySQL*
- To connect to an RDS instance use:
`mysql -h testing-rds.us-east-1.rds.amazonaws.com -u master -p -A`
A is for making the DB more responsive and quicker.
- To locate the largest application table on your DB instance, you can run a query similar to the following:
```
SELECT
table_schema,
table_name,
(data_length + index_length + data_free)/1024/1024 AS total_mb,
(data_length)/1024/1024 AS data_mb,
(index_length)/1024/1024 AS index_mb,
(data_free)/1024/1024 AS free_mb,
CURDATE() AS today
FROM
information_schema.tables
ORDER BY 3 DESC;
```
When migrating to a newer RDS database:
- Create a snapshot for rollback:
- Create a schema for the new DB: `mysql -h new-host-endpoint -u master -ppassword testRDB < /usr/share/zabbix-mysql/schema.sql`
- Import the needed data and drop what we don"t want: `mysqldump -h new-host-endpoint -u master -ppassword zabbixRDB --ignore-table=zabbixRDB.history --ignore-table=zabbixRDB.history_log --ignore-table=zabbixRDB.history_text --ignore-table=zabbixRDB.history_str --ignore-table=zabbixRDB.history_uint > zabbix_migration.sql`
- Import the data: mysql -h new-host-endpoint -u master -ppassword zabbixRDB < zabbix_migration.sql
-> Now you got your new empty database without the unneeded old junk.
<file_sep># nix expressions notes
### Export a hell path variable
```nix
environment.shellInit = ''
export NIX_PATH=$NIX_PATH:new_path=$HOME/new_path
export PYTHONPATH=$PYTHONPATH:"${pkgs.python27Packages.boto}/lib/python2.7/site-packages/"
'';
```
Add a binary cache to a server:
```nix
nix.binaryCaches = [ "http://cache.nixos.org" "dovahkin.nix"];
nix.binaryCachePublicKeys = [ "bianrykey of the binary cache" ];
```
<file_sep>--- # Master Playbook for web servers
- hosts: apacheweb
user: test
sudo: yes
connection: ssh
pre_tasks:
- name: when did the role start
raw: date > /home/test/startofrole.log
roles:
- { role: redhat_webservers, when: "ansible_os_family == 'RedHat'"}
post_task:
- name: When did the Role end
raw: date > /home/test/endofrole.log
<file_sep>--- # AT example
- hosts: apacheb
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: example of a future command with at module
at: command="ls -al /var/log > /home/test/at.log" count=1 units="minutes"
///// to kill the command we match it and we remove the cound and replcae it with state=abscent
<file_sep># ssh Stuff
- To Remove passphrase from the private ssh key:
ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]
or jus use
ssh-keygen
and let the terminal ask for the rest
- My `.ssh/config` file:
User nagato.pain
Host *
ForwardAgent yes
<file_sep>#Datadog tricks and tips.
Remove users using the datadog API:
* `pip install datadog`
* Get an API key with enough privileges, update the script then your good to go.
* Run the script using `python remove-user.py --username "dovahkin" --mail "gmail.com"`
* Run `python remove-user.py --help` for help
<file_sep>{ region ? "us-east-1"
, vpcId ? "vpc-blabla"
, accessKeyId ? "None"
, ...
}:
{
resources.ec2SecurityGroups =
{
mygroup = {
inherit region accessKeyId vpcId;
name = "kobaySG1";
description = "kobaySG1";
rules = [
{ fromPort = 22; toPort = 22; protocol = "tcp"; sourceIp = "11.11.11.11/32"; }
{ fromPort = 80; toPort = 80; protocol = "tcp"; sourceIp = "11.11.22.33/32"; }
];
};
mygroup2 = {
inherit region accessKeyId vpcId;
name = "kobaySG2";
description = "kobaySG2";
rules = [
{ fromPort = 22; toPort = 22; sourceIp = "11.11.11.11/32"; }
{ fromPort = 80; toPort = 80; sourceIp = "11.11.22.33/32"; }
];
};
};
}
<file_sep>#!/bin/bash
yum update -y
yum remove cloud-init -y
yum install epel-release -y
yum clean all
yum install -y python-pip
yum install -y mercurial
pip install awscli --upgrade
yum install -y rsync
service sshd restart
rm -rf ~/.hisotry
<file_sep>* Remove all comments and spaces from a file
cat /etc/httpd/conf.d/ssl.conf | grep -v "#" | sed '/^$/d'
* Comment
sed -i 's/^/#/g' /example/file/here.txt
* Uncomment
sed -i 's/^#//g' /example/file/here.txt
* Manipulate a varibale
website=$(sed 's|/|\/|g' <<< $website)
* Log as sshd using bash to check if sshd can open `authorized_keys`
su - sshd -s /bin/bash
* Create a dummy file with a given size on the disk:
fallocate -l 40G /tmp/a
* symlinks
ln -sf /path/to/file /path/to/symlink
* RAM
free -g
* Disk
lsblk
* CPU cores
lscpu (multiply Sockets \* Cores per socket)
* abourt command after some time
timeout 5 My_command
* size of a path
du -sh path/to/folder/or/file
* Get out of stuck terminal
entre ~.
* Allocate a file with a given size.
fallocate -l $((980*1024*1024)) dovah.txt
## Package manager
* Install local rpms
yum localinstall
rpm -ivh package.rpm
* search packages
yum search ldap
* Clear cache
yum clean all
* Install DNF
https://www.ostechnix.com/install-dnf-centos-7/
## IO
_You cannot safely write to a file while reading, it is better to read the file into memory, update it, and rewrite it to file._
```bash
with open("file.txt", "r") as in_file:
buf = in_file.readlines()
with open("file.txt", "w") as out_file:
for line in buf:
if line == "; Include this text\n":
line = line + "Include below\n"
out_file.write(line)
```
<file_sep>{
"dovah.assassin".uid = 1022;
"dovah.assassin".group = "group1";
"dovah.assassin".publicKey = ''ssh-rsa <KEY>';
"thename.isgreed".uid = 1023;
"thename.isgreed".group = "grou2";
"thename.isgreed".publicKey = ''ssh-rsa <KEY>'';
"kaliaws.fate".uid = 1029;
"kaliaws.fate".group = "grou3";
"kaliaws.fate".publicKey = ''ssh-rsa <KEY>'';
"psyanticy.dovah".uid = 1025;
"psyanticy.dovah".group = "group4";
"psyanticy.dovah".publicKey = ''ssh-rsa <KEY>'';
}
<file_sep>--- # raw example run a raw command just like on a server
- hosts: apachweb
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: find the system uptime for the hosts ubove
raw: /usr/bin/uptime > uptime.log executable=/bin/bash
<file_sep>--- # yum example
- host: apapcheweb
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: Install apache web server
action: yum name=httpd state=installed #absent or latest
- name: equivalant of yum upgrade
action: yum name=* state=latest #absent or latest
<file_sep># Fail2ban
Todo: Check datepattern
### This was during configuring fail2ban to keep a FreeIPA server safe:
Install it using `yum` or `apt-get` or `nix-env`
Need to set up firewalld/iptables to allow all traffic and only bans non needed IP addresses who want to brute force things
Let's discuss firewalld in our case:
* we need to install firewalld and set the zone to trusted named `freeipa` is this case
* Only deny access to given IPs using firewalld's rich rules:
`firewall-cmd --zone=freeipa --add-rich-rule='rule family="ipv4" source address="172.16.119.1" port protocol="tcp" port="22" reject'`
__Note__: This is not permanent as it is not permanent banned in fail2ban anyway
- Change firewalld interface: `firewall-cmd --zone=public --change-interface=eth0`
- Change zone default behaviour: `firewall-cmd --zone=public --set-target=ACCEPT --permanent`
--------------------------------------------------------------------------------
### Fail2ban config files:
jail.local
```
[DEFAULT]
# Ban hosts for two hours:
bantime = 7200
findtime = 300
maxretry = 2
banaction = firewallcmd-rich-rules
ignoreip = 127.0.0.1/8, 10.100.46.0/24 # ...
[freeipa]
enabled = true
port = ldaps
filter = freeipa
logpath = /var/log/dirsrv/slapd-EXAMPLE-COM/access
datepattern = [%%d/%%m/%%Y:%%H:%%M:%%S]
# action = # what command to execute (commonly iptables or firewalld commands)
```
jail.conf:
```
[freeipa]
port = ldaps, ldap
filter = freeipa
logpath = /var/log/dirsrv/slapd-PREDICTIX-COM/access
datepattern = [%%d/%%m/%%Y:%%H:%%M:%%S]
```
filter.d/freeipa.conf
```
# 289 Access Directory In a FreeIPA server.
#
# Detecting invalid credentials: error code 49
[INCLUDES]
# Read common prefixes. If any customizations available -- read them from
# common.local
#before = common.conf
[Definition]
failregex = ^.* conn=(?P<_conn_>\d+) fd=\d+ slot=\d+ SSL connection from <HOST> to \b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b$<SKIPLINES>^.* conn=(?P=_conn_) op=\d+ RESULT err=49 .* Invalid credentials$
ignoreregex =
[Init]
# "maxlines" is number of log lines to buffer for multi-line regex searches
maxlines = 20
# Author: <NAME>
```
<file_sep>--- # group exampel
- hosts: all
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: Managing groups
group: name=newgroup state=present gid=1050
<file_sep>__Notes from : https://dbader.org/blog/python-dunder-methods .__
## Python With Dunder methods
In Python, special methods are a set of predefined methods you can use to enrich your classes. They are easy to recognize because they start and end with double underscores, for example `__init__` or `__str__`.
Dunder methods let you emulate the behavior of built-in types. For example, to get the length of a string you can call `len('string')`. But an empty class definition doesn’t support this behavior out of the box:
Examples:
```python
class NoLenSupport:
pass
>>> obj = NoLenSupport()
>>> len(obj)
TypeError: "object of type 'NoLenSupport' has no len()"
```
->
```Python
class LenSupport:
def __len__(self):
return 42
>>> obj = LenSupport()
>>> len(obj)
42
```
=> This elegant design is known as the Python data model and lets developers tap into rich language features like sequences, iteration, operator overloading, attribute access, etc.
Use case example:
## Enriching a Simple Account Class
### Object Initialization: `__init__`:
To construct account objects from the Account class I need a constructor (the `__init__` function).
```Python
class Account:
"""A simple account class"""
def __init__(self, owner, amount=0):
"""
This is the constructor that lets us create
objects from this class
"""
self.owner = owner
self.amount = amount
self._transactions = []
```
The constructor create the object. To initialize a new account : `acc = Account('bob', 10)`
### Object Representation: `__str__`, `__repr__`:
We usually provide a string representation of our object for the consumer of our class:
- `__repr__`: The “official” string representation of an object. This is how you would make an object of the class. The goal of __repr__ is to be unambiguous.
- `__str__`: The “informal” or nicely printable string representation of an object. This is for the enduser.
-> If we need to implement just one of these to-string methods on a Python class, make sure it’s `__repr__`.
```python
def __repr__(self):
return 'Account({!r}, {!r})'.format(self.owner, self.amount)
def __str__(self):
return 'Account of {} with starting amount: {}'.format(
self.owner, self.amount)
```
If we don’t want to hardcode "Account" as the name for the class we can also use `self.__class__.__name__` to access it programmatically.
->
```python
>>> str(acc)
'Account of bob with starting amount: 10'
>>> print(acc)
"Account of bob with starting amount: 10"
>>> repr(acc)
"Account('bob', 10)"
```
### Iteration: `__len__`
In order to iterate over our account object I need to add some transactions. So first, I’ll define a simple method to add transactions.
->
```Python
def add_transaction(self, amount):
if not isinstance(amount, int):
raise ValueError('please use int for amount')
self._transactions.append(amount)
```
We also need to define a property to calculate the balance on the account so I can conveniently access it with account.balance. This method takes the start amount and adds a sum of all the transactions:
```Python
@property
def balance(self):
return self.amount + sum(self._transactions)
```
Dunder methods allows the class to be iterable:
```Python
def __len__(self):
return len(self._transactions)
def __getitem__(self, position):
return self._transactions[position]
```
now we can run these commands :
```python
>>> len(acc)
5
>>> for t in acc:
... print(t)
20
-10
50
-20
30
>>> acc[1]
-10
```
Also to be able to iterate over the transaction in reverse mode we need to implement `__reversed__`.
## Others
Many other Dender methods can be implemented to ease the use of the classes:
- Operator Overloading for Comparing Accounts: `__eq__`, `__lt__`.
- Operator Overloading for Merging Accounts: `__add__`.
- Callable Python Objects: `__call__`.
- Context Manager Support and the With Statement: `__enter__`, `__exit__`.
<file_sep>--- # mount exampel
- hosts: all
user: test
sudo: yes
connection: ssh
gather_facts: no
tasks:
- name: mount the remote data patition
mount: name=/mnt/data src=/dev=xvdf1 fstype=ext3 opts=rw state=present
| 03704ffba9ea350a979a8adaafdee403959edb9f | [
"Shell",
"Markdown",
"YAML",
"Nix",
"Jinja",
"Python"
] | 70 | Shell | IsmailAbdellaoui/t5adhrit | e21332c1831d321c6b3844a177ac11e61f07def3 | be4a67a33af9e6fb579e7b1a6b6b67087471c03c |
refs/heads/master | <file_sep># Tarea0-INF393-II-2019
Tarea Machine Learning
| 72e739e68ed9bdeeac5ba75e1e96372cc9134800 | [
"Markdown"
] | 1 | Markdown | GVergaraD/Tarea0-INF393-II-2019 | e017421bd5881527a4cca522022b9306d688fb59 | 4f53fffc2b6a284f50eeb33931c91a7bd92820a7 |
refs/heads/master | <repo_name>StrawHatter/Haskell<file_sep>/Week 2/nobles.hs
-- make people noble
mknoble :: Bool -> String -> String
mknoble female name = (if female then "Dame " else "Sir ") ++ name
-- Ashley is cute
-- Speller is wack
speller :: [[Char]] -> [Char]
speller = (intercalate ", ") . map (\w@(x:_) -> (x : " is for ") ++ w)
| 9c66323684e803b942b7aa3cb73508f391d8ea17 | [
"Haskell"
] | 1 | Haskell | StrawHatter/Haskell | 659390abc56d03a98a03e3d2cf9731b16bbf16c8 | f3fb5bd7fd1cc6f9e50c3e9b536c037ef62ae5ba |
refs/heads/master | <file_sep>import unittest
from src.data_loaders.euro_soccer_db_loader import EuroSoccerDatabaseLoader
class TestEuroSoccerDBLoader(unittest.Testcase):
def setUp(self):
self.loader = EuroSoccerDatabaseLoader()
def test_load_countries(self):
countries = self.loader.load_countries()
for country in countries:
print(country)
<file_sep>class DataManager():
def __init__(self):
pass
def get_matches(self, league, validity):
<file_sep>"""
In this experiment we work with matches from the last 10 years in the English Premier League.
The experiment moves along the timeline and for each timestamp it trains a model over all games before this timeline. Then it predicts scores for the games in that timestanp,
typically 10 matches per week. The experiment's output is an array of accuracy scores that can be summarized to a single score depending who running this experiment.
"""
import numpy as np
from typing import List
from src.dataset_builder.dataset_builder import DatasetBuilder
from src.model_factory.model_factory import ModelFactory
from src.models.match import Match
from src.data_manager.data_manager import DataManager
class EPLExperiment():
def __init__(self, dm: DataManager, ds_builder: DatasetBuilder, model_factory: ModelFactory):
self.dm = dm
self.ds_builder = ds_builder
self.model_factory = model_factory
def create_match_batches(self, matches) -> List[List[Match]]:
pass
def run(self) -> List[float]:
accuracies = []
matches = self.dm.get_matches(league='EPL', validity=10)
batches = self.create_match_batches(matches)
for i in range(1, len(batches)):
model = self.model_factory.get_model()
x_train, y_train = self.ds_builder(batches[:i])
x_test, y_test = self.ds_builder(batches[i])
model.fit(x_train, y_train)
predictions = model.predict(x_test)
accuracy = np.sum(predictions == y_test) / len(predictions)
accuracies.append(accuracy)
return accuracies
<file_sep>class ModelFactory():
def __init__(self):
pass
def get_model(self):
pass<file_sep>import datetime
class Match():
def __init__(self, home_team: str, away_team: str, home_goals: int, away_goals: int, start_time: datetime.datetime):
self.home_team = home_team
self.away_team = away_team
self.home_goals = home_goals
self.away_goals = away_goals
self.start_time = start_time
<file_sep>This is a list of useful data sources for football analysis:
1. footballcsv
link: https://github.com/footballcsv
description: this project contains many repositories, each for different country, and it contains all game basic results (means home team, away team, score and data). Specifically, this link (https://github.com/footballcsv/england) contains all english leauges (down to league 2) results since 92-93 season.
It's updated automatically all the time!
2. statsbomb open data
link: https://github.com/statsbomb/open-data
description: contains detailed matches information including: date, managers, stadium, referee, lineups and events (passes, presure, carry, ball receipt and more). Downsize: it only contains a very few competitions. It does contain LaLiga and champions league last seasons (excluding the 19/20).
3. football-data.org
link: https://www.football-data.org
description: an API containing basic updated data (matches, lineups, standings). Might be useful if the API allows big requests, but it is mostly for sports websites.
4. Wyscout
link: https://footballdata.wyscout.com/download-samples/
description: gives very detailed freely data samples with player stats, team stats and event stats.
5. Understat kaggle
link: https://www.kaggle.com/slehkyi/extended-football-stats-for-european-leagues-xg?select=understat.com.csv
description: static aggregative dataset contatining xG data overall the season.
6. Understat
link: https://understat.com/
description: contains lots of updating data from the big 5 leagues (and russian league) on match scores, lineups, xG, xA and more! there's no convinient way to approach the data so it must be parser manually.
7. European Soccer Database
link: https://www.kaggle.com/hugomathien/soccer?
description: contains seasons 2008 to 2016 from 11 european leagues, containing matche results, lineups (not always), players attributes from FIFA and team attributes. It also contains betting odds.
8. SOFIFA
link: https://sofifa.com/
description: amazing source contating FIFA 21 data on most players in the world. Theres a crawler repository here: https://github.com/hugomathien/football-data-collection/tree/master/footballData/footballData
9. football-data.co.uk
link: https://www.football-data.co.uk/
description: contatins data from main leagues matches - containing basic statistics and bet odds from many different betting agencies. Data given in csv files and it's updating. <file_sep>import sqlite3
import pandas as pd
from src.data_loaders.data_loader import DataLoader
class EuroSoccerDatabaseLoader(DataLoader):
def __init__(self):
self.cnx = sqlite3.connect('../../European Soccer Database/database.sqlite')
def load_countries(self):
df = pd.read_sql("SELECT * FROM Country", self.cnx)
return df
def load_leagues(self):
df = pd.read_sql("SELECT * FROM League", self.cnx)
return df
def load_matches(self):
df = pd.read_sql("SELECT * FROM Match", self.cnx)
return df
def load_players(self):
df = pd.read_sql("SELECT * FROM Player", self.cnx)
return df
def load_player_attributes(self):
df = pd.read_sql("SELECT * FROM Player_Attributes", self.cnx)
return df
def load_teams(self):
df = pd.read_sql("SELECT * FROM Team", self.cnx)
return df
def load_team_attributes(self):
df = pd.read_sql("SELECT * FROM Team_Attributes", self.cnx)
return df
<file_sep>class DataLoader(ABC):
@abstractmethod
def load():
pass
| 805241a21c6717653866aa89ce943d52719487bf | [
"Markdown",
"Python"
] | 8 | Markdown | amitBotzer/football_research | fbf951ca546a0b22ba2f90a06afa95b465fcae36 | cf238a7a9226efa8af42a7d17d35c1dfed89da68 |
refs/heads/master | <repo_name>Qi-Z/daily-question-answer<file_sep>/README.md
# daily-question-answer
一亩三分地的每日答题Chrome插件
该插件保存一亩三分地题库,自动识别问题并给出答案。
新增题库请到 <添加Google Form链接>
| 09499db4faa227098eaa548d20363291b0b6e080 | [
"Markdown"
] | 1 | Markdown | Qi-Z/daily-question-answer | ac03f18bbdd282a63de22fd27aefd4e9e6aa9f2b | 9495b87e7a281a618a03432ad2e9c20cd36861eb |
refs/heads/master | <repo_name>rwssdsda/cms-1<file_sep>/src/main/java/com/briup/cms/service/ILinkService.java
package com.briup.cms.service;
import com.briup.cms.bean.Link;
import com.briup.cms.exception.CustomerException;
public interface ILinkService {
void addLink(Link link)throws CustomerException;
}
| 8eca6dd582008162a4d7472bcf8a5cec4201bcc7 | [
"Java"
] | 1 | Java | rwssdsda/cms-1 | e0ddd0ac7d4a0fb193f13ef73800e992b5c548fa | 13f4a3599fa2faebdf6493e01e49ae555f386776 |
refs/heads/master | <repo_name>rosoty/bs_donate<file_sep>/bs/lib/Backend_Router.js
Router.configure({
//layoutTemplate: 'mainLayout',
notFoundTemplate: "notFound"
});
Router.route('/signin',{
layoutTemplate: 'signin'
});
// admin Products
Router.route('/cpanel/dashboad',{
layoutTemplate: 'mainLayout',
name:'dashboad'
});
Router.route('/cpanel/shop',{
layoutTemplate: 'mainLayout',
name:'shop',
waitOn:function(){
return [Meteor.subscribe("allshop")]
}
});
Router.route('/cpanel/shop/add',{
layoutTemplate: 'mainLayout',
name:'shopadd'
});
Router.route('/cpanel/shop/edit/:id',{
layoutTemplate: 'mainLayout',
name:'shopedit',
data:function(){
var id = this.params.id;
var result = shops.findOne({'_id':id});
return {getOneShop:result};
},
waitOn:function(){
var id = this.params.id;
return [Meteor.subscribe("oneshop",id)]
}
});
Router.route('/cpanel/product',{
layoutTemplate: 'mainLayout',
name:'product',
waitOn:function(){
return [Meteor.subscribe("allcategory"),Meteor.subscribe("allproducts"),Meteor.subscribe("allshop")]
}
});
Router.route('/cpanel/product/add',{
layoutTemplate: 'mainLayout',
name:'productadd',
waitOn:function(){
return [Meteor.subscribe("allcategory"),Meteor.subscribe("allshop")]
}
});
Router.route('/cpanel/product/edit/:id',{
layoutTemplate: 'mainLayout',
name:'productedit',
data:function(){
var id = this.params.id;
var result = products.findOne({'_id':id});
return {getOneProduct:result};
},
waitOn:function(){
var id = this.params.id;
return [Meteor.subscribe("allcategory"),Meteor.subscribe("allshop"),Meteor.subscribe("oneproduct",id)]
}
});
Router.route('/cpanel/category',{
layoutTemplate: 'mainLayout',
name:'category',
waitOn:function(){
return [Meteor.subscribe("allcategory")]
}
});
Router.route('/cpanel/category/edit/:id',{
layoutTemplate: 'mainLayout',
name:'categoryedit',
data:function(){
var id = this.params.id;
var result = categories.findOne({'_id':id});
return {GetOneCategory:result};
},
waitOn:function(){
var id = this.params.id;
return [Meteor.subscribe("oneCategory",id)]
}
});
Router.route('/cpanel/category/add',{
layoutTemplate: 'mainLayout',
name:'categoryadd'
});
Router.route('/cpanel/section',{
layoutTemplate: 'mainLayout',
name:'section'
});
Router.route('/cpanel/section/add',{
layoutTemplate: 'mainLayout',
name:'sectionadd'
});
Router.route('/cpanel/section/edit/:id',{
layoutTemplate: 'mainLayout',
name:'sectionedit',
data:function(){
var id = this.params.id;
var result = section.findOne({'_id':id});
return {GetOne:result};
}
});
Router.route('/cpanel/user/add',{
layoutTemplate: 'mainLayout',
name:'adduser'
});
Router.route('/cpanel/user',{
layoutTemplate: 'mainLayout',
name:'user'
});
Router.route('/cpanel/user/edit/:id',{
layoutTemplate: 'mainLayout',
name:'useredit',
data:function(){
var id = this.params.id;
var result = users.findOne({'_id':id});
return {GetOne:result};
}
});
Router.route('/cpanel/orders',{
layoutTemplate: 'mainLayout',
name:'orders',
waitOn:function(){
//var p=this.params.id;
Session.set('CATEGORYDATA', {page:1});
},
onBeforeAction: function(){
var pagination = IRLibLoader.load('/js/jquery.simplePagination.js');
if( pagination.ready() ){
this.next();
}
}
});
Router.route('/cpanel/orders/edit/:id',{
layoutTemplate: 'mainLayout',
name:'editorders',
data:function(){
var id = this.params.id;
var result = orders.findOne({'_id':id});
return {GetOne:result};
}
});
Router.route('/cpanel/taxi',{
layoutTemplate: 'mainLayout',
name:'taxi'
});
Router.route('/cpanel/taxi/add',{
layoutTemplate: 'mainLayout',
name:'addtaxi'
});
Router.route('/cpanel/taxi/edit/:id',{
layoutTemplate: 'mainLayout',
name:'taxiedit',
data:function(){
var id = this.params.id;
var result = taxi.findOne({'_id':id});
return {GetOne:result};
}
});
Router.route('/cpanel/pshop',{
layoutTemplate: 'mainLayout',
name:'pshop'
});
Router.route('/cpanel/pshop/add',{
layoutTemplate: 'mainLayout',
name:'addpshop'
});
Router.route('/cpanel/pshop/edit/:id',{
layoutTemplate: 'mainLayout',
name:'editpshop',
data:function(){
var id = this.params.id;
var result = pshop.findOne({'_id':id});
return {GetOne:result};
}
});
Router.route('/cpanel/status',{
layoutTemplate: 'mainLayout',
name:'status'
});
Router.route('/cpanel/status/add',{
layoutTemplate: 'mainLayout',
name:'addstatus'
});
Router.route('/cpanel/info',{
layoutTemplate: 'mainLayout',
name:'info'
});
Router.route('/cpanel/info/add',{
layoutTemplate: 'mainLayout',
name:'addinfo'
});
Router.route('/cpanel/info/edit/:id',{
layoutTemplate: 'mainLayout',
name:'editinfo',
data:function(){
var id = this.params.id;
var result = info.findOne({'_id':id});
return {GetOne:result};
}
});
Router.route('/registeradmin/P7x5lM3aVmsu57LWhIg62qEV0a547gpe',{
layoutTemplate: 'registeradmin'
//name:'registeradmin'
});<file_sep>/bs/server/product.js
Meteor.methods({
insertProduct:function(obj){
return products.insert(obj);
},
updateProduct:function(id,obj){
return products.update({_id:id},{$set:obj});
}
});
<file_sep>/bs/client/application/controller/status.js
Template.addstatus.events({
'click #btn-save':function(e){
e.preventDefault();
var value = $('[name="name"]').val();
var obj = {'value':value,'step':7}
Meteor.call("InsertStatus",obj,function(error){
if(!error){
console.log("InsertStatus Success");
Router.go('/cpanel/status');
}
});
}
});
Template.status.helpers({
GetStatus:function(){
var result = orderstatus.find({}).map(function(document, index){
document.index = index+1;
return document;
});
return result;
}
});
Template.status.events({
"click .btn-del": function(e){
e.preventDefault();
if(confirm("Are you sure want to delete this???")){
Meteor.call("RemoveStatus",this._id);
}
},
});<file_sep>/bs/server/order.js
Meteor.methods({
RemoveOrder:function(id){
orders.remove({'_id':id});
},
UpdateOrders:function(id,obj){
if(id){
orders.update({'_id':id},{$set:obj});
}
},
UpdateOrderStatus:function(id,next){
orders.update({'_id':id},{$set:{'STATUS':next}});
},
countOrder:function(){
var allorder=orders.find({});
return allorder.count();
}
});
/*=======
UpdateOrderStatus:function(id,next){
orders.update({'_id':id},{$set:{'status':next}});
}
});
>>>>>>> 8dc505429328342303cd12f719fa0b8d57b82249
*/<file_sep>/bs/client/application/controller/subscribe.js
Meteor.subscribe('orders');
Meteor.subscribe('items');
Meteor.subscribe('users');
Meteor.subscribe('images');
Meteor.subscribe('taxi');
Meteor.subscribe('pshop');
Meteor.subscribe('orderstatus');
Meteor.subscribe('info');<file_sep>/bs/client/application/controller/info.js
Template.addinfo.events({
"click #btn-save": function(e){
e.preventDefault();
var title = $("[name='title']").val();
var price = $("[name='price']").val();
var image_url = $("[name='url']").val();
var obj = {
title:title,
price:price,
image_url:image_url,
createdAt: Date.now()
}
Meteor.call("InsertInfo",obj, function(error){
if(!error){
console.log('InsertInfo Success');
Router.go('/cpanel/info');
}
});
}
});
Template.info.helpers({
GetInfo:function(){
return info.find();
}
});
Template.info.events({
"click .btn-del": function(e){
e.preventDefault();
if(confirm("Are you sure want to delete this???")){
Meteor.call("RemoveInfo",this._id);
}
},
});
Template.editinfo.events({
"click #btn-update": function(e){
e.preventDefault();
var id = $("[name='id']").val();
var title = $("[name='title']").val();
var price = $("[name='price']").val();
var image_url = $("[name='url']").val();
var obj = {
title:title,
price:price,
image_url:image_url,
createdAt: Date.now()
}
Meteor.call('UpdateInfo',id, obj , function(error){
if(!error){
console.log('UpdateInfo Success');
Router.go('/cpanel/info')
}
});
}
});<file_sep>/bs/server/pshop.js
Meteor.methods({
InsertPshop:function(obj){
pshop.insert(obj);
},
RemovePshop:function(id){
pshop.remove({'_id':id});
},
UpdatePshop:function(id,obj){
if(id){
pshop.update({'_id':id},{$set:obj});
}
}
});<file_sep>/bs/client/application/controller/shop.js
Template.shop.helpers({
getallshop:function(){
return shops.find({});
},
});
Template.shop.events({
"click .btndel":function(e){
e.preventDefault();
if(confirm("Are you sure want to delete this???")){
shops.remove(this._id);
}
}
});
Template.shopadd.events({
"click #btnaddshop":function(e){
e.preventDefault();
var name=$("#name").val();
var ownername=$("#ownername").val();
var phone=$("#phone").val();
var address=$("#address").val();
var obj={
name:name,
ownername:ownername,
phone:phone,
address:address
}
Meteor.call("insertShop",obj,function(err){
if(!err){
Router.go("/cpanel/shop");
}
})
}
});
Template.shopedit.events({
"click #btnupdateshop":function(e){
e.preventDefault();
var id=$("#shopid").val();
var name=$("#name").val();
var ownername=$("#ownername").val();
var phone=$("#phone").val();
var address=$("#address").val();
var obj={
name:name,
ownername:ownername,
phone:phone,
address:address
}
Meteor.call("updateShop",id,obj,function(err){
if(!err){
Router.go("/cpanel/shop");
}
})
}
});<file_sep>/bs/lib/Collection.js
/*if (Meteor.isServer) {
var database = new MongoInternals.RemoteCollectionDriver("mongodb://djisse:<EMAIL>:39278/heroku_3xpfhsv3");
MyCollection = new Mongo.Collection("collection_name", { _driver: database });
categories = new Mongo.Collection('categories'{ _driver: database });
}
*/
//var connection = DDP.connect("mongodb://djisse:<EMAIL>:39278/heroku_3xpfhsv3");
//Cats = Meteor.Collection('cats', {connection: connection});
section = new Mongo.Collection('section');
categories = new Mongo.Collection('categories');
products = new Mongo.Collection('products');
shops = new Mongo.Collection('shops');
users = Meteor.users;
orders = new Mongo.Collection('orders');
taxi = new Mongo.Collection('taxi');
pshop = new Mongo.Collection('pshop');
orderstatus = new Mongo.Collection('status');
info = new Mongo.Collection('info');
fullpath="/public/upload";
if (Meteor.isServer) {
fullpath=process.env.PWD;
console.log('linux path:'+fullpath);
if( typeof fullpath == 'undefined' ){
base_path = Meteor.npmRequire('fs').realpathSync( process.cwd() + '../../' );
console.log('window path:'+base_path);
base_path = base_path.split('\\').join('/');
base_path = base_path.replace(/\/\.meteor.*$/, '');
}else{
base_path=fullpath;
}
}
else{
base_path="/";
}
console.log( 'BASE PATH: '+base_path );
images = new FS.Collection("images", {
//stores: [new FS.Store.FileSystem("images", {path:"/opt/safir/app/uploads"})]
stores: [new FS.Store.FileSystem("images", {path:base_path+"/uploads"})]
});
<file_sep>/bs/server/shop.js
Meteor.methods({
insertShop:function(obj){
return shops.insert(obj);
},
updateShop:function(id,obj){
return shops.update({_id:id},{$set:obj})
}
});<file_sep>/bs/server/publish.js
Meteor.publish("users", function () {
return users.find();
});
Meteor.publish('images', function (){
return images.find({});
});
/*Meteor.publish('orders', function (){
return orders.find({});
});*/
Meteor.publish("myOrder",function(page,limit){
//var limit = 4;
var limit=parseInt(limit);
page = (page)? page:1;
var skip = (page<=1)? 0 : (page - 1) * limit;
//limit = limit * page;
return orders.find({},{limit:limit, skip:skip})
});
Meteor.publish('taxi', function (){
return taxi.find({});
});
Meteor.publish('pshop', function (){
return pshop.find({});
});
Meteor.publish('allcategory', function (){
return categories.find({});
});
Meteor.publish("oneCategory",function(id){
return categories.find({_id:id});
});
Meteor.publish("oneproduct",function(id){
return products.find({_id:id});
});
Meteor.publish('allproducts', function (){
return products.find({});
});
Meteor.publish('allshop', function (){
return shops.find({});
});
Meteor.publish("oneshop",function(id){
return shops.find({_id:id});
});
Meteor.publish("orderstatus",function(){
return orderstatus.find({});
});
Meteor.publish("info",function(){
return info.find({});
}); | a8f124b681d46217eceba97193680896029811a9 | [
"JavaScript"
] | 11 | JavaScript | rosoty/bs_donate | 09c968487dcd3f14714de9168c47cce1f5287fee | 0b82e25f204b8ce6cdf0f80619d990f2a5c8d806 |
refs/heads/master | <file_sep># js-tdd
JS com TDD na Prática
| a8dd36d1dd183cf2c9b03d7728224196242a7750 | [
"Markdown"
] | 1 | Markdown | danilocgraciano/js-tdd | 4c4acb393fc59df76469be35a072cbf2cd32d5d9 | b33f27a841b83e1b0d584659da97e1f8cd05b176 |
refs/heads/master | <repo_name>TheMysteriousX/trust_router<file_sep>/common/tr_config.c
/*
* Copyright (c) 2012, JANET(UK)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of JANET(UK) nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdlib.h>
#include <string.h>
#include <jansson.h>
#include <dirent.h>
#include <talloc.h>
#include <tr_cfgwatch.h>
#include <tr_comm.h>
#include <tr_config.h>
#include <tr_gss.h>
#include <tr_debug.h>
#include <tr_filter.h>
#include <trust_router/tr_constraint.h>
#include <tr_idp.h>
#include <tr.h>
#include <trust_router/trp.h>
void tr_print_config (TR_CFG *cfg) {
tr_notice("tr_print_config: Logging running trust router configuration.");
tr_print_comms(cfg->ctable);
}
void tr_print_comms (TR_COMM_TABLE *ctab)
{
TR_COMM *comm = NULL;
for (comm = ctab->comms; NULL != comm; comm = comm->next) {
tr_notice("tr_print_config: Community %s:", comm->id->buf);
tr_notice("tr_print_config: - Member IdPs:");
tr_print_comm_idps(ctab, comm);
tr_notice("tr_print_config: - Member RPs:");
tr_print_comm_rps(ctab, comm);
}
}
void tr_print_comm_idps(TR_COMM_TABLE *ctab, TR_COMM *comm)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_COMM_ITER *iter=NULL;
TR_IDP_REALM *idp = NULL;
char *s=NULL;
iter=tr_comm_iter_new(tmp_ctx);
if (iter==NULL) {
tr_notice("tr_print_config: unable to allocate IdP iterator.");
talloc_free(tmp_ctx);
return;
}
for (idp=tr_idp_realm_iter_first(iter, ctab, tr_comm_get_id(comm));
NULL!=idp;
idp=tr_idp_realm_iter_next(iter)) {
s=tr_idp_realm_to_str(tmp_ctx, idp);
if (s!=NULL)
tr_notice("tr_print_config: - @%s", s);
else
tr_notice("tr_print_config: unable to allocate IdP output string.");
}
talloc_free(tmp_ctx);
}
void tr_print_comm_rps(TR_COMM_TABLE *ctab, TR_COMM *comm)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_COMM_ITER *iter=NULL;
TR_RP_REALM *rp = NULL;
char *s=NULL;
iter=tr_comm_iter_new(tmp_ctx);
if (iter==NULL) {
tr_notice("tr_print_config: unable to allocate RP iterator.");
talloc_free(tmp_ctx);
return;
}
for (rp=tr_rp_realm_iter_first(iter, ctab, tr_comm_get_id(comm));
NULL!=rp;
rp=tr_rp_realm_iter_next(iter)) {
s=tr_rp_realm_to_str(tmp_ctx, rp);
if (s!=NULL)
tr_notice("tr_print_config: - @%s", s);
else
tr_notice("tr_print_config: unable to allocate RP output string.");
}
talloc_free(tmp_ctx);
}
TR_CFG *tr_cfg_new(TALLOC_CTX *mem_ctx)
{
TR_CFG *cfg=talloc(mem_ctx, TR_CFG);
if (cfg!=NULL) {
cfg->internal=NULL;
cfg->rp_clients=NULL;
cfg->peers=NULL;
cfg->default_servers=NULL;
cfg->ctable=tr_comm_table_new(cfg);
if (cfg->ctable==NULL) {
talloc_free(cfg);
cfg=NULL;
}
}
return cfg;
}
void tr_cfg_free (TR_CFG *cfg)
{
talloc_free(cfg);
}
TR_CFG_MGR *tr_cfg_mgr_new(TALLOC_CTX *mem_ctx)
{
return talloc_zero(mem_ctx, TR_CFG_MGR);
}
void tr_cfg_mgr_free (TR_CFG_MGR *cfg_mgr) {
talloc_free(cfg_mgr);
}
TR_CFG_RC tr_apply_new_config (TR_CFG_MGR *cfg_mgr)
{
/* cfg_mgr->active is allowed to be null, but new cannot be */
if ((cfg_mgr==NULL) || (cfg_mgr->new==NULL))
return TR_CFG_BAD_PARAMS;
if (cfg_mgr->active != NULL)
tr_cfg_free(cfg_mgr->active);
cfg_mgr->active = cfg_mgr->new;
cfg_mgr->new=NULL; /* only keep a single handle on the new configuration */
tr_log_threshold(cfg_mgr->active->internal->log_threshold);
tr_console_threshold(cfg_mgr->active->internal->console_threshold);
return TR_CFG_SUCCESS;
}
static TR_CFG_RC tr_cfg_parse_internal(TR_CFG *trc, json_t *jcfg)
{
json_t *jint = NULL;
json_t *jmtd = NULL;
json_t *jtidsp = NULL;
json_t *jtrpsp = NULL;
json_t *jhname = NULL;
json_t *jlog = NULL;
json_t *jconthres = NULL;
json_t *jlogthres = NULL;
json_t *jcfgpoll = NULL;
json_t *jcfgsettle = NULL;
json_t *jroutesweep = NULL;
json_t *jrouteupdate = NULL;
json_t *jtidreq_timeout = NULL;
json_t *jtidresp_numer = NULL;
json_t *jtidresp_denom = NULL;
json_t *jrouteconnect = NULL;
if ((!trc) || (!jcfg))
return TR_CFG_BAD_PARAMS;
if (NULL == trc->internal) {
if (NULL == (trc->internal = talloc_zero(trc, TR_CFG_INTERNAL)))
return TR_CFG_NOMEM;
}
if (NULL != (jint = json_object_get(jcfg, "tr_internal"))) {
if (NULL != (jmtd = json_object_get(jint, "max_tree_depth"))) {
if (json_is_number(jmtd)) {
trc->internal->max_tree_depth = json_integer_value(jmtd);
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, max_tree_depth is not a number.");
return TR_CFG_NOPARSE;
}
} else {
/* If not configured, use the default */
trc->internal->max_tree_depth = TR_DEFAULT_MAX_TREE_DEPTH;
}
if (NULL != (jtidsp = json_object_get(jint, "tids_port"))) {
if (json_is_number(jtidsp)) {
trc->internal->tids_port = json_integer_value(jtidsp);
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, tids_port is not a number.");
return TR_CFG_NOPARSE;
}
} else {
/* If not configured, use the default */
trc->internal->tids_port = TR_DEFAULT_TIDS_PORT;
}
if (NULL != (jtrpsp = json_object_get(jint, "trps_port"))) {
if (json_is_number(jtrpsp)) {
trc->internal->trps_port = json_integer_value(jtrpsp);
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, trps_port is not a number.");
return TR_CFG_NOPARSE;
}
} else {
/* If not configured, use the default */
trc->internal->trps_port = TR_DEFAULT_TRPS_PORT;
}
if (NULL != (jhname = json_object_get(jint, "hostname"))) {
if (json_is_string(jhname)) {
trc->internal->hostname = json_string_value(jhname);
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, hostname is not a string.");
return TR_CFG_NOPARSE;
}
}
if (NULL != (jcfgpoll = json_object_get(jint, "cfg_poll_interval"))) {
if (json_is_number(jcfgpoll)) {
trc->internal->cfg_poll_interval = json_integer_value(jcfgpoll);
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, cfg_poll_interval is not a number.");
return TR_CFG_NOPARSE;
}
} else {
trc->internal->cfg_poll_interval = TR_CFGWATCH_DEFAULT_POLL;
}
if (NULL != (jcfgsettle = json_object_get(jint, "cfg_settling_time"))) {
if (json_is_number(jcfgsettle)) {
trc->internal->cfg_settling_time = json_integer_value(jcfgsettle);
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, cfg_settling_time is not a number.");
return TR_CFG_NOPARSE;
}
} else {
trc->internal->cfg_settling_time = TR_CFGWATCH_DEFAULT_SETTLE;
}
if (NULL != (jrouteconnect = json_object_get(jint, "trp_connect_interval"))) {
if (json_is_number(jrouteconnect)) {
trc->internal->trp_connect_interval = json_integer_value(jrouteconnect);
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, trp_connect_interval is not a number.");
return TR_CFG_NOPARSE;
}
} else {
/* if not configured, use the default */
trc->internal->trp_connect_interval=TR_DEFAULT_TRP_CONNECT_INTERVAL;
}
if (NULL != (jroutesweep = json_object_get(jint, "trp_sweep_interval"))) {
if (json_is_number(jroutesweep)) {
trc->internal->trp_sweep_interval = json_integer_value(jroutesweep);
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, trp_sweep_interval is not a number.");
return TR_CFG_NOPARSE;
}
} else {
/* if not configured, use the default */
trc->internal->trp_sweep_interval=TR_DEFAULT_TRP_SWEEP_INTERVAL;
}
if (NULL != (jrouteupdate = json_object_get(jint, "trp_update_interval"))) {
if (json_is_number(jrouteupdate)) {
trc->internal->trp_update_interval = json_integer_value(jrouteupdate);
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, trp_update_interval is not a number.");
return TR_CFG_NOPARSE;
}
} else {
/* if not configured, use the default */
trc->internal->trp_update_interval=TR_DEFAULT_TRP_UPDATE_INTERVAL;
}
if (NULL != (jtidreq_timeout = json_object_get(jint, "tid_request_timeout"))) {
if (json_is_number(jtidreq_timeout)) {
trc->internal->tid_req_timeout = json_integer_value(jtidreq_timeout);
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, tid_request_timeout is not a number.");
return TR_CFG_NOPARSE;
}
} else {
/* if not configured, use the default */
trc->internal->tid_req_timeout=TR_DEFAULT_TID_REQ_TIMEOUT;
}
if (NULL != (jtidresp_numer = json_object_get(jint, "tid_response_numerator"))) {
if (json_is_number(jtidresp_numer)) {
trc->internal->tid_resp_numer = json_integer_value(jtidresp_numer);
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, tid_response_numerator is not a number.");
return TR_CFG_NOPARSE;
}
} else {
/* if not configured, use the default */
trc->internal->tid_resp_numer=TR_DEFAULT_TID_RESP_NUMER;
}
if (NULL != (jtidresp_denom = json_object_get(jint, "tid_response_denominator"))) {
if (json_is_number(jtidresp_denom)) {
trc->internal->tid_resp_denom = json_integer_value(jtidresp_denom);
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, tid_response_denominator is not a number.");
return TR_CFG_NOPARSE;
}
} else {
/* if not configured, use the default */
trc->internal->tid_resp_denom=TR_DEFAULT_TID_RESP_DENOM;
}
if (NULL != (jlog = json_object_get(jint, "logging"))) {
if (NULL != (jlogthres = json_object_get(jlog, "log_threshold"))) {
if (json_is_string(jlogthres)) {
trc->internal->log_threshold = str2sev(json_string_value(jlogthres));
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, log_threshold is not a string.");
return TR_CFG_NOPARSE;
}
} else {
/* If not configured, use the default */
trc->internal->log_threshold = TR_DEFAULT_LOG_THRESHOLD;
}
if (NULL != (jconthres = json_object_get(jlog, "console_threshold"))) {
if (json_is_string(jconthres)) {
trc->internal->console_threshold = str2sev(json_string_value(jconthres));
} else {
tr_debug("tr_cfg_parse_internal: Parsing error, console_threshold is not a string.");
return TR_CFG_NOPARSE;
}
} else {
/* If not configured, use the default */
trc->internal->console_threshold = TR_DEFAULT_CONSOLE_THRESHOLD;
}
} else {
/* If not configured, use the default */
trc->internal->console_threshold = TR_DEFAULT_CONSOLE_THRESHOLD;
trc->internal->log_threshold = TR_DEFAULT_LOG_THRESHOLD;
}
tr_debug("tr_cfg_parse_internal: Internal config parsed.");
return TR_CFG_SUCCESS;
}
return TR_CFG_SUCCESS;
}
static TR_CONSTRAINT *tr_cfg_parse_one_constraint(TALLOC_CTX *mem_ctx, char *ctype, json_t *jc, TR_CFG_RC *rc)
{
TR_CONSTRAINT *cons=NULL;
int i=0;
if ((!ctype) || (!jc) || (!rc) ||
(!json_is_array(jc)) ||
(0 >= json_array_size(jc)) ||
(TR_MAX_CONST_MATCHES < json_array_size(jc)) ||
(!json_is_string(json_array_get(jc, 0)))) {
tr_err("tr_cfg_parse_one_constraint: config error.");
*rc=TR_CFG_NOPARSE;
return NULL;
}
if (NULL==(cons=tr_constraint_new(mem_ctx))) {
tr_debug("tr_cfg_parse_one_constraint: Out of memory (cons).");
*rc=TR_CFG_NOMEM;
return NULL;
}
if (NULL==(cons->type=tr_new_name(ctype))) {
tr_err("tr_cfg_parse_one_constraint: Out of memory (type).");
*rc=TR_CFG_NOMEM;
tr_constraint_free(cons);
return NULL;
}
for (i=0; i < json_array_size(jc); i++) {
cons->matches[i]=tr_new_name(json_string_value(json_array_get(jc, i)));
if (cons->matches[i]==NULL) {
tr_err("tr_cfg_parse_one_constraint: Out of memory (match %d).", i+1);
*rc=TR_CFG_NOMEM;
tr_constraint_free(cons);
return NULL;
}
}
return cons;
}
static TR_FILTER *tr_cfg_parse_one_filter(TALLOC_CTX *mem_ctx, json_t *jfilt, TR_FILTER_TYPE ftype, TR_CFG_RC *rc)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_FILTER *filt=NULL;
json_t *jfaction=NULL;
json_t *jfspecs=NULL;
json_t *jffield=NULL;
json_t *jfmatch=NULL;
json_t *jrc=NULL;
json_t *jdc=NULL;
TR_NAME *name=NULL;
int i=0, j=0;
*rc=TR_CFG_ERROR;
if ((jfilt==NULL) || (rc==NULL)) {
tr_err("tr_cfg_parse_one_filter: null argument");
*rc=TR_CFG_BAD_PARAMS;
goto cleanup;
}
if (NULL==(filt=tr_filter_new(tmp_ctx))) {
tr_err("tr_cfg_parse_one_filter: Out of memory.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
tr_filter_set_type(filt, ftype);
/* make sure we have space to represent the filter */
if (json_array_size(jfilt) > TR_MAX_FILTER_LINES) {
tr_err("tr_cfg_parse_one_filter: Filter has too many lines, maximum of %d.", TR_MAX_FILTER_LINES);
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
/* For each entry in the filter... */
for (i=0; i < json_array_size(jfilt); i++) {
if ((NULL==(jfaction=json_object_get(json_array_get(jfilt, i), "action"))) ||
(!json_is_string(jfaction))) {
tr_debug("tr_cfg_parse_one_filter: Error parsing filter action.");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
if ((NULL==(jfspecs=json_object_get(json_array_get(jfilt, i), "specs"))) ||
(!json_is_array(jfspecs)) ||
(0==json_array_size(jfspecs))) {
tr_debug("tr_cfg_parse_one_filter: Error parsing filter specs.");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
if (TR_MAX_FILTER_SPECS < json_array_size(jfspecs)) {
tr_debug("tr_cfg_parse_one_filter: Filter has too many specs, maximimum of %d.", TR_MAX_FILTER_SPECS);
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
if (NULL==(filt->lines[i]=tr_fline_new(filt))) {
tr_debug("tr_cfg_parse_one_filter: Out of memory allocating filter line %d.", i+1);
*rc=TR_CFG_NOMEM;
goto cleanup;
}
if (!strcmp(json_string_value(jfaction), "accept")) {
filt->lines[i]->action=TR_FILTER_ACTION_ACCEPT;
}
else if (!strcmp(json_string_value(jfaction), "reject")) {
filt->lines[i]->action=TR_FILTER_ACTION_REJECT;
}
else {
tr_debug("tr_cfg_parse_one_filter: Error parsing filter action, unknown action' %s'.", json_string_value(jfaction));
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
if (NULL!=(jrc=json_object_get(json_array_get(jfilt, i), "realm_constraints"))) {
if (!json_is_array(jrc)) {
tr_err("tr_cfg_parse_one_filter: cannot parse realm_constraints, not an array.");
*rc=TR_CFG_NOPARSE;
goto cleanup;
} else if (json_array_size(jrc)>TR_MAX_CONST_MATCHES) {
tr_err("tr_cfg_parse_one_filter: realm_constraints has too many entries, maximum of %d.",
TR_MAX_CONST_MATCHES);
*rc=TR_CFG_NOPARSE;
goto cleanup;
} else if (json_array_size(jrc)>0) {
/* ok we actually have entries to process */
if (NULL==(filt->lines[i]->realm_cons=tr_cfg_parse_one_constraint(filt->lines[i], "realm", jrc, rc))) {
tr_debug("tr_cfg_parse_one_filter: Error parsing realm constraint");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
}
}
if (NULL!=(jdc=json_object_get(json_array_get(jfilt, i), "domain_constraints"))) {
if (!json_is_array(jdc)) {
tr_err("tr_cfg_parse_one_filter: cannot parse domain_constraints, not an array.");
*rc=TR_CFG_NOPARSE;
goto cleanup;
} else if (json_array_size(jdc)>TR_MAX_CONST_MATCHES) {
tr_err("tr_cfg_parse_one_filter: domain_constraints has too many entries, maximum of %d.",
TR_MAX_CONST_MATCHES);
*rc=TR_CFG_NOPARSE;
goto cleanup;
} else if (json_array_size(jdc)>0) {
if (NULL==(filt->lines[i]->domain_cons=tr_cfg_parse_one_constraint(filt->lines[i], "domain", jdc, rc))) {
tr_debug("tr_cfg_parse_one_filter: Error parsing domain constraint");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
}
}
/*For each filter spec within the filter line... */
for (j=0; j <json_array_size(jfspecs); j++) {
if ((NULL==(jffield=json_object_get(json_array_get(jfspecs, j), "field"))) ||
(!json_is_string(jffield))) {
tr_debug("tr_cfg_parse_one_filter: Error parsing filter: missing field for filer spec %d, filter line %d.", i, j);
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
/* check that we have a match attribute */
if (NULL==(jfmatch=json_object_get(json_array_get(jfspecs, j), "match"))) {
tr_debug("tr_cfg_parse_one_filter: Error parsing filter: missing match for filer spec %d, filter line %d.", i, j);
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
/* check that match is a string */
if (!json_is_string(jfmatch)) {
tr_debug("tr_cfg_parse_one_filter: Error parsing filter: match not a string for filter spec %d, filter line %d.", i, j);
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
/* allocate the filter spec */
if (NULL==(filt->lines[i]->specs[j]=tr_fspec_new(filt->lines[i]))) {
tr_debug("tr_cfg_parse_one_filter: Out of memory.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
/* fill in the field */
if (NULL==(filt->lines[i]->specs[j]->field=tr_new_name(json_string_value(jffield)))) {
tr_debug("tr_cfg_parse_one_filter: Out of memory.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
/* fill in the matches */
if (NULL==(name=tr_new_name(json_string_value(jfmatch)))) {
tr_debug("tr_cfg_parse_one_filter: Out of memory.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
tr_fspec_set_match(filt->lines[i]->specs[j], name);
}
}
*rc=TR_CFG_SUCCESS;
talloc_steal(mem_ctx, filt);
cleanup:
talloc_free(tmp_ctx);
if (*rc!=TR_CFG_SUCCESS)
filt=NULL;
return filt;
}
static TR_FILTER *tr_cfg_parse_filters(TALLOC_CTX *mem_ctx, json_t *jfilts, TR_CFG_RC *rc)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
json_t *jfilt;
TR_FILTER *filt=NULL;
*rc=TR_CFG_ERROR;
/* no filters */
if (jfilts==NULL) {
*rc=TR_CFG_SUCCESS;
goto cleanup;
}
jfilt=json_object_get(jfilts, "tid_inbound");
if (jfilt!=NULL) {
filt=tr_cfg_parse_one_filter(tmp_ctx, jfilt, TR_FILTER_TYPE_TID_INCOMING, rc);
if (*rc!=TR_CFG_SUCCESS) {
tr_debug("tr_cfg_parse_filters: Error parsing tid_inbound filter.");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
} else {
tr_debug("tr_cfg_parse_filters: Unknown filter types in filter block.");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
*rc=TR_CFG_SUCCESS;
cleanup:
if (*rc==TR_CFG_SUCCESS)
talloc_steal(mem_ctx, filt);
else if (filt!=NULL) {
talloc_free(filt);
filt=NULL;
}
talloc_free(tmp_ctx);
return filt;
}
static TR_AAA_SERVER *tr_cfg_parse_one_aaa_server(TALLOC_CTX *mem_ctx, json_t *jaddr, TR_CFG_RC *rc)
{
TR_AAA_SERVER *aaa = NULL;
TR_NAME *name=NULL;
if ((!jaddr) || (!json_is_string(jaddr))) {
tr_debug("tr_cfg_parse_one_aaa_server: Bad parameters.");
*rc = TR_CFG_BAD_PARAMS;
return NULL;
}
name=tr_new_name(json_string_value(jaddr));
if (name==NULL) {
tr_debug("tr_cfg_parse_one_aaa_server: Out of memory allocating hostname.");
*rc = TR_CFG_NOMEM;
return NULL;
}
aaa=tr_aaa_server_new(mem_ctx, name);
if (aaa==NULL) {
tr_free_name(name);
tr_debug("tr_cfg_parse_one_aaa_server: Out of memory allocating AAA server.");
*rc = TR_CFG_NOMEM;
return NULL;
}
return aaa;
}
static TR_AAA_SERVER *tr_cfg_parse_aaa_servers(TALLOC_CTX *mem_ctx, json_t *jaaas, TR_CFG_RC *rc)
{
TALLOC_CTX *tmp_ctx=NULL;
TR_AAA_SERVER *aaa = NULL;
TR_AAA_SERVER *temp_aaa = NULL;
int i = 0;
for (i = 0; i < json_array_size(jaaas); i++) {
/* rc gets set in here */
if (NULL == (temp_aaa = tr_cfg_parse_one_aaa_server(tmp_ctx, json_array_get(jaaas, i), rc))) {
talloc_free(tmp_ctx);
return NULL;
}
/* TBD -- IPv6 addresses */
// tr_debug("tr_cfg_parse_aaa_servers: Configuring AAA Server: ip_addr = %s.", inet_ntoa(temp_aaa->aaa_server_addr));
temp_aaa->next = aaa;
aaa = temp_aaa;
}
tr_debug("tr_cfg_parse_aaa_servers: Finished (rc=%d)", *rc);
for (temp_aaa=aaa; temp_aaa!=NULL; temp_aaa=temp_aaa->next)
talloc_steal(mem_ctx, temp_aaa);
talloc_free(tmp_ctx);
return aaa;
}
static TR_APC *tr_cfg_parse_one_apc(TALLOC_CTX *mem_ctx, json_t *japc, TR_CFG_RC *rc)
{
TR_APC *apc=NULL;
TR_NAME *name=NULL;
*rc = TR_CFG_SUCCESS; /* presume success */
if ((!japc) || (!rc) || (!json_is_string(japc))) {
tr_debug("tr_cfg_parse_one_apc: Bad parameters.");
if (rc)
*rc = TR_CFG_BAD_PARAMS;
return NULL;
}
apc=tr_apc_new(mem_ctx);
if (apc==NULL) {
tr_debug("tr_cfg_parse_one_apc: Out of memory.");
*rc = TR_CFG_NOMEM;
return NULL;
}
name=tr_new_name(json_string_value(japc));
if (name==NULL) {
tr_debug("tr_cfg_parse_one_apc: No memory for APC name.");
tr_apc_free(apc);
*rc = TR_CFG_NOMEM;
return NULL;
}
tr_apc_set_id(apc, name); /* apc is now responsible for freeing the name */
return apc;
}
static TR_APC *tr_cfg_parse_apcs(TALLOC_CTX *mem_ctx, json_t *japcs, TR_CFG_RC *rc)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_APC *apcs=NULL;
TR_APC *new_apc=NULL;
int ii=0;
TR_CFG_RC call_rc=TR_CFG_ERROR;
*rc = TR_CFG_SUCCESS; /* presume success */
if ((!japcs) || (!rc) || (!json_is_array(japcs))) {
tr_debug("tr_cfg_parse_one_apc: Bad parameters.");
if (rc)
*rc = TR_CFG_BAD_PARAMS;
return NULL;
}
for (ii=0; ii<json_array_size(japcs); ii++) {
new_apc=tr_cfg_parse_one_apc(tmp_ctx, json_array_get(japcs, ii), &call_rc);
if ((call_rc!=TR_CFG_SUCCESS) || (new_apc==NULL)) {
tr_debug("tr_cfg_parse_apcs: Error parsing APC %d.", ii+1);
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
tr_apc_add(apcs, new_apc);
}
talloc_steal(mem_ctx, apcs);
*rc=TR_CFG_SUCCESS;
cleanup:
talloc_free(tmp_ctx);
return apcs;
}
static TR_NAME *tr_cfg_parse_name(TALLOC_CTX *mem_ctx, json_t *jname, TR_CFG_RC *rc)
{
TR_NAME *name=NULL;
*rc=TR_CFG_ERROR;
if ((jname==NULL) || (!json_is_string(jname))) {
tr_err("tr_cfg_parse_name: name missing or not a string");
*rc=TR_CFG_BAD_PARAMS;
name=NULL;
} else {
name=tr_new_name(json_string_value(jname));
if (name==NULL) {
tr_err("tr_cfg_parse_name: could not allocate name");
*rc=TR_CFG_NOMEM;
} else {
*rc=TR_CFG_SUCCESS;
}
}
return name;
}
static int tr_cfg_parse_shared_config(json_t *jsc, TR_CFG_RC *rc)
{
const char *shared=NULL;
*rc=TR_CFG_SUCCESS;
if ((jsc==NULL) ||
(!json_is_string(jsc)) ||
(NULL==(shared=json_string_value(jsc)))) {
*rc=TR_CFG_BAD_PARAMS;
return -1;
}
if (0==strcmp(shared, "no"))
return 0;
else if (0==strcmp(shared, "yes"))
return 1;
/* any other value is an error */
tr_debug("tr_cfg_parse_shared_config: invalid shared_config value \"%s\" (should be \"yes\" or \"no\")",
shared);
*rc=TR_CFG_NOPARSE;
return -1;
}
static TR_REALM_ORIGIN tr_cfg_realm_origin(json_t *jrealm)
{
json_t *jremote=json_object_get(jrealm, "remote");
const char *s=NULL;
if (jremote==NULL)
return TR_REALM_LOCAL;
if (!json_is_string(jremote)) {
tr_warning("tr_cfg_realm_origin: \"remote\" is not a string, assuming this is a local realm.");
return TR_REALM_LOCAL;
}
s=json_string_value(jremote);
if (strcasecmp(s, "yes")==0)
return TR_REALM_REMOTE_INCOMPLETE;
else if (strcasecmp(s, "no")!=0)
tr_warning("tr_cfg_realm_origin: \"remote\" is neither 'yes' nor 'no', assuming this is a local realm.");
return TR_REALM_LOCAL;
}
/* Parse the identity provider object from a realm and fill in the given TR_IDP_REALM. */
static TR_CFG_RC tr_cfg_parse_idp(TR_IDP_REALM *idp, json_t *jidp)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_APC *apcs=NULL;
TR_AAA_SERVER *aaa=NULL;
TR_CFG_RC rc=TR_CFG_ERROR;
if (jidp==NULL)
goto cleanup;
idp->shared_config=tr_cfg_parse_shared_config(json_object_get(jidp, "shared_config"), &rc);
if (rc!=TR_CFG_SUCCESS) {
tr_err("tr_cfg_parse_idp: missing or malformed shared_config specification");
rc=TR_CFG_NOPARSE;
goto cleanup;
}
apcs=tr_cfg_parse_apcs(tmp_ctx, json_object_get(jidp, "apcs"), &rc);
if ((rc!=TR_CFG_SUCCESS) || (apcs==NULL)) {
tr_err("tr_cfg_parse_idp: unable to parse APC");
rc=TR_CFG_NOPARSE;
goto cleanup;
}
aaa=tr_cfg_parse_aaa_servers(idp, json_object_get(jidp, "aaa_servers"), &rc);
if (rc!=TR_CFG_SUCCESS) {
tr_err("tr_cfg_parse_idp: unable to parse AAA servers");
rc=TR_CFG_NOPARSE;
goto cleanup;
}
tr_debug("tr_cfg_parse_idp: APC=\"%.*s\"",
apcs->id->len,
apcs->id->buf);
/* done, fill in the idp structures */
idp->apcs=apcs;
talloc_steal(idp, apcs);
idp->aaa_servers=aaa;
rc=TR_CFG_SUCCESS;
cleanup:
if (rc!=TR_CFG_SUCCESS) {
if (apcs!=NULL)
tr_apc_free(apcs);
if (aaa!=NULL)
tr_aaa_server_free(aaa);
}
talloc_free(tmp_ctx);
return rc;
}
/* parses idp realm */
static TR_IDP_REALM *tr_cfg_parse_one_idp_realm(TALLOC_CTX *mem_ctx, json_t *jrealm, TR_CFG_RC *rc)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_IDP_REALM *realm=NULL;
TR_CFG_RC call_rc=TR_CFG_ERROR;
*rc=TR_CFG_ERROR; /* default to error if not set */
if ((!jrealm) || (!rc)) {
tr_err("tr_cfg_parse_one_idp_realm: Bad parameters.");
if (rc)
*rc=TR_CFG_BAD_PARAMS;
goto cleanup;
}
if (NULL==(realm=tr_idp_realm_new(tmp_ctx))) {
tr_err("tr_cfg_parse_one_idp_realm: could not allocate idp realm.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
realm->origin=tr_cfg_realm_origin(jrealm);
if (realm->origin!=TR_REALM_LOCAL) {
tr_debug("tr_cfg_parse_one_idp_realm: realm is remote, should not have full IdP info.");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
/* must have a name */
realm->realm_id=tr_cfg_parse_name(realm,
json_object_get(jrealm, "realm"),
&call_rc);
if ((call_rc!=TR_CFG_SUCCESS) || (realm->realm_id==NULL)) {
tr_err("tr_cfg_parse_one_idp_realm: could not parse realm name");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
tr_debug("tr_cfg_parse_one_idp_realm: realm_id=\"%.*s\"",
realm->realm_id->len,
realm->realm_id->buf);
call_rc=tr_cfg_parse_idp(realm, json_object_get(jrealm, "identity_provider"));
if (call_rc!=TR_CFG_SUCCESS) {
tr_err("tr_cfg_parse_one_idp_realm: could not parse identity_provider.");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
*rc=TR_CFG_SUCCESS;
cleanup:
if (*rc==TR_CFG_SUCCESS)
talloc_steal(mem_ctx, realm);
else {
talloc_free(realm);
realm=NULL;
}
talloc_free(tmp_ctx);
return realm;
}
/* Determine whether the realm is an IDP realm */
static int tr_cfg_is_idp_realm(json_t *jrealm)
{
/* If a realm spec contains an identity_provider, it's an IDP realm. */
if (NULL != json_object_get(jrealm, "identity_provider"))
return 1;
else
return 0;
}
static TR_IDP_REALM *tr_cfg_parse_one_remote_realm(TALLOC_CTX *mem_ctx, json_t *jrealm, TR_CFG_RC *rc)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_IDP_REALM *realm=talloc(mem_ctx, TR_IDP_REALM);
*rc=TR_CFG_ERROR; /* default to error if not set */
if ((!jrealm) || (!rc)) {
tr_err("tr_cfg_parse_one_remote_realm: Bad parameters.");
if (rc)
*rc=TR_CFG_BAD_PARAMS;
goto cleanup;
}
if (NULL==(realm=tr_idp_realm_new(tmp_ctx))) {
tr_err("tr_cfg_parse_one_remote_realm: could not allocate idp realm.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
/* must have a name */
realm->realm_id=tr_cfg_parse_name(realm,
json_object_get(jrealm, "realm"),
rc);
if ((*rc!=TR_CFG_SUCCESS) || (realm->realm_id==NULL)) {
tr_err("tr_cfg_parse_one_remote_realm: could not parse realm name");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
tr_debug("tr_cfg_parse_one_remote_realm: realm_id=\"%.*s\"",
realm->realm_id->len,
realm->realm_id->buf);
realm->origin=tr_cfg_realm_origin(jrealm);
*rc=TR_CFG_SUCCESS;
cleanup:
if (*rc==TR_CFG_SUCCESS)
talloc_steal(mem_ctx, realm);
else {
talloc_free(realm);
realm=NULL;
}
talloc_free(tmp_ctx);
return realm;
}
static int tr_cfg_is_remote_realm(json_t *jrealm)
{
return (tr_cfg_realm_origin(jrealm)!=TR_REALM_LOCAL);
}
/* Parse any idp realms in the j_realms object. Ignores other realm types. */
static TR_IDP_REALM *tr_cfg_parse_idp_realms(TALLOC_CTX *mem_ctx, json_t *jrealms, TR_CFG_RC *rc)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_IDP_REALM *realms=NULL;
TR_IDP_REALM *new_realm=NULL;
json_t *this_jrealm=NULL;
int ii=0;
*rc=TR_CFG_ERROR;
if ((jrealms==NULL) || (!json_is_array(jrealms))) {
tr_err("tr_cfg_parse_idp_realms: realms not an array");
*rc=TR_CFG_BAD_PARAMS;
goto cleanup;
}
for (ii=0; ii<json_array_size(jrealms); ii++) {
this_jrealm=json_array_get(jrealms, ii);
if (tr_cfg_is_idp_realm(this_jrealm)) {
new_realm=tr_cfg_parse_one_idp_realm(tmp_ctx, this_jrealm, rc);
if ((*rc)!=TR_CFG_SUCCESS) {
tr_err("tr_cfg_parse_idp_realms: error decoding realm entry %d", ii+1);
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
tr_idp_realm_add(realms, new_realm);
} else if (tr_cfg_is_remote_realm(this_jrealm)) {
new_realm=tr_cfg_parse_one_remote_realm(tmp_ctx, this_jrealm, rc);
if ((*rc)!=TR_CFG_SUCCESS) {
tr_err("tr_cfg_parse_idp_realms: error decoding remote realm entry %d", ii+1);
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
tr_idp_realm_add(realms, new_realm);
}
}
*rc=TR_CFG_SUCCESS;
talloc_steal(mem_ctx, realms);
cleanup:
talloc_free(tmp_ctx);
return realms;
}
static TR_GSS_NAMES *tr_cfg_parse_gss_names(TALLOC_CTX *mem_ctx, json_t *jgss_names, TR_CFG_RC *rc)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_GSS_NAMES *gn=NULL;
json_t *jname=NULL;
int ii=0;
TR_NAME *name=NULL;
if ((rc==NULL) || (jgss_names==NULL)) {
tr_err("tr_cfg_parse_gss_names: Bad parameters.");
*rc=TR_CFG_BAD_PARAMS;
}
if (!json_is_array(jgss_names)) {
tr_err("tr_cfg_parse_gss_names: gss_names not an array.");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
gn=tr_gss_names_new(tmp_ctx);
for (ii=0; ii<json_array_size(jgss_names); ii++) {
jname=json_array_get(jgss_names, ii);
if (!json_is_string(jname)) {
tr_err("tr_cfg_parse_gss_names: Encountered non-string gss name.");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
name=tr_new_name(json_string_value(jname));
if (name==NULL) {
tr_err("tr_cfg_parse_gss_names: Out of memory allocating gss name.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
if (tr_gss_names_add(gn, name)!=0) {
tr_free_name(name);
tr_err("tr_cfg_parse_gss_names: Unable to add gss name to RP client.");
*rc=TR_CFG_ERROR;
goto cleanup;
}
}
talloc_steal(mem_ctx, gn);
*rc=TR_CFG_SUCCESS;
cleanup:
talloc_free(tmp_ctx);
if ((*rc!=TR_CFG_SUCCESS) && (gn!=NULL))
gn=NULL;
return gn;
}
/* default filter accepts realm and *.realm */
static TR_FILTER *tr_cfg_default_filter(TALLOC_CTX *mem_ctx, TR_NAME *realm, TR_CFG_RC *rc)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_FILTER *filt=NULL;
TR_CONSTRAINT *cons=NULL;
TR_NAME *name=NULL;
TR_NAME *n_prefix=tr_new_name("*.");
TR_NAME *n_rp_realm_1=tr_new_name("rp_realm");
TR_NAME *n_rp_realm_2=tr_new_name("rp_realm");
TR_NAME *n_domain=tr_new_name("domain");
TR_NAME *n_realm=tr_new_name("realm");
if ((realm==NULL) || (rc==NULL)) {
tr_debug("tr_cfg_default_filter: invalid arguments.");
if (rc!=NULL)
*rc=TR_CFG_BAD_PARAMS;
goto cleanup;
}
if ((n_prefix==NULL) ||
(n_rp_realm_1==NULL) ||
(n_rp_realm_2==NULL) ||
(n_domain==NULL) ||
(n_realm==NULL)) {
tr_debug("tr_cfg_default_filter: unable to allocate names.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
filt=tr_filter_new(tmp_ctx);
if (filt==NULL) {
tr_debug("tr_cfg_default_filter: could not allocate filter.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
tr_filter_set_type(filt, TR_FILTER_TYPE_TID_INCOMING);
filt->lines[0]=tr_fline_new(filt);
if (filt->lines[0]==NULL) {
tr_debug("tr_cfg_default_filter: could not allocate filter line.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
filt->lines[0]->action=TR_FILTER_ACTION_ACCEPT;
filt->lines[0]->specs[0]=tr_fspec_new(filt->lines[0]);
filt->lines[0]->specs[0]->field=n_rp_realm_1;
n_rp_realm_1=NULL; /* we don't own this name any more */
name=tr_dup_name(realm);
if (name==NULL) {
tr_debug("tr_cfg_default_filter: could not allocate realm name.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
tr_fspec_set_match(filt->lines[0]->specs[0], name);
name=NULL; /* we no longer own the name */
/* now do the wildcard name */
filt->lines[0]->specs[1]=tr_fspec_new(filt->lines[0]);
filt->lines[0]->specs[1]->field=n_rp_realm_2;
n_rp_realm_2=NULL; /* we don't own this name any more */
if (NULL==(name=tr_name_cat(n_prefix, realm))) {
tr_debug("tr_cfg_default_filter: could not allocate wildcard realm name.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
tr_fspec_set_match(filt->lines[0]->specs[1], name);
name=NULL; /* we no longer own the name */
/* domain constraint */
if (NULL==(cons=tr_constraint_new(filt->lines[0]))) {
tr_debug("tr_cfg_default_filter: could not allocate domain constraint.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
cons->type=n_domain;
n_domain=NULL; /* belongs to the constraint now */
name=tr_dup_name(realm);
if (name==NULL) {
tr_debug("tr_cfg_default_filter: could not allocate realm name for domain constraint.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
cons->matches[0]=name;
name=tr_name_cat(n_prefix, realm);
if (name==NULL) {
tr_debug("tr_cfg_default_filter: could not allocate wildcard realm name for domain constraint.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
cons->matches[1]=name;
name=NULL;
filt->lines[0]->domain_cons=cons;
/* realm constraint */
if (NULL==(cons=tr_constraint_new(filt->lines[0]))) {
tr_debug("tr_cfg_default_filter: could not allocate realm constraint.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
cons->type=n_realm;
n_realm=NULL; /* belongs to the constraint now */
name=tr_dup_name(realm);
if (name==NULL) {
tr_debug("tr_cfg_default_filter: could not allocate realm name for realm constraint.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
cons->matches[0]=name;
name=tr_name_cat(n_prefix, realm);
if (name==NULL) {
tr_debug("tr_cfg_default_filter: could not allocate wildcard realm name for realm constraint.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
cons->matches[1]=name;
name=NULL;
filt->lines[0]->realm_cons=cons;
talloc_steal(mem_ctx, filt);
cleanup:
talloc_free(tmp_ctx);
if (*rc!=TR_CFG_SUCCESS)
filt=NULL;
if (n_prefix!=NULL)
tr_free_name(n_prefix);
if (n_rp_realm_1!=NULL)
tr_free_name(n_rp_realm_1);
if (n_rp_realm_2!=NULL)
tr_free_name(n_rp_realm_2);
if (n_realm!=NULL)
tr_free_name(n_realm);
if (n_domain!=NULL)
tr_free_name(n_domain);
if (name!=NULL)
tr_free_name(name);
return filt;
}
/* parses rp client */
static TR_RP_CLIENT *tr_cfg_parse_one_rp_client(TALLOC_CTX *mem_ctx, json_t *jrealm, TR_CFG_RC *rc)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_RP_CLIENT *client=NULL;
TR_CFG_RC call_rc=TR_CFG_ERROR;
TR_FILTER *new_filt=NULL;
TR_NAME *realm=NULL;
json_t *jfilt=NULL;
json_t *jrealm_id=NULL;
*rc=TR_CFG_ERROR; /* default to error if not set */
if ((!jrealm) || (!rc)) {
tr_err("tr_cfg_parse_one_rp_client: Bad parameters.");
if (rc)
*rc=TR_CFG_BAD_PARAMS;
goto cleanup;
}
if ((NULL==(jrealm_id=json_object_get(jrealm, "realm"))) || (!json_is_string(jrealm_id))) {
tr_debug("tr_cfg_parse_one_rp_client: no realm ID found.");
*rc=TR_CFG_BAD_PARAMS;
goto cleanup;
}
tr_debug("tr_cfg_parse_one_rp_client: realm_id=\"%s\"", json_string_value(jrealm_id));
realm=tr_new_name(json_string_value(jrealm_id));
if (realm==NULL) {
tr_err("tr_cfg_parse_one_rp_client: could not allocate realm ID.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
if (NULL==(client=tr_rp_client_new(tmp_ctx))) {
tr_err("tr_cfg_parse_one_rp_client: could not allocate rp client.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
client->gss_names=tr_cfg_parse_gss_names(client, json_object_get(jrealm, "gss_names"), &call_rc);
if (call_rc!=TR_CFG_SUCCESS) {
tr_err("tr_cfg_parse_one_rp_client: could not parse gss_names.");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
/* parse filters */
jfilt=json_object_get(jrealm, "filters");
if (jfilt!=NULL) {
new_filt=tr_cfg_parse_filters(tmp_ctx, jfilt, &call_rc);
if (call_rc!=TR_CFG_SUCCESS) {
tr_err("tr_cfg_parse_one_rp_client: could not parse filters.");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
} else {
tr_debug("tr_cfg_parse_one_rp_client: no filters specified, using default filters.");
new_filt=tr_cfg_default_filter(tmp_ctx, realm, &call_rc);
if (call_rc!=TR_CFG_SUCCESS) {
tr_err("tr_cfg_parse_one_rp_client: could not set default filters.");
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
}
tr_rp_client_set_filter(client, new_filt);
*rc=TR_CFG_SUCCESS;
cleanup:
if (realm!=NULL)
tr_free_name(realm);
if (*rc==TR_CFG_SUCCESS)
talloc_steal(mem_ctx, client);
else {
talloc_free(client);
client=NULL;
}
talloc_free(tmp_ctx);
return client;
}
/* Determine whether the realm is an RP realm */
static int tr_cfg_is_rp_realm(json_t *jrealm)
{
/* Check that we have a gss name. */
if (NULL != json_object_get(jrealm, "gss_names"))
return 1;
else
return 0;
}
/* Parse any rp clients in the j_realms object. Ignores other realms. */
static TR_RP_CLIENT *tr_cfg_parse_rp_clients(TALLOC_CTX *mem_ctx, json_t *jrealms, TR_CFG_RC *rc)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_RP_CLIENT *clients=NULL;
TR_RP_CLIENT *new_client=NULL;
json_t *this_jrealm=NULL;
int ii=0;
*rc=TR_CFG_ERROR;
if ((jrealms==NULL) || (!json_is_array(jrealms))) {
tr_err("tr_cfg_parse_rp_clients: realms not an array");
*rc=TR_CFG_BAD_PARAMS;
goto cleanup;
}
for (ii=0; ii<json_array_size(jrealms); ii++) {
this_jrealm=json_array_get(jrealms, ii);
if (tr_cfg_is_rp_realm(this_jrealm)) {
new_client=tr_cfg_parse_one_rp_client(tmp_ctx, this_jrealm, rc);
if ((*rc)!=TR_CFG_SUCCESS) {
tr_err("tr_cfg_parse_rp_clients: error decoding realm entry %d", ii+1);
*rc=TR_CFG_NOPARSE;
goto cleanup;
}
tr_rp_client_add(clients, new_client);
}
}
*rc=TR_CFG_SUCCESS;
talloc_steal(mem_ctx, clients);
cleanup:
talloc_free(tmp_ctx);
return clients;
}
/* takes a talloc context, but currently does not use it */
static TR_NAME *tr_cfg_parse_org_name(TALLOC_CTX *mem_ctx, json_t *j_org, TR_CFG_RC *rc)
{
TR_NAME *name=NULL;
if ((j_org==NULL) || (rc==NULL) || (!json_is_string(j_org))) {
tr_debug("tr_cfg_parse_org_name: Bad parameters.");
if (rc!=NULL)
*rc = TR_CFG_BAD_PARAMS; /* fill in return value if we can */
return NULL;
}
name=tr_new_name(json_string_value(j_org));
if (name==NULL)
*rc=TR_CFG_NOMEM;
else
*rc=TR_CFG_SUCCESS;
return name;
}
#if 0
/* TODO: are we using this? JLR */
/* Update the community information with data from a new batch of IDP realms.
* May partially add realms if there is a failure, no guarantees.
* Call like comms=tr_comm_idp_update(comms, new_realms, &rc) */
static TR_COMM *tr_cfg_comm_idp_update(TALLOC_CTX *mem_ctx,
TR_COMM_TABLE *ctab,
TR_IDP_REALM *new_realms,
TR_CFG_RC *rc)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_COMM *comm=NULL; /* community looked up in comms table */
TR_COMM *new_comms=NULL; /* new communities as we create them */
TR_IDP_REALM *realm=NULL;
TR_APC *apc=NULL; /* apc of one realm */
if (rc==NULL) {
*rc=TR_CFG_BAD_PARAMS;
goto cleanup;
}
/* start with an empty list communities, then fill that in */
for (realm=new_realms; realm!=NULL; realm=realm->next) {
for (apc=realm->apcs; apc!=NULL; apc=apc->next) {
comm=tr_comm_lookup(comms, apc->id);
if (comm==NULL) {
comm=tr_comm_new(tmp_ctx);
if (comm==NULL) {
tr_debug("tr_cfg_comm_idp_update: unable to allocate new community.");
*rc=TR_CFG_NOMEM;
goto cleanup;
}
/* fill in the community with info */
comm->type=TR_COMM_APC; /* realms added this way are in APCs */
comm->expiration_interval=TR_DEFAULT_APC_EXPIRATION_INTERVAL;
tr_comm_set_id(comm, tr_dup_name(apc->id));
tr_comm_add_idp_realm(comm, realm);
tr_comm_add(new_comms, comm);
} else {
/* add this realm to the comm */
tr_comm_add_idp_realm(comm, realm);
}
}
}
/* we successfully built a list, add it to the other list */
tr_comm_add(comms, new_comms);
talloc_steal(mem_ctx, comms);
cleanup:
talloc_free(tmp_ctx);
return comms;
}
#endif
static TR_CFG_RC tr_cfg_parse_one_local_org(TR_CFG *trc, json_t *jlorg)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_CFG_RC retval=TR_CFG_ERROR; /* our return code */
TR_CFG_RC rc=TR_CFG_ERROR; /* return code from functions we call */
TR_NAME *org_name=NULL;
json_t *j_org=NULL;
json_t *j_realms=NULL;
TR_IDP_REALM *new_idp_realms=NULL;
TR_RP_CLIENT *new_rp_clients=NULL;
tr_debug("tr_cfg_parse_one_local_org: parsing local organization");
/* get organization_name (optional) */
if (NULL==(j_org=json_object_get(jlorg, "organization_name"))) {
tr_debug("tr_cfg_parse_one_local_org: organization_name unspecified");
} else {
org_name=tr_cfg_parse_org_name(tmp_ctx, j_org, &rc);
if (rc==TR_CFG_SUCCESS) {
tr_debug("tr_cfg_parse_one_local_org: organization_name=\"%.*s\"",
org_name->len,
org_name->buf);
/* we don't actually do anything with this, but we could */
tr_free_name(org_name);
org_name=NULL;
}
}
/* Now get realms. Allow this to be missing; even though that is a pointless organization entry,
* it's harmless. Report a warning because that might be unintentional. */
if (NULL==(j_realms=json_object_get(jlorg, "realms"))) {
tr_warning("tr_cfg_parse_one_local_org: warning - no realms in this local organization");
} else {
/* Allocate in the tmp_ctx so these will be cleaned up if we do not complete successfully. */
new_idp_realms=tr_cfg_parse_idp_realms(tmp_ctx, j_realms, &rc);
if (rc!=TR_CFG_SUCCESS)
goto cleanup;
new_rp_clients=tr_cfg_parse_rp_clients(tmp_ctx, j_realms, &rc);
if (rc!=TR_CFG_SUCCESS)
goto cleanup;
}
retval=TR_CFG_SUCCESS;
cleanup:
/* if we succeeded, link things to the configuration and move out of tmp context */
if (retval==TR_CFG_SUCCESS) {
if (new_idp_realms!=NULL) {
tr_idp_realm_add(trc->ctable->idp_realms, new_idp_realms); /* fixes talloc contexts except for head*/
talloc_steal(trc, trc->ctable->idp_realms); /* make sure the head is in the right context */
}
if (new_rp_clients!=NULL) {
tr_rp_client_add(trc->rp_clients, new_rp_clients); /* fixes talloc contexts */
talloc_steal(trc, trc->rp_clients); /* make sure head is in the right context */
}
}
talloc_free(tmp_ctx);
return rc;
}
/* Parse local organizations if present. Returns success if there are none. On failure, the configuration is unreliable. */
static TR_CFG_RC tr_cfg_parse_local_orgs(TR_CFG *trc, json_t *jcfg)
{
json_t *jlocorgs=NULL;
int ii=0;
jlocorgs=json_object_get(jcfg, "local_organizations");
if (jlocorgs==NULL)
return TR_CFG_SUCCESS;
if (!json_is_array(jlocorgs)) {
tr_err("tr_cfg_parse_local_orgs: local_organizations is not an array.");
return TR_CFG_NOPARSE;
}
for (ii=0; ii<json_array_size(jlocorgs); ii++) {
if (tr_cfg_parse_one_local_org(trc, json_array_get(jlocorgs, ii))!=TR_CFG_SUCCESS) {
tr_err("tr_cfg_parse_local_orgs: error parsing local_organization %d.", ii+1);
return TR_CFG_NOPARSE;
}
}
return TR_CFG_SUCCESS;
}
static TR_CFG_RC tr_cfg_parse_one_peer_org(TR_CFG *trc, json_t *jporg)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
json_t *jhost=NULL;
json_t *jport=NULL;
json_t *jgss=NULL;
TRP_PEER *new_peer=NULL;
TR_GSS_NAMES *names=NULL;
TR_CFG_RC rc=TR_CFG_ERROR;
jhost=json_object_get(jporg, "hostname");
jport=json_object_get(jporg, "port");
jgss=json_object_get(jporg, "gss_names");
if ((jhost==NULL) || (!json_is_string(jhost))) {
tr_err("tr_cfg_parse_one_peer_org: hostname not specified or not a string.");
rc=TR_CFG_NOPARSE;
goto cleanup;
}
if ((jport!=NULL) && (!json_is_number(jport))) {
/* note that not specifying the port is allowed, but if set it must be a number */
tr_err("tr_cfg_parse_one_peer_org: port is not a number.");
rc=TR_CFG_NOPARSE;
goto cleanup;
}
if ((jgss==NULL) || (!json_is_array(jgss))) {
tr_err("tr_cfg_parse_one_peer_org: gss_names not specified or not an array.");
rc=TR_CFG_NOPARSE;
goto cleanup;
}
new_peer=trp_peer_new(tmp_ctx);
if (new_peer==NULL) {
tr_err("tr_cfg_parse_one_peer_org: could not allocate new peer.");
rc=TR_CFG_NOMEM;
goto cleanup;
}
trp_peer_set_server(new_peer, json_string_value(jhost));
if (jport==NULL)
trp_peer_set_port(new_peer, TRP_PORT);
else
trp_peer_set_port(new_peer, json_integer_value(jport));
names=tr_cfg_parse_gss_names(tmp_ctx, jgss, &rc);
if (rc!=TR_CFG_SUCCESS) {
tr_err("tr_cfg_parse_one_peer_org: unable to parse gss names.");
rc=TR_CFG_NOPARSE;
goto cleanup;
}
trp_peer_set_gss_names(new_peer, names);
/* success! */
trp_ptable_add(trc->peers, new_peer);
rc=TR_CFG_SUCCESS;
cleanup:
talloc_free(tmp_ctx);
return rc;
}
/* Parse peer organizations, if present. Returns success if there are none. */
static TR_CFG_RC tr_cfg_parse_peer_orgs(TR_CFG *trc, json_t *jcfg)
{
json_t *jpeerorgs=NULL;
int ii=0;
jpeerorgs=json_object_get(jcfg, "peer_organizations");
if (jpeerorgs==NULL)
return TR_CFG_SUCCESS;
if (!json_is_array(jpeerorgs)) {
tr_err("tr_cfg_parse_peer_orgs: peer_organizations is not an array.");
return TR_CFG_NOPARSE;
}
for (ii=0; ii<json_array_size(jpeerorgs); ii++) {
if (tr_cfg_parse_one_peer_org(trc, json_array_get(jpeerorgs, ii))!=TR_CFG_SUCCESS) {
tr_err("tr_cfg_parse_peer_orgs: error parsing peer_organization %d.", ii+1);
return TR_CFG_NOPARSE;
}
}
return TR_CFG_SUCCESS;
}
static TR_CFG_RC tr_cfg_parse_default_servers (TR_CFG *trc, json_t *jcfg)
{
json_t *jdss = NULL;
TR_CFG_RC rc = TR_CFG_SUCCESS;
TR_AAA_SERVER *ds = NULL;
int i = 0;
if ((!trc) || (!jcfg))
return TR_CFG_BAD_PARAMS;
/* If there are default servers, store them */
if ((NULL != (jdss = json_object_get(jcfg, "default_servers"))) &&
(json_is_array(jdss)) &&
(0 < json_array_size(jdss))) {
for (i = 0; i < json_array_size(jdss); i++) {
if (NULL == (ds = tr_cfg_parse_one_aaa_server(trc,
json_array_get(jdss, i),
&rc))) {
return rc;
}
tr_debug("tr_cfg_parse_default_servers: Default server configured: %s", ds->hostname->buf);
ds->next = trc->default_servers;
trc->default_servers = ds;
}
}
tr_debug("tr_cfg_parse_default_servers: Finished (rc=%d)", rc);
return rc;
}
static void tr_cfg_parse_comm_idps(TR_CFG *trc, json_t *jidps, TR_COMM *comm, TR_CFG_RC *rc)
{
TR_IDP_REALM *found_idp=NULL;
int i = 0;
if ((!trc) ||
(!jidps) ||
(!json_is_array(jidps))) {
if (rc)
*rc = TR_CFG_BAD_PARAMS;
return;
}
for (i=0; i < json_array_size(jidps); i++) {
found_idp=tr_cfg_find_idp(trc,
tr_new_name((char *)json_string_value(json_array_get(jidps, i))),
rc);
if ((found_idp==NULL) || (*rc!=TR_CFG_SUCCESS)) {
tr_debug("tr_cfg_parse_comm_idps: Unknown IDP %s.",
(char *)json_string_value(json_array_get(jidps, i)));
*rc=TR_CFG_ERROR;
return;
}
tr_comm_add_idp_realm(trc->ctable, comm, found_idp, 0, NULL, NULL); /* no provenance, never expires */
}
*rc=TR_CFG_SUCCESS;
return;
}
static void tr_cfg_parse_comm_rps(TR_CFG *trc, json_t *jrps, TR_COMM *comm, TR_CFG_RC *rc)
{
TR_RP_REALM *found_rp=NULL;
TR_RP_REALM *new_rp=NULL;
TR_NAME *rp_name=NULL;
const char *s=NULL;
int ii=0;
if ((!trc) ||
(!jrps) ||
(!json_is_array(jrps))) {
if (rc)
*rc = TR_CFG_BAD_PARAMS;
return;
}
for (ii=0; ii<json_array_size(jrps); ii++) {
/* get the RP name as a string */
s=json_string_value(json_array_get(jrps, ii));
if (s==NULL) {
tr_notice("tr_cfg_parse_comm_rps: null RP found in community %.*s, ignoring.",
tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
continue;
}
/* convert string to TR_NAME */
rp_name=tr_new_name(s);
if (rp_name==NULL) {
tr_err("tr_cfg_parse_comm_rps: unable to allocate RP name for %s in community %.*s.",
s, tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
}
/* see if we already have this RP in this community */
found_rp=tr_comm_find_rp(trc->ctable, comm, rp_name);
if (found_rp!=NULL) {
tr_notice("tr_cfg_parse_comm_rps: RP %s repeated in community %.*s.",
s, tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
tr_free_name(rp_name);
continue;
}
/* Add the RP to the community, first see if we have the RP in any community */
found_rp=tr_rp_realm_lookup(trc->ctable->rp_realms, rp_name);
if (found_rp!=NULL) {
tr_debug("tr_cfg_parse_comm_rps: RP realm %s already exists.", s);
new_rp=found_rp; /* use it rather than creating a new realm record */
} else {
new_rp=tr_rp_realm_new(NULL);
if (new_rp==NULL) {
tr_err("tr_cfg_parse_comm_rps: unable to allocate RP record for %s in community %.*s.",
s, tr_comm_get_id(comm)->len, tr_comm_get_id(comm)->buf);
}
tr_debug("tr_cfg_parse_comm_rps: setting name to %s", rp_name->buf);
tr_rp_realm_set_id(new_rp, rp_name);
rp_name=NULL; /* rp_name no longer belongs to us */
tr_rp_realm_add(trc->ctable->rp_realms, new_rp);
talloc_steal(trc->ctable, trc->ctable->rp_realms); /* make sure head is in the right context */
}
tr_comm_add_rp_realm(trc->ctable, comm, new_rp, 0, NULL, NULL);
}
}
static TR_COMM *tr_cfg_parse_one_comm (TALLOC_CTX *mem_ctx, TR_CFG *trc, json_t *jcomm, TR_CFG_RC *rc)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
TR_COMM *comm = NULL;
json_t *jid = NULL;
json_t *jtype = NULL;
json_t *japcs = NULL;
json_t *jidps = NULL;
json_t *jrps = NULL;
if ((!trc) || (!jcomm) || (!rc)) {
tr_debug("tr_cfg_parse_one_comm: Bad parameters.");
if (rc)
*rc = TR_CFG_BAD_PARAMS;
goto cleanup;
}
comm=tr_comm_new(tmp_ctx);
if (comm==NULL) {
tr_crit("tr_cfg_parse_one_comm: Out of memory.");
*rc = TR_CFG_NOMEM;
goto cleanup;
}
if ((NULL == (jid = json_object_get(jcomm, "community_id"))) ||
(!json_is_string(jid)) ||
(NULL == (jtype = json_object_get(jcomm, "type"))) ||
(!json_is_string(jtype)) ||
(NULL == (japcs = json_object_get(jcomm, "apcs"))) ||
(!json_is_array(japcs)) ||
(NULL == (jidps = json_object_get(jcomm, "idp_realms"))) ||
(!json_is_array(jidps)) ||
(NULL == (jrps = json_object_get(jcomm, "rp_realms"))) ||
(!json_is_array(jrps))) {
tr_debug("tr_cfg_parse_one_comm: Error parsing Communities configuration.");
*rc = TR_CFG_NOPARSE;
comm=NULL;
goto cleanup;
}
tr_comm_set_id(comm, tr_new_name(json_string_value(jid)));
if (NULL == tr_comm_get_id(comm)) {
tr_debug("tr_cfg_parse_one_comm: No memory for community id.");
*rc = TR_CFG_NOMEM;
comm=NULL;
goto cleanup;
}
if (0 == strcmp(json_string_value(jtype), "apc")) {
comm->type = TR_COMM_APC;
} else if (0 == strcmp(json_string_value(jtype), "coi")) {
comm->type = TR_COMM_COI;
if (NULL == (comm->apcs = tr_cfg_parse_apcs(trc, japcs, rc))) {
tr_debug("tr_cfg_parse_one_comm: Can't parse APCs for COI %s.",
tr_comm_get_id(comm)->buf);
comm=NULL;
goto cleanup;
}
} else {
tr_debug("tr_cfg_parse_one_comm: Invalid community type, comm = %s, type = %s",
tr_comm_get_id(comm)->buf, json_string_value(jtype));
*rc = TR_CFG_NOPARSE;
comm=NULL;
goto cleanup;
}
tr_cfg_parse_comm_idps(trc, jidps, comm, rc);
if (TR_CFG_SUCCESS != *rc) {
tr_debug("tr_cfg_parse_one_comm: Can't parse IDP realms for comm %s.",
tr_comm_get_id(comm)->buf);
comm=NULL;
goto cleanup;
}
tr_cfg_parse_comm_rps(trc, jrps, comm, rc);
if (TR_CFG_SUCCESS != *rc) {
tr_debug("tr_cfg_parse_one_comm: Can't parse RP realms for comm %s .",
tr_comm_get_id(comm)->buf);
comm=NULL;
goto cleanup;
}
if (TR_COMM_APC == comm->type) {
json_t *jexpire = json_object_get(jcomm, "expiration_interval");
comm->expiration_interval = 43200; /*30 days*/
if (jexpire) {
if (!json_is_integer(jexpire)) {
fprintf(stderr, "tr_parse_one_comm: expiration_interval is not an integer\n");
comm=NULL;
goto cleanup;
}
comm->expiration_interval = json_integer_value(jexpire);
if (comm->expiration_interval <= 10)
comm->expiration_interval = 11; /* Freeradius waits 10 minutes between successful TR queries*/
if (comm->expiration_interval > 129600) /* 90 days*/
comm->expiration_interval = 129600;
}
}
cleanup:
if (comm!=NULL)
talloc_steal(mem_ctx, comm);
talloc_free(tmp_ctx);
return comm;
}
static TR_CFG_RC tr_cfg_parse_comms (TR_CFG *trc, json_t *jcfg)
{
json_t *jcomms = NULL;
TR_CFG_RC rc = TR_CFG_SUCCESS;
TR_COMM *comm = NULL;
int i = 0;
if ((!trc) || (!jcfg)) {
tr_debug("tr_cfg_parse_comms: Bad Parameters.");
return TR_CFG_BAD_PARAMS;
}
if (NULL != (jcomms = json_object_get(jcfg, "communities"))) {
if (!json_is_array(jcomms)) {
return TR_CFG_NOPARSE;
}
for (i = 0; i < json_array_size(jcomms); i++) {
if (NULL == (comm = tr_cfg_parse_one_comm(NULL, /* TODO: use a talloc context */
trc,
json_array_get(jcomms, i),
&rc))) {
return rc;
}
tr_debug("tr_cfg_parse_comms: Community configured: %s.",
tr_comm_get_id(comm)->buf);
tr_comm_table_add_comm(trc->ctable, comm);
}
}
tr_debug("tr_cfg_parse_comms: Finished (rc=%d)", rc);
return rc;
}
TR_CFG_RC tr_cfg_validate(TR_CFG *trc)
{
TR_CFG_RC rc = TR_CFG_SUCCESS;
if (!trc)
return TR_CFG_BAD_PARAMS;
if ((NULL == trc->internal)||
(NULL == trc->internal->hostname)) {
tr_debug("tr_cfg_validate: Error: No internal configuration, or no hostname.");
rc = TR_CFG_ERROR;
}
if (NULL == trc->rp_clients) {
tr_debug("tr_cfg_validate: Error: No RP Clients configured");
rc = TR_CFG_ERROR;
}
if (0==tr_comm_table_size(trc->ctable)) {
tr_debug("tr_cfg_validate: Error: No Communities configured");
rc = TR_CFG_ERROR;
}
if ((NULL == trc->default_servers) && (NULL == trc->ctable->idp_realms)) {
tr_debug("tr_cfg_validate: Error: No default servers or IDPs configured.");
rc = TR_CFG_ERROR;
}
return rc;
}
/* Join two paths and return a pointer to the result. This should be freed
* via talloc_free. Returns NULL on failure. */
static char *join_paths(TALLOC_CTX *mem_ctx, const char *p1, const char *p2)
{
return talloc_asprintf(mem_ctx, "%s/%s", p1, p2); /* returns NULL on a failure */
}
static void tr_cfg_log_json_error(const char *label, json_error_t *rc)
{
tr_debug("%s: JSON parse error on line %d: %s",
label,
rc->line,
rc->text);
}
TR_CFG_RC tr_cfg_parse_one_config_file(TR_CFG *cfg, const char *file_with_path)
{
json_t *jcfg=NULL;
json_t *jser=NULL;
json_error_t rc;
if (NULL==(jcfg=json_load_file(file_with_path,
JSON_DISABLE_EOF_CHECK, &rc))) {
tr_debug("tr_cfg_parse_one_config_file: Error parsing config file %s.",
file_with_path);
tr_cfg_log_json_error("tr_cfg_parse_one_config_file", &rc);
return TR_CFG_NOPARSE;
}
// Look for serial number and log it if it exists
if (NULL!=(jser=json_object_get(jcfg, "serial_number"))) {
if (json_is_number(jser)) {
tr_notice("tr_parse_one_config_file: Attempting to load revision %" JSON_INTEGER_FORMAT " of '%s'.",
json_integer_value(jser),
file_with_path);
}
}
if ((TR_CFG_SUCCESS != tr_cfg_parse_internal(cfg, jcfg)) ||
(TR_CFG_SUCCESS != tr_cfg_parse_local_orgs(cfg, jcfg)) ||
(TR_CFG_SUCCESS != tr_cfg_parse_peer_orgs(cfg, jcfg)) ||
(TR_CFG_SUCCESS != tr_cfg_parse_default_servers(cfg, jcfg)) ||
(TR_CFG_SUCCESS != tr_cfg_parse_comms(cfg, jcfg)))
return TR_CFG_ERROR;
return TR_CFG_SUCCESS;
}
/* Reads configuration files in config_dir ("" or "./" will use the current directory). */
TR_CFG_RC tr_parse_config(TR_CFG_MGR *cfg_mgr, const char *config_dir, int n, struct dirent **cfg_files)
{
TALLOC_CTX *tmp_ctx=talloc_new(NULL);
char *file_with_path;
int ii;
TR_CFG_RC cfg_rc=TR_CFG_ERROR;
if ((!cfg_mgr) || (!cfg_files) || (n<=0)) {
cfg_rc=TR_CFG_BAD_PARAMS;
goto cleanup;
}
if (cfg_mgr->new != NULL)
tr_cfg_free(cfg_mgr->new);
cfg_mgr->new=tr_cfg_new(tmp_ctx); /* belongs to the temporary context for now */
if (cfg_mgr->new == NULL) {
cfg_rc=TR_CFG_NOMEM;
goto cleanup;
}
cfg_mgr->new->peers=trp_ptable_new(cfg_mgr);
/* Parse configuration information from each config file */
for (ii=0; ii<n; ii++) {
file_with_path=join_paths(tmp_ctx, config_dir, cfg_files[ii]->d_name); /* must free result with talloc_free */
if(file_with_path == NULL) {
tr_crit("tr_parse_config: error joining path.");
cfg_rc=TR_CFG_NOMEM;
goto cleanup;
}
tr_debug("tr_parse_config: Parsing %s.", cfg_files[ii]->d_name); /* print the filename without the path */
cfg_rc=tr_cfg_parse_one_config_file(cfg_mgr->new, file_with_path);
if (cfg_rc!=TR_CFG_SUCCESS) {
tr_crit("tr_parse_config: Error parsing %s", file_with_path);
goto cleanup;
}
talloc_free(file_with_path); /* done with filename */
}
/* make sure we got a complete, consistent configuration */
if (TR_CFG_SUCCESS != tr_cfg_validate(cfg_mgr->new)) {
tr_err("tr_parse_config: Error: INVALID CONFIGURATION");
cfg_rc=TR_CFG_ERROR;
goto cleanup;
}
/* success! */
talloc_steal(cfg_mgr, cfg_mgr->new); /* hand this over to the cfg_mgr context */
cfg_rc=TR_CFG_SUCCESS;
cleanup:
talloc_free(tmp_ctx);
return cfg_rc;
}
TR_IDP_REALM *tr_cfg_find_idp (TR_CFG *tr_cfg, TR_NAME *idp_id, TR_CFG_RC *rc)
{
TR_IDP_REALM *cfg_idp;
if ((!tr_cfg) || (!idp_id)) {
if (rc)
*rc = TR_CFG_BAD_PARAMS;
return NULL;
}
for (cfg_idp = tr_cfg->ctable->idp_realms; NULL != cfg_idp; cfg_idp = cfg_idp->next) {
if (!tr_name_cmp (idp_id, cfg_idp->realm_id)) {
tr_debug("tr_cfg_find_idp: Found %s.", idp_id->buf);
return cfg_idp;
}
}
/* if we didn't find one, return NULL */
return NULL;
}
TR_RP_CLIENT *tr_cfg_find_rp (TR_CFG *tr_cfg, TR_NAME *rp_gss, TR_CFG_RC *rc)
{
TR_RP_CLIENT *cfg_rp;
if ((!tr_cfg) || (!rp_gss)) {
if (rc)
*rc = TR_CFG_BAD_PARAMS;
return NULL;
}
for (cfg_rp = tr_cfg->rp_clients; NULL != cfg_rp; cfg_rp = cfg_rp->next) {
if (tr_gss_names_matches(cfg_rp->gss_names, rp_gss)) {
tr_debug("tr_cfg_find_rp: Found %s.", rp_gss->buf);
return cfg_rp;
}
}
/* if we didn't find one, return NULL */
return NULL;
}
static int is_cfg_file(const struct dirent *dent) {
int n;
/* Only accept filenames ending in ".cfg" and starting with a character
* other than an ASCII '.' */
/* filename must be at least 4 characters long to be acceptable */
n=strlen(dent->d_name);
if (n < 4) {
return 0;
}
/* filename must not start with '.' */
if ('.' == dent->d_name[0]) {
return 0;
}
/* If the above passed and the last four characters of the filename are .cfg, accept.
* (n.b., assumes an earlier test checked that the name is >= 4 chars long.) */
if (0 == strcmp(&(dent->d_name[n-4]), ".cfg")) {
return 1;
}
/* otherwise, return false. */
return 0;
}
/* Find configuration files in a particular directory. Returns the
* number of entries found, 0 if none are found, or <0 for some
* errors. If n>=0, the cfg_files parameter will contain a newly
* allocated array of pointers to struct dirent entries, as returned
* by scandir(). These can be freed with tr_free_config_file_list().
*/
int tr_find_config_files (const char *config_dir, struct dirent ***cfg_files) {
int n = 0;
n = scandir(config_dir, cfg_files, is_cfg_file, alphasort);
if (n < 0) {
perror("scandir");
tr_debug("tr_find_config: scandir error trying to scan %s.", config_dir);
}
return n;
}
/* Free memory allocated for configuration file list returned from tr_find_config_files().
* This can be called regardless of the return value of tr_find_config_values(). */
void tr_free_config_file_list(int n, struct dirent ***cfg_files) {
int ii;
/* if n < 0, then scandir did not allocate anything because it failed */
if((n>=0) && (*cfg_files != NULL)) {
for(ii=0; ii<n; ii++) {
free((*cfg_files)[ii]);
}
free(*cfg_files); /* safe even if n==0 */
*cfg_files=NULL; /* this will help prevent accidentally freeing twice */
}
}
<file_sep>/common/tr_filter.c
/*
* Copyright (c) 2012, 2013, JANET(UK)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of JANET(UK) nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <talloc.h>
#include <tr_filter.h>
int tr_filter_process_rp_permitted (TR_NAME *rp_realm, TR_FILTER *rpp_filter, TR_CONSTRAINT_SET *in_constraints, TR_CONSTRAINT_SET **out_constraints, int *out_action)
{
int i = 0, j = 0;
*out_action = TR_FILTER_ACTION_REJECT;
*out_constraints = NULL;
/* If this isn't a valid rp_permitted filter, return no match. */
if ((!rpp_filter) ||
(TR_FILTER_TYPE_RP_PERMITTED != rpp_filter->type)) {
return TR_FILTER_NO_MATCH;
}
/* Check if there is a match for this filter. */
for (i = 0; i < TR_MAX_FILTER_LINES; i++) {
for (j = 0; j < TR_MAX_FILTER_SPECS; j++) {
if ((rpp_filter->lines[i]) &&
(rpp_filter->lines[i]->specs[j]) &&
(tr_fspec_matches(rpp_filter->lines[i]->specs[j], rp_realm))) {
*out_action = rpp_filter->lines[i]->action;
*out_constraints = in_constraints;
if (rpp_filter->lines[i]->realm_cons)
tr_constraint_add_to_set(out_constraints,
rpp_filter->lines[i]->realm_cons);
if (rpp_filter->lines[i]->domain_cons)
tr_constraint_add_to_set(out_constraints,
rpp_filter->lines[i]->domain_cons);
return TR_FILTER_MATCH;
}
}
}
/* If there is no match, indicate that. */
return TR_FILTER_NO_MATCH;
}
void tr_fspec_free(TR_FSPEC *fspec)
{
talloc_free(fspec);
}
static int tr_fspec_destructor(void *obj)
{
TR_FSPEC *fspec=talloc_get_type_abort(obj, TR_FSPEC);
if (fspec->field!=NULL)
tr_free_name(fspec->field);
if (fspec->match!=NULL)
tr_free_name(fspec->match);
return 0;
}
TR_FSPEC *tr_fspec_new(TALLOC_CTX *mem_ctx)
{
TR_FSPEC *fspec=talloc(mem_ctx, TR_FSPEC);
if (fspec!=NULL) {
fspec->field=NULL;
fspec->match=NULL;
talloc_set_destructor((void *)fspec, tr_fspec_destructor);
}
return fspec;
}
void tr_fspec_set_match(TR_FSPEC *fspec, TR_NAME *match)
{
if (fspec->match!=NULL)
tr_free_name(fspec->match);
fspec->match=match;
}
/* returns 1 if the spec matches */
int tr_fspec_matches(TR_FSPEC *fspec, TR_NAME *name)
{
return ((fspec->match!=NULL) &&
(0!=tr_prefix_wildcard_match(name->buf, fspec->match->buf)));
}
void tr_fline_free(TR_FLINE *fline)
{
talloc_free(fline);
}
TR_FLINE *tr_fline_new(TALLOC_CTX *mem_ctx)
{
TR_FLINE *fl=talloc(mem_ctx, TR_FLINE);
int ii=0;
if (fl!=NULL) {
fl->action=TR_FILTER_ACTION_UNKNOWN;
fl->realm_cons=NULL;
fl->domain_cons=NULL;
for (ii=0; ii<TR_MAX_FILTER_SPECS; ii++)
fl->specs[ii]=NULL;
}
return fl;
}
TR_FILTER *tr_filter_new(TALLOC_CTX *mem_ctx)
{
TR_FILTER *f=talloc(mem_ctx, TR_FILTER);
int ii=0;
if (f!=NULL) {
f->type=TR_FILTER_TYPE_UNKNOWN;
for (ii=0; ii<TR_MAX_FILTER_LINES; ii++)
f->lines[ii]=NULL;
}
return f;
}
void tr_filter_free(TR_FILTER *filt)
{
talloc_free(filt);
}
void tr_filter_set_type(TR_FILTER *filt, TR_FILTER_TYPE type)
{
filt->type=type;
}
TR_FILTER_TYPE tr_filter_get_type(TR_FILTER *filt)
{
return filt->type;
}
<file_sep>/include/tr_filter.h
/*
* Copyright (c) 2012, 2013, JANET(UK)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of JANET(UK) nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef TR_FILTER_H
#define TR_FILTER_H
#include <talloc.h>
#include <jansson.h>
#include <trust_router/tr_name.h>
#include <trust_router/tr_constraint.h>
#define TR_MAX_FILTERS 5
#define TR_MAX_FILTER_LINES 8
#define TR_MAX_FILTER_SPECS 8
/* Filter actions */
typedef enum {
TR_FILTER_ACTION_REJECT=0,
TR_FILTER_ACTION_ACCEPT,
TR_FILTER_ACTION_UNKNOWN
} TR_FILTER_ACTION;
/* Match codes */
#define TR_FILTER_MATCH 0
#define TR_FILTER_NO_MATCH 1
/* Filter types */
typedef enum {
TR_FILTER_TYPE_TID_INCOMING=0,
TR_FILTER_TYPE_UNKNOWN
} TR_FILTER_TYPE;
/* #define for backward compatibility, TODO: get rid of this -jlr */
#define TR_FILTER_TYPE_RP_PERMITTED TR_FILTER_TYPE_TID_INCOMING
typedef struct tr_fspec {
TR_NAME *field;
TR_NAME *match;
} TR_FSPEC;
typedef struct tr_fline {
TR_FILTER_ACTION action;
TR_FSPEC *specs[TR_MAX_FILTER_SPECS];
TR_CONSTRAINT *realm_cons;
TR_CONSTRAINT *domain_cons;
} TR_FLINE;
typedef struct tr_filter {
TR_FILTER_TYPE type;
TR_FLINE *lines[TR_MAX_FILTER_LINES];
} TR_FILTER;
TR_FILTER *tr_filter_new(TALLOC_CTX *mem_ctx);
void tr_filter_free(TR_FILTER *filt);
void tr_filter_set_type(TR_FILTER *filt, TR_FILTER_TYPE type);
TR_FILTER_TYPE tr_filter_get_type(TR_FILTER *filt);
TR_FLINE *tr_fline_new(TALLOC_CTX *mem_ctx);
void tr_fline_free(TR_FLINE *fline);
TR_FSPEC *tr_fspec_new(TALLOC_CTX *mem_ctx);
void tr_fspec_free(TR_FSPEC *fspec);
void tr_fspec_set_match(TR_FSPEC *fspec, TR_NAME *match);
int tr_fspec_matches(TR_FSPEC *fspec, TR_NAME *name);
/*In tr_constraint.c and exported, but not really a public symbol; needed by tr_filter.c and by tr_constraint.c*/
int TR_EXPORT tr_prefix_wildcard_match (const char *str, const char *wc_str);
int tr_filter_process_rp_permitted (TR_NAME *rp_realm, TR_FILTER *rpp_filter, TR_CONSTRAINT_SET *in_constraints, TR_CONSTRAINT_SET **out_constraints, int *out_action);
TR_CONSTRAINT_SET *tr_constraint_set_from_fline (TR_FLINE *fline);
#endif
| a534df9ea32e1025b8f5a9f75047e5e964a27243 | [
"C"
] | 3 | C | TheMysteriousX/trust_router | ec5f59e28876b84caea5d4df06a9789c7bf25038 | 5c7b099600ea6a0959fef20e191825255125c76b |
refs/heads/main | <file_sep># SnakeGame1
* This is a GUI application based on the implementation of Java Swing
* It has been built using JDK 14.0.2 version
* To run it JDK 14.0.2 or more needs to be installed
* JDK 14 Download Link:https://www.oracle.com/in/java/technologies/javase/jdk14-archive-downloads.html
* Permanent Path setting for JDK https://www.javatpoint.com/how-to-set-path-in-java
* Good to Go, download the jar file as follows:
* ![Reference Screenshot](image.png)
* Double-Click and It runs😃
| 44cea6b20af015941a8044ffb7b4b0ef79ded844 | [
"Markdown"
] | 1 | Markdown | AlkaDas991/SnakeGame1 | 77f6eb13ba85097d1556401b939d3c10f2f26dde | 457a4126d4ec437822ae74a8a0743499cb20fc0d |
refs/heads/master | <file_sep># ip.qq.com | be7e167a204cb7b7c289cf80956d9defc2a5313f | [
"Markdown"
] | 1 | Markdown | c3827286/ip.qq.com | 71a7e1506500706c913ea4577245257eb6c047af | 173d0226af97307905cfd28af9813fdce4fa5143 |
refs/heads/master | <file_sep># PR-Booster! - for Atlassian Bitbucket (Server) #
## What is this site? ##
This site contains our project bug tracker, our support wiki, some of our code, and some test repos (for testing the plugin).
## What does the plugin do? ##
The plugin contains 3 features we believe our essential for users of Bitbucket:
- **Commit Graph** - Display branch history visually on the Bitbucket Commits page.
- **Commit Time** - Display the correct commit time on the Bitbucket Commits page.
- **Protect First Parent** (Pre-Receive & Merge Hook) - Ensure consistency of the master branch (e.g., protect against 2nd-parent kidnappings.)
### How do I set it up? ###
- **Commit Graph** and **Commit Time** are both automatically enabled for all repositories the moment Bit-Booster is installed. **Note:** they also automatically disable themselves if your trial license expires (paid licenses never expire).
- **Protect First Parent** appears in the "Hooks" section of your repositories. It is "disabled" by default, and you must click "enable" inside each repository to activate its function for said repository. **Protect First Parent** is not affected by license status, and remains fully functional even if your license expires.
### Who do I talk to? ###
* For technical support and general questions about the plugin, you can use our public mailing list: [<EMAIL>](mailto:<EMAIL>). You can subscribe [here](http://ml.bit-booster.com/listinfo.cgi/users-bit-booster.com)). Or you can email support directly: [<EMAIL>](mailto:<EMAIL>).
* For consulting work, please email me directly (<EMAIL>).
### Is Bit-Booster really the best commit graph on Bitbucket Server? ###
* Take a look at our analysis for yourself and see if you agree: [bit-booster.com/best.html](http://bit-booster.com/best.html).
| 05107608011f991d498f7c1e5a3ee97246f2f98c | [
"Markdown"
] | 1 | Markdown | delanAtMergebase/flower | 54d509f0b20265e83c2e5d3474f126fac52e79de | bcde549f7e1384feeb2b07f32353b502006c3b32 |
refs/heads/master | <repo_name>gedelumbung/reactjs-smartfren-balance-everywhere<file_sep>/src/index.css
.smartpret-container{
position: fixed;
background-color: #fff;
opacity: 0.8;
z-index: 9999;
padding: 3px;
font-weight: bold;
width: 100%;
text-align: center;
bottom: 0;
font-family: sans-serif;
font-size: 12px;
}
.smartpret-container > span:first-child{
border-left : none;
padding-right: 3px;
}
.smartpret-container > span{
border-left : 1px solid #000;
padding: 0px 3px;
}
<file_sep>/README.md
# Smartfren Balance (Everywhere)
### Attach Your Current Smartfren Balance in Every Browser Page
This is just another version of [this Chrome Extension](https://github.com/gedelumbung/reactjs-smartfren-balance) to check your current Smartfren balance, no need to click the icon to show your current balance. It will automatically show in every browser page.
### Why I need this (maybe you too :D)?
I have no time to click the extension everytime only to checking the current balance, so I just need to attach it in every browser page (inside body tag) and it will call official API to fetch all data :D
![enter image description here](https://lh3.googleusercontent.com/-SDDfVi2zkmLIHbG1CnOTJdlGLQiGh2G-pQtpXj9swSsfLzkk58cweqxYHnGLyfo77c1x4FikHV9 "As you can see, the current Smartfren Balance appear at the bottom of page")
| ab660138eedabb467289100503d6da6f3bddcd42 | [
"Markdown",
"CSS"
] | 2 | Markdown | gedelumbung/reactjs-smartfren-balance-everywhere | 32a897c112c1d2c8f9f744ef89b12db75f8922a8 | f7c2f5e3f52a870fef0d22a89b468c889344ef92 |
refs/heads/master | <repo_name>GelLiNN/DataSender<file_sep>/SplunkLogger.cs
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Diagnostics;
namespace SplunkClient
{
/*
* Logger is a portable class that easily sends data
* to Splunk over HTTP/HTTPS providing great abstraction
* for developers logging mobile data to Splunk */
public class SplunkLogger
{
private string level;
private string uri;
private HttpClient client;
private bool sslEnabled;
private string sourcetype;
// Keeps track of severity levels
private List<string> levels;
// Keeps track of any errors, and their respective events
private List<KeyValuePair<string, string>> errors;
// Introducing batching functionality
private bool batchingEnabled;
private Queue<string> eventBatch;
private long batchInterval;
private long batchSize;
// Default batching values
private const long DEFAULT_BATCH_INTERVAL = 500;
private const long DEFAULT_BATCH_SIZE = 500;
/*
* Constructs a SplunkLogger with endpoint URI, Http Event Collector token, bool SSL */
public SplunkLogger(string newUri, string token, bool ssl)
{
client = new HttpClient();
eventBatch = new Queue<string>();
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Splunk", token);
this.uri = newUri;
batchingEnabled = false;
// Adds severity levels for SplunkLogger
levels = new List<string>();
levels.Add("ERROR");
levels.Add("INFO");
levels.Add("OFF");
levels.Add("VERBOSE");
levels.Add("WARNING");
this.level = "INFO";
this.sourcetype = "Mobile Application";
errors = new List<KeyValuePair<string, string>>();
sslEnabled = ssl;
/*
if (sslEnabled) {
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;
}
*/
}
/*
* Changes the severity level of this SplunkLogger */
public void SetLevel(string newLevel)
{
string levelVal = newLevel.ToUpper();
if (levels != null && levels.Contains(levelVal))
{
this.level = levelVal;
}
}
/*
* Changes the sourcetype of this SplunkLogger */
public void SetSourcetype(string type)
{
this.sourcetype = type;
}
/*
* Enables batching with default values */
public void EnableBatching()
{
EnableBatching(DEFAULT_BATCH_INTERVAL, DEFAULT_BATCH_SIZE);
}
/*
* Enables batching with passed parameters Batch Interval and Batch Size */
public void EnableBatching(long batchInterval, long batchSize)
{
this.batchInterval = batchInterval;
this.batchSize = batchSize;
batchingEnabled = true;
AutoSendBatches();
}
/*
* Changes the sourcetype of this SplunkLogger */
public void DisableBatching()
{
batchingEnabled = false;
}
/*
* Logs a string message/event to Splunk's Http Event Collector, Sync */
public void Log(string message)
{
HandleLog(message, false);
}
/*
* Logs a string message/event to Splunk's Http Event Collector, Async */
async public Task LogAsync(string message)
{
await HandleLog(message, true);
}
/*
* Sends string message/event to Splunk's Http Event
* Collector, Sync or Async depending on the passed bool */
async private Task HandleLog(string message, bool async)
{
if (string.Equals(this.level, "OFF"))
{
errors.Add(new KeyValuePair<string, string>(
"Cannot send events when SplunkLogger is turned off", message));
return;
}
else if (batchingEnabled)
{
await HandleBatching(message);
}
else
{
try
{
var content = GetHttpContent(message);
var response = async ? await client.PostAsync(this.uri, content) :
client.PostAsync(this.uri, content).Result;
response.EnsureSuccessStatusCode();
}
catch (Exception e)
{
errors.Add(new KeyValuePair<string, string>(e.Message, message));
}
}
}
/*
* Handles the logic of making and sending event batches by size, Async */
async private Task HandleBatching(string message)
{
eventBatch.Enqueue(message);
if (eventBatch.Count == batchSize)
{
await SendAsync(eventBatch);
}
}
/*
* Handles batching by time interval, runs in background, Async */
async private Task AutoSendBatches()
{
while (batchingEnabled)
{
await Task.Delay((int)batchInterval);
if (eventBatch.Count > 0)
{
await SendAsync(eventBatch);
}
}
}
/*
* Sends events to this Logger's URI,
* events queue is empty upon completion, Async */
async public Task SendAsync(Queue<string> events)
{
string JSONstr = "";
while (events.Count > 0)
{
string curMessage = events.Dequeue();
JSONstr += "{\"event\":{\"message\":\"" + curMessage + "\", \"severity\":\"" +
this.level + "\"}, \"sourcetype\":\"" + this.sourcetype + "\"}";
}
HttpContent content = new StringContent(JSONstr);
await client.PostAsync(this.uri, content);
}
/*
* Returns a JSON populated HttpContent object with the given message */
private HttpContent GetHttpContent(string message)
{
string JSONstr = "{\"event\":{\"message\":\"" + message +
"\", \"severity\":\"" + this.level + "\"}, \"sourcetype\":\"" + this.sourcetype + "\"}";
return new StringContent(JSONstr);
}
/*
* Resends all events that caused exceptions, Async */
async public void ResendErrorsAsync()
{
while (errors.Count > 0)
{
foreach (var error in errors)
{
await LogAsync(error.Value);
}
}
}
/*
* Empties the stored list of errors/failed requests */
public void ClearErrors()
{
errors.Clear();
}
}
}<file_sep>/TestClient.cs
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SplunkClient
{
public class TestClient
{
public static long SendMultipleTestEvents(int howMany, SplunkLogger logger)
{
Stopwatch timer = new Stopwatch();
timer.Start();
for (int i = 1; i <= howMany; i++)
{
string time = timer.ElapsedMilliseconds.ToString();
logger.Log("This is test event " + i + " out of " + howMany +
". It has been " + time + " millis since requests started.");
}
timer.Stop();
return timer.ElapsedMilliseconds;
}
public static async Task<long> SendMultipleTestEventsAsync(int howMany, SplunkLogger logger)
{
Stopwatch timer = new Stopwatch();
timer.Start();
for (int i = 1; i <= howMany; i++) {
string time = timer.ElapsedMilliseconds.ToString();
await logger.LogAsync ("This is test event " + i + " out of " + howMany +
". It has been " + time + " millis since requests started.");
}
timer.Stop();
return timer.ElapsedMilliseconds;
}
}
}
<file_sep>/README.md
# Splunk Logger PCL
This lightweight logger was developed to provide an easy way to log events to a Splunk instance through the Http Event Collector data input. Since it’s a portable class library, it can be used with any .NET application. More importantly, it can be used within the Xamarin platform (Xamarin Studio or Xamarin tools within Visual Studio) to allow easy event logging from cross-platform mobile applications!
# How-to:
## INSTALLATION
- Clone this git repository, and add a reference in your project to the SplunkClient project.
- Make sure to add a using statement to the top of the classes you’d like to log events from: `using SplunkClient;`
## LOGGING EVENTS
After you’ve referenced the SplunkClient project and added your using statements, the next step is to construct a SplunkLogger. **The first thing the constructor method takes** is a URI string of the Splunk instance you’re sending data to, for example: `http://localhost:8088/services/collector`
8088 is the default port for the HTTP Event Collector, and `/services/collector` is the rest of the path to the collector. These may be different depending on your Splunk deployment or system admin’s preferences.
**The next thing the constructor takes** is a unique token GUID string, that can be generated when you add inputs to the Http Event Collector. This can be done from Splunk’s UI (settings > data inputs > Http Event Collector > New Token) or Splunk’s command line interface. **The next thing the constructor takes** is a boolean indicating whether or not the request requires SSL.
Once the SplunkLogger is constructed, you can simply call `myLogger.Log();` for normal synchronous logging, or `myLogger.LogAsync();` for asynchronous logging. This means that calling `myLogger.LogAsync();` will not interrupt the thread it is called from. This is extremely helpful in mobile applications, where you don’t want the user interface thread to experience any interruptions.
Also, call `myLogger.EnableBatching();` if you want SplunkLogger to package up the individual events your application sends, and send them as batches in less frequent requests. This can help your application’s performance if you find yourself trying to send lots of events at once. To disable, call `myLogger.DisableBatching();`
### EXAMPLE CODE
```csharp
using SplunkClient;
namespace MyApplication
{
public class MyClass
{
//Can also construct SplunkLogger here if you want to log from different methods
public static void SomeMethod()
{
SplunkLogger spl = new SplunkLogger ("http://localhost:8088/services/collector",
"81EBB9BA-BEAC-43AF-B482-F683CFBBE68C", false);
spl.Log(“My First Event”);
}
public static async void SomeUIHandlerMethod()
{
SplunkLogger spl = new SplunkLogger ("http://localhost:8088/services/collector",
"81EBB9BA-BEAC-43AF-B482-F683CFBBE68C", false);
await spl.LogAsync(“My First Non-blocking Event”);
}
}
}
```
<file_sep>/iOS/ViewController.cs
using System;
using UIKit;
using SplunkClient;
using System.Diagnostics;
using System.Threading.Tasks;
namespace DataSender.iOS
{
public partial class ViewController : UIViewController
{
public ViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
Button.AccessibilityIdentifier = "Splunk>®";
SplunkLogger spl = new SplunkLogger ("http://10.80.8.76:8088/services/collector",
"9658F9CB-796C-4C0B-A1EC-84CEA4B9F768", false);
spl.EnableBatching ();
SendRandomEvents (spl);
}
async private Task SendRandomEvents(SplunkLogger spl)
{
Stopwatch timer = new Stopwatch ();
timer.Start ();
Random r = new Random();
while (true)
{
int waitTimeMillis = r.Next(250, 1500);
await Task.Delay(waitTimeMillis);
int numEvents = r.Next (1,10);
for (int i = 1; i <= numEvents; i++) {
await spl.LogAsync ("This is event " + i + " out of " + numEvents + ", sent " +
timer.ElapsedMilliseconds + " milliseconds after application started");
}
}
}
public override void DidReceiveMemoryWarning ()
{
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
}
}
<file_sep>/Droid/MainActivity.cs
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Diagnostics;
using System.Threading.Tasks;
using SplunkClient;
namespace DataSender.Droid
{
[Activity (Label = "DataSender.Droid", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
//Start sending random events
SplunkLogger spl = new SplunkLogger ("http://10.80.8.76:8088/services/collector",
"81EBB9BA-BEAC-43AF-B482-F683CFBBE68C", false);
spl.EnableBatching ();
SendRandomEvents (spl);
}
async private Task SendRandomEvents(SplunkLogger spl)
{
Stopwatch timer = new Stopwatch ();
timer.Start ();
Random r = new Random();
while (true)
{
int waitTimeMillis = r.Next(250, 1500);
await Task.Delay(waitTimeMillis);
int numEvents = r.Next (1,10);
for (int i = 1; i <= numEvents; i++) {
await spl.LogAsync ("This is event " + i + " out of " + numEvents + ", sent " +
timer.ElapsedMilliseconds + " milliseconds after application started");
}
}
}
}
}
| a4af09218a982fec151d48fe4c392a942bf5a7b0 | [
"C#",
"Markdown"
] | 5 | C# | GelLiNN/DataSender | 5d07cc430b8e748f0e1699136b4bf8133db1be16 | 89d098fd0e275de17f72d88c299d2cd8963733c5 |
refs/heads/master | <file_sep>#include <stdio.h>
int main() {
int a;
if(a=23){
printf("I AM 23");
}
else {
printf("I AM NOT 23");
}
return 0;
}<file_sep>#include <stdio.h>
#include <math.h>
int main() {
int a = 6;
int b = 6;
printf("THE EXPONENT OF THIS IS %f", pow(a,b) );
return 0;
}<file_sep>#include <stdio.h>
int main() {
int a=0;
do{
printf("%d \n", a);
if(a==4){
break;
}
a++;
}while(a < 10);
return 0;
}<file_sep>#include <stdio.h>
int main() {
int a = 4;
int k = 8;
float b = 8.5;
char c = 'u';
// printf("The value of a is %d %c \n", a, c);
// printf("The value of a is %d %c \n", a, c);
// printf("The value of a is %d %f \n", a, b);
printf("SUM is = %d", k+a );
return 0;
} <file_sep>## QUESTIONS FOR PRACTICE SETS
1. WRITE A C PROGRAM TO CALCULATE THE AREA OF A RECTANGLE:
> - using user inputs
> - using inputs supplied by the users
2. CALCULATE THE AREA OF A CIRCLE AND MODIFY THE SAME PROGRAM TO CALCULATE THE VOLUME OF A CYLINDER GIVEN ie: RADIUS AND HEIGHT
3. WRITE A PROGRAM TO CONVERT CELCIUS TO FARENHEIT
4. WRITE A PROGRAM TO CALCULATE SIMPLEINTEREST
<file_sep>#include <stdio.h>
int main() {
int a = 25;
printf("VALUE IS %d \n", a++);
printf("VALUE IS %d \n", a);
// printf("THE VALUE IS %d \n", a--);
a+=10;
printf("THE VALUE IS %d", a);
return 0;
}<file_sep>#include <stdio.h>
int main() {
int maths, english, sst;
float total;
printf("ENTER MATHS MARKS ");
scanf("%d", &maths);
printf("ENTER ENGLISH MARKS ");
scanf("%d", &english);
printf("ENTER SST MARKS ");
scanf("%d", &sst);
total = (maths + english + sst) / 3;
// printf("%d", total);
if((total < 40) || english < 33 || maths < 33 || sst < 33 ) {
printf("YOU ARE FAILED ANDN YOUR PERCENTAGE IS %f", total);
}
else {
printf("YOU ARE PASSED AND YOUR PERCENTAGE IS %f", total);
}
return 0;
}<file_sep>#include <stdio.h>
int main() {
int a;
int b;
printf("I AM JUSTIN");
return 0;
}
<file_sep>#include <stdio.h>
int main() {
char c;
printf("ENTER THE CHRACTER ");
scanf("%c", &c);
if(c <=122 && c >=97){
printf("IT IS LOWERCASE ");
}
else {
printf("IT IS NOT LOWERCASE");
}
return 0;
}<file_sep>#include <stdio.h>
int main() {
int radius = 3;
float pi = 3.14;
// printf("THE AREA OF THE CIRCLE IS %f", pi*radius*radius);
int height = 3;
printf("VOLUME OF THE CYLINDER IS %f", pi * radius * radius * height);
return 0;
}<file_sep># Variables
> 1 - it is a container which stores value
> 2 - no int or special symbol can def a variable
# Constants
## - Types Of Constant
> 1 - Integer Constant (1, 7, -3 )
> 2 - Real Constant (322.1, 22.3)
> 3 - Character Constant ('a', '$', '@')
# Keywords
> - 1.auto
> - 2.break
> - 3.case
> - 4.char
> - 5.const
> - 6.continue
> - 7.default
> - 8.do <!-- --!>
> - 9.double
> - 10.long
> - 11.return
> - 12.register
> - 13.short
> - 14.signed
> - 15.sizeof
> - 16.static
> - 17.int
> - 18.else
> - 19.enum
> - 20.extern
> - 21.float
> - 22.for
> - 23.goto
> - 24.if
> - 25.struct
> - 26.switch
> - 27.typedef
> - 28.union
> - 29.unsigned
> - 30.void
> - 31.volatile
> - 32.while
# basic structure of a C program
> - A C program starts with a main function
# Library Functions
> - print("This is %d")
- %d is for integers
- %f for real values
- %c for chracters
## How to take input from the user
- declare a variable
- for asking use printf
- for answering use scanf
<file_sep>#include <stdio.h>
int main() {
int no;
printf("ENTER YOUR NUMBER ");
scanf("%d", &no);
if(no==9999){
printf("THE NO. %d IS THE GREATEST 4 DIGIT NUMBER ", no);
}
if(no < 9999) {
printf("THE NO. %d IS NOT THE GREATEST 4 DIGIT NUMBER", no);
}
return 0;
}<file_sep>#include <stdio.h>
int main() {
float leap = 4 , year;
printf("ENTER THE YEAR TO CHECK LEAP YEAR ");
scanf("%d", year);
float a = year / leap;
if (a==0){
printf("THE YEAR %d is a leap year", year);
}
return 0;
}<file_sep>#include <stdio.h>
int main() {
int a = 45;
int b = 25;
int c = a + b;
printf("THE VALUE OF C IS %d", c);
return 0;
}<file_sep>#include <stdio.h>
int main() {
/* Code Daal Ithar */
printf('I AM THE HEADER');
return 0;
}<file_sep>#include <stdio.h>
int main() {
int a;
printf("ENTER A NO. \n");
scanf("%d", &a);
// if(a%2==0){
// printf("%d is even", a);
// }
// else {
// printf("%d is an odd no.", a);
// }
return 0;
}
<file_sep>#include <stdio.h>
int main() {
// int a = 5; // type declaration
// printf("%d", a);
float a = 1.1;
float b = a + 8.9;
printf("%f", b);
return 0;
}<file_sep>## CHAPTER 2 - INSTRUCTIONS AND OPERATORS
- A C PROGRAM IS A SET OF INSTRUCTIONS
#### TYPES OF INSTRUCTIONS
1. Type declaration instruction - int, float, char etc
2. ARITHMETIC INSTRUCTION - +, -, etc etc
3. CONTROL INSTRUCTION - for loop, while loop etc etc
<file_sep>#include <stdio.h>
int main() {
int a;
printf("ENTER THE NO. \n");
scanf("%d", &a);
if(a == 1){
printf("A IS 1");
}
else if(a == 2){
printf("A IS 2");
}
else if(a == 3){
printf("A IS 3");
}
else {
printf("ITS NOT 1,2,3");
}
return 0;
}<file_sep>#include <stdio.h>
int main() {
int age;
printf("WHAT IS YOUR AGE ");
scanf("%d", &age);
// if(age == 18) {
// printf("YOU ARE ABOVE 18 and your age is %d , hence YOU CAN APPLY", age);
// }else{
// printf("YOU ARE A TEENAGER %d , YOU CANNOT APPLY", age);
// }
if(age==50) {
printf("HALF CENTURY ");
}
return 0;
}<file_sep>#include <stdio.h>
int main() {
int b = 1;
do{
printf("%d \n", b);
b++;
}while(b <= 4);
return 0;
}<file_sep>#include <stdio.h>
int main() {
float celsius = 37;
float far = (celsius * 9 / 5 ) + 32;
printf("THE VALUE OF CELSIUS TEMPARATURE IN F IS %f", far);
return 0;
}<file_sep>- learning alot from this courses
- learnt
> - what are variables
> - how to print
> - how to take input from the user
<file_sep>#include <stdio.h>
int main() {
int pri = 200, r=10, years=1;
int simpleInterest = (pri * r * years ) / 100;
printf("THE VALUE OF SI is %d", simpleInterest);
return 0;
}<file_sep># Relational operators in C
> - == (equal)
> - > = (greater than and is equal to )
> - <= (greater than and equal to )
> - != (not equal to)
> - == is used for equality check
> - = is an assignment operator
# Logical
- ! for not
- && for and
- || for vip's inshort xD
- \ \*, / , %
- +,-
- <>, < = > > =
# ELSE IF
-else if
##<file_sep>#include <stdio.h>
int main() {
int a = 1;
float b = 9.5;
char c = 'c';
// printf("THE VALUE OF A IS %d", a);
// printf("THE VALUE OF B IS %f", b);
printf("THE VALUE OF C IS %c", c);
return 0;
}<file_sep>#include <stdio.h>
int main() {
int a,b;
printf("1st no. to be added \n");
scanf("%d", &a); // important
printf("2nd no. to be added \n");
scanf("%d", &b); // important
printf("THE VALUE IS %d", a+b);
return 0;
}
<file_sep>- loops are used to repeat a similar part of the code snippet repeatedly
- types of Loops
1.While Loops
2.Do- While loops
3.For Loops
- increment => i++, ++i
- decrement => i--, --i
- i+++ => DOES NOT EXIST
- += => COMPOUND
- do while loop => similar as while loop
do {
}while();
while => checks the condition and runs the code
do-while => check the code & then checks the condition
- For loop => for(initialize; test; increment/decrement){
// code
// code
// code
}
- In Case of Decrementing for loop
for(i = 5; i; i--){
// code
}
- in this case i is said to br true in the place of test
- break => THIS IS USE TO EXIT THE LOOP WHETHER IT IS TRUE OR FALSE
<file_sep># CONDITIONAL STATEMENTS
- if else
- switch
<file_sep>- didnt finished leap year
| aa77ebfbe2b1eb27ed0aaffea2ee65299d48c489 | [
"Markdown",
"C"
] | 30 | Markdown | Justinnn07/C-Notes | a4c4c2fda7225aee897fcc46e664c6a4ab2c13db | dd77ad02cf528dfcb377b16bb95f95c7d987f565 |
refs/heads/master | <repo_name>ultra84/HELLO-WORLD<file_sep>/README.md
# HELLO-WORLD
1.versuch eines maurers
| 9640a3d8bbce343557c6303f6e80087469e38675 | [
"Markdown"
] | 1 | Markdown | ultra84/HELLO-WORLD | 00336026264d06a85b913565c375dfdff3de4062 | cc7219ba5c15710b16ea19a3491dc0e219242581 |
refs/heads/master | <file_sep>.docs-main {
padding-left: 320px; }
.docs-main .docs-main--inner {
padding: 32px; }
.docs-main h3#preview,
.docs-main h3#code {
margin-top: 48px; }
.docs-sidebar {
width: 320px;
position: fixed;
float: left;
left: 0;
top: 0;
bottom: 0;
background: var(--gray-dark);
height: calc(100vh);
padding: 1rem; }
.docs-sidebar h4 {
color: var(--white);
opacity: 0.5;
margin-top: 2rem; }
.docs-sidebar .site-title h1 {
font-size: 1.5rem;
text-decoration: none;
margin-top: 0.5rem;
color: var(--white); }
.docs-sidebar .site-title:hover {
text-decoration: none; }
.docs-sidebar .site-title:hover h1 {
opacity: 0.5; }
.docs-sidebar .site-nav {
padding: 0; }
.docs-sidebar .site-nav li {
list-style: none; }
.docs-sidebar .site-nav a {
color: var(--white); }
.docs-sidebar .site-nav a:hover {
opacity: 0.5; }
pre {
padding: 24px;
background: var(--gray-dark);
border-radius: 4px;
color: #ccc; }
<file_sep>---
title: Tabs
permalink: components/tabs
layout: page
group: Components
toc: true
---
Tabs are mainly used in the dashboard. They embed some information about workflow and status.
### Preview
<ul class="nav nav-tabs w-100 car-dashboard--status--tabs">
<li class="nav-item">
<a class="nav-link" href="#"><h5>0</h5><span class="badge badge-primary w-100">To do</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#"><h5>0</h5><span class="badge badge-warning w-100">Needs progress</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#"><h5>0</h5><span class="badge badge-danger w-100">Needs review</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#"><h5>2</h5><span class="badge badge-success w-100">Approved</span></a>
</li>
<li class="nav-item">
<a class="nav-link active" href="#"><h5>99</h5><span class="badge badge-secondary w-100">No status</span></a>
</li>
</ul>
### Code
{% highlight html %}
<ul class="nav nav-tabs w-100 car-dashboard--status--tabs">
<li class="nav-item">
<a class="nav-link" href="#"><h5>0</h5><span class="badge badge-primary w-100">To do</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#"><h5>0</h5><span class="badge badge-warning w-100">Needs progress</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#"><h5>0</h5><span class="badge badge-danger w-100">Needs review</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#"><h5>2</h5><span class="badge badge-success w-100">Approved</span></a>
</li>
<li class="nav-item">
<a class="nav-link active" href="#"><h5>99</h5><span class="badge badge-secondary w-100">No status</span></a>
</li>
</ul>
{% endhighlight %}
<file_sep>Design system + documentation. Basé sur Bootstrap.
## Design system
La base Bootstrap provient de `node_modules/bootstrap`
Cette base est importée dans `scss/custom.scss`, avant les imports locaux — `_fonts.scss`, `_variables.scss`, etc.
Tout cela est ensuite compilé dans `dist/css/all.min.css`
La compilation est effectuée à partir de fichiers scss, via Gulp.
#### Installation
```bash
$ npm install
```
#### Compilation SCSS + JS (dev)
```bash
$ npm start
> design-system@0.1.0 start /Library/WebServer/www/design-system-documentation
> gulp
[13:59:51] Using gulpfile /Library/WebServer/www/design-system-documentation/gulpfile.js
[13:59:51] Starting 'watch'...
[13:59:51] Watching scss files for modifications
[13:59:51] Finished 'watch' after 9.67 ms
[13:59:51] Starting 'clean'...
[13:59:51] Starting 'sass'...
[13:59:51] Generate CSS files Wed Feb 07 2018 13:59:51 GMT+0100 (CET)
```
## Documentation
La partie documentation est basée sur Jekyll
#### Installation
```bash
$ cd docs
$ gem install jekyll bundler
```
#### Lancement
```bash
$ bundle exec jekyll serve
# La documentation est accessible à http://localhost:4000
```
#### Style
Deux feuilles de style sont intégrées au site de documentation :
+ le style du Design System
+ le style de la documentation
Tout cela se passe dans `_includes/head.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">
<link rel="stylesheet" href="http://localhost/design-system-documentation/dist/css/all.css">
```
On intègre ensuite le style de la documentation
```html
<link rel="stylesheet" href="{{ "/assets/css/main.css" | relative_url }}">
```
Fin du fichier `head.html`
```html
<link rel="alternate" type="application/rss+xml" title="{{ site.title | escape }}" href="{{ "/feed.xml" | relative_url }}">
{% if jekyll.environment == 'production' and site.google_analytics %}
{% include google-analytics.html %}
{% endif %}
</head>
```
Le style de la documentation est compilé à partir des fichiers .scss situés dans `assets/sass/`. Ceux-ci sont compilés dans `_site/assets/css/main.css`. Voir la partie [Structure](https://jekyllrb.com/docs/structure/) dans la doc Jekyll
## Exemples
Les exemples sont situés dans `examples/`. On peut les construire en partant de la base suivante.
```html
<html>
<head>
<link href="../dist/css/all.min.css" rel="stylesheet" type="text/css"/>
<script src="../dist/js/all.min.js"></script>
</head>
<body>
...
</body>
</html>
```
## Plus
+ [Bootstrap 4.0](http://getbootstrap.com/docs/4.0/)
+ [Gulp documentation](https://gulpjs.com)
+ [Jekyll documentation](https://jekyllrb.com/docs)
<file_sep>.main{
padding-left: 320px;
.hero{
background: url(../assets/1503334206648.png);
background-size: cover;
background-position-y: center;
*{
width: 50%;
color: #FFF;
}
}
}
<file_sep>pre{
padding: 24px;
background: var(--gray-dark);
border-radius: 4px;
color: #ccc;
}
<file_sep>---
title: Typography
permalink: general/typography
layout: default
---
# Typography
### Code
{% highlight html %}
<h1>h1 title</h1>
<h2>h2 title</h2>
<h3>h3 title</h3>
<h4>h4 title</h4>
<h5>h5 title</h5>
<h6>h6 title</h6>
{% endhighlight %}
### Preview
<h1>h1 title</h1>
<h2>h2 title</h2>
<h3>h3 title</h3>
<h4>h4 title</h4>
<h5>h5 title</h5>
<h6>h6 title</h6>
<file_sep>---
title: Card
permalink: components/card
layout: page
group: Components
toc: true
---
A card is a component
### Preview
<div class="card card--section mr-2 mb-2">
<img class="card-img-top" src="../assets/images/hubble_newold09.jpeg" alt="Card image cap">
<div class="card-body">
<div class="row">
<div class="col-md-auto px-0 ml-3">
<span class="oi oi-puzzle-piece align-top" data-glyph="puzzle-piece" title="icon puzzle-piece" aria-hidden="true"></span>
</div>
<div class="col-9">
<h6 class="card-title">Card title</h6>
</div>
</div>
</div>
</div>
### Code
{% highlight html %}
<div class="card card--section mr-2 mb-2">
<img class="card-img-top" src="../assets/images/hubble_newold09.jpeg" alt="Card image cap">
<div class="card-body">
<div class="row">
<div class="col-md-auto px-0 ml-3">
<span class="oi oi-puzzle-piece align-top" data-glyph="puzzle-piece" title="icon puzzle-piece" aria-hidden="true"></span>
</div>
<div class="col-9">
<h6 class="card-title">Card title</h6>
</div>
</div>
</div>
</div>
{% endhighlight %}
<file_sep>---
layout: page
title: Introduction
permalink: /intro/
---
### A design system documentation
This website is a tool for blabla
<file_sep>.card--section{
width: 214px;
.oi{
font-size: 1rem*1.25;
color: var(--gray);
}
}
<file_sep>---
title: Colors
permalink: general/colors
layout: page
---
Cette partie parle de couleurs
<file_sep>.btn-primary{
// background-color: var(--blue);
}
<file_sep>console.log("Design System documentation on fire !");
| 4930d1963b6600999c8214f831aebe86d44efa6b | [
"Markdown",
"SCSS",
"JavaScript",
"CSS"
] | 12 | Markdown | patjennings/design-system-documentation | 0d15de6e101c5c491b045441a47dc180c4e76faf | 4de069f6a03146dda59eec7fab368a36944f6231 |
refs/heads/master | <file_sep><?php
ini_set('display_errors','on');
error_reporting(-1);
$xml='../../log/1.xml';
$xml_obj=simplexml_load_file($xml);
$xml_obj->name='chenlei88';
$xml_obj->addAttribute('sex','man');
$xml_obj->addChild('phone',88888888);
echo $xml_obj->phone;
echo $xml_obj->sex;
$xml_str=$xml_obj->asXML();
var_dump($xml_str);
file_put_contents($xml,$xml_str);<file_sep><?php
/**
* 执行并传递参数
* D:\code\sw\php-cli\bin/php two_timer.php -a 7 -b 9
* D:\code\sw\php-cli\bin/sw two_timer.php -a 7 -b 9
*
* kill -9 pid
* dos命令杀死进程命令
* taskkill /F /im php.exe
* taskkill /F /im php-cgi.exe
* taskkill /F /im sw.exe
*
*
* ps -auxf | grep "php-fpm"
* dos命令查找进程命令
* tasklist | findstr php.exe
* tasklist | findstr php-cgi.exe
* tasklist | findstr sw.exe
*/
require "../../curl/Curl.php";
$curl = new Curl();
$params = getopt('a:b:');
$ship_company = $params['a'] = 4;
$counter = 0;
$process = new \Swoole\Process(function (\Swoole\Process $process) use($ship_company,$curl){
//一分钟以后才会 发出请求
Swoole\Timer::tick(60*1000, function (int $timer_id) use($ship_company,$process,$curl){
//$url ="http://www.tms-b.com/cargoapisys/api/Demo/wet?debug=y";
//$url ="http://192.168.71.141:92/ordersys/console/ShipFee/pullTailData";
$url ="http://192.168.71.141:92/ordersys/console/ShipFee/getTailFee";
//$url ="http://192.168.71.141:92/ordersys/console/ShipFee/pullHeaderData";
//$url ="http://192.168.71.141:92/ordersys/console/ShipFee/getHeaderFee";
$curl->requestByCurlGet($url);
});
});
$process->start(); // 启动子进程
<file_sep><div>
<div id = "array" style="display:block; width: 49.5%">
<?php
$arrResult= json_decode($_POST['str'],true);
echo "<pre>";
echo var_export($arrResult);
echo "</pre>";
?>
</div>
</div>
<file_sep><?php
class Udesk{
private $url = "http://shenzhenudesk2018.udesk.cn/open_api_v1/log_in";
private $email = "<EMAIL>";
private $password = "<PASSWORD>";
private $time;
public function __construct($params)
{
$this->email=$params['email'];
$this->password=$params['<PASSWORD>'];
$this->time=time();
}
/**
* 获取open_api_token
* @return mixed|string
*/
private function getToken(){
$ch=curl_init();
curl_setopt_array($ch,[
CURLOPT_URL =>$this->url, //请求的url
CURLOPT_RETURNTRANSFER =>1, //不要把请求的结果直接输出到浏览器
CURLOPT_TIMEOUT =>30, //请求超时设置
CURLOPT_POST =>1, //使用post请求此url
CURLOPT_SSL_VERIFYPEER=>0, //服务端不验证ssl证书
CURLOPT_SSL_VERIFYHOST=>0, //服务端不验证ssl证书
CURLOPT_HTTPPROXYTUNNEL=>1, //启用时会通过HTTP代理来传输
CURLOPT_HTTPHEADER =>['content-type: application/json'],//请求头部设置
CURLOPT_POSTFIELDS =>json_encode(['email'=>$this->email,'password'=>$this->password],JSON_UNESCAPED_UNICODE), //post请求时传递的参数
]);
$content = curl_exec($ch); //执行
$err = curl_error($ch);
curl_close($ch);
if($err){
return $err;
}
return json_decode($content);
}
public function generateSign(){
//调用获取token的函数
$content=$this->getToken();
if(isset($content->code) && $content->code==1000){
$open_api_token= $content->open_api_auth_token;//获取token;
$sign = sha1($this->email.'&'.$open_api_token.'&'.$this->time);// 生成签名
//登陆成功后可以把以下几个参数保存到session中
session_start();
$_SESSION['udest_time']=$this->time;
$_SESSION['udest_email']=$this->email;
$_SESSION['udest_sign']=$sign;
return $sign;
}
return false;
}
/**
* 获取agent_api_token
*/
public function getAgent(){
$content=$this->getToken();
$ch=curl_init();
curl_setopt_array($ch,[
CURLOPT_URL =>"http://shenzhenudesk2018.udesk.cn/open_api_v1/get_agent_token", //请求的url
CURLOPT_RETURNTRANSFER =>1, //不要把请求的结果直接输出到浏览器
CURLOPT_TIMEOUT =>30, //请求超时设置
CURLOPT_POST =>1, //使用post请求此url
CURLOPT_SSL_VERIFYPEER=>0, //服务端不验证ssl证书
CURLOPT_SSL_VERIFYHOST=>0, //服务端不验证ssl证书
CURLOPT_HTTPPROXYTUNNEL=>1, //启用时会通过HTTP代理来传输
CURLOPT_HTTPHEADER =>['content-type:application/json','open_api_token:'.$content->open_api_auth_token],//请求头部设置
CURLOPT_POSTFIELDS =>json_encode(['email'=>$this->email,'agent_email'=>'<EMAIL>','timestamp'=>$this->time,'sign'=>$this->generateSign()],JSON_UNESCAPED_UNICODE), //post请求时传递的参数
]);
$content = curl_exec($ch); //执行
$err = curl_error($ch);
curl_close($ch);
if($err){
return $err;
}
return json_decode($content);
}
}
$udesk= new Udesk(['email'=>'<EMAIL>','password'=>'<PASSWORD>']);
var_dump($udesk->getAgent());
echo "<br>";
$sign=$udesk->generateSign();
echo "http://shenzhenudesk2018.udesk.cn/open_api_v1/customers?email=".$_SESSION['udest_email']."&timestamp=".$_SESSION['udest_time']."&sign=".$sign; //用&代替&不然报错
<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py
# 第一个注释
# print ("11")
#import winsound
#winsound.Beep(600,1000)
import easygui
easygui.ynbox('Hello World','Title',('Yes','No'))
<file_sep><?php
/**
* Created by PhpStorm.
* User: Yibai
* Date: 2019/7/31
* Time: 18:51
*/
class Curl
{
/**
* 此方法依赖php的扩展模块pecl_http
* 单进程
* @param $url
* @return mixed|string
*/
function requestCurl($url,$header,$data_json){
$request = new HttpRequest();
$request->setUrl($url);
$request->setMethod(HTTP_METH_POST);
$request->setHeaders($header);
$request->setBody($data_json);
// $request->setHeaders(array(
// 'Postman-Token' => '<PASSWORD>',
// 'cache-control' => 'no-cache',
// 'Content-Type' => 'application/json'
// ));
// $request->setBody('{
// "email": "<EMAIL>",
// "password": "<PASSWORD>"
// }');
$response = $request->send();
return $content = $response->getBody();
}
/**
* 单进程
* @param $url
* @return mixed|string
*/
function requestByCurlPost($url,$params){
$ch = curl_init();
curl_setopt_array($ch,[
CURLOPT_URL =>$url, //请求的url
CURLOPT_RETURNTRANSFER =>1, //不要把请求的结果直接输出到屏幕上
CURLOPT_TIMEOUT =>30, //请求超时设置
CURLOPT_POST =>1, //使用post请求此url
CURLOPT_SSL_VERIFYPEER=>0, //服务端不验证ssl证书
CURLOPT_SSL_VERIFYHOST=>0, //服务端不验证ssl证书
CURLOPT_HTTPPROXYTUNNEL=>0, //启用时会通过HTTP代理来传输
CURLOPT_HTTPHEADER =>['content-type: application/json'],//请求头部设置
//CURLOPT_POSTFIELDS =>json_encode(['uid'=>'227899','msgType'=>'TEXT','content'=>'888888888888888'],JSON_UNESCAPED_UNICODE), //post请求时传递的参数
CURLOPT_POSTFIELDS =>json_encode($params,JSON_UNESCAPED_UNICODE), //post请求时传递的参数
]);
$content = curl_exec($ch); //执行
$err = curl_error($ch);
curl_close($ch);
if($err){
return $err;
}
return json_decode($content,true);
}
function requestByCurlGet($url){
$ch = curl_init();
curl_setopt_array($ch,[
CURLOPT_URL =>$url, //请求的url
CURLOPT_RETURNTRANSFER =>1, //不要把请求的结果直接输出到屏幕上
CURLOPT_CUSTOMREQUEST=>'GET',
CURLOPT_TIMEOUT =>30, //请求超时设置
CURLOPT_SSL_VERIFYPEER=>0, //服务端不验证ssl证书
CURLOPT_SSL_VERIFYHOST=>0, //服务端不验证ssl证书
CURLOPT_HTTPPROXYTUNNEL=>1, //启用时会通过HTTP代理来传输
//CURLOPT_NOBODY=>1, //启用时会通过HTTP代理来传输
//CURLOPT_HTTPHEADER =>['Content-type:text/html;charset=utf-8'],//请求头部设置
]);
$content = curl_exec($ch); //执行
$err = curl_error($ch);
curl_close($ch);
if($err){
return $err;
}
return $content;
}
/**
* 模拟表单提交及Json提交
* @param $url
* @param array $data
* @param bool $isJson
* @param array $headers
* @param int $timeout
* @return bool|string
*/
function post($url, $data = [], $isJson = true, $headers = [], $timeout = 10)
{
if ($isJson) {
$headers['Content-Type'] = 'application/json';
$postFields = json_encode($data);
} else {
$headers['Content-Type'] = 'application/x-www-form-urlencoded';
$postFields = http_build_query($data);
}
$headers = $this->formatHeader($headers);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//设定请求后返回结果
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//忽略证书
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
// 忽略返回的header头信息
curl_setopt($ch, CURLOPT_HEADER, 0);
// 请求头信息
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 设置超时时间
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
//模仿浏览器发出的请求 可以解决跨域问题 尤其当返回字符串为空时
curl_setopt($ch, CURLOPT_USERAGENT, "mozilla/5.0 (ipad; cpu os 7_0_4 like mac os x) applewebkit/537.51.1 (khtml, like gecko) version/7.0 mobile/11b554a safari/9537.53");
$response = curl_exec($ch);
var_dump($response);die;
$curlInfo = curl_getinfo($ch);
curl_close($ch);
return $response;
}
/**
* 对header信息进行格式化处理
* @param $headers
* @return array
*/
public function formatHeader($headers)
{
if (empty($headers)) return [];
$result = [];
foreach ($headers as $key => $value) {
$result[] = "$key:$value";
}
return $result;
}
/*
* 描述: 多进程处理
* 作者: wujianming
*/
public function getMultiProcess($urls = array()) {
$handles = $contents = array();
//初始化curl multi对象
$mh = curl_multi_init();
//添加curl 批处理会话
foreach($urls as $key => $url) {
$handles[$key] = curl_init($url);
//不输出头
curl_setopt($handles[$key], CURLOPT_HEADER, 0);
//exec返回结果而不是输出,用于赋值
curl_setopt($handles[$key], CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($handles[$key], CURLOPT_TIMEOUT, 10);
//决定exec输出顺序
curl_multi_add_handle($mh, $handles[$key]);
}
//======================执行批处理句柄=================================
$active = null;
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active and $mrc == CURLM_OK) {
if(curl_multi_select($mh) === -1){
usleep(100);
}
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
//====================================================================
//获取批处理内容
foreach($handles as $i => $ch) {
$content = curl_multi_getcontent($ch);
$contents[$i] = curl_errno($ch) == 0 ? $content : '';
}
//移除批处理句柄
foreach($handles as $ch) {
curl_multi_remove_handle($mh, $ch);
}
//关闭批处理句柄
curl_multi_close($mh);
return $contents;
}
}<file_sep><?php
include ('function.php');
include ('config.php');
include ('Payment.php');
include ('qrcode.php');
//扫码支付模式一
$product_id=10000;
$payment = new Payment();
$url =$payment->generateScanUrl($product_id); //调用生成二维码url的方法
//支付sdk里面的类 qrcode为生成二维码的类
qrcode::png($url);
<file_sep><?php
ini_set("display_errors", "On");
error_reporting(-1);
//swoole定时器
//每隔2000ms触发一次 swoole_timer_tick函数就相当于setInterval,是持续触发的
swoole_timer_tick(2000, function ($timer_id) {
echo date("Y-m-d H:i:s",time())."\n";
});
<file_sep><?php
include './sphinxapi.php'; //包含sphinxapi类
$sphinx= new SphinxClient(); //实例化
$sphinx->SetServer('localhost',9312);//链接
$sphinx->setFilter('is_delete',[0]);
$sphinx->setFilter('state',[1]);
$sphinx->setMatchMode(SPH_MATCH_EXTENDED2);
$res=$sphinx->Query("编码","knowledge");//查询的字段第二参数是你配置文件里面写得规则这里是*就会匹配所有规则
var_dump($res);die;//打印数据<file_sep><?php
/**
* 非对称加密
*/
//1.资源配置
$config = array(
'config'=>'E:\software\xampp\php\extras\openssl\openssl.cnf',
"digest_alg" => "sha512",
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
//2.根据创建一个私钥资源
$res = openssl_pkey_new($config);
//3.获取私钥$priKey
openssl_pkey_export($res, $priKey,null, $config);
var_dump($priKey);
//4.获取公钥$pubKey
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];
var_dump($pubKey);
//5.需要加密的字符串
$data = 'plaintext data goes here';
//6.使用公钥加密字符串 获取加密后的字符串$encrypted
openssl_public_encrypt($data, $encrypted, $pubKey);
//7.使用私钥解密字符串 获取解密后的字符串$decrypted
openssl_private_decrypt($encrypted, $decrypted, $priKey);
var_dump($decrypted);<file_sep><?php
/**
* 导出Excel
* @author 14485 2020-03-26
*/
function export_inspect_log(){
error_reporting(0);
//主体数据
$inspect_log = require_once './data.php';
//数据字段
$index_field = ['inspect_grade','spot_grade', 'apply_no', 'po', 'sku', 'inspect_type', 'dev_imgs', 'inspect_detail_address', 'title_cn', 'devp_type', 'supplier_name',
'real_purchase_num', 'real_collect_num', 'unqualify_num', 'short_supply_num', 'is_abnormal', 'inspector', 'product_inspect_time', 'applicant', 'purchase_apply_time',
'unqualify_type', 'unqualify_reason', 'improve_measure', 'inspect_remark', 'duty_dept', 'duty_user', 'is_lead_inspect', 'inspect_result'];
//单元格列
$unit_title = ['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', 'AA', 'AB'];
//头部列标题
$title = ['验货等级','抽检等级','验货编号','采购单号','sku','验货类型','商品图片','验货区域','商品名称','开发类型','供应商名称',
'有效采购数量','实收数量','不良数','缺货数量','是否异常','验货员','验货时间','申请人','申请时间','不良类型','不良原因','改善措施',
'验货备注','责任部门','责任人','是否组长验货','验货结果'];
$head_data = array_combine($unit_title,$title);
//引入PHP EXCEL类
require APPPATH . "third_party/PHPExcel.php";
require APPPATH . "third_party/Handle_Excel.php";
$objPHPExcel = new PHPExcel();
$handle_excel = new Handle_Excel();
$handle_excel->excel_init_set($objPHPExcel);//初始设置
//设置Excel表的头部列标题
foreach ($head_data as $k => $v) {
if(in_array($k,$unit_title)){
$objPHPExcel->getActiveSheet()->setCellValue($k . 1, $v);//设置标题
}
}
//设置Excel表的数据内容
$startRow = 2;
foreach ($inspect_log as $row){
foreach ($index_field as $key =>$value){
$objPHPExcel->getActiveSheet()->setCellValue($unit_title[$key].$startRow, $row[$value].'\t');
}
$objPHPExcel->getActiveSheet()->getRowDimension($startRow)->setRowHeight(30);//设置每列宽度
$startRow++;
}
//Excel表在浏览器输出
$file_name = 'inspect_report_' . date('YmdHis') . '.xls';
$write = new PHPExcel_Writer_Excel2007($objPHPExcel);
header("Pragma: public");
//header("Expires: 0");
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type:application/vnd.ms-execl");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");
header("Content-Disposition:attachment;filename=" . $file_name);
header("Content-Transfer-Encoding:binary");
ob_clean();
$write->save('php://output');
}
<file_sep><?php
function export_excel($heads, $datalist, $filename, $field_img_name = array('图片'), $field_img_key = array('')){
set_time_limit(0);
ini_set('memory_limit', '500M');
ini_set('post_max_size', '500M');
ini_set('upload_max_filesize', '1000M');
header( "Content-Type: application/vnd.ms-excel; name='excel'" );
header( "Content-type: application/octet-stream" );
header( "Content-Disposition: attachment; filename=".$filename );
header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
header( "Pragma: no-cache" );
header( "Expires: 0" );
$str = "<html xmlns:c=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"
\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type
content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>";
$str .="<style>tr{height: 50px;}</style>";
$str .="<table border=1>";
$str .= "<tr>";
$line_arr = array();
foreach ($heads as $line => $title) {
if (in_array($title, $field_img_name)) {
$line_arr[] = $line;
$str .= "<th width='50'>{$title}</th>";
} else {
$str .= "<th>{$title}</th>";
}
}
foreach ($datalist as $key=> $rt )
{
$str .= "<tr>";
foreach ( $rt as $k => $v )
{
if ((in_array($k, $line_arr) || in_array($k, $field_img_key))) {
$str .= "<td><img src='{$v}' width='50' height='50' /></td>";
} elseif(is_numeric($v) && strlen($v) > 9) {
$str .= "<td width='300' style='vnd.ms-excel.numberformat:@'>".$v."</td>";
}else{
if( is_array($v))
{
continue;
}
$str .= "<td style='vnd.ms-excel.numberformat:@'>{$v}</td>";
}
}
$str .= "</tr>\n";
}
$str .= "</table></body></html>";
$str = str_replace(",","",$str);
exit( $str );
}
//主体数据
$inspect_log = require_once './data.php';
//头部列标题
$title =['验货等级','抽检等级','验货编号','采购单号','sku','验货类型','商品图片','验货区域','商品名称','开发类型','供应商名称',
'有效采购数量','实收数量','不良数','缺货数量','是否异常','验货员','验货时间','申请人','申请时间','不良类型','不良原因','改善措施',
'验货备注','责任部门','责任人','是否组长验货','验货结果'];
//Excel图片列标题
$field_img_name = array('商品图片');
//图片字段
$field_img_key = array('dev_imgs');
//文件名
$file_name = 'inspect_report_' . date('YmdHis') . '.xls';
export_excel($title,$inspect_log,$file_name,$field_img_name,$field_img_key);
<file_sep><?php
getcwd();//获取当前工作目录路径<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py
# 第一个注释
# print ("11")
#import winsound
#winsound.Beep(600,1000)
#import easygui
#easygui.msgbox('Hello World')
#引入库
import pyaudio
import wave
import sys
#定义数据流块
chunk = 1024
#只读方式打开wav文件
f = wave.open(r"./8868.wav","rb")
#f = wave.open(r"./4251.mp3","rb")
p = pyaudio.PyAudio()
#打开数据流
stream = p.open(format = p.get_format_from_width(f.getsampwidth()),
channels = f.getnchannels(),
rate = f.getframerate(),
output = True)
#读取数据
data = f.readframes(chunk)
#播放
while data !="":
stream.write(data)
data = f.readframes(chunk)
#停止数据流
stream.stop_stream()
stream.close()
#关闭 PyAudio
p.terminate()<file_sep><?php
/**
* 扇形交换机
* 该模式下的交换机是广播模式, 交换机会向所有绑定的队列分发消息, 不需要设置交换机和队列的 routing key. 即使设置了, 也会被忽略.
* Fanout模式下不需要指定routing key
*/
//www.try.com/php/rabbitmq/default_exchange/product.php
header('Content-Type: text/html; charset=utf-8');
// 连接设置
$conConfig = [
'host' => '127.0.0.1',
'port' => 5672,
'login' => 'mandelay',
'password' => '<PASSWORD>***',
'vhost' => 'test_host'
];
try {
// RabbitMQ 连接实例
$con = new AMQPConnection($conConfig);
// 发起连接
$con->connect();
// 判断连接是否仍然有效
if (!$con->isConnected()) {
echo '连接失败';
die;
}
// 新建通道
$channel = new AMQPChannel($con);
//通过通道创建及声明扇形交换机(广播模式)
$exchange_name = 'test_fanout'; //交换机名称
$exchange = new AMQPExchange($channel);
$exchange ->setName($exchange_name);
$exchange ->setType(AMQP_EX_TYPE_FANOUT);
$exchange ->setFlags(AMQP_DURABLE);
$exchange->declareExchange();
//创建及声明队列一
$queue_name_one = 'test.queue1';
$queue_one = new AMQPQueue($channel);
$queue_one->setName($queue_name_one);
$queue_one->setFlags(AMQP_DURABLE);
$queue_one->declareQueue();
$queue_one->bind($exchange_name); // 绑定队列到交换机。Fanout模式下不需要指定routing key,即使指定也会被忽略
//创建及声明队列二
$queue_name_two = 'test.queue2';
$queue_two = new AMQPQueue($channel);
$queue_two->setName($queue_name_two);
$queue_two->setFlags(AMQP_DURABLE);
$queue_two->declareQueue();
$queue_two->bind($exchange_name); // 绑定队列到交换机。Fanout模式下不需要指定routing key,即使指定也会被忽略
for ($i = 1; $i <= 6; $i++) {
$message = [
'name' => '默认交换机,消息-' . $i,
'info' => 'Hello World!'
];
// 发送消息,Fanout模式下不需要指定routing key,即使指定也会被忽略
$state = $exchange->publish(json_encode($message, JSON_UNESCAPED_UNICODE));
if ($state) {
echo 'Success' . PHP_EOL;
} else {
echo 'Fail' . PHP_EOL;
}
}
// 关闭连接
$con->disconnect();
} catch (Exception $e) {
echo $e->getMessage();
}<file_sep><?php
/**
* 此锁的局限性: 业务的执行时间必须小于锁的过期时间 如果业务的执行时间大于锁的过期时间 锁过期后自动解锁 其他客户端可以获取锁 而当前的业务还在执行 就不满足锁的互斥性
* 分布式锁 下面是分布式满足条件
* 1.互斥性 在任意时刻 只能有一个客户端持有锁
* 2.不会发生死锁 即使有一个客户端在持有锁的期间程序发生崩溃而没有主动解锁,也能保证后续其他客户端能加锁
* 3.解铃还须系铃人,加锁和解锁必须是同一个客户端,客户端自己不能把别人加的锁给解锁,即不能误解锁
* Class Lock
*/
class Lock_one
{
public $redis;
public $token;
public $lock_pool;
public function __construct()
{
$this->redis = new redisClient();
}
/**
* 获取锁
* @param $key 锁名
* @param int $maxTtl 锁的过期时间还剩余的最大值 即所设置的锁过期时间
* @param $reTryNum 重复获取锁的次数
* @$usleep 时间间隔
* @return bool
*/
public function lock($key, $maxTtl = 10, $reTryNum = 10, $usleep = 10000)
{
//互斥性 在任意时刻 只能有一个客户端持有锁
$getLock = false;
//锁的唯一标识 防止当前客户端解锁了别的客户端加的锁 对于同一个资源加锁 $key是一样的 值要不一样
$this->token = uniqid() . mt_rand(111111111, 999999999);
while ($reTryNum-- > 0) {
// 加锁并保存锁的唯一标识 NX 保证锁的互斥性,EX:保证不会发生死锁 即使程序发生意外 没有主动解锁 也能通过自动过期而解锁
$res = $this->redis->set($key, $this->token, ['NX', 'EX' => $maxTtl]);
if ($res) {
$this->lock_pool[$key] = $this->token;
$getLock = true;
break;
}
usleep($usleep);
}
return $getLock;
}
/**
* 释放锁
* @param $key 锁名
*
* @param $token 锁的唯一标识 防止当前客户端解锁了别的客户端加的锁
*
* @return mixed
*/
public function unlock($key, $token)
{
$script = '
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
';
return $this->redis->eval($script, [$key, $token], 1);
}
}
function secKill(){
$lock = new Lock_one();
$key = "secKill";
//获取锁
if($lock->lock($key,5,2)){
//假设某业务处理耗时过长,发生阻塞10s
sleep(10);
//业务执行完毕释放锁
$lock->unlock($key);
}
}
<file_sep><?php
class PlatformShelfOutGc_model extends Api_base_model
{
const MODULE_NAME = 'ORDER_SYS'; // 模块名称
protected $_baseUrl; // 统一地址前缀
protected $_importUrl; // 导入
protected $_listUrl; // 列表
protected $_addUrl; // 添加
protected $_editUrl; // 编辑
protected $_dropUrl; // 删除
protected $_logUrl; // 日志
protected $_exportUrl; // 导出
//页面头部字段
protected $_tableHeader = array(
'处理时间','仓库','SKU','数量','销售','转入账号名','新标签','货件编号(平台单号)','谷仓订单号','物流单号','配送地址','偏远费','运费','FBA换标费','操作费','操作费按件数','操作费按重量','燃油附加费','杂费燃油附加费','总费用','出库时间','汇率','运输费(RMB)','附加费(RMB)','总费用(RMB)','操作人员','操作时间','操作'
);
public function __construct()
{
parent::__construct();
$this->init();
}
/**
* 导入
* 导入Excel
*/
public function import(array $params) {
$url = $this->_baseUrl . $this->_importUrl;
$result = $this->httpRequest($url, $params, 'POST');
if (empty($result) || !isset($result['status']) || !isset($result['data']))
{
return [false, json_encode($result, JSON_UNESCAPED_UNICODE),null];
}
return [$result['status'],$result['message'],$result['data']];
}
/**
* 创建导出配置任务
* @param array $params
* @return array
*/
public function export(array $params)
{
$url = $this->_baseUrl . $this->_exportUrl;
$result = $this->httpRequest($url, $params, 'POST');
if (empty($result) || !isset($result['status']))
{
return [false, json_encode($result, JSON_UNESCAPED_UNICODE)];
}
return [$result['status'], $result['message']];
}
/**
* 列表页接口
* @return array
*/
public function getList($params = array())
{
// 1.预处理请求参数
$params['page_size'] = !isset($params['page_size']) || intval($params['page_size']) <= 0 ?
$this->_defaultPageSize : intval($params['page_size']);
if (!isset($params['page']) || intval($params['page']) <= 0) {
$params['page'] = 1;
}
// 2.调用接口
$url = $this->_baseUrl . $this->_listUrl;
$url .= '?' . http_build_query($params);
$result = $this->httpRequest($url, '', 'GET');
// 3.确认返回的数据是否与预期一样
if (empty($result) || !isset($result['status']) || !isset($result['data'])) {
$this->_errorMsg = json_encode($result);
return null;
}
if (!empty($result['message'])) {
$this->_errorMsg = $result['message'];
}
if (!$result['status']) {
return null;
}
$data = $result['data'];
// 下拉数据
$dropdownList = !empty($data['drop_down_box']) ? $data['drop_down_box'] : [];
//列表数据
$records = !empty($data['list']) ? $data['list'] : [];
return array(
'data_list' => array(
'key' => $this->_tableHeader,
'value' => $records,
'drop_down_box' => $dropdownList,
),
'page_data' => array(
'offset' => $params['page'],
'limit' => intval($params['page_size']),
'total' => $data['count'],
)
);
}
/**
* 添加一条记录
* @param $params
* @return array
*/
public function addOne($params)
{
$url = $this->_baseUrl . $this->_addUrl;
$result = $this->httpRequest($url, $params, 'POST');
// 确认下返回的数据是否与预期一样
if (empty($result) || !isset($result['status']))
{
return array(false, json_encode($result, JSON_UNESCAPED_UNICODE));
}
return array($result['status'], $result['message']);
}
/**
* 编辑
* @return array
*/
public function editOne($params)
{
// 1.调用接口
$url = $this->_baseUrl . $this->_editUrl;
$result = $this->httpRequest($url, $params, 'POST');
// 确认下返回的数据是否与预期一样
if (empty($result) || !isset($result['status']))
{
return array(false, json_encode($result, JSON_UNESCAPED_UNICODE));
}
return array($result['status'], $result['message']);
}
/**
* 删除一条记录
* @param array $params = array(
* 'ids' => string required 记录ID,多个以逗号隔开
* )
* @return array = array(
* $status => bool 是否成功
* $msg => string 错误信息
* )
* @return array
*/
public function drop(array $params)
{
// 1.调用接口
$url = $this->_baseUrl . $this->_dropUrl;
$result = $this->httpRequest($url, $params, 'POST');
// 2.确认返回的数据是否与预期一样
if (empty($result) || !isset($result['status']))
{
return array(false, json_encode($result, JSON_UNESCAPED_UNICODE));
}
return array($result['status'], $result['message']);
}
}<file_sep><?php
sleep(10);
echo 888888888888;
<file_sep><?php
/**
* Created by PhpStorm.
* User: mandelay
* Date: 12/03/19
* Time: 下午 11:15
*/
ini_set('default_socket_timeout', -1);//永不超时
require_once "redisClient.php";
require_once "tokenBucket.php";
$redis = new redisClient();
//例子(1)
//$redis->redis->set('set mian','pp');
//var_dump($redis->redis->getLastError());
//echo $redis->redis->get('mian');
//例子(2)
//$command = "redis.call('set','key_1',55);redis.call('set','key_2',66); return 'succ';" ;
//$redis->eval_command($command);
//例子(3)
//$command = "redis.call('set',KEYS[1],ARGV[1]);redis.call('set',KEYS[2],ARGV[2]); return 'succ';";
//$value = ['key_1','key_2',88,99];
//$key_num =2;
//$redis->eval_command($command,$value,$key_num);
//var_dump($redis->redis->getLastError()); //获取执行原因错误
//令牌桶
//例子(4)
$redis->redis->del('token_limit');
$bucket = new tokenBucket('token_limit',1,10,60,1);
for ($i=0;$i<60;$i++){
//获取令牌
$result = $bucket->isPass();
if(!$result[0]){
//获取到令牌 方形
echo date("Y-m-d H:i:s").' yes'.PHP_EOL;
}else {
echo date("Y-m-d H:i:s").' no'.PHP_EOL;
}
if($result[3] >=0 ){
//每次休眠 $result[3]+1后 可以确保每次都能拿到令牌
sleep($result[3]+1);
}
}
<file_sep><?php
/**
* 执行并传递参数
* D:\code\sw\php-cli\bin/php one_timer.php -a 7 -b 9
* D:\code\sw\php-cli\bin/sw one_timer.php -a 7 -b 9
*
*
*
*
* kill -9 pid
* dos命令杀死进程命令
* taskkill /F /im php.exe
* taskkill /F /im php-cgi.exe
* taskkill /F /im sw.exe
*
*
* ps -auxf | grep "php-fpm"
*
* 树状查看
* pstree -hap 16791(父进程ID)
*
* dos命令查找进程命令
* tasklist | findstr php.exe
* tasklist | findstr php-cgi.exe
* tasklist | findstr sw.exe
*/
require "../../curl/Curl.php";
$curl = new Curl();
$params = getopt('a:b:');
$ship_company = $params['a'] = 4;
$counter = 0;
$process = new \Swoole\Process(function (\Swoole\Process $process) use ($ship_company, $curl) {
//一分钟以后才会 发出请求
Swoole\Timer::tick(1000, function (int $timer_id) use ($ship_company, $process, $curl) {
//$url = "http://www.tms-b.com/cargoapisys/api/Demo/wet?debug=y";
//$url = "http://192.168.71.141:92/ordersys/console/ShipFee/pullTailData";
//$url = "http://192.168.71.141:92/ordersys/console/ShipFee/getTailFee";
//$url = "http://192.168.71.141:92/ordersys/console/ShipFee/pullHeaderData";
//$url = "http://tmsservice.yibainetwork.com:92/ordersys/console/ShipFee/pullHeaderData";//生产环境
//$url = "http://192.168.71.141:92/ordersys/console/ShipCost/getCost?model=WYT_model";//开发环境
//$url = "http://192.168.31.29:92/ordersys/console/ShipCost/getCost?model=WYT_model"; //本地虚拟机
//$url = "http://192.168.71.195:92//ordersys/console/ShipCost/getCost?model=WYT_model"; //测试环境
$url ="http://tmsservice.yibainetwork.com:92/ordersys/console/ShipCost/getCost?model=WYT_model";//测试环境
$curl->requestByCurlGet($url);
// foreach (range(16,31) as $day){
// if($day < 10){
// $day = '0'.$day;
// }
// $task_day = "2020-10-".$day;
// // http://tmsservice.yibainetwork.com:92/ordersys/console/ShipCost/createTask?company=WYT&start_time=2020-11-01&end_time=2020-11-01&create_date=2020-11-01
// $url = "http://tmsservice.yibainetwork.com:92/ordersys/console/ShipCost/createTask?company=WYT&start_time={$task_day}&end_time={$task_day}&create_date={$task_day}";
// //http://192.168.31.29:92/ordersys/console/ShipCost/createTask?company=WYT&start_time=2020-11-01&end_time=2020-11-01&create_date=2020-11-01
// //$url = "http://192.168.31.29:92/ordersys/console/ShipCost/createTask?company=WYT&start_time={$task_day}&end_time={$task_day}&create_date={$task_day}";
// $curl->requestByCurlGet($url);
// }
// foreach (range(2,16) as $day){
// if($day < 10){
// $day = '0'.$day;
// }
// $task_day = "2020-11-".$day;
// $url = "http://tmsservice.yibainetwork.com:92/ordersys/console/ShipCost/createTask?company=WYT&start_time={$task_day}&end_time={$task_day}&create_date={$task_day}";
// //$url = "http://192.168.31.29:92/ordersys/console/ShipCost/createTask?company=WYT&start_time={$task_day}&end_time={$task_day}&create_date={$task_day}";
// $curl->requestByCurlGet($url);
// }
});
});
$process->start(); // 启动子进程
<file_sep><?php
/**
* 此种模式下,使用 RabbitMQ 的默认 Exchange 即可,默认的 Exchange 是 Direct 模式。
* 使用默认 Exchange 时,不需要对 Exchange 进行属性设置和声明,也不需要对 Queue 进行显示绑定和设置 routing key。
* Queue 默认会绑定到默认 Exchange,以及默认 routing key 与 Queue 的名称相同。
*/
//http://www.try.com/php/rabbitmq/dead_letter_exchange/product.php
header('Content-Type: text/html; charset=utf-8');
// 连接设置
$conConfig = [
'host' => '127.0.0.1',
'port' => 5672,
'login' => 'mandelay',
'password' => '<PASSWORD>***',
'vhost' => 'test_host'
];
try {
// RabbitMQ 连接实例
$con = new AMQPConnection($conConfig);
// 发起连接
$con->connect();
// 判断连接是否仍然有效
if (!$con->isConnected()) {
echo '连接失败';
die;
}
// 新建通道
$channel = new AMQPChannel($con);
//通过通道获取默认交换机,使用RabbitMQ的默认Exchange时 无需进行命名、持久化、设置交换机类型(默认为直连交换机)、申明等操作
$exchange = new AMQPExchange($channel);
$exchange ->setFlags(AMQP_DURABLE);
//创建及声明队列,不需要对Queue进行显示绑定到交换机和指定Queue的routing key 会默认绑定到默认交换机
$queue_name = 'test.queue1';
$queue = new AMQPQueue($channel);
$queue->setName($queue_name);
$queue->declareQueue();
for ($i = 1; $i <= 6; $i++) {
$message = [
'name' => '默认交换机,消息-' . $i,
'info' => 'Hello World!'
];
// 发送消息,为消息指定routing key,使用默认交换机时,routing key与队列名相同 成功返回true,失败false
$routing_key = $queue_name;
$state = $exchange->publish(json_encode($message, JSON_UNESCAPED_UNICODE), $routing_key);
if ($state) {
echo 'Success' . PHP_EOL;
} else {
echo 'Fail' . PHP_EOL;
}
}
// 关闭连接
$con->disconnect();
} catch (Exception $e) {
echo $e->getMessage();
}<file_sep><?php
/**
* www.try.com/php/rabbitmq/header_exchange/product.php
* 此模式下,消息的routing key 和队列的 routing key 会被完全忽略,而是在交换机推送消息和队列绑定交换机时, 分别为消息和队列设置 headers 属性, 通过匹配消息和队列的 header 决定消息的分发.
*/
//www.try.com/php/rabbitmq/default_exchange/product.php
header('Content-Type: text/html; charset=utf-8');
// 连接设置
$conConfig = [
'host' => '127.0.0.1',
'port' => 5672,
'login' => 'mandelay',
'password' => '<PASSWORD>***',
'vhost' => 'test_host'
];
try {
// RabbitMQ 连接实例
$con = new AMQPConnection($conConfig);
// 发起连接
$con->connect();
// 判断连接是否仍然有效
if (!$con->isConnected()) {
echo '连接失败';
die;
}
// 新建通道
$channel = new AMQPChannel($con);
//通过通道创建及声明主题交换机(头部模式)
$exchange_name = 'test_header'; //交换机名称
$exchange = new AMQPExchange($channel);
$exchange->setName($exchange_name);
$exchange->setType(AMQP_EX_TYPE_HEADERS);
$exchange->setFlags(AMQP_DURABLE);
$exchange->declareExchange();
//创建及声明队列一
$queue_name_one = 'test.queue1';
$queue_one = new AMQPQueue($channel);
$queue_one->setName($queue_name_one);
$queue_one->setFlags(AMQP_DURABLE);
$queue_one->declareQueue();
//绑定队列到交换机。head模式需要给routing key指定一个值 (routing key的值 可以是任意值,包括null 一般指定和队列名一致) 但不起什么实际作用,
//$routing_key = $queue_name_one;
$routing_key = null;
//设定队列的header信息,x-match:all 全匹配,消息的header信息与队列的header信息必须完全匹配
$header_one = ['x-match'=>'all', 'type'=>'even', 'color'=>'red'];
$queue_one->bind($exchange_name,$routing_key,$header_one);
//创建及声明队列二
$queue_name_two = 'test.queue2';
$queue_two = new AMQPQueue($channel);
$queue_two->setName($queue_name_two);
$queue_two->setFlags(AMQP_DURABLE);
$queue_two->declareQueue();
//绑定队列到交换机。head模式需要给routing key指定一个值 (routing key的值 可以是任意值,包括null 一般指定和队列名一致) 但不起什么实际作用,
//$routing_key = $queue_name_two;
$routing_key = null;
//设定队列的header信息,x-match:any:消息的headers消息与队列header信息的任意一项匹配即可
$header_two = ['x-match'=>'any', 'type'=>'odd', 'color'=>'red'];
$queue_two->bind($exchange_name,$routing_key,$header_two);
for ($i = 1; $i <= 10; $i++) {
$message = [
'name' => '默认交换机,消息-' . $i,
'info' => 'Hello World!'
];
//指定消息的header信息
$message_header['headers'] = $i%2==0 ? ['type'=>'even','color'=>'green'] : ['type'=>'odd','color'=>'green'];
$routing_key = null;
$state = $exchange->publish(json_encode($message, JSON_UNESCAPED_UNICODE),$routing_key,AMQP_NOPARAM,$message_header);
if ($state) {
echo 'Success' . PHP_EOL;
} else {
echo 'Fail' . PHP_EOL;
}
}
// 关闭连接
$con->disconnect();
} catch (Exception $e) {
echo $e->getMessage();
}<file_sep><?php
/**
* Created by PhpStorm.
* User: mandelay
* Date: 18/04/19
* Time: 下午 11:23
*/
git@192.168.74.105:/var/local/git/sample.git;
<file_sep><?php
use php\oop\first;
use php\oop\second;
use php\oop\third;
use php\oop\outoload;
require_once '../../outoload.php';
ini_set('display_errors','on');
error_reporting(-1);
$first = new first();
$first->who();
$first->identity();
$second = new second();
$second->who();
$second->identity();
<file_sep><?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://udeskdemo8732.udesk.cn/open_api_v1/log_in",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_SSL_VERIFYPEER=>0, //服务端不验证ssl证书
CURLOPT_SSL_VERIFYHOST=>0, //服务端不验证ssl证书
CURLOPT_POSTFIELDS => "{\r\n \"email\": \"<EMAIL>\",\r\n \"password\": \"<PASSWORD>\"\r\n}",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json",
"Postman-Token: <PASSWORD>",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
<file_sep><?php
$br='<br>';
echo 'kk\\kk\'88\'';
echo $br;
echo 'kkk"88"';
echo $br;
echo 'pp\\n88';
echo $br;
echo "pp\r\n88";
echo $br;
echo "pp".$br."88";
echo $br;
echo "pp{$br}88";
echo $br;
echo $br;<file_sep><?php
/**
* 说明:本类只使用php7的MongoDB扩展 不适用php5
* Class Mongodb
*/
class Mongodb{
//插入数据
public function insert($data){
try{
$bulk = new MongoDB\Driver\BulkWrite();
$result = $bulk->insert($data);
$id = '';
foreach($result as $key => $val){
if($key == 'oid'){
$id = $val;
}
}
if($id){
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$manager = new MongoDB\Driver\Manager ('mongodb://root:root@localhost:27017');
$result = $manager->executeBulkWrite('test.listing', $bulk, $writeConcern);//test 为数据库 listing为集合
if($result->getInsertedCount()){
return $id;
}else{
return false;
}
}else{
return false;
}
}catch (MongoDB\Driver\InvalidArgumentException $e){
echo "插入失败: ".$e->getMessage();
}
}
//删除
public function delete($where){
try{
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->delete($where,array('limit'=>1));// limit 为 1 时,删除第一条匹配数据; limit 为 0 时,删除所有匹配数据
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$manager = new MongoDB\Driver\Manager ('mongodb://root:root@localhost:27017');
$result = $manager->executeBulkWrite('test.listing', $bulk, $writeConcern);//test 为数据库 listing为集合
return $result->getDeletedCount();
}catch (MongoDB\Driver\InvalidArgumentException $e){
echo "删除失败: ".$e->getMessage();
}
}
//更新
public function update($where,$data,$upsert = false){
try{
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->update($where,array('$set' => $data), array('multi' => true, 'upsert' => $upsert)); //multi=>true 更新所有匹配到的数据 multi=>false 只更新一条数据
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$manager = new MongoDB\Driver\Manager ('mongodb://root:root@localhost:27017');
$result = $manager->executeBulkWrite('test.listing', $bulk, $writeConcern);//test 为数据库 listing为集合
return $result->getModifiedCount();
}catch (MongoDB\Driver\InvalidArgumentException $e){
echo "跟新失败: ".$e->getMessage();
}
}
//查询数据
public function query($where,$options){
$query = new MongoDB\Driver\Query($where, $options);
$manager = new MongoDB\Driver\Manager('mongodb://root:root@localhost:27017');
$cursor = $manager->executeQuery('test.listing', $query);//test 为数据库 listing为集合
$returns = array();
foreach ($cursor as $doc)
{
unset($doc->_id);
$returns[] = (array)$doc;
}
return $returns;
}
}
<file_sep><?php
/**
* 也可使用于一维关联数组
* 比较两个数组的键名,并返回差集:array_diff_key
* 比较两个数组的键名,并返回交集:array_intersect_key
*/
function array_diff_intersect_key(){
$a1=array("a"=>['age'=>188,'core'=>145],"b"=>['age'=>188,'core'=>999],"c"=>['age'=>188,'core'=>145],"d"=>['age'=>168,'core'=>555]);
//$a2=array("a"=>['age'=>288,'core'=>245],"c"=>['age'=>288,'core'=>245],"b"=>['age'=>288,'core'=>245]);
$a2=array("a"=>['age'=>298,'core'=>245],"c"=>['age'=>288,'core'=>225]);
//第一个参数中出现的key 其他参数中未出现的key 返回的值从第一个数组取
// $result_diff = array_values(array_diff_key($a1,$a2));
// print_r($result_diff);die;
//第一个参数中出现的key 其他参数中都出现的key 返回的值从第一个数组取
$result_intersect = array_intersect_key($a1,$a2);
print_r($result_intersect);
print_r(array_values($result_intersect));die;
}
print_r(array_diff_intersect_key());die;
/**
* php list()
*/
function list_test(){
// list函数是用数组对一列值进行赋值,该函数只用于数字索引的数组,且假定数字索引从0开始。(这句话很重要,是从索引0开始为变量赋值,如果对应的数字索引不存在,则对应位的变量也为空值。)
$arr = [[11,45],'kkk']; // 必须为索引数组
list($list,$gids) = $arr;
var_dump($list,$gids);die;
}
/**
* array_column()
*/
function array_column_test(){
$arr = [
[
'id' => 1,
'name' => 'a'
],
[
'id' => 2,
'name' => 'b',
],
[
'id' => 4,
'name' => 'c'
],
[
'id' => 3,
'name' => 'd'
]
];
print_r(array_column($arr,'name'));
//运行结果:Array ( [0] => a [1] => b [2] => c [3] => d )
print_r(array_column($arr,'name','id'));
//运行结果:Array ( [1] => a [2] => b [4] => c [3] => d )
print_r(array_column($arr, null, 'name'));
//运行结果:Array ( [a] => Array ( [id] => 1 [name] => a ) [b] => Array ( [id] => 2 [name] => b ) [c] => Array ( [id] => 4 [name] => c ) [d] => Array ( [id] => 3 [name] => d ) )
}
/**
* 只能是一维关联数组
* 只有在第一个数组中出现,且在所有其他输入数组中也出现的键/值对才返回到结果数组中 键和值都必须一样
* 关联数组的交集 array_intersect_assoc()
*/
function array_intersect_assoc_test(){
$fruit1 = array("red"=>"Apple","yellow"=>"Banana","orange"=>"Orange");
$fruit2 = array("yellow"=>"Pear","red"=>"Apple","purple"=>"Grape");
$fruit3 = array("green"=>"Watermelon","orange"=>"Orange","red"=>"Apple");
$intersection = array_intersect_assoc($fruit1, $fruit2, $fruit3);
var_dump($intersection);
}
/**
* 匿名义函数处理 给定数组键值对中的值
* array_walk()
*/
function array_walk_test(){
$a = ['a'=>3,'b'=>4];
$out = 3;
$key = "d";
array_walk($a,function (&$v,$k,$out){
$v = $v*$out;
},$out);
print_r($a);
}
/**
* 把第一个参数作为回调函数调用
* call_user_func()
*/
function call_user_func_test(){
}
function sprintf_test(){
$tracking_number = 'DD';
$app_key = 'FF';
$app_password= 'SS';
sprintf('/PrintPDFLableServlet.xsv?serverewbcode=%s&username=%s&password=%s',$tracking_number,$app_key,$app_password);
}<file_sep><div>
<div id = "array" style="display:block; width: 49.5%">
<?php
echo json_encode(trim($_POST['str'],'"'));
?>
</div>
</div>
<file_sep><?php
header("content-type:text/html;charset=utf-8");
$order = "C:\Users\Yibai\AppData\Local\Programs\Python\Python37\pythonw.exe .\\test.py";
echo shell_exec($order);
//die(shell_exec($order));<file_sep><?php
/**
* 1、 一直执行到 $pool->start() 这里 就会有10个进程产生
* 2、只要这段程序在运行 就会一直保持进程池 有10个进程 其中有进程执行完退出 还会有新的进程产生补充已经退出的进程
*/
$workerNum = 10; //设置10个进程
$pool = new Swoole\Process\Pool($workerNum,SWOOLE_IPC_UNIXSOCK, 0, true);
$pool->on("WorkerStart", function (Swoole\Process\Pool $pool, $workerId) {
//$process = $pool->getProcess();
echo "time: ".time()."; workID: '.$workerId\n";
$redis = new Redis();
$redis->connect('192.168.71.141',7001);
$redis->auth('yis@2019._');
$redis->select(9);
$key = "key_queue";
$msgs = $redis->lPush($key, $workerId);
var_dump($msgs);
});
$pool->on("WorkerStop", function ($pool, $workerId) {
echo "Worker#{$workerId} is stopped\n";
});
$pool->start();
<file_sep><?php
namespace php\oop;
class first{
public function __construct()
{
$this->who();
}
public function identity(){
$this->who();
}
public function who(){
echo 'first';
}
}
<file_sep><?php
namespace php\oop;
use php\oop\first;
class second extends first {
public function who(){
echo 'second';
}
}<file_sep><?php
namespace php\oop;
use php\oop\first;
class third extends first {
public function who(){
echo 'third'.'<br>';
}
}<file_sep><?php
require 'Curl.php';
$url = 'https://www.googleapis.com/oauth2/v4/token';
$curl = new Curl();
const CLIENT_ID = '824205327910-8lldk1bumj122tgcsk5u2a0prikc3pav.apps.googleusercontent.com';
const CLIENT_SECRET = '<KEY>';
const REDIRECT_URI = 'https://image-us.bigbuy.win/google/token'; #需要在开发者应用中配置该url
$auth_code = '<KEY>';
$param = array(
'code' => $auth_code,
'client_id' => CLIENT_ID,
'client_secret' => CLIENT_SECRET,
'redirect_uri' => REDIRECT_URI,
'grant_type' => 'authorization_code'
);
$header = array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Type' => 'application/json'
);
$data_json = json_encode($param);
$result = $curl->requestCurl($url,$header,$data_json);
print_r($result);die;
<file_sep><?php
require './xmlReader.php';
require './xmlWrite.php';
function read(){
$xml = new cdXmlReader();
$content = file_get_contents('./1.xml');
$result = $xml->fromString($content);
file_put_contents('./1.php',"<?php\n".'return '.var_export($result, true).";\n\n?>");
print_r($result);die;
}
function write(){
$data = array(
'user' => array(
'attr'=>array('xing' =>'chen','ming' =>'lei'),
'value'=>'月光光abcd'
),
'pvs' => array('value'=>'888888'),
'date' => array('value'=>'2016-08-29'),
'info'=>array(
'attr'=>array('xing' =>'chen','ming' =>'lei'),
'value'=>array(
'age'=>array('value'=>'10'),
'sex'=>array('value'=>'man')
)
)
);
$xml = new xmlWrite();
$result = $xml->writer_2($data);
file_put_contents('./3.xml',$result.PHP_EOL,FILE_APPEND);
}
function writer(){
$data = array(
'user' => array(
'attr'=>array('xing' =>'chen','ming' =>'lei'),
'value'=>'月光光abcd'
),
'pvs' => array('value'=>'888888'),
'date' => array('value'=>'2016-08-29'),
'info'=>array(
'attr'=>array('xing' =>'chen','ming' =>'lei'),
'value'=>array(
'age'=>array('value'=>'10'),
'sex'=>array('value'=>'man'),
'hobby'=>array(
'attr'=>array('define'=>'自定义'),
'value'=>array(
'read'=>array('value'=>'xiyouji'),
'music'=>array('value'=>'tiantang'),
)
)
)
)
);
$xml = new xmlWrite();
$xml->writer_3($data);
}
//read();
writer();
<file_sep><?php
class PlatformShelfOutGc extends MY_ApiBaseController
{
private $_modelObj;
public function __construct()
{
parent::__construct();
$this->load->model('order_sys/PlatformShelfOutGc_model');
$this->_modelObj = $this->PlatformShelfOutGc_model;
}
/**
*
* 导入
* www.tms-f.com/api/platformShelfOutGc/import
*/
public function import(){
$this->load->library('journal_helper');
$subdir = "journal/platform_shelf_out_gc/import/".date("Ym", time()).'/';
list($status, $data) = $this->journal_helper->doUpload($subdir);
if (!$status) {
$this->_code = $this->getServerErrorCode();
$this->_msg = $this->lang->line('upload_error') . $data;
$this->sendData();
}
$params = ["file_path"=>$data['file_name']];
list($status,$msg,$result) = $this->_modelObj->import($params);
if (!$status) {
$this->_code = $this->getServerErrorCode();
$this->_msg = $msg;
}
$this->sendData($result);
}
/**
* 下载导入失败列表
* http://www.tms-f.com/api/platformShelfOutGc/download
*/
public function download(){
$params = gp();
$file_path = $params['file_path'];
$this->load->library('journal_helper');
$filename = '平台仓换标登记表之FB4上架出库导入失败列表.csv';
if(!file_exists($file_path)){
$file_fail_path = APPPATH.'/upload/template/download_file_not_find.csv';
$this->journal_helper->download($file_fail_path,$filename);
}else{
$this->journal_helper->download($file_path,$filename);
}
}
/**
* 列表
* www.tms-f.com/api/platformShelfOutGc/index
*/
public function index()
{
$params = $this->_requestParams;
// 一起返回下拉数据
$data = $this->_modelObj->getList($params);
if (is_null($data))
{
$this->_code = $this->getServerErrorCode();
$this->_msg = $this->_modelObj->getErrorMsg();
}
$this->sendData($data);
}
/**
* 新增
* www.tms-f.com/api/platformShelfOutGc/addOne
*/
public function addOne()
{
$params = $this->_requestParams;
$params['add_data'] = '[
{
"warehouse_name": "出口易英国仓",
"sku": "JM9999_01",
"amount": "12",
"seller_name": "张珊11",
"account_name": "IN_ACCOUT_01",
"new_tag": "儿童",
"platform_order_id": "407-4307883-8197155",
"gc_no": "gc_8888999666",
"tracking_number": "WELED9345000625YQ",
"ship_address": "dsklf kkkkk ljkj dslfdslfj",
"far_fee": "0.560",
"ship_fee": "0.56",
"fba_change_fee": "6.00",
"operate_fee": "0.53",
"operate_piece_fee": "2.13",
"operate_weight_fee": "2.40",
"fuel_fee": "1.51",
"mix_fuel_fee": "0.20",
"total_fee": "13.89",
"inbound_time": "2020-05-30",
"exchange_rate": "6.5000",
"rmb_ship_fee": "39.00",
"surcharge": "0.00",
"rmb_total_fee": "129.29",
"handle_time": "2020-05-30"
},
{
"warehouse_name": "出口易英国仓",
"sku": "JM9999_02",
"amount": "10",
"seller_name": "张珊",
"account_name": "IN_ACCOUT_01",
"new_tag": "儿童",
"platform_order_id": "407-4307883-8197155",
"gc_no": "gc_8888999666",
"tracking_number": "WELED9345000625YQ",
"ship_address": "dsklf kkkkk ljkj dslfdslfj",
"far_fee": "0.560",
"ship_fee": "0.56",
"fba_change_fee": "6.00",
"operate_fee": "0.53",
"operate_piece_fee": "2.13",
"operate_weight_fee": "2.40",
"fuel_fee": "1.51",
"mix_fuel_fee": "0.20",
"total_fee": "13.89",
"inbound_time": "2020-05-30",
"exchange_rate": "6.5000",
"rmb_ship_fee": "39.00",
"surcharge": "0.00",
"rmb_total_fee": "129.29",
"handle_time": "2020-05-30"
},
{
"warehouse_name": "出口易英国仓",
"sku": "JM9999_03",
"amount": "10",
"seller_name": "张珊",
"account_name": "IN_ACCOUT_01",
"new_tag": "儿童",
"platform_order_id": "407-4307883-8197155",
"gc_no": "gc_8888999666",
"tracking_number": "WELED9345000625YQ",
"ship_address": "dsklf kkkkk ljkj dslfdslfj",
"far_fee": "0.560",
"ship_fee": "0.56",
"fba_change_fee": "6.00",
"operate_fee": "0.53",
"operate_piece_fee": "2.13",
"operate_weight_fee": "2.40",
"fuel_fee": "1.51",
"mix_fuel_fee": "0.20",
"total_fee": "13.89",
"inbound_time": "2020-05-30",
"exchange_rate": "6.5000",
"rmb_ship_fee": "39.00",
"surcharge": "0.00",
"rmb_total_fee": "129.29",
"handle_time": "2020-05-30"
}
]';
list($status, $msg) = $this->_modelObj->addOne($params);
if (!$status)
{
$this->_code = $this->getServerErrorCode();
}
$this->_msg = $msg;
$this->sendData();
}
/**
* 编辑
* www.tms-f.com/api/platformShelfOutGc/editOne
*/
public function editOne()
{
$params = $this->_requestParams;
$params['id'] =48;
$params['edit_data'] ='{
"warehouse_name": "出口易英国仓",
"sku": "JM9999_01",
"amount": "10",
"seller_name": "张珊",
"account_name": "IN_ACCOUT_01",
"new_tag": "儿童",
"platform_order_id": "407-4307883-8197155",
"gc_no": "gc_8888999666",
"tracking_number": "WELED9345000625YQ",
"ship_address": "dsklf kkkkk ljkj dslfdslfj",
"far_fee": "0.560",
"ship_fee": "0.56",
"fba_change_fee": "6.00",
"operate_fee": "0.53",
"operate_piece_fee": "2.13",
"operate_weight_fee": "2.40",
"fuel_fee": "1.51",
"mix_fuel_fee": "0.20",
"total_fee": "13.89",
"inbound_time": "2020-05-30",
"exchange_rate": "6.5000",
"rmb_ship_fee": "39.00",
"surcharge": "0.00",
"rmb_total_fee": "129.29",
"handle_time": "2020-05-30"
}';
list($status, $msg) = $this->_modelObj->editOne($params);
if (!$status)
{
$this->_code = $this->getServerErrorCode();
}
$this->_msg = $msg;
$this->sendData();
}
/**
* 删除记录(支持批量删除)
* www.tms-f.com/api/platformShelfOutGc/drop
*/
public function drop()
{
$params = $this->_requestParams;
//$params['gc_no'] = 'gc_8888999444,gc_8888999333';
list($status, $msg) = $this->_modelObj->drop($params);
if (!$status)
{
$this->_code = $this->getServerErrorCode();
}
$this->_msg = $msg;
$this->sendData();
}
/**
* 操作日志
* www.tms-f.com/api/platformShelfOutGc/actionLog
*/
public function actionLog()
{
$params = $this->_requestParams;
$data = $this->PlatformShelfOutGc_model->getActionLog($params);
$this->sendData($data);
}
/**
* 创建导出任务
* http://www.tms-f.com/api/platformShelfOutGc/export
*/
public function export()
{
// 支持GET参数,方便测试
$params = array_merge($this->input->get(), $this->_requestParams);
$params['gc_no'] = "gc_8888999333,gc_8888999444,gc_8888999666";
list($status, $msg) = $this->_modelObj->export($params);
if (!$status)
{
$this->_code = $this->getServerErrorCode();
}
$this->_msg = $msg;
$this->sendData();
}
/**
* 下载导入模板(前端需要传入参数指明 渠道业务类型 下载相应的模板)
* http://www.tms-f.com/api/platformShelfOutGc/downloadTpl
*/
public function downloadTpl()
{
$params = $this->_requestParams;
$params['page_size'] = 1;
$result = $this->_modelObj->getList($params);
$titleTpl = array_keys($result['data_list']['drop_down_box']['template_title']);
$filedTitle = array_flip($result['data_list']['drop_down_box']['template_title']);
$this->load->helper('Excel');
$excelHelper = new Excel_helper('write_row');
$excelHelper->writeRow(1, 1, $titleTpl);
$lastRow = chr(65 + count($titleTpl) - 1);
$excelHelper->getExcelObj()->getActiveSheet()->getStyle('A1:' . ($lastRow . '1'))->applyFromArray(
array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => '008000') // 绿色
)
)
);
$data = $result['data_list']['value'];
$row = 2;
foreach ($data as $k => $item)
{
array_walk($filedTitle,function (&$v,$k,$item){
$v = $item[$k];
},$item);
$row = $row +$k;
$col = $k+1;
$excelHelper->writeRow($row, $col, $filedTitle);
}
$excelHelper->download("物流轨迹拉取配置导入模板.xlsx");
}
}<file_sep><?php
require './Mongodb.php';
$mongo = new Mongodb();
save($mongo);
// del($mongo);
// up($mongo);
// select($mongo);
//新增数据
function save($mongo){
$data = array(
'account_id'=>308,
'item_id'=>date('Y-m-d H:i:s')
);
$result = $mongo->insert($data);
var_dump($result);
}
//删除数据
function del($mongo){
$where = array('account_id'=>308);
//$where = array('account_id'=>['$gt'=>0]); // account_id >0
$result= $mongo->delete($where);
var_dump($result);
}
//更新数据
function up($mongo){
$where = array('account_id'=>300);
//$where = array('account_id'=>['$gt'=>0]); // account_id >0
$data = array('item_id'=>99);
$result= $mongo->update($where,$data);
var_dump($result);
}
//查询实例
function select($mongo){
$where = array('account_id'=>300);
//$where = array('account_id'=>array('$gt'=>0));// account_id >0
$options = array(
//相当于mysql的offset
'skip' =>0,
//排序 -1 降序 1 升序
'sort' =>array('account_id'=> -1),
//相当于mysql的limit
'limit' => 999999999999,
//要查询的字段
'projection' => array(
'_id' => 1,
'item_id' => 1,
'account_id' => 1
),
);
$result = $mongo->query($where,$options);
print_r($result);
}
<file_sep><?php
define('APPPATH','../try/log/');
require "Lock.php";
file_put_contents(APPPATH.'/lock.txt',"110 start fpid:".posix_getpid().PHP_EOL.PHP_EOL,FILE_APPEND);
/**
* 悲观锁测试
*/
function test(){
file_put_contents(APPPATH.'/lock.txt',"111 start fpid:".posix_getpid().PHP_EOL.PHP_EOL,FILE_APPEND);
$lock = new Lock();
$key = "secKill";
//获取锁
if($lock->lock($key,10,2)){
//假设某业务处理耗时过长,发生阻塞30s
for($i=0;$i<30;$i++){
// if($i == 45){
// file_put_contents(APPPATH.'/lock.txt'," 主进程意外死亡: time: ".microtime().PHP_EOL.PHP_EOL,FILE_APPEND);
// die();
// }
sleep(1);
}
//业务执行完毕释放锁
$lock->unlock($key);
}
}
test();
<file_sep><?php
require 'Curl.php';
$curl = new Curl();
$url = "http://hq.sinajs.cn/list=sh519096";
$url = "http://www.tms-b.com/tracksys/logistics/logisticsPullConfig/index?__withList=logisticsList&page_size=1&page=1";
$result = $curl->requestByCurlGet($url);
print_r($result);die;
$data = json_decode($result,true);
file_put_contents('./1.php',"<?php\n".'return '.var_export($data['data'], true).";\n\n?>",FILE_APPEND);
<file_sep><?php
/**
* Created by PhpStorm.
* User: mandelay
* Date: 30/03/19
* Time: 上午 10:23
*/
include('function.php');
class order {
const APL_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";//统一下单接口
const APL_QUERY = "https://api.mch.weixin.qq.com/pay/orderquery";//查询接口
/**
*
* 调用微信统一下单接口获取获取预支付信息 其中code_url字符串用于生成支付二维码
* @param $params
*/
public function prepare($params){
$params['nonce_str'] = uniqid();
$params['sign'] = generateSign($params,KEY);
$xml=toXml($params); //获取xml的请求参数
$result = http_request(self::APL_URL,$xml);
return xmlToArray($result);
}
public function query_order($params){
$params['nonce_str'] = uniqid();
$params['sign'] = generateSign($params,KEY);
$xml=toXml($params); //获取xml的请求参数
$result = http_request(self::APL_QUERY,$xml,false);
return xmlToArray($result);
}
}<file_sep><?php
/**
* sw crontab.php
*/
require './timer.php';
//$jobs[0] = new timer("0,30 18-23 * * * index.php");
$jobs[0] = new timer("* * * * *","ordersys/console/ShipCost/getQueue");
swoole_timer_tick(1000, function($timeId, $params = null) use ($jobs, &$prevTime) {
$current = time();
//week, month, day, hour, min
$ref = explode('|', date('w|n|j|G|i', $current));
if ($prevTime) {
$prevMin = date('i', $prevTime);
if ($prevMin == $ref[4]) {
return true;
}
}
foreach ($jobs as $task) {
$ready = 0;
//$diff = $task->getTimeAttribute('runTime') - $current;
//对应上面的$ref数组
foreach (['week', 'month', 'day', 'hour', 'min'] as $key => $field) {
$value = $task->getTimeAttribute($field);
if ($value === '*') {
$ready += 1;
continue;
}
$ready += in_array($ref[$key], $value) ? 1: 0;
}
if (5 === $ready) {
//执行任务
$task->run_curl();
//$task->run_cli();
//更新运行时间
$task->setRunTime($current);
}
}
$prevTime = $current;
return true;
//swoole_timer_clear($timeId);
});
<file_sep><?php
$edit_before_data = require './4.php';
$edit_after_data = require './3.php';
$compare_field = [
'sample_link',//采集链接
'supplier_code' ,//供应商
'title_cn',//标题
'product_category_id',// 分类
'material_cn',//商品材质
'use_cn',//商品用途
'key_words',//关键词
'sale_points',//买点
'pack_list',//todo: 包装清单
'product_brand_attr',//品牌属性
'product_brand_id',//产品品牌
'is_logo',//有无logo
'spu_logistics_attr',//物流属性
'sku_info',//sku属性
'sku_pack_info',//sku属性
];
$compare_special_field = [
'spu_logistics_attr' => [
'net_weight',
'gross_weight',
'size',
],
'sku_info'=>[],
'sku_pack_info'=>[],
];
function compare_diff($edit_before_data,$edit_after_data,$compare_field,$compare_special_field){
$diff = [];
foreach ($compare_field as $filed){
// var_dump($filed);echo "<br>";
$before = $edit_before_data[$filed]??null;
$after = $edit_after_data[$filed]??null;
// print_r($after);echo "<br>";
//字段值为 字符串
if(is_string($before) && is_string($after) && ($before!==$after)){
$diff[$filed] = $before;
}
// 字段值为 一维数组
if(!array_key_exists($filed,$compare_special_field) && is_array($before) && is_array(json_decode($after,true))){
$after = json_decode($after,true);
if(count($before) != count($after)){
$diff[$filed] = implode(',',$before);
}else{
$data = array_diff($before,$after);
if(!empty($data)){
$diff[$filed] = implode(',',$before);
}
}
}
//字段值 为二维数组
if(array_key_exists($filed,$compare_special_field) && is_array($before) && is_array(json_decode($after,true))){
if(empty($compare_special_field[$filed])){
$after = json_decode($after,true);
$exist_sku = array_intersect_key($before,$after);
foreach ($exist_sku as $key=>$value){
$sku_before = $before[$key];
$sku_after = $after[$key];
foreach ($sku_before as $k=>$v){
if(is_string($sku_after[$k]) && is_string($v) && ($v != $sku_after[$k])){
$diff[$filed][$key][$k] = $v;
}
if (is_array($sku_after[$k]) && is_array($v)){
if(count($sku_after[$k]) != count($v)){
$diff[$filed][$key][$k] = $v;
}else{
$data = array_diff($sku_after[$k],$v);
if(!empty($data)){
$diff[$filed][$key][$k] = implode(',',$v);
}
}
}
}
}
}else{
$after = json_decode($after,true);
foreach ($compare_special_field[$filed] as $sub_filed){
$sub_before = $before[$sub_filed]??null;
$sub_after = $after[$sub_filed]??null;
if(is_string($sub_before) && is_string($sub_after) && ($sub_before!==$sub_after)){
$diff[$filed][$sub_filed] = $sub_before;
}
}
}
}
}
return $diff;
}
$data = compare_diff($edit_before_data,$edit_after_data,$compare_field,$compare_special_field);
print_r($data);<file_sep><?php
ini_set("display_errors", "On");
error_reporting(-1);
class mysql {
public $source;
public $config = [
'host' => '127.0.0.1',
'port' => 3306,
'user' => 'root',
'password' => '<PASSWORD>',
'database' => 'ecp_stock',
'charset' => 'utf8', //指定字符集
'timeout' => 2, // 可选:连
];
public function __construct()
{
$this->source = new swoole_mysql();
}
public function execute(){
$this->source->connect($this->config, function ($db,$result){
if(!$result){
var_dump($db->connect_errno, $db->connect_error);die;
}
$sql= "select * from ecp_stock where id = 1";
$db->query($sql,function ($link,$result){
if($result === false){
var_dump($link->error,$link->errno);die;
}elseif($result === true){ //增删改
var_dump($link->affected_rows);
}else{ //查
print_r($result);
}
$link->close();
});
});
return true;
}
}
$db = new mysql();
$result = $db->execute();
var_dump($result);
echo 888888;<file_sep><?php
//扫码支付模式二(常用)
//24小时内未支付的订单 要系统自动帮用户取消 定时任务执行
include ('function.php');
include ('config.php');
include ('Payment.php');
include ('qrcode.php');
include ('order.php');
$params = [
'body' =>'防水剃须刀',
'detail' => '限时优惠',
'out_trade_no' => time().mt_rand(10000,20000),//商城系统中唯一性 订单号
'total_free' =>10000, //单位分 100元 支付宝的单位为元
'notify_url' => 'notify_url.php',//异步接收微信支付结果通知的回调地址
//'open_id' => 'jdfgjdflgjdflllf' //可选 当你需要限定只有该open_id的用户才能支付时 就添加此参数
'spbill_create_ip' =>get_client_ip(),//获取客服端IP地址 即下单用户的电脑的ip
'app_id' => APP_ID,
'mch_id' => MCH_ID,
'trade_type' => 'NATIVE'
];
$order =new order();
$result=$order->prepare($params); //获取code_url
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../js/jquery-1.9.0.min.js"></script>
</head>
<body>
<div>请扫码支付</div>
<div><img src="<?php echo qrcode($result['code_url']) //此为支付二维码 ?>" alt=""></div>
<input id="out_trade_no" type="hidden" value="<?php echo $result['out_trade_no'] //商城系统订单号?>">
<script>>
//js长轮询查询订单支付状态 如果订单状态为未支付 则一直轮询 如果为已支付 则停止轮询 跳转到订单支付成功页面提示用户支付成功
$(function () {
var t1;
var sum = 0;
var out_trade_no = $("#out_trade_no").val()
t1 = setInterval("queryOrderStatus()",3000);
function queryOrderStatus(){
sum++;
//如果查询次数多余600次就放弃
if(sum>600){ window.clearInterval(t1);return false;}
//如果查询次数大于180次后 就3000毫秒*10的时间间隔查询一次(30秒)
if(sum>180){
m=sum % 10;
if(m!=0){return false;}
}
if(out_trade_no != ''){
$.post('query_order.php',{'out_trade_no':out_trade_no},function(data){
if(data=="SUCCESS"){
window.location.href="跳转到支付成功提页面";
}
})
}
}
})
</script>
</body>
</html>
<file_sep><?php
// www.try.com/php/rabbitmq/header_exchange/customer_two.php
// php D:\code\phpstudy\PHPTutorial\WWW\try\php\rabbitmq\header_exchange\customer_two.php
header('Content-Type: text/html; charset=utf-8');
$conConfig = [
'host' => '127.0.0.1',
'port' => 5672,
'login' => 'mandelay',
'password' => '<PASSWORD>***',
'vhost' => 'test_host'
];
while (true){
try {
//创建连接
$con = new AMQPConnection($conConfig);
$con->connect();
if (!$con->isConnected()) {
echo '连接失败';
die;
}
//根据连接创建通道
$channel = new AMQPChannel($con);
//根据通道创建并指明要消费的队列
$queue_name_two = 'test.queue2';
$queue_two = new AMQPQueue($channel);
$queue_two->setName($queue_name_two);
//获取队列里的消息进行消费处理 发送ack自动确认(AMQP_AUTOACK) 确认已收到消息,把消息从队列中移除
$queue_two->consume(function ($envelope, $queue) {
$msg = $envelope->getBody();
file_put_contents('./../../../log/mq_2.txt',json_encode($msg).PHP_EOL,FILE_APPEND);
}, AMQP_AUTOACK);
$con->disconnect();
} catch (Exception $e) {
echo $e->getMessage();
}
}
<file_sep><?php
/**
* 生成签名的方法
* @param $params
* @param $key
* @param string $encrypt
* @return string
*/
function generateSign($params,$key,$encrypt = 'md5'){
//参数按照参数名ASCII码从小到大排序(字典序)
ksort($params);
//密钥
$params['key']=$key;
//生成请求字符窜
$str = http_build_query($params);
//MD5假名 生成签名
return strtoupper(md5(urlencode($str)));
}
/**
* 获取客户端ip地址
*/
function get_client_ip(){
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}elseif (!empty($_SERVER['REMOTE_ADDR'])){
$ip = $_SERVER['REMOTE_ADDR'];
}else{
$ip = "无法获取";
}
return $ip;
}
/**
* 把數組转换成微信支付要求的xml格式
*/
function toXml($params){
$xml='<xml>';
foreach ($params as $key => $val){
if(is_numeric($val)){
$xml.="<$key>$val</$key>";
}else{
$xml.="<$key><![CDATA[$val]]></$key>";
}
}
$xml.='</xml>';
return $xml;
}
/**
* 把xml转换成数组
*/
function xmlToArray($data){
return (array)simplexml_load_string($data,'SimpleXLMElement',LIBXML_NOCDATA);
}
/**
* @param $url
* @param string $data
* @param bool $pem
* @return bool|string
*/
function http_request($url,$data='',$pem=false){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, 0);//检查服务器SSL证书中是否存在一个公用名
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);//将执行curl_exec()获取的信息以字符串返回,而不是直接输出到屏幕。
//设置请求方式及请求参数
if(!empty($data)){
curl_setopt($ch,CURLOPT_PORT, 1); //设置post提交方式
curl_setopt($ch,CURLOPT_POSTFIELDS, $data); //设置post方式提交的数据
}
//携带证书 微信支付商户中心下载的cert证书
if($pem){
curl_setopt($ch,CURLOPT_SSLCERT, CERT_PATH);
curl_setopt($ch,CURLOPT_SSLKEY,KEY_PATH );
curl_setopt($ch,CURLOPT_CAINFO,CA_PATH );
}
//执行请求
$result = curl_exec($ch);
if($result === false){
$result = "curl 错误信息: ".curl_error();
}
curl_close($ch);
return $result;
}
/**
* 日志记录
*/
function logInfo($info,$fileName="log"){
$debugInfo= debug_backtrace();
$message = date("Y-m-d H:i:s").PHP_EOL.$info.PHP_EOL;
$message .= '[ '.$debugInfo[0]['file'].' ]line '.$debugInfo[0]['line'].PHP_EOL;
$fileName = $fileName.'-'.date("Y-m-d").'.txt';
file_put_contents($fileName,$message);
}
<file_sep><?php
class mysql_oop {
public $conn;
public $error = null;
public function __construct($config)
{
//$config['host'] = 'localhost:3306'; // mysql服务器主机地址
$conn = mysqli_connect($config['dbhost'], $config['dbuser'], $config['dbpass']);
if(!$conn){
$this->error = '连接失败: ' . mysqli_error($conn);
}else{
$this->conn = $conn;
}
}
public function db($db){
if(!$this->error){
mysqli_query($this->conn , "set names utf8");
mysqli_select_db($this->conn, $db);
}
return $this;
}
/**
* 查询数据较大时 占用内存 较多
* @param $sql
* @return array
*/
public function query($sql){
$retval = mysqli_query($this->conn,$sql);
$result =[];
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC))
{
$result[] = $row;
}
return $result;
}
/**
* 采用生成器 占用内存 较少
* 查询数据较大时 占用内存 较多
* @param $sql
* @return array
*/
public function cursor($sql){
$retval = mysqli_query($this->conn,$sql);
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC))
{
yield $row;
}
}
public function query_one($sql){
$retval = mysqli_query($this->conn,$sql);
$result = [];
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC))
{
$result[] = $row;
}
return $result[0];
}
public function __destruct(){
mysqli_close($this->conn);
}
}<file_sep><?php
//require APPPATH.'/php/redis/redisClient.php';
/**
* 悲观锁
* 命令行 php要支持 redis、pcntl、posix、swoole 扩展
* 锁的说明 前提单个redis服务器 能够完美的运用实际生产中
* 分布式锁 下面是分布式满足条件
* 1.互斥性 在任意时刻 只能有一个客户端持有锁
* 2.不会发生死锁 即使有一个客户端在持有锁的期间程序发生崩溃而没有主动解锁,也能保证后续其他客户端能加锁
* 3.解铃还须系铃人,加锁和解锁必须是同一个客户端,客户端自己不能把别人加的锁给解锁,即不能误解锁
* Class Lock
*/
class Lock
{
public $redis;
public $token; // 锁的唯一标识 防止当前客户端解锁了别的客户端加的锁
public $lock_pool;
public $ParentPid;
public function __construct()
{
$this->ParentPid = posix_getpid();
file_put_contents(APPPATH.'/lock.txt',"112 start fpid:".$this->ParentPid.PHP_EOL.PHP_EOL,FILE_APPEND);
$this->redis = new Redis();
$this->redis->connect('192.168.71.141',7001);
$this->redis->auth('yis@2019._');
$this->redis->select(8);
}
/**
* 获取锁
* @param $key 锁名
*
* @param int $maxTtl 锁的过期时间还剩余的最大值 即所设置的锁过期时间
*
* @param int $minTtl 锁的过期时间还剩余的最小限制值 如果某业务处理耗时过长, 发生阻塞 , 如果阻塞时间超过了锁设置的过期时间 ,那锁就会自动释放
* 此时业务还未执行完成 就导致其他客户端获得锁,获得相同的资源, 执行了操作, 这就不满足高并发下锁的互斥性
* 所以当某业务处理耗时过长 发生阻塞时 就要检查锁的过期时间还剩余的时长是否小于此值(锁的过期时间还剩余的最小限制值)
* 如果小于此值,就给锁续命,直到该业务执行完毕后主动释放锁
* @param int $reTryNum 旋时尝试获取锁的次数
* @param int $usleep 旋时尝时间间隔
* @return bool
*/
public function lock($key,$maxTtl = 10,$minTtl = 2,$reTryNum = 10,$usleep = 10000)
{
//互斥性 在任意时刻 只能有一个客户端持有锁
$getLock = false;
//锁的唯一标识 防止当前客户端解锁了别的客户端加的锁 对于同一个资源加锁 $key是一样的 值要不一样
$this->token = $this->generateUniqid();
while($reTryNum-- >0){
// 加锁并保存锁的唯一标识 NX 保证锁的互斥性,EX:保证不会发生死锁 即使程序发生意外 没有主动解锁 也能通过自动过期而解锁
$res = $this->redis->set($key,$this->token,['NX','EX' =>$maxTtl]);
if($res){
$this->lock_pool[$key] = $this->token;
$getLock = true;
file_put_contents(APPPATH.'/lock.txt',"22 get lock: ".$this->ParentPid.PHP_EOL.PHP_EOL,FILE_APPEND);
break;
}else{
file_put_contents(APPPATH.'/lock_exist.txt',"22 lock_exist: ".$this->ParentPid.PHP_EOL.PHP_EOL,FILE_APPEND);
}
usleep($usleep);
}
if($getLock){
// 创建一个子进程 子进程给锁续命
// 如果某业务处理耗时过长, 发生阻塞 , 如果阻塞时间超过了锁设置的过期时间 ,那锁就会自动释放
// 此时父进程的业务还未执行完成 就导致其他客户端获得锁,获得相同的资源 为避免这种情况的发生,子进程就要给锁续命 直到该父进程的业务执行完毕后主动释放锁 这就又保证锁的互斥性
// 这里会又有一个问题产生 如果父进程业务执行完毕后 发生异常 意外退出 锁没有得到释放 子进程中锁又被一直续命 就会产生死锁 这时候子进程会检测执行业务的父进程是否存在 如果不存在子进程退出 不再给锁续命
$parent_process = new Swoole\Process(function($son_process)use($key,$minTtl,$maxTtl,$usleep){
file_put_contents(APPPATH.'/lock.txt',"33 son process: ".microtime().PHP_EOL.PHP_EOL,FILE_APPEND);
file_put_contents(APPPATH.'/lock.txt'," son process data: token:{$this->token}".PHP_EOL.PHP_EOL,FILE_APPEND);
$flag = true;
do{
$delay = $this->delayExpire($key,$this->token,$minTtl,$maxTtl);
file_put_contents(APPPATH.'/lock.txt'," 66 son process delay: ".$delay.' time: '.microtime().PHP_EOL.PHP_EOL,FILE_APPEND);
if(!$delay){
file_put_contents(APPPATH.'/lock.txt',"lock not exist : ".$delay.' time: '.microtime().PHP_EOL.PHP_EOL,FILE_APPEND);
$flag = false;
}
//心跳测试 查看父进程是否还在运运行
if(!swoole_process::kill($this->ParentPid,0)){
file_put_contents(APPPATH.'/lock.txt',"die parentPid:".$this->ParentPid.PHP_EOL.PHP_EOL,FILE_APPEND);
$flag = false;
}
usleep($usleep);
}while($flag);
//子进程退出
$son_process->exit();
});
//子进程ID
$sonPid = $parent_process->start();
file_put_contents(APPPATH.'/lock.txt',"44 son process pid : ".$sonPid.' time: '.microtime().PHP_EOL.PHP_EOL,FILE_APPEND);
}
return $getLock;
}
/**
* 生成客户端唯一标识
*/
public function generateUniqid(){
$microtime = explode(' ',microtime());
$micro = $microtime[0]*1000000;
$second = $microtime[1];
return $this->token = uniqid().$micro.$second.mt_rand(111111111,999999999);
}
/**
* 检测父进程是否还处在
* @param $worker
*/
public function checkMpid(&$worker){
//检测父进程是否还处在 $sig = 0时 检测该pid 是否存在 如果存在则返回true 否则返回false
if(!swoole_process::kill($this->ParentPid,0)){
$worker->exit();
echo "这句提示,实际是看不到的.需要写到日志中,Master process exited, I [{$worker['pid']}] also quit\n";
}
}
/**
* 延长锁的过期时间 给锁续命或续租
* @param $key 锁名
*
* @param $token 锁的唯一标识 防止当前客户端解锁了别的客户端加的锁
*
* @param $maxTtl 锁的过期时间还剩余的最大值 即所设置的锁过期时间
*
* @param $minTtl 锁的过期时间还剩余的最小限制值 如果某业务处理耗时过长, 发生阻塞 , 如果阻塞时间超过了锁设置的过期时间 ,那锁就会自动释放
* 此时业务还未执行完成 就导致其他客户端获得锁,获得相同的资源, 执行了操作, 这就不满足高并发下锁的互斥性
* 所以当某业务处理耗时过长 发生阻塞时 就要检查锁的过期时间还剩余的时长是否小于此值(锁的过期时间还剩余的最小限制值)
* 如果小于此值 就给锁续命 直到该业务执行完毕后主动释放锁
* @return mixed
*/
public function delayExpire($key,$token,$minTtl,$maxTtl){
$script = '
if redis.call("exists", KEYS[1]) and redis.call("GET", KEYS[1]) == ARGV[1] then
local ttl = redis.call("ttl", KEYS[1])
if tonumber(ttl) <= tonumber(ARGV[2]) then
return redis.call("EXPIRE", KEYS[1],ARGV[3])
else
return ttl;
end
else
return 0
end
';
return $this->redis->eval($script, [$key,$token,$minTtl,$maxTtl], 1);
}
/**
* 释放锁
* @param $key 锁名
*
* @param $token 锁的唯一标识 防止当前客户端解锁了别的客户端加的锁
*
* @return mixed
*/
public function unlock($key)
{
$script = '
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
';
file_put_contents(APPPATH.'/lock.txt',"77 unlock time: ".microtime().PHP_EOL.PHP_EOL,FILE_APPEND);
return $this->redis->eval($script, [$key, $this->token], 1);
}
}<file_sep><?php
$data = [
'apply_no'=>'20191030153625',
'po'=>'20191030153625',
'batch' => 1,
'user_id'=>'12654',//验货人工号
'inspect_info'=>[
'sku1'=>[
'unqualify_num'=>30,//不良数
'real_collect_num'=>0,//实收数
'inspect_result'=>1,//检验结果
'unqualify_type'=>'配件不良,订单错误',//不良类型
'unqualify_reason'=>'次品',//不良原因
'improve_measure'=>'加强产品质量把关',//改进措施
'inspect_remark'=>'供应商态度良好',//验货备注
'duty_dept'=>'开发部,品控部',//责任部门
'duty_user'=>'开发部,品控部',//责任人
'appendix'=>['www.appendix.com/1.jpg', 'www.appendix.com/1.jpg', 'www.appendix.com/1.jpg', 'www.appendix.com/1.jpg',] //附件
],
'sku2'=>[
'purchase_num'=>80,
'unqualify_num'=>30,//不良数
'real_collect_num'=>0,//实收数
'inspect_result'=>1,//检验结果
'unqualify_type'=>'配件不良,订单错误',//不良类型
'unqualify_reason'=>'次品',//不良原因
'improve_measure'=>'加强产品质量把关',//改进措施
'inspect_remark'=>'供应商态度良好',//验货备注
'duty_dept'=>'开发部,品控部',//责任部门
'duty_user'=>'开发部,品控部',//责任人
'appendix'=>['www.appendix.com/1.jpg', 'www.appendix.com/1.jpg', 'www.appendix.com/1.jpg', 'www.appendix.com/1.jpg',] //附件
]
]
];<file_sep><?php
$request = new HttpRequest();
$request->setUrl('https://xxxx.udesk.cn/open_api_v1/log_in');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array(
'Postman-Token' => '<PASSWORD>',
'cache-control' => 'no-cache',
'Content-Type' => 'application/json'
));
$request->setBody('{
"email": "<EMAIL>",
"password": "<PASSWORD>"
}');
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}<file_sep><?php
/*
//例子1
//以下父进程运行的逻辑代码环境
$a = 'hello';
//说明 $parent_process与$son_process其实是同一个对象 只是所在的环境不同 $parent_process在父进程环境中运行,$son_process在子进程环境中运行
$parent_process = new Swoole\Process(function($son_process)use($a){
//以下为子进程运行的逻辑代码环境
sleep(30);
echo 88888;
});
//启动进程
$parent_process->start();
echo 7777;
swoole_process::wait();
*/
/*
//例子2 父子进程通过管道通信
$a = 'hello';
$parent_process = new Swoole\Process(function($son_process)use($a){
$son_process->write($a);//子进程向管道内写入数据
});
$parent_process->start();
echo $parent_process->read();//父进程从管道内读取数据
swoole_process::wait();
*/
/*
//例子3 设置管道读写操作的超时时间超时
$a = 'hello';
$parent_process = new Swoole\Process(function($son_process)use($a){
//sleep(1);
sleep(3);
$son_process->write($a);
});
//设置管道读写操作的超时时间
$parent_process->setTimeout(2);
$parent_process->start();
echo $parent_process->read();
swoole_process::wait();
*/
/*
例子4 父子进程通过协程进行通信
$process = new Swoole\Process(function ($proc) {
$socket = $proc->exportSocket();//子进程中创建一个协程对象
var_dump('son start');
//var_dump($socket->recv());//接受父进程向子进程发送的消息
$socket->send("hello parent");//子进程向父进程发送消息
var_dump("son stop");
}, false, 1, true);
$process->start();
//父进程创建一个协程容器
Co\run(function() use ($process) {
$socket = $process->exportSocket(); // 父进程中创建一个协程对象
var_dump('parent start');
//$socket->send("hello son"); //父进程向子进程发送消息
var_dump($socket->recv()); //接受子进程向父进程发送的消息
var_dump('parent stop');
});
//在父进程中回收结束运行的子进程
Swoole\Process::wait(true);
*/
/*
//例子5 父子进程通过中黏包问题的测试
$process = new Swoole\Process(function ($proc) {
$socket = $proc->exportSocket();
//子进程当中 间隔1000毫秒向 父进程发送消息
Swoole\Timer::tick(1000, function () use ($socket) {
$socket->send("hello parent".time());
});
}, false, 2, true); //参数create_pipe为2不会产生黏包问题; 当为1时可能产生黏包问题
$process->start();
//父进程创建一个协程容器
Co\run(function() use ($process) {
while (1){
Co::sleep(5); // 间隔五秒
$socket = $process->exportSocket(); // 创建一个协程对象
var_dump($socket->recv()); // 接受子进程向父进程发送的消息
}
});
//在父进程中回收结束运行的子进程
Swoole\Process::wait(true);
*/
//例子6 父进程与新进程之间可以通过标准输入输出进行通信,必须启用标准输入输出重定向。设置参数redirect_stdin_stdout为true
$process = new Swoole\Process("callback_function", true, 1, true);
$process->start();
function callback_function(Swoole\Process $worker)
{
//必须为绝对路径
$worker->exec("D:\code\swoole\php-cli\bin\swoole.exe",['D:\code\phpstudy\PHPTutorial\WWW\try\php\swoole\process\echo.php']);
//swoole_set_process_name("swoole_test");//修改进程名称 没起作用 不知道为何
//$worker->name("andex_process");//修改进程名称 没起作用 不知道为何
//$worker->close(); // 关闭子进程 有一些特殊的情况 子进程对象无法释放,如果持续创建进程会导致连接泄漏。调用此函数就可以直接关闭 unixSocket,释放资源。
//$worker->exit(); // 退出子进程
}
//父进程创建一个协程容器
Co\run(function() use ($process) {
Co:sleep(15);
$socket = $process->exportSocket(); // 创建一个协程对象
var_dump($socket->recv()); // 接受子进程向父进程发送的消息
});
//在父进程中回收结束运行的子进程
$result = Swoole\Process::wait(true);
var_dump($result);die;
<file_sep><?php
function debug($result){
//报错日志开启
ini_set("display_errors","1");//开启报错日志
error_reporting(-1); //所有报错
error_reporting(E_ERROR); //所有致命错误
error_reporting(E_ALL ^ (E_NOTICE | E_STRICT | E_WARNING | E_DEPRECATED));//除了通知、严格模式、警告
//临时扩大内存 /延长请求时间
ignore_user_abort(true); // 浏览器关闭的情况下 可以继续运行PHP
set_time_limit(0); //永不超时
ini_set("memory_limit", "1024M");
set_time_limit(3600); // 超市时间为3600秒
//获取执行当前脚的进程PID 这两个函数都可以
$pid = getmypid();
$pid = posix_getpid(); // 这个函数要安装php的扩展posix
//在PHP中,可以使用memory_get_usage()获取当前分配给你的PHP脚本的内存量,单位是字节;使用memory_get_peak_usage()获取分配给你的PHP脚本的内存峰值字节数。
//PHP中的选项memory_limit,指定了脚本允许申请的最大内存量,单位是字节。如果没有限制,将这个值设置为-1。
echo "初始: ".memory_get_usage()."B\n";
$str = str_repeat('hello', 1000);
echo "使用: ".memory_get_usage()."B\n";
unset($str);
echo "释放: ".memory_get_usage()."B\n";
echo "峰值: ".memory_get_peak_usage()."B\n";
//php 命令行开启一个后台守护进程
$session_uid = '788888';
$path_entry = FCPATH.'index.php';
//(
// 第一种方式
// 可以把/dev/null 可以看作"黑洞". 它等价于一个只写文件. 所有写入它的内容都会永远丢失. 而尝试从它那儿读取内容则什么也读不到.
// /dev/null 2>&1则表示吧标准输出和错误输出都放到这个“黑洞”,表示什么也不输出
//)
$cmd = sprintf('/usr/bin/php %s inland PR rebuild_pr %s > /dev/null 2>&1 &', $path_entry, $session_uid);
//(
// 第二种方式 记录日志到php.log
// nohup命令用于不挂断地运行命令(关闭当前session不会中断改程序,只能通过kill等命令删除)。
// 使用nohup命令提交作业,如果使用nohup命令提交作业,那么在缺省情况下该作业的所有输出都被重定向到一个名为nohup.out的文件中,除非另外指定了输出文件。
// 2>&1就是用来将标准错误2重定向到标准输出1中的。此处1前面的&就是为了让bash将1解释成标准输出而不是文件1。至于最后一个&,则是让bash在后台执行。
//)
$cmd = sprintf('nohup /usr/bin/php %s inland PR rebuild_pr %s >> php.log 2>&1 &', $path_entry, $session_uid);
//第三种
$path_entry = '/home/wwwroot/tms/appdal/index.php';
$cmd = sprintf('/usr/bin/php %s ordersys/console/ShipCost/getCost %s %s > /dev/null 2>&1 &', $path_entry, 'WYT_model','jhkhkjh');
// php 接受命令行形式传递的参数
// func_num_args() 命令行形式传递的参数个数
// func_get_args() 命令行形式传递的参数数组
// if(is_cli() && (func_num_args() >0)) { $params = func_get_args()}
shell_exec($cmd);
//文件写入调试
$data = [];
$inputs = [];
file_put_contents(Yii::getPathOfAlias('webroot').'/protected/runtime/1.txt','11'.PHP_EOL);//清空原来的内容 写入现在的内容
file_put_contents(Yii::getPathOfAlias('webroot').'/protected/runtime/1.txt','11'.PHP_EOL,FILE_APPEND);//文件内容后追加
file_put_contents(Yii::getPathOfAlias('webroot').'/protected/runtime/1.txt',json_encode($result).PHP_EOL,FILE_APPEND);
file_put_contents(Yii::getPathOfAlias('webroot').'/protected/runtime/1.txt',"<?php\n".'return '.var_export($data, true).";\n\n?>",FILE_APPEND);
file_put_contents(APPPATH.'/cache/100.php',"<?php\n".'return '.var_export(['11'=>$inputs], true).";\n\n?>",FILE_APPEND);
file_put_contents(APPPATH.'/cache/100.php',"<?php\n".'return '.var_export($this->db->total_query(), true).";\n\n?>",FILE_APPEND);
file_put_contents(APPPATH.'/cache/100.php','11'.PHP_EOL.PHP_EOL,FILE_APPEND);
}
//各进制数据转换
function baseConvert(){
echo bindec('110011'); // 二进制转十进制
echo "<br>";
echo octdec()('030'); // 八进制转十进制 八进制值被定义为带前置 0
echo "<br>";
echo hexdec()('0x56'); // 十六进制转十进制 十六进制值被定义为带前置 0x
echo "<br>";
echo base_convert();//各种进制相互转换
echo "<br>";
//chr() 函数从指定的 ASCII 值返回字符。
//ASCII 值可被指定为十进制值、八进制值或十六进制值。八进制值被定义为带前置 0,而十六进制值被定义为带前置 0x。
echo chr(61) . "<br>"; // 从十进制的ASCII值返回字符
echo chr(061) . "<br>"; // 从八进制值的ASCII值返回字符
echo chr(0x61) . "<br>"; // 从十六进制值的ASCII值返回字符
//ord() 函数返回字符串第一个字符的ASCII值。是chr反向函数
echo ord("h");
echo ord("hello");
}
//调试打印
if (!function_exists('pr')) {
function pr($arr, $escape_html = true, $bg_color = '#EEEEE0', $txt_color = '#000000')
{
echo sprintf('<pre style="background-color: %s; color: %s;">', $bg_color, $txt_color);
if ($arr) {
if ($escape_html) {
echo htmlspecialchars(print_r($arr, true));
} else {
print_r($arr);
}
} else {
var_dump($arr);
}
echo '</pre>';
}
}
/**
* 读取内容转化为字符串
* @param string $file
* @return array
*/
function rFile($file = "./log.txt" ,$before = "'",$after="',"){
$handle = fopen($file,'r');
$data = [];
while(!feof($handle))
{
$row = fgets($handle);
$str = str_replace(array("\r\n", "\r", "\n"), "", $row);
$data[] = strval($str);
file_put_contents('./test.log',$before.$str.$after.PHP_EOL,FILE_APPEND);
}
fclose($handle);
return $data;
}
/**
* 获取当前进程数量
* @return int
*/
function get_process_num(){
$check_process = shell_exec("ps -ef | grep 'fba PR rebuild_pr' | grep -v grep | awk '{print $2}' ");
if (!is_null($check_process)) {
$running_pids = array_filter(explode("\n", $check_process));
if (!empty($running_pids)) {
return count($running_pids);
}else{
return 0;
}
}else{
return 0;
}
}
/**
* 更新与新增的数据分组
* @param $passData 此数组包含更新与新增的数据
* @param $model 此为表的实体对象
*/
public function groupUpdateInsertData($model,$passData)
{
//根据 $passData 到数据库中查询 已处在的数据 inbound_number在数据表中可以确定唯一一条数据
$condition = ['where_in' => ['inbound_number' => array_column($passData, 'inbound_number')]];
$exit_data = $model->getDataByCondition($condition);
//获取要更新的数据的唯一值条件集合
$exit_data_gid = array_column($exit_data, null, 'inbound_number');
$passData_gid = array_column($passData, null, 'inbound_number');
$update_data_gid = array_intersect_key($passData_gid, $exit_data_gid);//唯一值条件集合
//获取要新增的数据
$insert_data = array_values(array_diff_key($passData_gid, $exit_data_gid));
}
/**
* 调试性能
*/
function performance()
{
$s = time();
pr('初始内存:'.memory_get_usage());
//todo :主体逻辑
$e = time();
pr('耗时:'.($e-$s));
pr($this->db->total_query());
pr('结束内存:'.memory_get_usage());
pr('内存峰值:'.memory_get_peak_usage());
die;
}
/**
* 获取微妙数
* @return float|int
*/
function getMicroTime(){
$time = explode(' ',microtime());
return ($time[1] + $time[0])*1000000;
}
//function grid($price){
// $grid_array = [];
// for ($i=0;$i<=99;$i++){
// $pow_base = 1-1.1/100;
// $pow = pow($pow_base,$i);
// $grid_array[$i] = round($price*$pow,3);
// }
// return $grid_array;
//}
//
//
//$grid = grid(7);
//print_r($grid);
//
//echo array_sum($grid)/count($grid);
<file_sep>#php_value auto_prepend_file "/home/username/include/header.php"
#php_value auto_append_file "/home/username/include/footer.php"<file_sep><?php
ignore_user_abort(true); // 浏览器关闭的情况下 可以继续运行PHP
set_time_limit(0); //永不超时
/**
* RabbitMQ死信机制实现延迟队列
* 实现的方式有两种:
* 通过消息过期后进入死信交换器,再由交换器转发到延迟消费队列,实现延迟功能;
* 使用rabbitmq-delayed-message-exchange插件实现延迟功能;
*
* 说明:
* 消息的TTL就是消息的存活时间。RabbitMQ可以对队列和消息分别设置TTL。
* 对队列设置就是队列没有消费者连着的保留时间,也可以对每一个单独的消息做单独的设置。
* 超过了这个时间,我们认为这个消息就死了,称之为死信。如果队列设置了,消息也设置了,那么会取小的。
* 所以一个消息如果被路由到不同的队列中,这个消息死亡的时间有可能不一样(不同的队列设置)。
* 这里单讲单个消息的TTL,因为它才是实现延迟任务的关键。
*
* 执行顺序:
* 先运行消费者 然后在运行生产者 因为死信交换机及死信队列是在消费者中创建和声明的
*/
//www.try.com/php/rabbitmq/dead_letter_exchange/product.php
header('Content-Type: text/html; charset=utf-8');
// 连接设置
//192.168.31.16:15672
$conConfig = [
'host' => '127.0.0.1',
'port' => 5672,
'login' => 'mandelay',
'password' => '<PASSWORD>***',
'vhost' => 'test_host'
];
try {
// RabbitMQ 连接实例
$con = new AMQPConnection($conConfig);
// 发起连接
$con->connect();
// 判断连接是否仍然有效
if (!$con->isConnected()) {
echo '连接失败';
die;
}
// 新建通道
$channel = new AMQPChannel($con);
//通过通道获取默认交换机
$exchange = new AMQPExchange($channel);
$exchange_name = 'normal_business_handle_exchange';
$exchange->setName($exchange_name); // 设置交换机名称
$exchange->setType( AMQP_EX_TYPE_DIRECT); // 设置交换机类型
$exchange->setFlags(AMQP_DURABLE); // 持久化 即使重启数据依旧存在
$exchange->declareExchange(); // 声明此交换机
//创建及声明正常的业务处理队列
$queue_name = 'normal_business_handle_queue';
$queue = new AMQPQueue($channel);
$queue->setName($queue_name); // 队列名称
$queue->setFlags(AMQP_DURABLE); // 持久化 即使重启数据依旧存在
//为该队列关联死信交换机及死信交换机rounting-key而添加的必须设置的参数
$queue->setArgument('x-message-ttl',10000); //设置队列的过期时间是10秒 队列过期后 队列中的消息会由死信交换机跟据死信路由发送给绑定的死信队列
$queue->setArgument('x-dead-letter-exchange','dlx_exchange');//设置该队列关联的死信交换机
$queue->setArgument('x-dead-letter-routing-key','dead_letter_key');//设置死信路由key
$queue->declareQueue(); // 声明此队列
//将队列、交换机、rounting-key 三者绑定
$routing_key = "normal_business_key";
$queue->bind($exchange_name, $routing_key); // 将队列、交换机、rounting-key 三者绑定
for ($i = 1; $i <= 6; $i++) {
$message = [
'name' => '默认交换机,消息-' . $i,
'info' => 'Hello World!'
];
// 发送消息,为消息指定routing key,成功返回true,失败false
if(($i%2)==1){
//过期时间为10秒 遵循对队列设置的过期时间 这种可以
$state = $exchange->publish(json_encode($message, JSON_UNESCAPED_UNICODE), $routing_key);
}else{
//单独为某个消息设置过期时间 每个消息的过期时间可以不一样 如果队列设置过期时间,消息也设置了过期时间,那么会取小的 理论是这样好像不起作用
$state = $exchange->publish(json_encode($message, JSON_UNESCAPED_UNICODE), $routing_key,AMQP_NOPARAM,['expiration'=>1000*$i]);
}
if ($state) {
echo 'Success' . PHP_EOL;
} else {
echo 'Fail' . PHP_EOL;
}
sleep(10);
}
// 关闭连接
$con->disconnect();
} catch (Exception $e) {
echo $e->getMessage();
}<file_sep><?php
ini_set("display_errors", "On");
error_reporting(-1);
Swoole\Async::readFile(__DIR__."/read.txt",function ($filename, $content){
echo $filename.' : '.$content;
});
echo 888888;<file_sep><?php
//生成器
require "D:\code\phpstudy\PHPTutorial\WWW\\try\php\mysql\mysql_oop.php";
$config = [
'dbhost' => '192.168.71.141:3306', // mysql服务器主机地址
'dbuser' => 'devuser', // mysql用户名
'dbpass' => '<PASSWORD>',
];
// // 普通查询
//$x1 = round(memory_get_usage()/1024/1024, 4);
//$query = new mysql_oop($config);
//$sql = "select * from yibai_sql_log_detail limit 100";
//$result = $query->db('yb_tms_logistics_basic')->query($sql);
//echo $x2 = round(memory_get_usage()/1024/1024, 4) - $x1;die;
//print_r($result);die;
// //生成器
//$x1 = round(memory_get_usage()/1024/1024, 4);
//$query = new mysql_oop($config);
//$sql = "select * from yibai_sql_log_detail limit 100";
//$result = $query->db('yb_tms_logistics_basic')->cursor($sql);
//echo $x2 = round(memory_get_usage()/1024/1024, 4) - $x1;die;
//foreach ($result as $item){
// print_r($item);
//}
<file_sep><?php
define ('MCH_ID','1382578526456');
define ('APP_ID','GDFGJDFUIGGFJDFLGKS');
define ('KEY','1382578526456');//商户中心设置的支付时的秘钥
define ('CERT_PATH','./cert/apiclient_cert.pem');
define ('KEY_PATH','./cert/apiclient_key.pem');
define ('CA_PATH','./cert/rootca.pem');<file_sep><?php
require "socket.php";
$socket = new Socket();
$url="/php/debug/log.php";
$socket->runThreadSOCKET($url);<file_sep><?php
return array(
0 =>
array(
'inspect_grade' => 'A',
'spot_grade' => 'S-1',
'apply_no' => '201910311018',
'po' => '20191015',
'sku' => '1010190001911',
'inspect_type' => '客诉',
'dev_imgs' => 'http://192.168.71.146:5000/file/file/download/image?filePath=group1/M01/00/74/wKhHklyy2yKACRYIAABmhW955IY712.jpg',
'inspect_detail_address' => '龙岗区五和大道8888号',
'title_cn' => '飞机大炮EF',
'devp_type' => '',
'supplier_name' => '深圳市鸟怒拉斯公司',
'real_purchase_num' => '12',
'real_collect_num' => '0',
'unqualify_num' => '0',
'short_supply_num' => '3',
'is_abnormal' => '正常',
'inspector' => '杨钦-13715',
'product_inspect_time' => '2020-03-06',
'applicant' => '王威-12561',
'purchase_apply_time' => '0000-00-00 00:00:00',
'unqualify_type' => '配件不良',
'unqualify_reason' => '不良99',
'improve_measure' => '加强产品质量把关',
'inspect_remark' => '供应商态度良好',
'duty_dept' => '开发部,品控部',
'duty_user' => '开发部,品控部',
'is_lead_inspect' => '是',
'inspect_result' => '不合格',
),
1 =>
array(
'inspect_grade' => 'A',
'spot_grade' => 'S-1',
'apply_no' => '201910301019',
'po' => '20191030',
'sku' => '1010190016211',
'inspect_type' => '客诉',
'dev_imgs' => 'http://192.168.71.104:5000/file/file/download/image?filePath=group1/M01/00/99/wKhHkl0cU6qAYYSOAASIWdmmCjk301.jpg',
'inspect_detail_address' => '龙岗区五和大道8888号',
'title_cn' => 'test商品品控-0703-yqa1',
'devp_type' => '常规',
'supplier_name' => '深圳市鸟怒拉斯公司',
'real_purchase_num' => '43',
'real_collect_num' => '0',
'unqualify_num' => '0',
'short_supply_num' => '2',
'is_abnormal' => '正常',
'inspector' => '-',
'product_inspect_time' => '0000-00-00',
'applicant' => '王威-12561',
'purchase_apply_time' => '0000-00-00 00:00:00',
'unqualify_type' => '',
'unqualify_reason' => '',
'improve_measure' => '',
'inspect_remark' => '',
'duty_dept' => '',
'duty_user' => '',
'is_lead_inspect' => '否',
'inspect_result' => '待排期',
),
2 =>
array(
'inspect_grade' => 'A',
'spot_grade' => 'S-1',
'apply_no' => '201910301019',
'po' => '20191030',
'sku' => '1010190016212',
'inspect_type' => '客诉',
'dev_imgs' => 'http://192.168.71.104:5000/file/file/download/image?filePath=group1/M01/00/99/wKhHkl0cU6qAYYSOAASIWdmmCjk301.jpg',
'inspect_detail_address' => '龙岗区五和大道8888号',
'title_cn' => 'test商品品控-0703-yqb1',
'devp_type' => '常规',
'supplier_name' => '深圳市鸟怒拉斯公司',
'real_purchase_num' => '11',
'real_collect_num' => '0',
'unqualify_num' => '0',
'short_supply_num' => '3',
'is_abnormal' => '正常',
'inspector' => '-',
'product_inspect_time' => '0000-00-00',
'applicant' => '王威-12561',
'purchase_apply_time' => '0000-00-00 00:00:00',
'unqualify_type' => '',
'unqualify_reason' => '',
'improve_measure' => '',
'inspect_remark' => '',
'duty_dept' => '',
'duty_user' => '',
'is_lead_inspect' => '否',
'inspect_result' => '待排期',
),
3 =>
array(
'inspect_grade' => 'S',
'spot_grade' => 'S-1',
'apply_no' => '201910311020',
'po' => '20191038',
'sku' => '1011190004611',
'inspect_type' => '客诉',
'dev_imgs' => 'end/upload/image/productImages/8a8e83cd1619af937b19f91c0a9dde08.jpg',
'inspect_detail_address' => '龙岗区五和大道8888号',
'title_cn' => '2019秋款童装打底衫纯棉 儿童长袖男童T恤中小宝宝体恤孩子的衣服3109-花灰/蓝色90cm',
'devp_type' => '常规',
'supplier_name' => '深圳市鸟怒拉斯公司',
'real_purchase_num' => '12',
'real_collect_num' => '0',
'unqualify_num' => '0',
'short_supply_num' => '3',
'is_abnormal' => '正常',
'inspector' => '陈磊-14485',
'product_inspect_time' => '2020-03-06',
'applicant' => '王威-12561',
'purchase_apply_time' => '0000-00-00 00:00:00',
'unqualify_type' => '配件不良',
'unqualify_reason' => '不良99',
'improve_measure' => '加强产品质量把关',
'inspect_remark' => '',
'duty_dept' => '开发部,品控部',
'duty_user' => '开发部,品控部',
'is_lead_inspect' => '是',
'inspect_result' => '申请转合格通过',
),
4 =>
array(
'inspect_grade' => 'A',
'spot_grade' => 'Ⅱ',
'apply_no' => 'YH-2020031900006',
'po' => 'PO8601876',
'sku' => 'JY15488',
'inspect_type' => '首单',
'dev_imgs' => '',
'inspect_detail_address' => '上剑山村杨梅大道800号中国邮政二楼xxx',
'title_cn' => NULL,
'devp_type' => '',
'supplier_name' => '福安市时上元素工艺品有限公司',
'real_purchase_num' => '0',
'real_collect_num' => '0',
'unqualify_num' => '0',
'short_supply_num' => '0',
'is_abnormal' => '异常',
'inspector' => '陈磊-14485',
'product_inspect_time' => '0000-00-00',
'applicant' => '彭光基13066-13066',
'purchase_apply_time' => '2020-03-19 17:17:21',
'unqualify_type' => '',
'unqualify_reason' => '',
'improve_measure' => '',
'inspect_remark' => '',
'duty_dept' => '',
'duty_user' => '',
'is_lead_inspect' => '是',
'inspect_result' => '不合格',
),
5 =>
array(
'inspect_grade' => 'A',
'spot_grade' => 'Ⅱ',
'apply_no' => 'YH-2020031900006',
'po' => 'PO8601876',
'sku' => 'JY15491',
'inspect_type' => '首单',
'dev_imgs' => '',
'inspect_detail_address' => '上剑山村杨梅大道800号中国邮政二楼xxx',
'title_cn' => NULL,
'devp_type' => '',
'supplier_name' => '福安市时上元素工艺品有限公司',
'real_purchase_num' => '0',
'real_collect_num' => '0',
'unqualify_num' => '0',
'short_supply_num' => '0',
'is_abnormal' => '异常',
'inspector' => '陈磊-14485',
'product_inspect_time' => '0000-00-00',
'applicant' => '彭光基13066-13066',
'purchase_apply_time' => '2020-03-19 17:17:21',
'unqualify_type' => '',
'unqualify_reason' => '',
'improve_measure' => '',
'inspect_remark' => '',
'duty_dept' => '',
'duty_user' => '',
'is_lead_inspect' => '是',
'inspect_result' => '不合格',
),
6 =>
array(
'inspect_grade' => 'S',
'spot_grade' => 'Ⅱ',
'apply_no' => 'YH-2020032400007',
'po' => 'PO100757979',
'sku' => '101019HS43011',
'inspect_type' => '首单',
'dev_imgs' => 'end/upload/image/productImages/57643eeb5b694f524c8758783644eccb.jpg',
'inspect_detail_address' => '上剑山村杨梅大道800号中国邮政二楼xxx',
'title_cn' => 'test111s1111111111111',
'devp_type' => '常规',
'supplier_name' => '宁波市海曙定及金属制品有限公司',
'real_purchase_num' => '20',
'real_collect_num' => '0',
'unqualify_num' => '0',
'short_supply_num' => '8',
'is_abnormal' => '正常',
'inspector' => '付荣-13718',
'product_inspect_time' => '2020-03-31',
'applicant' => '彭光基13066-13066',
'purchase_apply_time' => '2020-03-24 11:37:01',
'unqualify_type' => '',
'unqualify_reason' => '',
'improve_measure' => '',
'inspect_remark' => '',
'duty_dept' => '',
'duty_user' => '',
'is_lead_inspect' => '否',
'inspect_result' => '待验货',
),
);
?><file_sep><?php
require "../curl/Curl.php";
$url = 'www.tms-b.com/ordersys/api/WarehouseAgeFeeList/exportToFile';
$curl = new Curl();
$header = array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Type' => 'application/json'
);
$data_json = '{"request_params":{"list_type":"1","charge_date_start":"2020-06-12","charge_date_end":"2020-06-12"},"request_type":"1","user_id":"1678"}';
$result = $curl->requestByCurlPost($url,$header,$data_json);
print_r($result);die;
<file_sep> <?php
//配置数据
$appKey = "<KEY>";
$appSecret = "<KEY>";
$time=time();
//订单数据(加密数据)
$order=[
['uid'=>'uid1','amount'=>1,'orderTime'=>'1478826671000','orderId'=>'orderId1','payTime'=>'1478833871000','price'=>100],
['uid'=>'uid2','amount'=>2,'orderTime'=>'1478826881888','orderId'=>'orderId2','payTime'=>'1478833888888','price'=>213]
];
$data =strtolower(json_encode($order));
/**
* 数据校验
* @param $appSecret
* @param $data 被校验的数据
* @param $time 当前时间戳
* @return string
*/
function getChecksum($appSecret,$data,$time){
return sha1($appSecret.md5($data).$time);
}
/**
* @param $data 被加密的数据
* @param $secret_key 密钥
* @param string $method 加解密方法,可通过openssl_get_cipher_methods()获得
* @param int $options
* @param string $iv
* @return string 返回加密后的字符串
*/
function encrypt($data,$secret_key,$method='AES-128-ECB',$options=1,$iv=''){
$secret_key= substr(openssl_digest(openssl_digest($secret_key, 'sha1', true), 'sha1', true), 0, 16);
$data_encode = openssl_encrypt($data,$method,$secret_key,$options,$iv);
return Str2Ascii2hex($data_encode);
}
/**
* @param $data 被解密的数据
* @param $secret_key 密钥
* @param string $method 加解密方法,可通过openssl_get_cipher_methods()获得
* @param int $options
* @param string $iv
* @return string 返回解密后的字符串
*/
function decrypt($data,$secret_key,$method='AES-128-ECB',$options=1,$iv=''){
$data=Str2Dec2chr($data);
$secret_key= substr(openssl_digest(openssl_digest($secret_key, 'sha1', true), 'sha1', true), 0, 16);
return openssl_decrypt($data,$method,$secret_key,$options,$iv);
}
/**
* 把字符串转为16进制表示,其中ord函数将字符串中的每个字符转为对应的ASCII码,dechex 函数将ASCII码数字从十进制转为十六进制,然后链接成十六进制字符串
* @param $str
* @return string
*/
function Str2Ascii2hex($str){
$str_hex='';
for ($i=0;$i<strlen($str);$i++){
$temp= ord($str[$i]);
if ($temp<0){
$temp+=256;
}
if($temp<16){
$str_hex.='0';
}
$dechex=dechex($temp);
$str_hex.=$dechex;
}
return $str_hex;
}
/**
* 把16进制字符串的每两个字符转化为十进制 然后再把十进制的数字转化成字符 再然后把字符连接成字符串
* @param $str
* @return string
*/
function Str2Dec2chr($str){
$str_dec='';
for ($i=0;$i<strlen($str);$i+=2){
$str_dec.=chr(hexdec(substr($str,$i,2)));
}
return $str_dec;
}
var_dump($data);
//加密
$data_encode=encrypt($data,$appSecret);
var_dump($data_encode);
//解密
$data_decode=decrypt($data_encode,$appSecret);
var_dump($data_decode);
/**
* 请求方法
* @return mixed|string
*/
$url="http://dfs02.qiyukf.com/openapi/message/send?appKey=".$appKey."&time=".$time."&checksum=".getChecksum($appSecret,$data,$time);
function requestByCurl($url){
$ch=curl_init();
curl_setopt_array($ch,[
CURLOPT_URL =>$url, //请求的url
CURLOPT_RETURNTRANSFER =>1, //不要把请求的结果直接输出到屏幕上
CURLOPT_TIMEOUT =>30, //请求超时设置
CURLOPT_POST =>1, //使用post请求此url
CURLOPT_SSL_VERIFYPEER=>0, //服务端不验证ssl证书
CURLOPT_SSL_VERIFYHOST=>0, //服务端不验证ssl证书
CURLOPT_HTTPPROXYTUNNEL=>1, //启用时会通过HTTP代理来传输
CURLOPT_HTTPHEADER =>['content-type: application/json'],//请求头部设置
CURLOPT_POSTFIELDS =>json_encode(['uid'=>'227899','msgType'=>'TEXT','content'=>'888888888888888'],JSON_UNESCAPED_UNICODE), //post请求时传递的参数
]);
$content = curl_exec($ch); //执行
$err = curl_error($ch);
curl_close($ch);
if($err){
return $err;
}
return json_decode($content);
}
var_dump(requestByCurl($url));
<file_sep><?php
/**
* 处理微信结果通知
* 1.如何调试(postman,记录日志)
* 2.安全性_1 微信给我们的通知结果 我们只需处理一次
* 3.安全性—2 防止别人伪造微信服务器发送结果通知给我们 我们要进行签名验证 并校验返回的订单金额是否与商户侧的订单金额一致 避免不必要的损失
*/
include('function.php');
//1.调试 记录日志
$info= file_get_contents('php://input'); //用PHP协议获取输入流 用get,post也行
logInfo($info);//把微信支付传给这个接口的数据 记录到日志当中 调试的时候用 或者也可以在生产环境保留
//2.测试从微信服务支付器接收到的数据
$order = xmlToArray($info);
$trade['order_sn'] = $order['out_trade_no'];
$trade['total_free'] = $order['total_free'];
//签名的验证
$mySign= generateSign($order,KEY);
//订单金额的验证 到数据库中查找该订单的订单支付金额
$order_amount=Order::find()->select('pay_amount')->where(['order_sn'=>$trade['order_sn']])->one();
if($order_amount==$trade['total_free'] && $mySign == $order['sign']){
if($order_status=="已支付"){
//已支付不做任何处理 直接return就行了
return;
}else{
//todo:如果订单状态为未支付 更改订单状态为已支付和其他的逻辑处理
}
//通知微信支付服务器结束回调通知
return toXml(['return_code'=>'SUCCESS','return_msg'=>'OK']);
}
<file_sep><?php
ini_set("display_errors","1");//开启报错日志
error_reporting(-1); //所有报错
require "./server/Fedex_model.php";
define('PATH_WSDL',__DIR__.'/wsdl');
$fedex = new Fedex_model();
$fedex->uploadEtdImage();
<file_sep><?php
require "../../curl/Curl.php";
$pool = new Swoole\Process\Pool(10, 0, 0);
$pool->on('workerStart', function (Swoole\Process\Pool $pool, int $workerId) {
$curl = new Curl();
Swoole\Timer::tick(1000, function (int $timer_id) use ($curl) {
$url ="www.tms-b.com/ordersys/console/ShipCost/getQueue";
$curl->requestByCurlGet($url);
});
});
$pool->start();
<file_sep><?php
//发布
require_once "redisClient.php";
$redis = new redisClient();
$redis->redis->publish('msg','44_'.time());
<file_sep><?php
class webSocket{
const IP = "0.0.0.0";
const PORT = 9504;
private $ws;
public function __construct()
{
//创建websocket服务器对象,监听0.0.0.0:9504端口
$this->ws = new swoole_websocket_server(self::IP,self::PORT);
$this->ws->set([
'worker_num' => 2,
'task_worker_num' => 4,
]);
//监听WebSocket连接打开事件
$this->ws->on('open',[$this,'onOpen']);
//监听WebSocket消息事件
$this->ws->on('message',[$this,'onMessage']);
//监听投递的异步任务
$this->ws->on('task',[$this,'onTask']);
//监听投递的异步任务
$this->ws->on('finish',[$this,'onFinish']);
//监听WebSocket连接关闭事件
$this->ws->on('close',[$this,'onClose']);
//开启服务
$this->ws->start();
}
public function onOpen($ws, $request){
echo"客服端与服务端已建立链接_".$request->fd;
}
public function onMessage($ws, $frame){
$data=[
'msg'=>$frame->data."_task",
'frame_id' => $frame->fd
];
echo "开始任务投递";
$ws->task($data);//投递一个异步任务到task_worker进程池中 触发服务的task事件
$ws->push($frame->fd, "server: {$frame->data}");
}
public function onTask($ws, $task_id, $from_id, $data){
sleep(10);
echo '处理异步投递的任务';
$ws->finish($data);//触发服务的finish事件
}
public function onFinish($ws, $task_id, $data){
echo "异步投递的任务处理完成";
$ws->push($data['frame_id'], "server: {$data['msg']}");//向客户端发送消息
}
public function onClose($ws, $frame){
echo "客服端与服务端链接断开";
}
}
$ws = new webSocket();
<file_sep><?php
?>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="../../js/jquery-1.9.0.min.js"></script>
</head>
<body>
<form name="talk">
<textarea rows="5" cols="50" id="content" value=""></textarea>
</form>
<h3>WebSocket协议的客户端程序</h3>
<button id="btConnect">连接到WS服务器</button>
<button id="btSendAndReceive">向WS服务器发消息并接收消息</button>
<button id="btClose">断开与WS服务器的连接</button>
<div id="val"></div>
<script>
var wsClient = null; //WS客户端对象
// var content = document.getElementById('content').innerHTML;
// console.log(content)
btConnect.onclick = function(){
//连接到WS服务器,注意:协议名不是http!
wsClient = new WebSocket('ws://127.0.0.1:9504');
//wsClient = new WebSocket('ws://127.0.0.1:9502');
// wsClient.onopen = function(){
// console.log("已连接")
// }
}
btSendAndReceive.onclick = function(){
//用户输入消息
var content=$("#content").val();
//向WS服务器发送一个消息
//wsClient.send('Hello Server');
wsClient.send(content);
//接收WS服务器返回的消息
wsClient.onmessage = function(e){
console.log('WS客户端接收到一个服务器的消息:'+ e.data);
val.innerHTML=e.data;
}
}
btClose.onclick = function(){
//断开到WS服务器的连接
wsClient.close(); //向服务器发消息,主动断开连接
wsClient.onclose = function(){
//经过客户端和服务器的四次挥手后,二者的连接断开了
console.log('到服务器的连接已经断开')
}
}
</script>
</body>
</html>
<file_sep><?php
file_put_contents('./lock.txt',"110 start fpid:".posix_getpid().PHP_EOL.PHP_EOL,FILE_APPEND);
$pm = new Swoole\Process\Manager();
//Manager进程
$pm->addBatch(1,function (Swoole\Process\Pool $pool, int $workerId){
//工作进程 当工作进程执行完毕后 Manager进程会自动重新进行addBatch 周而复始 循环下去
file_put_contents('./lock.txt',"110 start fpid:".posix_getpid().PHP_EOL.PHP_EOL,FILE_APPEND);
$process = $pool->getProcess();
$process->exec('/usr/local/php/bin/php', array(__DIR__.'/php/lock/test_lock.php'));
});
$pm->start();
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="../js/jquery-1.9.0.min.js"></script>
</head>
<body>
<div id="container" style="width: 100%">
<form action="http://www.try.com/tool/show.php" method="post" target="_blank">
<textarea id = "json_str" style="height: 200px;width:100%" name="str"></textarea>
<div>
<input id = "test" style="display: inline-block;width: 49.5%" type="submit" value ="提交">
<input style="display: inline-block;width: 49.5%" type="reset" value ="重置">
</div>
</form>
</div>
<!--<script>
$("#test").click(function () {
var str = $("#json_str").val();
$.ajax({
type: "POST",
url:'http://www.try.com/tool/jta.php',
dataType:'json',
data:{'str':str},
success:function (data) {
console.log(data);
}
})
})
</script>-->
</body>
</html>
<file_sep><?php
class socketClient{
/**
* 主要是利用socket的客户端函数 fsockopen 向服务端发出批量请求
* @param $urls
* @param string $hostname
* @param int $port
*/
public function runThreadSocketBatch($urls, $hostname = '', $port = 80) {
if (!$hostname) {
$hostname = $_SERVER['HTTP_HOST'];
$port = $_SERVER['SERVER_PORT'] ?: $port;
}
if (!is_array($urls)){
$urls = (array)$urls;
}
foreach ($urls as $url) {
$fp=fsockopen($hostname, $port, $errno, $errstr,18000);
stream_set_blocking ( $fp, true );
stream_set_timeout ( $fp, 18000 );
fputs($fp,"GET ".$url." HTTP/1.1\r\n");
fputs($fp,"Host: ".$hostname."\r\n\r\n");
fclose($fp);
}
}
/**
* 描述:模拟多线程
* @param $urls
* @param int $timeOut
* $url = 'http://tmsservice.yibainetwork.com:92/ordersys/api/FailOrder/getTrackNumber?platformCode=WISH&order=wh789451234582';
*/
public static function runThreadSocket($urls, $timeOut = 1800)
{
if (!is_array($urls)) {
$urls = (array)$urls;
}
foreach ($urls as $url) {
$info = parse_url($url);
$hostname = $info['host']; //主机
$port = isset($info['port']) ? $info['port'] : 80; //端口号
$path = isset($info['query']) ? $info['path'] . "?" . $info['query'] : $info['path']; //相对路径与请求参数
$fp = fsockopen($hostname, $port, $errno, $errstr, $timeOut);
stream_set_blocking($fp, true);
stream_set_timeout($fp, $timeOut);
fputs($fp, "GET " . $path . " HTTP/1.1\r\n");
fputs($fp, "Host: " . $hostname . "\r\n\r\n");
fclose($fp);
}
}
}<file_sep><?php
/**
* 令牌桶限流
* 需要安装redis服务端的扩展redis-cell
* Class redisClient
*/
class tokenBucket {
protected $redis;
protected $key = null;
protected $max_burst = null;
protected $tokens = null;
protected $seconds = null;
protected $apply = 1;
/**
* LeakyBucket construct
* @param $key string
* @param $max_burst int 初始桶数量
* @param $tokens int 速率
* @param $seconds int 时间
* @param int $apply 每次漏水数量
*/
public function __construct($key, $max_burst, $tokens, $seconds, $apply = 1)
{
$this->init();
$this->key = $key;
$this->max_burst = $max_burst;
$this->tokens = $tokens;
$this->seconds = $seconds;
$this->apply = $apply;
}
/**
*
*/
public function init(){
$this->redis = new Redis();//安装PHP的redis C语言扩展 各种操作方法名与redis命令名相同
//$this->redis->connect('127.0.0.1',6379);
//$this->redis->connect('192.168.71.141',7001);
//$this->redis->auth('yis@2019._');
$this->redis->connect('192.168.31.29',6379);
$this->redis->auth('123456');
$this->redis->select(0);
}
/**
* 是否放行
* @return int 0 or 1 0:放行 1:拒绝
* CL.THROTTLE user123 15 30 60
0) (integer) 0 # 0 表示允许,1表示拒绝
1) (integer) 16 # 漏斗容量
2) (integer) 15 # 漏斗剩余空间
3) (integer) -1 # 如果拒绝了,需要多长时间后再试(漏斗有空间了,单位秒)
4) (integer) 2 # 多长时间后,漏斗完全空出来
*/
public function isPass()
{
$rs = $this->redis->rawCommand('CL.THROTTLE', $this->key, $this->max_burst, $this->tokens, $this->seconds, $this->apply);
return $rs;
}
}
<file_sep><?php
/**
* 查询订单支付状态
*/
include ('function.php');
include ('config.php');
include ('Payment.php');
include ('order.php');
$params = [
'app_id' => APP_ID,
'mch_id' => MCH_ID,
'out_trade_no' =>$_POST['out_trade_no']
];
$order =new order();
$result=$order->query_order($params); //获取code_url
logInfo('query_result: '.json_encode($result),'qurey');//把查询结果写到日志中
if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){//返回查询结果
echo $result['trade_state'];
}else{
echo "FAIL";
}
<file_sep><?php
require __DIR__."/php/excel/Excel_helper.php";
$export = new Excel_helper();
//$export->export();
//$export->exporter();
$export->import();<file_sep><?php
/**
* 直连交换机
* 显示声明路由及交换机
*/
//www.try.com/php/rabbitmq/direct_exchange/product.php
require "rabbitmq.php";
$message ='{"available_stock":2,"on_way_stock":1,"sku":"JY18009-013","warehouse_code":"CKY_AU","type":"add"}';
$queueName = "test_upload_data";
$key_route ="test_key_route";
$exchange_name = "test_exchange_name";
$rabbitmq = new RabbitMQ();
$rabbitmq->sendMessage($message,$queueName,$key_route,$exchange_name);
$rabbitmq_1 = new RabbitMQ();
$rabbitmq_1->sendMessage($message,$queueName,'test_key_route_1',$exchange_name);
<file_sep><?php
class RabbitMQ{
//消息队列服务器配置
// private static $config =array(
// 'host' => '192.168.71.192',
// 'port' => 5672,
// 'login' => 'mquser',
// 'password' => '<PASSWORD>***',
// //'vhost' => '/'
// );
//本地测试配置
private static $config =array(
'host' => '127.0.0.1',
'port' => 5672,
'login' => 'mandelay',
'password' => '<PASSWORD>***',
'vhost' => 'test_host'
);
//MQ连接对象
private static $rabbitClient = null;
public function __construct()
{
$connection = new AMQPConnection(self::$config);
$connection->connect();
if($connection->isConnected()){
self::$rabbitClient = $connection;
}else{
throw new Exception("连接失败");
}
}
/**
* 说明 不需要以守护进程的方式在服务端运行
* 发送消息 生产者
* @param string $message 要发送的信息
* @param string $queue_name 队列名称
* @param string $key 路由KEY rounting-key
* @param string $exchange_name 交换机名称
* @return mixed
*/
public function sendMessage($message, $queue_name = 'df_queue', $key = 'df_key', $exchange_name = 'yb_erp_dc')
{
//检测是否连接
if(is_null(self::$rabbitClient)){
throw new Exception("连接MQ失败");
}
//重连机制
if (self::$rabbitClient->isConnected() == false) {
if (!self::$rabbitClient->reconnect()) {
throw new Exception("重新连接MQ失败");
}
}
try{
//第一步创建信号通道
$channel = new AMQPChannel(self::$rabbitClient);
//第二步根据信号通道创建交换机
$exchange = new AMQPExchange($channel); // 创建交换机
$exchange->setName($exchange_name); // 设置交换机名称
$exchange->setType( AMQP_EX_TYPE_DIRECT); // 设置交换机类型
$exchange->setFlags(AMQP_DURABLE); // 持久化 即使重启数据依旧存在
$exchange->declareExchange(); // 声明此交换机
//第三步 根据信号通道创建队列
$queue = new AMQPQueue($channel); // 创建队列
$queue->setName($queue_name); // 队列名称
$queue->setFlags(AMQP_DURABLE); // 持久化 即使重启数据依旧存在
$queue->declareQueue(); // 声明此队列
//第四步将队列、交换机、rounting-key 三者绑定
$queue->bind($exchange_name, $key); // 将队列、交换机、rounting-key 三者绑定
//第五部将消息存入队列
if (is_array($message) || is_object($message)) { // 存入的消息数据一定是字符串
$message = json_encode($message);
}
$result = $exchange->publish($message,$key); //发送消息数据到队列
if(!$result){
throw new Exception('发送MQ消息失败');
}
return $result;
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
/**
* 说明:需要以守护进程的方式在服务端运行
* 接收消息 消费者
* @param funtion $callback 消息回调方法
* @return [type] [description]
*/
public function receiveMessage($callback,$queue_name = 'df_queue'){
//检测是否连接
if (is_null(self::$rabbitClient)) {
throw new Exception("连接MQ失败");
}
//重连机制
if (self::$rabbitClient->isConnected() == false) {
if(!self::$rabbitClient->reconnect()){
throw new Exception("重新连接MQ失败");
}
}
//判断是否为回调函数
if (empty($callback) || !is_callable($callback)) {
throw new Exception("callback 必须是回调函数");
}
try{
//第一步创建信号通道
$channel = new AMQPChannel(self::$rabbitClient);
//第二步 根据信号通道创建队列
$queue = new AMQPQueue($channel); // 创建队列
$queue->setName($queue_name); // 队列名称
//消费对列里面的消息
$queue->consume(function($envelope, $queue) use ($callback){
$msg = $envelope->getBody (); //拿出来的一定是字符串
$reMsg = json_decode($msg,true);
if(!is_null($reMsg)){
$msg = $reMsg;
}
$result = call_user_func ( $callback, $msg );
if ($result) {
$queue->ack ($envelope->getDeliveryTag ()); //消息确认 自动发送ack确认(AMQP_AUTOACK) 确认已收到消息,并把消息从队列中移除
}else{
//nack调用测试
$queue->nack($envelope->getDeliveryTag()); //默认是不传递第二个参数(AMQP_NOPARAM),此种情况下 消息从队列中删除,不会重新赛回队列
//$queue->nack($envelope->getDeliveryTag(), AMQP_REQUEUE); //传递第二个参数(AMQP_REQUEUE) 消息数据会重新赛回队列的最前面 此时获取的一直是这条消息,那些未处理的数据谁也拿不到,包括当前消费者
}
});
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
public function __destruct(){
if(self::$rabbitClient){
self::$rabbitClient->disconnect();
}
self::$rabbitClient = null;
}
}<file_sep><?php
class Logic{
//消息处理逻辑
public function msgHandle($msg){
file_put_contents('./../../../log/mq.txt',json_encode($msg).PHP_EOL,FILE_APPEND);
}
}<file_sep><?php
/**
* swoole 进程池
*
* 后台守护进程 模式运行
* /usr/local/php/bin/php /home/wwwroot/try/pool.php > /dev/null 2>&1 &
*
* ps -ef | grep pool.php
*
* ps -ef | grep ordersys*
*
*
* /usr/local/php/bin/php /home/wwwroot/tms/appdal/index.php /ordersys/console/ShipCost/sync
*
*/
//报错日志开启
ini_set("display_errors","1");//开启报错日志
error_reporting(-1); //所有报错
//$workerNum = 5;
$workerNum = 10;
$pool = new Swoole\Process\Pool($workerNum,SWOOLE_IPC_UNIXSOCK, 0, true);
$pool->on("WorkerStart", function (Swoole\Process\Pool $pool, $workerId) {
$process = $pool->getProcess();
$path_entry = '/home/wwwroot/tms/appdal/index.php';
//传递2个参数 'WYT_model'和 "1"
//$process->exec("/usr/local/php/bin/php", [$path_entry, 'ordersys/console/ShipCost/getCost','WYT_model',"1"]);
//$process->exec("/usr/local/php/bin/php", [$path_entry, 'ordersys/console/ShipCost/getCost','WYT_model']); // 拉去万邑通财务费用项数据
$process->exec("/usr/local/php/bin/php", [$path_entry, '/ordersys/console/ShipCost/sync']); // 包裹重量回推给物流商
});
$pool->on("WorkerStop", function ($pool, $workerId) {
echo "Worker#{$workerId} is stopped\n";
});
$pool->start();
<file_sep><?php
$before = inputs_multi_1();
$after = inputs_multi_2();
function diff($before,$after,&$diff = []){
$before_keys = array_keys($before);
$after_keys = array_keys($after);
$keys = array_unique(array_merge($before_keys,$after_keys));
foreach ($keys as $key){
if(array_key_exists($key,$after) && array_key_exists($key,$before) && is_array($before[$key]) && is_array($after[$key])){
$result = diff($before[$key],$after[$key],$diff[$key]);
if(!empty($result)){
$diff[$key] = $result;
}else{
unset($diff[$key]);
}
}else{
if(isset($before[$key]) && isset($after[$key])){
if($before[$key] !== $after[$key]){
$diff[$key] = $after[$key];
}
}elseif(isset($before[$key]) && !isset($after[$key])){
$diff[$key] = null;//被删除
}elseif(!isset($before[$key]) && isset($after[$key])){
$diff[$key] = $after[$key];//新添加
}
}
}
return $diff;
}
$diff = diff($before,$after);
// print_r(json_encode($diff));
function inputs_multi_1(){
$data = array(
'id' => 3,
'spu'=> '201915888',//商品spu
'category_id'=>'4859',//分类id
'product_type'=>1,//多属性
'product_status'=>1,//商品状态
'en_title'=>'英文名称',//英文名称
'zh_title'=>'中文名称',//中文名称
'orgin_img_url'=>'www.baidu.com',//来源
'description'=>'gdfhfgjhgjgkrttyrdfhfgjjf0000000',//描述
'height'=>'10',//高
'width'=>'20',//宽
'length'=>'30',//长
'developer'=>'144859',//开发人
'purchaser'=>'12561',//采购人
'bind_rule'=> '',//组合规则
//sku信息
'sku_info'=>[
'201915777-01'=>[
'attribute'=>json_encode([
['variant_name'=>'color','variant_value'=>'blue'],
['variant_name'=>'size','variant_value'=>'XXL'],
]),
'en_title'=>'英文名称-red-XXL',
'zh_title'=>'中文名称-red-XXL',
'gross_weight'=>'5.698',
'net_weight'=>'5.698',
'purchase_cost'=>'8',
'zh_customs_declaration'=>'报关中文名',
'en_customs_declaration'=>'报关英文名',
'customs_declaration_weight'=>'5.69',
'customs_declaration_value'=>'5.69',
'customs_code'=>'hg_8888888',
'transport_attribute'=>1,
],
'201915777-02'=>[
'attribute'=>json_encode([
['variant_name'=>'color','variant_value'=>'red'],
['variant_name'=>'size','variant_value'=>'XXL'],
]),
'en_title'=>'英文00000名称-red-XL',
'zh_title'=>'中文00000名称-red-XL',
'gross_weight'=>'5.698',
'net_weight'=>'5.698',
'purchase_cost'=>'9',
'zh_customs_declaration'=>'报关中文名',
'en_customs_declaration'=>'报关英文名',
'customs_declaration_weight'=>'5.69',
'customs_declaration_value'=>'5.69',
'customs_code'=>'hg_8888888',
'transport_attribute'=>1,
],
'201915777-03'=>[
'attribute'=>json_encode([
['variant_name'=>'color','variant_value'=>'blue'],
['variant_name'=>'size','variant_value'=>'XL'],
]),
'en_title'=>'英文0000名称-blue-XXL',
'zh_title'=>'中文0000名称-blue-XXL',
'gross_weight'=>'5.698',
'net_weight'=>'5.698',
'purchase_cost'=>'10',
'zh_customs_declaration'=>'报关中文名',
'en_customs_declaration'=>'报关英文名',
'customs_declaration_weight'=>'5.69',
'customs_declaration_value'=>'5.69',
'customs_code'=>'hg_8888888',
'transport_attribute'=>1,
],
'201915777-04'=>[
'en_title'=>'英文0000名称-blue-XL',
'zh_title'=>'中文0000名称-blue-XL',
'gross_weight'=>'5.698',
'net_weight'=>'5.698',
'purchase_cost'=>'11',
'zh_customs_declaration'=>'报关中文名',
'en_customs_declaration'=>'报关英文名',
'customs_declaration_weight'=>'5.69',
'customs_declaration_value'=>'5.69',
'customs_code'=>'hg_8888888',
'transport_attribute'=>1,
]
],
);
return $data;
}
function inputs_multi_2(){
$data = array(
'id' => 3,
'spu'=> '201915777',//商品spu
'category_id'=>'4859',//分类id
'product_type'=>1,//多属性
'product_status'=>1,//商品状态
'en_title'=>'英文名称',//英文名称
'zh_title'=>'中文名称',//中文名称
'orgin_img_url'=>'www.baidu.com',//来源
'description'=>'gdfhfgjhgjgkrttyrdfhfgjjf0000000',//描述
'height'=>'10',//高
'width'=>'20',//宽
'length'=>'30',//长
'developer'=>'144859',//开发人
'purchaser'=>'12561',//采购人
'bind_rule'=> '',//组合规则
//sku信息
'sku_info' => [
'201915777-01' => [
'en_title' => '英文0000名称-red-XXL',
'zh_title' => '中文0000名称-red-XXL',
'gross_weight'=> '5.698',
'net_weight'=> '5.698',
'purchase_cost'=> '8',
'zh_customs_declaration' => '报关中文名',
'en_customs_declaration' => '报关英文名',
'customs_declaration_weight' => '5.69',
'customs_declaration_value' => '5.69',
'customs_code' => 'hg_8888888',
'transport_attribute' => 1,
],
'201915777-02' => [
'en_title'=>'英文00000名称-red-XL',
'zh_title'=>'中文00000名称-red-XL',
'gross_weight'=>'5.698',
'net_weight'=>'5.698',
'purchase_cost'=>'9',
'zh_customs_declaration' => '报关99中文名',
'en_customs_declaration' => '报关英文名',
'customs_declaration_weight' => '5.69',
'customs_declaration_value' => '5.69',
'customs_code' => 'hg_8888888',
'transport_attribute' => 1,
],
'201915777-03' => [
'en_title'=>'英文0000名称-blue-XXL',
'zh_title'=>'中文0000名称-blue-XXL',
'gross_weight'=>'5.698',
'net_weight'=>'5.698',
'purchase_cost'=>'10',
'zh_customs_declaration'=>'报关中文名',
'en_customs_declaration'=>'报关英文名',
'customs_declaration_weight'=>'5.69',
'customs_declaration_value'=>'5.69',
'customs_code'=>'hg_8888888',
'transport_attribute'=>1,
],
'201915777-05' => [
'en_title'=>'英文0000名称-blue-XL',
'zh_title'=>'中文0000名称-blue-XL',
'gross_weight'=>'5.698',
'net_weight'=>'5.698',
'purchase_cost'=>'11',
'zh_customs_declaration'=>'报关中文名',
'en_customs_declaration'=>'报关英文名',
'customs_declaration_weight'=>'5.69',
'customs_declaration_value'=>'5.69',
'customs_code'=>'hg_8888888',
'transport_attribute'=>1,
]
],
);
return $data;
}
<file_sep><?php
$targetUrl = "https://api.jiaxincloud.com/rest/workgroup/token";
$ch = curl_init($targetUrl);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HTTPGET, 1);
curl_setopt($ch,CURLOPT_TIMEOUT,30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch,CURLOPT_HTTPPROXYTUNNEL, 1);
$content = curl_exec($ch);
curl_close($ch);
echo $content;
echo "\r\n";
$content = json_decode($content);
$authstring = $content->www_Authenticate;
$auth = explode(",",$authstring);
foreach ($auth as $value){
if ( strstr($value,"nonce") ){
$Anonce = explode("=",$value);
$nonce = str_replace("\"","",$Anonce[1]);
}
if ( strstr($value,"opaque") ){
$Aopaque = explode("=",$value);
$opaque = str_replace("\"","",$Aopaque[1]);
}
}
echo $authstring;
echo "\r\n";
echo "nonce:" . $nonce;
echo "\r\n";
echo "opaque:" . $opaque;
$username = "<EMAIL>";
$password = "<PASSWORD>";
$real = "jiaxincloud.com";
$mdstr = $username . ":" . $real . ":" . $password;
$ha1 = md5($mdstr);
echo "\r\n";
echo "ha1:". $ha1;
$mdstr = "GET:" . "https://api.jiaxincloud.com/rest/workgroup/token";
$ha2 = MD5($mdstr);
echo "\r\n";
echo "ha2:". $ha2;
$nc = "00000001";
$cnonce=md5(time().mt_rand(10000,99999));//由我们定义,保证唯一性就可以了
//$cnonce = "ab1b2f2d-3b0a-4eba-bd93-d56b5879a139";
$qop = "auth";
$mdstr = $ha1 . ":" . $nonce . ":" . $nc . ":" . $cnonce . ":" . $qop . ":" . $ha2;
$response = MD5($mdstr);
echo "\r\n";
echo "response:". $response;
$tmp_value = "Digest username=\"".$username."\",realm=\"jiaxincloud.com\",nonce=\"" . $nonce;
$tmp_value = $tmp_value . "\",uri=\"" . $targetUrl . "\",qop=\"auth\",nc=\"" . $nc . "\",cnonce=\"" . $cnonce . "\",response=\"" . $response . "\",opaque=\"" . $opaque . "\"";
echo "\r\n";
echo $tmp_value;
echo "\r\n";
//$headers = array('Authorization:' => $tmp_value);
$headers = array(
'Authorization:'.$tmp_value
);
$ch = curl_init($targetUrl);
curl_setopt($ch,CURLOPT_HEADER,1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HTTPGET, 1);
curl_setopt($ch,CURLOPT_TIMEOUT,30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch,CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch,CURLOPT_HTTPPROXYTUNNEL, 1);
$content = curl_exec($ch);
curl_close($ch);
echo "\r\n";
echo "content:". $content;
echo "\r\n";
$result = explode("\r\n",$content);
$content = $result[count($result) - 1];
$content = json_decode($content);
echo "\r\n";
$token = $content->token;
echo "\r\n";
echo "token:" . $token;
echo "\r\n";
?><file_sep><?php
require '../redis/redisClient.php';
/**
* 命令行 php要支持 redis、pcntl、posix扩展
* 分布式锁的说明 前提单个redis服务器 这个类对锁进行详细分析说明
* 分布式锁 下面是分布式满足条件
* 1.互斥性 在任意时刻 只能有一个客户端持有锁
* 2.不会发生死锁 即使有一个客户端在持有锁的期间程序发生崩溃而没有主动解锁,也能保证后续其他客户端能加锁
* 3.解铃还须系铃人,加锁和解锁必须是同一个客户端,客户端自己不能把别人加的锁给解锁,即不能误解锁
* Class Lock
*/
class Lock_two
{
public $redis;
public $token;
public $lock_pool;
public $ParentPid; //父进程ID
public function __construct()
{
$this->ParentPid = posix_getpid();
$this->redis = new redisClient();
}
/**
* 获取锁
* @param $key 锁名
*
* @param int $maxTtl 锁的过期时间还剩余的最大值 即所设置的锁过期时间
*
* @param int $minTtl 锁的过期时间还剩余的最小限制值 如果某业务处理耗时过长, 发生阻塞 , 如果阻塞时间超过了锁设置的过期时间 ,那锁就会自动释放
* 此时业务还未执行完成 就导致其他客户端获得锁,获得相同的资源, 执行了操作, 这就不满足高并发下锁的互斥性
* 所以当某业务处理耗时过长 发生阻塞时 就要检查锁的过期时间还剩余的时长是否小于此值(锁的过期时间还剩余的最小限制值)
* 如果小于此值,就给锁续命,直到该业务执行完毕后主动释放锁
* $waitLock
* @return bool
*/
public function lock($key,$maxTtl=10,$minTtl = 2,$reTryNum = 10,$usleep = 10000)
{
//互斥性 在任意时刻 只能有一个客户端持有锁
$getLock = false;
//if($this->redis->exists($key)) return $getLock;
//锁的唯一标识 防止当前客户端解锁了别的客户端加的锁 对于同一个资源加锁 $key是一样的 值要不一样
$this->token = uniqid().mt_rand(111111111,999999999);
while($reTryNum-- >0){
// 加锁并保存锁的唯一标识 NX 保证锁的互斥性,EX:保证不会发生死锁 即使程序发生意外 没有主动解锁 也能通过自动过期而解锁
$res = $this->redis->set($key,$this->token,['NX','EX' =>$maxTtl]);
if($res){
$this->lock_pool[$key] = $this->token;
$getLock = true;
break;
}
usleep($usleep);
}
//同时产生父进程与子进程 父进程先于子进程执行
$pid = pcntl_fork();
if($pid == -1 ){
//子进程产生失败
$this->unlock($key, $this->token);
return false;
}elseif ($pid){
//$pid>0 父进程
return $getLock;
}else{
// $pid=0 子进程 如果某业务处理耗时过长, 发生阻塞 , 如果阻塞时间超过了锁设置的过期时间 ,那锁就会自动释放
// 此时业务还未执行完成 就导致其他客户端获得锁,获得相同的资源 为避免这种情况的发生,就要给锁续命 直到该业务执行完毕后主动释放锁 这就又保证锁的互斥性
// 这里会有一个问题产生 如果业务执行完毕后 发生异常 锁没有得到释放 锁又被一直续命 就会产生死锁(父进程执行结束,子进程依然会自行)
sleep($reTryNum*$usleep);
$startMonitor = microtime(true);
$flag = true;
do{
$delay = $this->redis->delayExpire($key,$this->token,$minTtl,$maxTtl);
if(!$delay){
$flag = false;
}
//心跳测试 查看父进程是否还在运运行
if(!posix_kill($this->ParentPid, 0)){
$flag = false;
}
}while($flag);
}
pcntl_waitpid($pid);
}
/**
* 延长锁的过期时间 给锁续命或续租
* @param $key 锁名
*
* @param $token 锁的唯一标识 防止当前客户端解锁了别的客户端加的锁
*
* @param $maxTtl 锁的过期时间还剩余的最大值 即所设置的锁过期时间
*
* @param $minTtl 锁的过期时间还剩余的最小限制值 如果某业务处理耗时过长, 发生阻塞 , 如果阻塞时间超过了锁设置的过期时间 ,那锁就会自动释放
* 此时业务还未执行完成 就导致其他客户端获得锁,获得相同的资源, 执行了操作, 这就不满足高并发下锁的互斥性
* 所以当某业务处理耗时过长 发生阻塞时 就要检查锁的过期时间还剩余的时长是否小于此值(锁的过期时间还剩余的最小限制值)
* 如果小于此值 就给锁续命 知道改业务执行完毕后主动释放锁
* @return mixed
*/
private function delayExpire($key,$token,$minTtl,$maxTtl){
$script = '
if redis.call("exists", KEYS[1]) and redis.call("GET", KEYS[1]) == ARGV[1] then
if redis.call("ttl", KEYS[1]) <= ARGV[2] then
return redis.call("EXPIRE", KEYS[1],ARGV[3])
else
return 1
end
else
return 0
end
';
return $this->redis->eval($script, [$key, $token,$minTtl,$maxTtl], 1);
}
/**
* 释放锁
* @param $key 锁名
*
* @param $token 锁的唯一标识 防止当前客户端解锁了别的客户端加的锁
*
* @return mixed
*/
public function unlock($key, $token)
{
$script = '
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
';
return $this->redis->eval($script, [$key, $token], 1);
}
}
function secKill(){
$lock = new Lock();
$key = "secKill";
//获取锁
if($lock->lock($key,5,2)){
//假设某业务处理耗时过长,发生阻塞10s
sleep(10);
//业务执行完毕释放锁
$lock->unlock($key);
}
}<file_sep><?php
ini_set("display_errors", "On");
error_reporting(-1);
$file_content = date();
swoole_async_writefile(__DIR__.'/write.txt', $file_content, function($filename) {
echo "wirte ok.\n";
}, $flags = 0);
echo 99999999;<file_sep><?php
/**
* Created by Apple.
* Date: 2019/02/14
*
* 平台仓换标登记表-上架出库1 FBA 接口URL文件
* 主机名的配置在 config/host_config.php 中
*/
$config['api_order_sys_platformShelfOutGc'] = array(
'_baseUrl' => '/ordersys/api/platformShelfOutGc',
'_listUrl' => '/index', //页面显示
'_addUrl' => '/addOne', //添加
'_editUrl' => '/editOne', //修改
'_dropUrl' => '/drop', //删除
'_importUrl' => '/import', //导入
'_exportUrl' => '/export', //导出
);<file_sep><?php
//PHP运行过程中出现 notice warning、fatal错误时 获取报错信息
// 错误处理函数
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "已通知网站管理员";
// message_type 是0,发送信息到php.ini配置的 error_log 参数的文件中
// message_type 是1,直接发送到邮箱,需要配置postfix和php.ini的sendmail
// message_type 是3就发送到第三个参数指定的文件中
// message_type 是4直接发送到 SAPI 的日志处理程序中,比如返回给了nginx,可以在nginx配置的error_log里看到。
error_log("Error: [$errno] $errstr", $message_type=1, "<EMAIL>", "From: <EMAIL>");
}
// 设置错误处理函数
set_error_handler("customError");
//echo 5/0;
// 触发错误
$test = 2;
if ($test > 1) {
trigger_error("变量值必须小于等于 1", E_USER_WARNING);
}
<file_sep><?php
class redisClient
{
public $redis;
public function __construct()
{
$this->redis = new Redis();//安装PHP的redis C语言扩展 各种操作方法名与redis命令名相同
//$this->redis->connect('127.0.0.1',6379);
$this->redis->connect('192.168.71.141',7001);
$this->redis->auth('yis@2019._');
$this->redis->select(0);
}
/**
* 直接传入命令配置
* @param $command 命令字符串 遵循lua语法 必选参数
* @param $value 含有键和值的数组 可选参数
* @param $key_num 建的数量 可选参数
* redis.call() 可以执行redis的任何命令
*/
public function eval_command($command,$value,$key_num){
$this->redis->eval($command,$value,$key_num);
}
public function __set($name, $value)
{
$this->redis->$name();
}
public function __destruct()
{
$this->redis->close();
}
}<file_sep><?php
/**
* 文档:https://xlswriter-docs.viest.me/zh-cn
* 需要装php 安装 扩展 xmlwriter
* excel 表格数据导入 (读取)
* excel 表格数据导出 (写入)
* Class Excel_helper
*/
class Excel_helper {
public $redis;
public $query;
public $db;
public $limit = 10000; //设置相对较大 导出速度越快
public $excel;
public function __construct()
{
$this->ParentPid = posix_getpid();
$this->redis = new Redis();
$this->redis->connect('192.168.71.141',7001);
$this->redis->auth('yis@2019._');
$this->redis->select(9);
$this->db = new mysqli('192.168.71.141','devuser','yb123456','yb_tms_logistics');
$this->excel = new \Vtiful\Kernel\Excel(['path' =>'/home/wwwroot/try']);
}
/**
* 导出
* 所有数据导出到同一个工作表
*/
public function export(){
//切分数据
if(!$this->redis->exists("export_queue")){
if(!$this->splitData('export_queue',$this->limit)) return [];
}
//分段取出
$export_fields = [
"task_id" => "任务ID",
"serial_no" => "费用流水号",
"business_document_no" => "业务单号",
"seller_no" => "订单号",
"tracking_no" => "跟踪号",
"company_code" => "物流公司code",
"business_type" => "业务类型名称",
"line_type" => "业务类型",
"fee_type" => "业务类型名称",
"weight" => "实重",
"charge_weight" => "计费重",
"weight_unit" => "计费重单位",
"volume" => "体积",
"charge_volume" => "计费体积",
"volume_unit" => "体积单位",
"charge_name" => "费用名称",
"source_amt" => "原币值",
"source_currency" => "原币种",
"acct_amt" => "目标币值",
"acct_currency" => "目标币种",
"exchange_rate" => "汇率",
"acct_date" => "记账时间",
"exchange_date" => "交易时间",
"trans_type" => "运输类型",
"ana_status" => "分析状态",
"create_time" => "创建时间",
"modify_time" => "更新时间",
];
$fields = array_keys($export_fields);
$header = array_values($export_fields);
$fileName = "test_".time().".xlsx";
$file = $this->excel->fileName($fileName)->header($header);
while (($start_id = $this->sampling("export_queue")) && $start_id !==true ){
$sql = "select * FROM yibai_logistics_wyt_hwc_ship_cost_copy1 where company_code='WYT' and id >={$start_id} limit {$this->limit}";
$result = $this->query($sql)->result_array($fields,true);
if(!empty($result)){
$file->data($result)->output();
unset($result);
}
}
}
/**
* 导出
* 数据导出到不同工作表
* @return array
*/
public function exporter(){
//切分数据
if(!$this->redis->exists("export_queue")){
if(!$this->splitData('export_queue',$this->limit)) return [];
}
//分段取出
$export_fields = [
"task_id" => "任务ID",
"serial_no" => "费用流水号",
"business_document_no" => "业务单号",
"seller_no" => "订单号",
"tracking_no" => "跟踪号",
"company_code" => "物流公司code",
"business_type" => "业务类型名称",
"line_type" => "业务类型",
"fee_type" => "业务类型名称",
"weight" => "实重",
"charge_weight" => "计费重",
"weight_unit" => "计费重单位",
"volume" => "体积",
"charge_volume" => "计费体积",
"volume_unit" => "体积单位",
"charge_name" => "费用名称",
"source_amt" => "原币值",
"source_currency" => "原币种",
"acct_amt" => "目标币值",
"acct_currency" => "目标币种",
"exchange_rate" => "汇率",
"acct_date" => "记账时间",
"exchange_date" => "交易时间",
"trans_type" => "运输类型",
"ana_status" => "分析状态",
"create_time" => "创建时间",
"modify_time" => "更新时间",
];
$fields = array_keys($export_fields);
$header = array_values($export_fields);
$fileName = "test_".time().".xlsx";
$file = $this->excel->fileName($fileName);
$count = 0;
while (($start_id = $this->sampling("export_queue")) && $start_id !==true ){
$sql = "select * FROM yibai_logistics_wyt_hwc_ship_cost_copy1 where company_code='WYT' and id >={$start_id} limit {$this->limit}";
$result = $this->query($sql)->result_array($fields,true);
if(!empty($result)){
//每10000条数据写入一个工作表
if((($count*$this->limit)%10000) == 0){
file_put_contents('/home/wwwroot/try/lockrty.txt',"page start fpid: ".$count.PHP_EOL.PHP_EOL,FILE_APPEND);
if($count===0){
//sheet1工作表
$file->header($header);
}else{
//sheet2、sheet3、sheet4 等工作表
$file->addSheet()->header($header);
}
}
$file->data($result)->output();
unset($result);
}
$count++;
}
}
/**
* 全量读取(导入)
*/
public function read_all(){
//全量读取 tutorial.xlsx test_1604498978.xlsx
$data = $this->excel->openFile('test_1604498978.xlsx')->openSheet("Sheet1")
//->setSkipRow(1) //忽略第一行
->getSheetData();
var_dump($data);
}
/**
* 使用该种方法 导入80万数据到数据库,只需90秒
* 逐行读取(导入)
*/
public function read_line(){
$start_time = time();
$export_fields = [
"task_id" => "任务ID",
"serial_no" => "费用流水号",
"business_document_no" => "业务单号",
"seller_no" => "订单号",
"tracking_no" => "跟踪号",
"company_code" => "物流公司code",
"business_type" => "业务类型名称",
"line_type" => "业务类型",
"fee_type" => "业务类型名称",
"weight" => "实重",
"charge_weight" => "计费重",
"weight_unit" => "计费重单位",
"volume" => "体积",
"charge_volume" => "计费体积",
"volume_unit" => "体积单位",
"charge_name" => "费用名称",
"source_amt" => "原币值",
"source_currency" => "原币种",
"acct_amt" => "目标币值",
"acct_currency" => "目标币种",
"exchange_rate" => "汇率",
"acct_date" => "记账时间",
"exchange_date" => "交易时间",
"trans_type" => "运输类型",
"ana_status" => "分析状态",
"create_time" => "创建时间",
"modify_time" => "更新时间",
];
$fields = implode(',',array_keys($export_fields));
//逐行读取 tutorial.xlsx test_1604498978.xlsx
$excel = $this->excel->openFile('test_1605665880.xlsx')->openSheet("Sheet1");
//读取标题头
$header = $excel->nextRow();
$values ='';
$i = 0;
//读取数据部分
while(($rows = $excel->nextRow()) !== null){
if(($i%10000) == 0){
$values = ltrim($values,',');
if(!empty($values)){
$sql = "insert into yibai_logistics_wyt_hwc_ship_cost_copy1 ({$fields}) values {$values};";
$this->db->query($sql);
file_put_contents('yy.txt',$sql.PHP_EOL,FILE_APPEND);
}
$values ='';
$values .= ",('".implode("','",$rows)."')";
}else{
$values .= ",('".implode("','",$rows)."')";
}
$i++;
}
if($values !=''){
$values = ltrim($values,',');
$sql = "insert into yibai_logistics_wyt_hwc_ship_cost_copy1 ({$fields}) values {$values};";
$this->db->query($sql);
}
$end_time = time();
echo "总行数 ",$i, "\n";
echo "总耗时", ($end_time - $start_time), "秒\n";
echo "峰值内存", round(memory_get_peak_usage()/1000), "KB\n";
}
/**
* 利用 mysql 的 load data infile命令实现
* 10万数据导入数据库中 可以说load data infile是秒级响应
*/
public function read_file(){
ini_set("display_errors","1");//开启报错日志
error_reporting(-1); //所有报错
$export_fields = [
"id" => "ID",
"task_id" => "任务ID",
"serial_no" => "费用流水号",
"business_document_no" =>"业务单号",
"seller_no" => "订单号",
"tracking_no" => "跟踪号",
"company_code" => "物流公司code",
"business_type" => "业务类型名称",
"line_type" => "业务类型",
"fee_type" => "业务类型名称",
"weight" => "实重",
"charge_weight" => "计费重",
"weight_unit" => "计费重单位",
"volume" => "体积",
"charge_volume" => "计费体积",
"volume_unit" => "体积单位",
"charge_name" => "费用名称",
"source_amt" => "原币值",
"source_currency" => "原币种",
"acct_amt" => "目标币值",
"acct_currency" => "目标币种",
"exchange_rate" => "汇率",
"acct_date" => "记账时间",
"exchange_date" => "交易时间",
"trans_type" => "运输类型",
"ana_status" => "分析状态",
"create_time" => "创建时间",
"modify_time" => "更新时间",
];
$fields = implode(',',array_keys($export_fields));
// load data local infile mysql服务器与 test_1605665888.csv在同一台主机
//$sql = "load data local infile '/home/wwwroot/try/test_1605665888.csv' into table yibai_logistics_wyt_hwc_ship_cost_copy1 fields terminated by',' enclosed by '\"' ignore 1 lines ({$fields});";
// load data infile mysql服务器与 test_1605665888.csv不在同一台主机
$sql = "load data infile '/home/wwwroot/try/test_1605665888.csv' into table yibai_logistics_wyt_hwc_ship_cost_copy1 fields terminated by',' enclosed by '\"' ignore 1 lines ({$fields});";
$this->db->query($sql);
}
/**
* 切分数据 进程从对列里拿去数据 进行处理
*/
public function splitData($tail_queue,$limit)
{
$this->getDB()->query("set @ind =0");
$this->getDB()->query("set @index =-1;");
$sql = "select * FROM (select @ind := @ind + 1 as rid,id FROM yibai_logistics_wyt_hwc_ship_cost where company_code='WYT') st where ((@INDEX := @INDEX + 1) > -1) and (@INDEX % {$limit} = 0);";
$result = $this->query($sql)->result_array();
if(!empty($result)){
foreach ($result as $item){
$this->redis->lPush($tail_queue,$item['id']);
}
return true;
}else{
return false;
}
}
/**
* 返回结果集
* @param $sql
* @return $this
*/
public function query($sql)
{
$this->query = $this->getDB()->query($sql);
return $this;
}
public function result_array($fields = "*",$export = false)
{
$result_array = [];
while($row = $this->query->fetch_assoc()){
if($export){
if(is_array($fields)){
$temp = [];
foreach ($fields as $field){
array_push($temp,$row[$field]);
}
$result_array[] = $temp;
}
}else{
$result_array[] = $row;
}
}
return empty($result_array)?[]:$result_array;
}
/**
*
* @param $lock_key
* @param $pool_key
* @return bool
*/
protected function sampling($queue)
{
$id = $this->redis->rpop($queue);
if (!$id) {
return true;
}else{
return $id;
}
}
/**
* @return mysqli
*/
public function getDB()
{
return $this->db;
}
/**
*
*/
public function __destruct()
{
$this->db->close();
}
}
//应用
//$export = new Excel_helper();
//$export->read_file();
//$export->exporter();
//$export->import_line();
<file_sep><?php
require "../../../curl/Curl.php";
class timer
{
//private $host = "http://www.tms-b.com/";
private $host = "www.tms-b.com/";
//private $host = "http://192.168.71.141:92/";
//private $php_cmd = "D:\code\phpstudy\PHPTutorial\php\php-7.1.13-nts\php D:\code\phpstudy\PHPTutorial\WWW\\tms\appdal\index.php ";
private $php_cmd = "php D:\code\phpstudy\PHPTutorial\WWW\\tms\appdal\index.php ";
private $taskString;
private $min;
private $hour;
private $day;
private $month;
private $week;
private $command;
private $process;
private $runTime;
private $first_min = 0;
private $last_min = 59;
private $first_hour = 0;
private $last_hour = 23;
private $first_day = 1;
private $last_day = 31;
private $first_month = 1;
private $last_month = 12;
private $first_week = 0;
private $last_week = 6;
/**
* @var string $taskString example: 10 * * * * php example.php
*/
public function __construct(string $taskString,$url)
{
$this->taskString = $taskString;
$this->command = $url;
$this->runTime = time();
$this->initialize();
//$reflect = new ReflectionClass(__CLASS__);
//$pros = $reflect->getProperties();
}
/**
* 初始化任务配置
*/
private function initialize()
{
//过滤多余的空格
$rule = array_filter(explode(" ", $this->taskString), function($value) {
return $value != "";
});
if (count($rule) < 5) {
throw new ErrorException("'taskString' parse failed");
}
$this->min = $this->format($rule[0], 'min');
$this->hour = $this->format($rule[1], 'hour');
$this->day = $this->format($rule[2], 'day');
$this->month = $this->format($rule[3], 'month');
$this->week = $this->format($rule[4], 'week');
}
private function format($value, $field)
{
if ($value === '*') {
return $value;
}
if (is_numeric($value)) {
return [$this->checkFieldRule($value, $field)];
}
$steps = explode(',', $value);
$scope = [];
foreach ($steps as $step) {
if (strpos($step, '/') !== false) {
$inter = explode('/', $step);
if(strpos($inter[0], '-') !== false){
$range = explode('-', $inter[0]);
$container = array_merge($scope, range(
$this->checkFieldRule($range[0], $field),
$this->checkFieldRule($range[1], $field)
));
foreach ($container as $v){
if($v%$inter[1] == 0){
$scope[] = intval($v);
}
}
}else{
$confirmInter = isset($inter[1]) ? $inter[1] : $inter[0];
if ($confirmInter === '/') {
$confirmInter = 1;
}
$scope = array_merge($scope, range(
$this->{"first_". strtolower($field)},
$this->{"last_". strtolower($field)},
$confirmInter
));
}
continue;
}
if (strpos($step, '-') !== false) {
$range = explode('-', $step);
$scope = array_merge($scope, range(
$this->checkFieldRule($range[0], $field),
$this->checkFieldRule($range[1], $field)
));
continue;
}
$scope[] = intval($step);
}
return $scope;
}
private function checkFieldRule($value, $field)
{
$first_const = 'first_' . strtolower($field);
$last_const = 'last_' . strtolower($field);
$first = $this->{$first_const};
$last = $this->{$last_const};
if ($value < $first) {
return $first;
}
if ($value > $last) {
return $last;
}
return (int) $value;
}
public function getTimeAttribute($attribute)
{
if (!in_array($attribute, ['min', 'hour', 'day', 'month', 'week', 'runTime'])) return null;
return $this->{$attribute} ?? null;
}
public function setRunTime($time)
{
$this->runTime = $time;
}
public function run_cli()
{
$command = $this->php_cmd.$this->command;
//shell_exec('cd ../../../../../tms/appdal && php index.php ordersys console ShipFee test');
exec($command);
}
public function run_curl()
{
if (null === $this->process) {
$this->process = new Curl();
}
$url = $this->host.$this->command;
$this->process->requestByCurlGet($url);
}
}<file_sep><?php
/**
* 主要采用 fputcsv 与 fgetcvs 函数实现
* Class Cvs_helper
*/
class Cvs_helper
{
public $redis;
public $query;
public $db;
public $limit = 10000; //设置相对较大 导出速度越快
public function __construct()
{
$this->ParentPid = posix_getpid();
$this->redis = new Redis();
$this->redis->connect('192.168.71.141',7001);
$this->redis->auth('yis@2019._');
$this->redis->select(9);
$this->db = new mysqli('192.168.71.141','devuser','yb123456','yb_tms_logistics');
}
/**
* 导出
* 80万数据15秒
* @param bool $download
* $download = true 时 浏览器直接下载打开
* @return array
*/
public function export($download=false){
//切分数据
if(!$this->redis->exists("export_queue")){
if(!$this->splitData('export_queue',$this->limit)) return [];
}
//分段取出
$export_fields = [
"task_id" => "任务ID",
"serial_no" => "费用流水号",
"business_document_no" => "业务单号",
"seller_no" => "订单号",
"tracking_no" => "跟踪号",
"company_code" => "物流公司code",
"business_type" => "业务类型名称",
"line_type" => "业务类型",
"fee_type" => "业务类型名称",
"weight" => "实重",
"charge_weight" => "计费重",
"weight_unit" => "计费重单位",
"volume" => "体积",
"charge_volume" => "计费体积",
"volume_unit" => "体积单位",
"charge_name" => "费用名称",
"source_amt" => "原币值",
"source_currency" => "原币种",
"acct_amt" => "目标币值",
"acct_currency" => "目标币种",
"exchange_rate" => "汇率",
"acct_date" => "记账时间",
"exchange_date" => "交易时间",
"trans_type" => "运输类型",
"ana_status" => "分析状态",
"create_time" => "创建时间",
"modify_time" => "更新时间",
];
$fields = array_keys($export_fields);
$fileName = "tester_".time().".csv";
if($download){
header('Content-Type: application/vnd.ms-execl');
header('Content-Disposition: attachment;filename="' . $fileName . '"');
//打开php标准输出流 以追加写入的方式打开
$fp = fopen('php://output', 'a');
}else{
$fp = fopen($fileName, 'w');
}
//header 标题
fputcsv($fp, array_values($export_fields));
//数据
while (($start_id = $this->sampling("export_queue")) && $start_id !==true ){
$sql = "select * FROM yibai_logistics_wyt_hwc_ship_cost_copy1 where company_code='WYT' and id >={$start_id} limit {$this->limit}";
$result = $this->query($sql)->result_array($fields,true);
foreach ($result as $item){
fputcsv($fp, $item);
}
if($download){
//刷新缓冲区
ob_flush();
flush();
}
unset($result);
}
fclose($fp);
}
/**
* 导入
* 80万数据70秒
*/
public function import()
{
if (($handle = fopen("test_1605665888.csv", "r")) !== FALSE) {
//读取标题
$start_time = time();
$header = fgetcsv($handle, 1500, ",");
$export_fields = [
"task_id" => "任务ID",
"serial_no" => "费用流水号",
"business_document_no" => "业务单号",
"seller_no" => "订单号",
"tracking_no" => "跟踪号",
"company_code" => "物流公司code",
"business_type" => "业务类型名称",
"line_type" => "业务类型",
"fee_type" => "业务类型名称",
"weight" => "实重",
"charge_weight" => "计费重",
"weight_unit" => "计费重单位",
"volume" => "体积",
"charge_volume" => "计费体积",
"volume_unit" => "体积单位",
"charge_name" => "费用名称",
"source_amt" => "原币值",
"source_currency" => "原币种",
"acct_amt" => "目标币值",
"acct_currency" => "目标币种",
"exchange_rate" => "汇率",
"acct_date" => "记账时间",
"exchange_date" => "交易时间",
"trans_type" => "运输类型",
"ana_status" => "分析状态",
"create_time" => "创建时间",
"modify_time" => "更新时间",
];
$fields = implode(',',array_keys($export_fields));
$values ='';
$i = 0;
//逐行读取
while (($rows = fgetcsv($handle, 1500, ",")) !== FALSE) {
foreach ($rows as $k => &$v){
if(in_array($k,[15])){
//乱码
$v = iconv('gbk','utf-8',$rows[15]);
}else{
$v = $rows[$k];
}
}
if(($i%10000) == 0){
$values = ltrim($values,',');
if(!empty($values)){
$sql = "insert into yibai_logistics_wyt_hwc_ship_cost_copy1 ({$fields}) values {$values};";
$this->db->query($sql);
file_put_contents('yy.txt',$sql.PHP_EOL,FILE_APPEND);
}
$values ='';
$values .= ",('".implode("','",$rows)."')";
}else{
$values .= ",('".implode("','",$rows)."')";
}
$i++;
}
if($values !=''){
$values = ltrim($values,',');
$sql = "insert into yibai_logistics_wyt_hwc_ship_cost_copy1 ({$fields}) values {$values};";
file_put_contents('yy.txt',$sql.PHP_EOL,FILE_APPEND);
$this->db->query($sql);
}
$end_time = time();
echo "总行数 ",$i, "\n";
echo "总耗时", ($end_time - $start_time), "秒\n";
echo "峰值内存", round(memory_get_peak_usage()/1000), "KB\n";
fclose($handle);
}
}
/**
* 切分数据 进程从对列里拿去数据 进行处理
*/
public function splitData($tail_queue,$limit)
{
$this->getDB()->query("set @ind =0");
$this->getDB()->query("set @index =-1;");
$sql = "select * FROM (select @ind := @ind + 1 as rid,id FROM yibai_logistics_wyt_hwc_ship_cost_copy1 where company_code='WYT') st where ((@INDEX := @INDEX + 1) > -1) and (@INDEX % {$limit} = 0);";
$result = $this->query($sql)->result_array();
if(!empty($result)){
foreach ($result as $item){
$this->redis->lPush($tail_queue,$item['id']);
}
return true;
}else{
return false;
}
}
public function query($sql){
$this->query = $this->getDB()->query($sql);
return $this;
}
/**
* @param string $fields
* @param bool $export
* @return array
*/
public function result_array($fields = "*",$export = false){
$result_array = [];
while($row = $this->query->fetch_assoc()){
if($export){
if(is_array($fields)){
$temp = [];
foreach ($fields as $field){
array_push($temp,$row[$field]);
}
$result_array[] = $temp;
}
}else{
$result_array[] = $row;
}
}
return empty($result_array)?[]:$result_array;
}
/**
*
* @param $lock_key
* @param $pool_key
* @return bool
*/
protected function sampling($queue)
{
$id = $this->redis->rpop($queue);
if (!$id) {
return true;
}else{
return $id;
}
}
/**
* @return mysqli
*/
public function getDB(){
return $this->db;
}
/**
*
*/
public function __destruct()
{
$this->db->close();
}
}
// 应用
//$export = new Cvs_helper();
//$export->import();
//$export->export(true);
<file_sep><?php
class xmlWrite {
/**
* 第一种方法:拼接
* @param array $data
* @return string
*/
function writer_1(array $data){
$html = '<?xml version="1.0"?>';
$html .='<root>';
foreach ($data as $key =>$val){
$html .='<'.$key.'>'.$val.'</'.$key.'>';
}
$html .='</root>';
return $html;
}
/**
* 第二种使用:DOMDocument对象
* @param $arr
* @param int $dom
* @param int $item
* @return string
*/
function writer_2($data){
$dom = new DOMDocument("1.0");
$dom->encoding = 'UTF-8';
$root = $dom->createElement("root");//创建root标签元素对象
$root->setAttribute("xmlns","http://www.cdiscount.com"); // 设置root标签元素的标签属性值
$this->test($data,$root,$dom);
$dom->appendChild($root);
return $dom->saveXML();
}
public function test($data,$root,$dom){
foreach ($data as $key=>$val){
if (!is_array($val['value'])){
$item = $dom->createElement($key,$val['value']);
if(isset($val['attr'])){
foreach ($val['attr']as $k => $v){
$item->setAttribute($k,$v);
}
}
$root->appendChild($item);
}else {
$item = $dom->createElement($key);
if(isset($val['attr'])){
foreach ($val['attr']as $k => $v){
$item->setAttribute($k,$v);
}
}
$root->appendChild($item);
$this->test($val['value'],$item,$dom);
}
}
}
/**
* 第三种使方法
*/
function writer_3($data){
header("Content-type: text/html; charset=utf-8");
$xml = new XMLWriter();
$xml->openUri("php://output");//输出到浏览器
$xml->openUri("./mimvp.xml");//输入到该文件
//设置缩进字符串
$xml->setIndentString("\t");
$xml->setIndent(true);
//xml文档开始
$xml->startDocument('1.0', 'utf-8');
//创建根节点
$xml->startElement("MimvpInfo");
$this->createSub($xml,$data);
$xml->endElement();
$xml->endDocument();
}
function createSub($xml,$data){
foreach ($data as $key =>$val){
if (!is_array($val['value'])){
$xml->startElement($key);
if(isset($val['attr'])){
foreach ($val['attr']as $k => $v){
$xml->writeAttribute($k,$v);
}
}
$xml->text($val['value']);
$xml->endElement();
}else{
$xml->startElement($key);
if(isset($val['attr'])){
foreach ($val['attr']as $k => $v){
$xml->writeAttribute($k,$v);
}
}
$this->createSub($xml,$val['value']);
$xml->endElement();
}
}
}
}
<file_sep><div>
<div id = "json" style="display:inline-block;width: 49.5%">
<?php echo
$json = '{
"ask": "Success",
"message": "",
"data": {
"order_business_type": "b2c",
"order_code": "90747-191209-0006",
"reference_no": "AL191209000688",
"platform": "ALIEXPRESS",
"order_status": "D",
"shipping_method": "IML-RU",
"tracking_no": "7181810235011",
"warehouse_code": "RUS2",
"order_weight": "2.3240",
"order_desc": "易佰API下单",
"date_create": "2019-12-09 02:20:02",
"date_release": "2019-12-09 02:20:03",
"date_shipping": "2019-12-10 07:03:04",
"date_modify": "2019-12-30 14:05:09",
"consignee_country_code": "RU",
"consignee_country_name": "RU",
"consignee_state": "Volgogradskaya oblast",
"consignee_city": "Volgograd",
"consignee_district": "",
"consignee_address1": "Eliseeva St,1-126",
"consignee_address2": "",
"consignee_address3": "",
"consigne_zipcode": "400120",
"consignee_doorplate": "",
"consignee_company": "",
"consignee_name": "<NAME>",
"consignee_phone": "9033776336",
"consignee_email": "",
"platform_shop": "",
"abnormal_reason": "",
"order_cod_price": "0.000",
"order_cod_currency": "",
"is_order_cod": "0",
"fee_details": {
"totalFee": "50.000",
"SHIPPING": "48.000",
"OPF": "2.000",
"FSC": "0.000",
"RSF": "0.000",
"WHF": "0.000",
"DT": "0.000",
"OTF": "0.000"
},
"currency": "RMB",
"items": [
{
"product_sku": "RU-YX01420",
"quantity": "2"
}
]
}
}';
?>
</div>
</div>
<file_sep><?php
// file_put_contents('./../../log/mq.txt',json_encode($msg).PHP_EOL,FILE_APPEND);
// $data 是个数组
$data = $_SERVER;
file_put_contents('./log.txt',"<?php\n".'return '.var_export($data, true).";\n\n?>",FILE_APPEND);<file_sep><?php
/**
* 直接消费死信队里里的消息
* 执行顺序:先运行消费者 然后在运行生产者 因为死信交换机及死信队列是在消费者中创建和声明的
*/
ini_set("display_errors","1");//开启报错日志
error_reporting(-1); //所有报错
//www.try.com/php/rabbitmq/dead_letter_exchange/customer.php
header('Content-Type: text/html; charset=utf-8');
$conConfig = [
'host' => '127.0.0.1',
'port' => 5672,
'login' => 'mandelay',
'password' => '<PASSWORD>***',
'vhost' => 'test_host'
];
while (true){
try {
//创建连接
$con = new AMQPConnection($conConfig);
$con->connect();
if (!$con->isConnected()) {
echo '连接失败';
die;
}
//根据连接创建通道 不设置预取数量时 工作队列模式下(一个队列有多个消费者) 采用的是轮询机制,高并发情况下,消息是完全平均分发给每个消费者
$channel = new AMQPChannel($con);
//通过通道获取默认交换机
$exchange = new AMQPExchange($channel);
$exchange_name = "dlx_exchange";
$exchange->setName($exchange_name); // 设置交换机名称
$exchange->setType( AMQP_EX_TYPE_DIRECT); // 设置交换机类型
$exchange->setFlags(AMQP_DURABLE); // 持久化 即使重启数据依旧存在
$exchange->declareExchange(); // 声明此交换机
//创建及声明一个队列作为死信对列 正常业务处理队列过期的消息会通过死信交换机发送给该队列
$queue_name = 'dead_letter_queue';
$queue = new AMQPQueue($channel);
$queue->setName($queue_name); // 队列名称
$queue->setFlags(AMQP_DURABLE); // 持久化 即使重启数据依旧存在
$queue->declareQueue(); // 声明此队列
//将队列、交换机、rounting-key 三者绑定
$routing_key = "dead_letter_key";
$queue->bind($exchange_name, $routing_key); // 将队列、交换机、rounting-key 三者绑定
//获取队列里的消息进行消费处理 手动发送ack确认(AMQP_NOPARAM) 确认已收到消息,并把消息从队列中移除
$queue->consume(function ($envelope, $queue) {
$msg = $envelope->getBody();
file_put_contents('./mq_2.txt',json_encode($msg).PHP_EOL,FILE_APPEND);
$queue->ack($envelope->getDeliveryTag());
},AMQP_NOPARAM);
$con->disconnect();
} catch (Exception $e) {
echo $e->getMessage();
}
}
<file_sep><?php
//www.try.com/php/rabbitmq/default_exchange/customer_one.php
header('Content-Type: text/html; charset=utf-8');
$conConfig = [
'host' => '127.0.0.1',
'port' => 5672,
'login' => 'mandelay',
'password' => '<PASSWORD>***',
'vhost' => 'test_host'
];
while (true){
try {
//创建连接
$con = new AMQPConnection($conConfig);
$con->connect();
if (!$con->isConnected()) {
echo '连接失败';
die;
}
//根据连接创建通道
$channel = new AMQPChannel($con);
$channel->setPrefetchCount(1); //设置预取消息个数为1, 工作队列模式下(一个队列有多个消费者) 确保每个消费者从同一个队里消费的消息数量一样多
//根据通道创建并指明要消费的队列
$queue_name = 'test.queue1';
$queue = new AMQPQueue($channel);
$queue->setName($queue_name);
//获取队列里的消息进行消费处理 不发送ack确认(AMQP_NOPARAM) 不确认已收到消息,不把消息从队列中移除
$queue->consume(function ($envelope, $queue) {
sleep(3);
$msg = $envelope->getBody();
//$queue->nack($envelope->getDeliveryTag());
//$queue->nack($envelope->getDeliveryTag(), AMQP_REQUEUE);
file_put_contents('./../../../log/mq_1.txt',json_encode($msg).PHP_EOL,FILE_APPEND);
});
$con->disconnect();
} catch (Exception $e) {
echo $e->getMessage();
}
}<file_sep><?php
//订阅
ini_set('default_socket_timeout', -1);//永不超时
require_once "redisClient.php";
$redis = new redisClient();
$channel = ['msg'];
//订阅是阻塞模式 有消息就处理; 没消息就阻塞等待 不用while(true){}结构
$redis->redis->subscribe($channel,function($redis, $chan, $msg) {
switch($chan) {
case 'msg':
file_put_contents('./100.txt',$msg.PHP_EOL.PHP_EOL,FILE_APPEND);
break;
case 'warn':
file_put_contents('./100.txt',$msg.PHP_EOL.PHP_EOL,FILE_APPEND);
break;
case 'error':
file_put_contents('./100.txt',$msg.PHP_EOL.PHP_EOL,FILE_APPEND);
break;
default:
file_put_contents('./100.txt',"default".PHP_EOL.PHP_EOL,FILE_APPEND);
}
});
<file_sep><?php
class Fedex_model
{
public $code = 'Fedex';
// 旧
// private $key = "<KEY>";
// private $password = "<PASSWORD>";
// private $account_number = "510088000";
// private $meter_number = "114090196";
//新
private $key = "<KEY>";
private $password = "<PASSWORD>";
private $account_number = "510087860";
private $meter_number = "119166370";
private $UploadDocumentServiceWsdl;
private $logo;
private $signature;
/**
* 实例化
* OST_model constructor.
* @throws Exception
*/
public function __construct()
{
$this->UploadDocumentServiceWsdl = PATH_WSDL.'/UploadDocumentService_v17.wsdl';
$this->logo = PATH_WSDL.'/logo.png';
$this->signature = PATH_WSDL.'/signature.png';
}
public function uploadEtdImage(){
//请求数据
$params = [
'WebAuthenticationDetail' => [
'UserCredential' => [
'Key' => $this->key,
'Password' => $<PASSWORD>
]
],
'ClientDetail' => [
'AccountNumber' => $this->account_number,
'MeterNumber' => $this->meter_number
],
'TransactionDetail' => [
'CustomerTransactionId' => time().mt_rand(100000000,999999999)
],
'Version' => [
'ServiceId' => 'cdus',
'Major' => '17',
'Intermediate' => '0',
'Minor' => '0'
],
'Images' => [
'0' => [
'Id' => 'IMAGE_1',
'Image' => $this->fileToBase64($this->logo)
],
'1' => [
'Id' => 'IMAGE_2',
'Image' => $this->fileToBase64($this->signature)
]
],
];
$result = $this->httpRequest($params,$this->UploadDocumentServiceWsdl,'uploadImages');
$this->pr($result);die;
}
/**
* 请求
* @param $data
* @param $wsdl
* @param $action
* @return array|bool
*/
private function httpRequest($data,$wsdl,$action)
{
try{
ini_set( 'soap.wsdl_cache_enabled', 0 );
$client = new SoapClient($wsdl, array('trace' => 1,'encoding'=>'ISO-8859-1'));
$client->__setLocation("https://wsbeta.fedex.com/web-services/uploaddocument");
return $result = $client->$action($data);
}
catch (SoapFault $exception)
{
var_dump($exception->getMessage());
return false;
}
}
/**
* 对象转数组
* @param $data
* @return array
*/
public function objectToArray($data)
{
if(is_array($data)){
foreach ($data as $key => $value){
$data[$key] = $this->objectToArray($value);
}
}elseif (is_object($data)){
$data = (array) $data;
foreach ($data as $key => $value){
$data[$key] = $this->objectToArray($value);
}
}
return $data;
}
/**
* 文件转base64输出
* @param String $file 文件路径
* @return String base64 string
*/
private function fileToBase64($file){
$base64_file = '';
if(file_exists($file)){
$mime_type = (new finfo(FILEINFO_MIME_TYPE))->file($file);
$base64_data = base64_encode(file_get_contents($file));
//$base64_file = 'data:'.$mime_type.';base64,'.$base64_data;
$base64_file = $base64_data;
}
return $base64_file;
}
private function pr($arr, $escape_html = true, $bg_color = '#EEEEE0', $txt_color = '#000000')
{
echo sprintf('<pre style="background-color: %s; color: %s;">', $bg_color, $txt_color);
if ($arr) {
if ($escape_html) {
echo htmlspecialchars(print_r($arr, true));
} else {
print_r($arr);
}
} else {
var_dump($arr);
}
echo '</pre>';
}
}<file_sep><?php
class Payment{
//获取用于生成二维码的url方法
function generateScanUrl($product_id){
$params= [
'appid' => APP_ID,
'mch_id' => MCH_ID,
'nonce_str' => uniqid(),//php生成唯一字符窜函数
'time_stamp'=> strval(time()),
'product_id' =>$product_id
];
$params['sign'] = generateSign($params,KEY);
$prefix = "weixin://wxpay/bizpayurl?";
$url = $prefix.http_build_query($params);
return $url;
}
}<file_sep><?php
//bin/php D:\code\phpstudy\PHPTutorial\WWW\try\php\rabbitmq\direct_exchange\customer.php 已守护进程的模式运行在服务端
require "rabbitmq.php";
require "logic.php";
$queueName = "test_upload_data";
$rabbitmq = new RabbitMQ();
$googleSyncStock = new Logic();
while(true) {
$rabbitmq->receiveMessage([$googleSyncStock, 'msgHandle'], $queueName);
sleep(2);
}
| 0f6df8329c313b66fbc12acca3cad5fc14bba21f | [
"Hack",
"ApacheConf",
"Python",
"PHP"
] | 97 | Hack | yourant/try | 2363fca81e34e5d7c2814f8e8b95c96146ffa5b5 | aebb2bf86e62eff016bd2fde70ebcae306e1e3bb |
refs/heads/master | <file_sep># TP Sintaxis y semántica de los lenguajes - Reconocimiento de palabras con automatas
## Requirements / Tested on
- Microsoft Visual Studio 2008
## Author
- <NAME>
## Project date
- 07/07/2013<file_sep>// automata.cpp: define el punto de entrada de la aplicación de consola.
//
#include "stdafx.h"
#include <Windows.h>
int columna(char caracter)
{
switch(caracter)
{
//caracteres del alfabeto
case 'a': return 0;
case 'b': return 1;
case '0': return 2;
case '1': return 3;
}
}
int esPalabra(char *cadena)
{
int estado = 0;
static int automata[8][4] = {
{1,7,7,7},{2,7,7,7},{3,5,4,4},{2,7,7,7},
{7,5,4,4},{7,6,7,7},{7,5,7,7},{7,7,7,7}
};
for(int i = 0; cadena[i] != '\0'; i++)
estado = automata[estado][columna(cadena[i])];
if(estado == 5) //5 es estado final.
return 1;
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
char cadena[100]; // 100 = tamaño máximo de cadena que ingresa
FILE *fIn = fopen("input.txt", "r");
FILE *fOut = fopen("output.txt", "w+");
while( fscanf(fIn, "%s", cadena) != EOF )
{
if( esPalabra(cadena) )
fprintf(fOut, "%s\r\n", cadena);
}
fclose(fIn);
fclose(fOut);
return 0;
}
| 70d6da11a7af87d66d9b83a389ab1a4b1079c383 | [
"Markdown",
"C++"
] | 2 | Markdown | FernandoVelcic/tp2013-ssl-automata-algorithm | 8ced1da54e6b7a827eca81da45c250b29017cb9c | 0227d670365f842fcb5fac7f3a64e0406646c286 |
refs/heads/master | <repo_name>jaiminpatel98/Paris-Metro-Dijkstra-Algorithm<file_sep>/ParisMetro.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.*;
import net.datastructures.*;
/**
* All code used to construct data structures is from the Net folder in this directory.
* The Net folder is used from CSI 2110 Lab 9 module, which sources the code as coming from
* Goodrich et al.
*/
public class ParisMetro {
static Vertex[] vertexList = new Vertex[376]; // Will store all Metro Station vertices in order from 000 to 375;
static Graph<Integer, Integer> parisMetro; // Stores the Graph with Stations Numbers as vertices and time between vertices as edge weightings
public ParisMetro(String fileName) throws Exception, IOException{
parisMetro = new AdjacencyMapGraph<Integer, Integer>(true);
readMetro(fileName); // Converts fileName from ParisMetro parameter into an Array of Station vertices and a Graph of the Metro system
}
public static Graph<Integer,Integer> getGraph() {return parisMetro;} // Returns Graph containing Metro system
public static Vertex[] getVertexList() {return vertexList;} // Returns array of Station vertices in order from 000 to 375
public static void readMetro(String fileName) throws Exception, IOException {
BufferedReader metroFile = new BufferedReader(new FileReader(fileName)); // New BufferReader that reads Class fileName parameter
String stationData = metroFile.readLine(); // Skips first line that states total number of vertices and edges in the Metro system
stationData = metroFile.readLine();
int i = 0; // Used to iterate through the array of vertices
while (!stationData.equals("$")) { // Stops when file is done listing the Station Numbers
String[] indivStationData = stationData.split(" "); // Seperates the line into the Station Number and Station Name
int stationNum = Integer.parseInt(indivStationData[0]);
Vertex newVertex = parisMetro.insertVertex(stationNum); // Creates vertex out of Station Number on current line
vertexList[i] = newVertex; // Adds vertex to the vertexList
stationData = metroFile.readLine(); // Goes to next line
i++;
}
stationData = metroFile.readLine(); // Skips line with '$'
// Inputs Vertices into a Graph and connects them by their common weighted edge
while (stationData != null) { // Stops at the end of the file
String[] pathData = stationData.split(" "); // Splits line into source Station, destination Station, and time (weighted edge)
int sourceStation = Integer.parseInt(pathData[0]);
int destStation = Integer.parseInt(pathData[1]);
int pathTime = Integer.parseInt(pathData[2]);
if (pathTime == -1) { // If the weighted edge is -1 it indicated it is a walking edge and we give it a walking constant of 90
pathTime = 90;
}
parisMetro.insertEdge(vertexList[sourceStation], vertexList[destStation], pathTime); // Inserts weighted edge connected by two vertices into Graph
stationData = metroFile.readLine(); // Goes to the next line in file
}
}
public static LinkedQueue<Vertex<Integer>> sameLine(Vertex<Integer> v) { // Returns a LinkedQueue containing all vertices on the same line as parameter vertex
LinkedStack<Vertex<Integer>> stack = new LinkedStack<Vertex<Integer>>(); // Will contain a vertex at a time to traverse along a line
HashSet visited = new HashSet(); // Will contain visted vertices as to be sure not to visit them again
Edge[] originalEdges = new Edge[2]; // Contains the one or two edges of parameter vertex that are not weighted as 90
LinkedQueue<Vertex<Integer>> onLine = new LinkedQueue<Vertex<Integer>>(); // Will contain all vertices on the same line as parameter vertex
onLine.enqueue(v);
visited.add(v);
Iterable<Edge<Integer>> edgeList = parisMetro.outgoingEdges(v); // Gets outgoing edges of parameter vertex as a Iterable
int index = 0;
for (Edge<Integer> e : edgeList) { // Looks for outgoing edges of parameter vertex that are not walking edges
if (e.getElement() != 90) {
originalEdges[index] = e;
index++;
}
}
Vertex<Integer> nextStation = parisMetro.opposite(v, originalEdges[0]); // Sets next station to visit
visited.add(nextStation); // Becomes 'visited' vertex
stack.push(nextStation); // Pushes on to stack
while (!stack.isEmpty()) { // Traverses line in one direction and adds each vertex visited to visited and onLine, then stops when it reaches an endpoint of the line
nextStation = stack.pop();
Iterable<Edge<Integer>> outgoingEdges = parisMetro.outgoingEdges(nextStation);
for (Edge<Integer> e : outgoingEdges) { // Iterates through nextStation's outgoing edges
if (e.getElement() != 90 && !visited.contains(parisMetro.opposite(nextStation, e))) { // Looks for edges that are not walking and that HashSet visited doesn't contain
nextStation = parisMetro.opposite(nextStation, e);
visited.add(nextStation);
stack.push(nextStation);
onLine.enqueue(nextStation);
break;
}
}
}
if (originalEdges[1] != null) { // Checks if parameter vertex is a line endpoint, if not it continues to check the other direction from the initial vertex
nextStation = parisMetro.opposite(v, originalEdges[1]);
visited.add(nextStation); // Becomes 'visited' vertex
stack.push(nextStation); // Pushes on to stack
while (!stack.isEmpty()) { // Traverses line in one direction and adds each vertex visited to visited and onLine, then stops when it reaches an endpoint of the line
nextStation = stack.pop();
Iterable<Edge<Integer>> outgoingEdges = parisMetro.outgoingEdges(nextStation);
for (Edge<Integer> e : outgoingEdges) { // Iterates through nextStation's outgoing edges
if (e.getElement() != 90 && !visited.contains(parisMetro.opposite(nextStation, e))) {
nextStation = parisMetro.opposite(nextStation, e); // Looks for edges that are not walking and that HashSet visited doesn't contain
visited.add(nextStation);
stack.push(nextStation);
onLine.enqueue(nextStation);
break;
}
}
}
return onLine;
} else { // If parameter vertex is an endpoint, then return LinkedQueue onLine
return onLine;
}
}
// Code taken from GraphAlgoritm class in Net folde from Lab 9
public static LinkedStack<Integer> shortestTimeToDestination(Vertex<Integer> src, Vertex<Integer> dest) {
ProbeHashMap<Vertex<Integer>, Vertex<Integer>> previousVisit = new ProbeHashMap<>(); // Key is the current vertex and value is its previous vertex on the shortest route from source
LinkedStack<Integer> shortestPath = new LinkedStack<Integer>(); // will contain the shortest path from src to dest with src being on top and dest being at the bottom
// d.get(v) is upper bound on distance from src to v
ProbeHashMap<Vertex<Integer>, Integer> d = new ProbeHashMap<>();
// map reachable v to its d value
ProbeHashMap<Vertex<Integer>, Integer> cloud = new ProbeHashMap<>();
// pq will have vertices as elements, with d.get(v) as key
AdaptablePriorityQueue<Integer, Vertex<Integer>> pq;
pq = new HeapAdaptablePriorityQueue<>();
// maps from vertex to its pq locator
ProbeHashMap<Vertex<Integer>, Entry<Integer,Vertex<Integer>>> pqTokens;
pqTokens = new ProbeHashMap<>();
// for each vertex v of the graph, add an entry to the priority queue, with
// the source having distance 0 and all others having infinite distance
for (Vertex<Integer> v : parisMetro.vertices()) {
if (v == src)
d.put(v,0);
else
d.put(v, Integer.MAX_VALUE);
pqTokens.put(v, pq.insert(d.get(v), v)); // save entry for future updates
}
// now begin adding reachable vertices to the cloud
while (!pq.isEmpty()) {
Entry<Integer, Vertex<Integer>> entry = pq.removeMin();
int key = entry.getKey();
Vertex<Integer> u = entry.getValue();
cloud.put(u, key); // this is actual distance to u
pqTokens.remove(u); // u is no longer in pq
for (Edge<Integer> e : parisMetro.outgoingEdges(u)) {
Vertex<Integer> v = parisMetro.opposite(u,e);
if (cloud.get(v) == null) {
// perform relaxation step on edge (u,v)
int wgt = e.getElement();
if (d.get(u) + wgt < d.get(v)) { // better path to v?
previousVisit.put(v, u);
d.put(v, d.get(u) + wgt); // update the distance
if (v == dest) { // if current vertex is dest halt process to find its shortest path
int time = d.get(u) + wgt; // store time for ease of access later
shortestPath.push(v.getElement()); // pushes current/dest vertex element into the stack so that it will be popped out last
while (v != src) { // Following through a previous vertices until it gets to the src vertex
shortestPath.push(previousVisit.get(v).getElement());
v = previousVisit.get(v);
} // End result is a stack with in order of shortest path from src to dest
shortestPath.push(time); // Push time onto the top of stack to easily get from main
return shortestPath; //
}
pq.replaceKey(pqTokens.get(v), d.get(v)); // update the pq entry
}
}
}
}
return shortestPath; // Safety return
}
public static void closeLine (Vertex<Integer> v) { // Takes paramter vertex and removes every vertex on the same line
LinkedQueue<Vertex<Integer>> line = sameLine(v); // Gets all vertices on the same line as parameter vertex v
while(!line.isEmpty()) { // Iterates through LinkedQueue line and removes each vertex from the Graph
Vertex<Integer> vertex = line.dequeue();
parisMetro.removeVertex(vertex);
}
}
public static void printLine(Vertex<Integer> v) { // Prints the line that parameter vertex is on, in a legible manner
LinkedQueue<Vertex<Integer>> queue = sameLine(v);
while (!queue.isEmpty()) {
System.out.print(queue.dequeue().getElement() + " ");
}
System.out.println();
}
public static void printStack(LinkedStack<Integer> stack) { // Prints a inputted stack of Station Numerbs in a legible order
while (!stack.isEmpty()) {
System.out.print(stack.pop() + " ");
}
System.out.println();
}
public static void main(String[] args) throws Exception, IOException {
int argsLength = args.length;
ParisMetro metro = new ParisMetro("metro.txt");
Vertex[] list = metro.getVertexList();
if (argsLength == 1) {
int N1 = Integer.parseInt(args[0]);
System.out.println("Test --------------------");
System.out.println(" Input: ");
System.out.println(" N1 = " + N1);
System.out.println(" Output: ");
System.out.print(" Path: ");
printLine(list[N1]);
System.out.println("End of Test -------------");
} else if (argsLength == 2) {
int N1 = Integer.parseInt(args[0]);
int N2 = Integer.parseInt(args[1]);
System.out.println("Test --------------------");
System.out.println(" Input: ");
System.out.println(" N1 = " + N1 + " N2 = " + N2);
System.out.println(" Output: ");
LinkedStack<Integer> stack = shortestTimeToDestination(list[N1], list[N2]);
System.out.println(" Time: " + stack.pop());
System.out.print(" Path: ");
printStack(stack);
System.out.println("End of Test -------------");
} else if (argsLength == 3) {
int N1 = Integer.parseInt(args[0]);
int N2 = Integer.parseInt(args[1]);
int N3 = Integer.parseInt(args[2]);
System.out.println("Test --------------------");
System.out.println(" Input: ");
System.out.println(" N1 = " + N1 + " N2 = " + N2);
System.out.println(" Output: ");
LinkedStack<Integer> stack = shortestTimeToDestination(list[N1], list[N2]);
System.out.println(" Time: " + stack.pop());
System.out.print(" Path: ");
printStack(stack);
System.out.println(" Input: ");
System.out.println(" N1 = " + N1 + " N2 = " + N2 + " N3 = " + N3);
System.out.println(" Output: ");
closeLine(list[N3]);
LinkedStack<Integer> stack2 = shortestTimeToDestination(list[N1], list[N2]);
System.out.println(" Time: " + stack2.pop());
System.out.print(" Path: ");
printStack(stack2);
System.out.println("End of Test -------------");
}
}
}
<file_sep>/out/production/assignment-4/README.md
# assignment-4
<NAME> Jaimin's Assignment 4
<file_sep>/README.md
# Application of Dijkstra's Algorithm on the Paris Metro
| e8f06c19dcf224907cf8641c41a40836019c7c16 | [
"Java",
"Markdown"
] | 3 | Java | jaiminpatel98/Paris-Metro-Dijkstra-Algorithm | cace29414ac6ced154256a314b4f7965a79be567 | dc7a06002cb5558012b945365677f5f9fa9985e4 |
refs/heads/master | <repo_name>rijank/hello-world<file_sep>/README.md
# hello-world
Name is Riz. Trying to learn programming and this seemed to be the first thing I am learning.
| ff8af64f7894f153d95db191cbcdfccb6b87b700 | [
"Markdown"
] | 1 | Markdown | rijank/hello-world | 1386b7044600b2f4e4d5315afab8abf6dce97f17 | b7a80e845dfa71f0158f7aa5346ae11f0f24b577 |
refs/heads/master | <repo_name>sofyandpony/RegistrySearchEngine<file_sep>/src/main/java/com/upraxis/registry/searchengine/config/YAMLConfig.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 com.upraxis.registry.searchengine.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
*
* @author jesse
*/
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class YAMLConfig {
private Logback logback;
public Logback getLogback() {
return logback;
}
public void setLogback(Logback logback) {
this.logback = logback;
}
public static class Logback {
private Log log;
public Log getLog() {
return log;
}
public void setLog(Log log) {
this.log = log;
}
public static class Log {
private String directory;
private String logFileName;
private String logFileError;
private String fileDirectory;
public String getDirectory() {
return directory;
}
public void setDirectory(String directory) {
this.directory = directory;
}
public String getLogFileName() {
return logFileName;
}
public void setLogFileName(String logFileName) {
this.logFileName = logFileName;
}
public String getLogFileError() {
return logFileError;
}
public void setLogFileError(String logFileError) {
this.logFileError = logFileError;
}
public String getFileDirectory() {
return fileDirectory;
}
public void setFileDirectory(String fileDirectory) {
this.fileDirectory = fileDirectory;
}
}
}
}
<file_sep>/src/main/java/com/upraxis/registry/searchengine/web/repository/UserRespository.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 com.upraxis.registry.searchengine.web.repository;
import com.upraxis.registry.searchengine.web.domain.Users;
import org.springframework.data.solr.repository.SolrCrudRepository;
/**
*
* @author jesse
*/
public interface UserRespository extends SolrCrudRepository<Users, String>{
}
<file_sep>/README.md
# RegistrySearchEngine
Registry Search Engine
| a7adda6d66a242c4b4f74eea9e2276e2a17ee8bb | [
"Java",
"Markdown"
] | 3 | Java | sofyandpony/RegistrySearchEngine | 0032ab8880db4189a780fbfc9bb8da59a88b9191 | e848adbf74574a1f93274908cf41f0b0502210e4 |
refs/heads/main | <file_sep>const express = require("express"); // require the express package
const app = express(); // initialize your express app instance
const cors = require("cors");
const axios = require("axios");
app.use(cors());
require("dotenv").config();
// a server endpoint
const port = process.env.PORT;
const weatherData = require("./data/weather.json");
const { query } = require("express");
app.get(
"/", // our endpoint name
function (req, res) {
// callback function of what we should do with our request
res.send("Hello World--"); // our endpoint function response
}
);
class Forecast {
constructor(date, discription) {
this.date = date;
this.discription = discription;
}
}
const WEATHER_API_KEY = process.env.WEATHER_API_KEY;
app.get("/weather", async (req, res) => {
try {
const searchQuery = req.query.city_name;
// const lat =req.query.lat;
// const lon=req.query.lon;
// const arrOfData = weatherData.find((city) => {
// console.log("cityname", city.city_name);
// console.log("searchquery", searchQuery);
// return city.city_name.toLowerCase() === searchQuery.toLowerCase();
// });
// console.log(arrOfData.data);
// if (arrOfData.data.length) {
// const resArr = arrOfData.data.map((ele) => {
// return new Forecast(ele.datetime, ele.weather.description);
// });
// res.json(resArr);
// } else {
// res.json("no dataaaaa found ");
// }
// } catch (err) {
// res.json(err.message);
const lat = req.query.lat;
const lon = req.query.lon;
const weatherUrl = "https://api.weatherbit.io/v2.0/forecast/daily";
const weatherRes = await axios.get(
`${weatherUrl}?lat=${lat}&lon=${lon}&key=${WEATHER_API_KEY}`
);
const weatherArr = weatherRes.data.data.map((ele) => {
return new Forecast(ele.valid_date, ele.weather.description);
});
res.json(weatherArr);
// console.log(weatherRes.data);
} catch (err) {
res.json(err.message);
}
});
// class Movie {
// constructor(
// title,
// overview,
// average_votes,
// total_votes,
// image_url,
// popularity,
// released_on
// ) {
// this.title = title;
// this.overview = overview;
// this.average_votes = average_votes;
// this.total_votes = total_votes;
// this.image_url = image_url;
// this.popularity = popularity;
// this.released_on = released_on;
// }
// }
const MOVIE_API_KEY = process.env.MOVIE_API_KEY;
app.get("/movies", async (req, res) => {
const city = req.query.city;
const movUrl = `https://api.themoviedb.org/3/search/movie?query=${city}&api_key=${MOVIE_API_KEY}`;
console.log(movUrl);
const movRes = await axios.get(movUrl);
const moviesData = movRes.data;
// const movieUrl = `https://api.themoviedb.org/3/movie/top_rated?query=${city}`;
// const movieRes = await axios.get(`${movieUrl}`);
if (city !== null) {
if (moviesData) {
let dataOfSelectedCity = moviesData.results;
let DataArr = [];
class Movie {
constructor(
title,
overview,
average_votes,
total_votes,
image_url,
popularity,
released_on
) {
this.title = title;
this.overview = overview;
this.average_votes = average_votes;
this.total_votes = total_votes;
this.image_url = image_url;
this.popularity = popularity;
this.released_on = released_on;
}
}
dataOfSelectedCity.map((ele) => {
let newObj = new Movie(
ele.title,
ele.overview,
ele.average_votes,
ele.total_votes,
ele.backdrop_path,
ele.popularity,
ele.released_on
);
DataArr.push(newObj);
});
res.json(DataArr);
} else {
res.send("the city is not defined");
}
} else {
res.send("you did not provide any data");
}
// console.log(movRes.data);
// if (movieArr.length > 1) {
// res.json(movieArr);
// } else {
// }
});
app.listen(port); // kick start the express server to work
| 2313549a8e15d77fbe564b75057cb2f3f55d907d | [
"JavaScript"
] | 1 | JavaScript | eng-ehabsaleh/city-explore-api | cd7625c5fca6003f756136204c8f8d28fe2cc20a | e24d366a0308ae70c224b839957a26ee5295be4c |
refs/heads/master | <file_sep>"# trying_fileio_java"
<file_sep>package testfileio;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.File;
public class TestFileIO {
public static void main(String[] args) throws IOException {
String s;
// File my_dir = new File("files");
File my_file = new File("files", "test_file.txt");
try (BufferedReader in = new BufferedReader(new FileReader(my_file))){
while ((s = in.readLine()) != null){
System.out.println(s);
}
}
}
}
<file_sep>package testfileio;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class TestFileScannerText {
public static void main(String[] args) throws IOException {
String line;
int count = 1;
File word_file = new File("files", "word_file.txt");
try (Scanner in = new Scanner(word_file)) {
while (in.hasNextLine()){
line = in.nextLine();
System.out.printf("Line number %d: %s%n", count, line);
count++;
}
}
System.out.println("end");
}
}
| 91832c1032ec8dede7f8c58fd663c0a5d3ca80fb | [
"Java",
"Markdown"
] | 3 | Java | Alan-Greene/trying_fileio_java | f3d44d8f39a9a91866230e5fdfec01b927ee1cb7 | d8bf2bab7f7f94015e2d44a001ed08859fb51e3c |
refs/heads/master | <repo_name>ncourty/PoissonGradient<file_sep>/poissonblending.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import scipy.sparse
import PIL.Image
import pyamg
import pylab as pl
from scipy.spatial.distance import cdist
import sys
import ot
import sklearn.cluster as skcluster
def subsample(G_src,G_tgt,nb):
ids=np.random.permutation(G_src.shape[0])
Xs=G_src[ids[:nb],:]
idt=np.random.permutation(G_tgt.shape[0])
Xt=G_tgt[idt[:nb],:]
return Xs,Xt
def getGradient_flatten(im):
[grad_x,grad_y] =np.gradient(im.astype(float))
return np.vstack((grad_x.flatten(),grad_y.flatten())).T
def adapt_Gradients_linear(G_src,G_tgt,mu=1e-2,eta=1e-6,nb=100,bias=True):
Xs, Xt = subsample(G_src,G_tgt,nb)
ot_mapping=ot.da.LinearTransport()
ot_mapping.fit(Xs,Xt=Xt)
return ot_mapping.transform(G_src)
def adapt_Gradients_kernel(G_src,G_tgt,mu=1e2,eta=1e-8,nb=10,bias=False,sigma=1e2):
Xs, Xt = subsample(G_src,G_tgt,nb)
ot_mapping_kernel=ot.da.MappingTransport(mu=mu,eta=eta,sigma=sigma,bias=bias, verbose=True)
ot_mapping_kernel.fit(Xs,Xt=Xt)
return ot_mapping_kernel.transform(G_src)
# pre-process the mask array so that uint64 types from opencv.imread can be adapted
def prepare_mask(mask):
if type(mask[0][0]) is np.ndarray:
result = np.ndarray((mask.shape[0], mask.shape[1]), dtype=np.uint8)
for i in range(mask.shape[0]):
for j in range(mask.shape[1]):
if sum(mask[i][j]) > 0:
result[i][j] = 1
else:
result[i][j] = 0
mask = result
return mask
def blend(img_target, img_source, img_mask_raw, nbsubsample=100, offset=(0, 0),adapt='none',reg=1.,eta=1e-9,visu=0,verbose=False):
# compute regions to be blended
if verbose:
print("Reticulating splines")
region_source = (
max(-offset[0], 0),
max(-offset[1], 0),
min(img_target.shape[0]-offset[0], img_source.shape[0]),
min(img_target.shape[1]-offset[1], img_source.shape[1]))
region_target = (
max(offset[0], 0),
max(offset[1], 0),
min(img_target.shape[0], img_source.shape[0]+offset[0]),
min(img_target.shape[1], img_source.shape[1]+offset[1]))
region_size = (region_source[2]-region_source[0], region_source[3]-region_source[1])
#print region_size
# clip and normalize mask image
img_mask = img_mask_raw[region_source[0]:region_source[2], region_source[1]:region_source[3]]
img_mask = prepare_mask(img_mask)
img_mask[img_mask==0] = False
img_mask[img_mask!=False] = True
# create coefficient matrix
A = scipy.sparse.identity(np.prod(region_size), format='lil')
for y in range(region_size[0]):
for x in range(region_size[1]):
if img_mask[y,x]:
index = x+y*region_size[1]
A[index, index] = 4
if index+1 < np.prod(region_size):
A[index, index+1] = -1
if index-1 >= 0:
A[index, index-1] = -1
if index+region_size[1] < np.prod(region_size):
A[index, index+region_size[1]] = -1
if index-region_size[1] >= 0:
A[index, index-region_size[1]] = -1
A = A.tocsr()
# adapt_gradient
G_src_tot = np.ndarray((region_size[0]*region_size[1],6),dtype=float)
G_tgt_tot = np.ndarray((region_size[0]*region_size[1],6),dtype=float)
for num_layer in range(img_target.shape[2]):
# get subimages
t = img_target[region_target[0]:region_target[2],region_target[1]:region_target[3],num_layer]
s = img_source[region_source[0]:region_source[2], region_source[1]:region_source[3],num_layer]
G_src_tot[:,2*num_layer:(2*num_layer+2)] = getGradient_flatten(s.astype(float))
G_tgt_tot[:,2*num_layer:(2*num_layer+2)] = getGradient_flatten(t.astype(float))
G_src = G_src_tot
G_tgt = G_tgt_tot
if verbose:
print("Reticulating gradients")
if adapt=='none':
newG = G_src
elif adapt=='linear':
newG = adapt_Gradients_linear(G_src,G_tgt,mu=reg,eta=eta,nb=nbsubsample)
elif adapt=='kernel':
newG = adapt_Gradients_kernel(G_src,G_tgt,mu=reg,eta=eta,nb=nbsubsample)
newGrad=newG
# for each layer (ex. RGB)
if verbose:
print("Reticulating fish")
im_return = img_target.copy()
for num_layer in range(img_target.shape[2]):
t = img_target[region_target[0]:region_target[2],region_target[1]:region_target[3],num_layer]
[grad_t_x,grad_t_y] =np.gradient(t.astype(float))
t = t.flatten()
grad_x = newGrad[:,2*num_layer].reshape(region_size[0],region_size[1])
grad_y = newGrad[:,2*num_layer+1].reshape(region_size[0],region_size[1])
g = np.zeros(img_mask.shape)
g[1:, :] =grad_x[:-1, :] - grad_x[1:, :]
g[:, 1:] = g[:, 1:] - grad_y[:, 1:]+grad_y[:, :-1]
b=g.flatten()
for y in range(region_size[0]):
for x in range(region_size[1]):
if not img_mask[y,x]:
index = x+y*region_size[1]
b[index] = t[index]
# solve Ax = b
x = pyamg.solve(A,b,verb=False,tol=1e-10)
# assign x to target image
x = np.reshape(x, region_size)
x[x>255] = 255
x[x<0] = 0
x = np.array(x, img_target.dtype)
im_return[region_target[0]:region_target[2],region_target[1]:region_target[3],num_layer] = x
if verbose:
print("Reticulating done")
return im_return
<file_sep>/test.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import PIL.Image
import pylab as pl
from poissonblending import blend
img_mask = np.asarray(PIL.Image.open('./data/me_mask.png'))
img_mask = img_mask[:,:,:3] # remove alpha
img_source = np.asarray(PIL.Image.open('./data/me.png'))
img_source = img_source[:,:,:3] # remove alpha
img_target = np.asarray(PIL.Image.open('./data/target.png'))
nbsample=500
off = (35,-15)
img_ret1 = blend(img_target, img_source, img_mask, offset=off)
img_ret3 = blend(img_target, img_source, img_mask, reg=5,eta=1, nbsubsample=nbsample,offset=off,adapt='linear')
img_ret4 = blend(img_target, img_source, img_mask, reg=5,eta=1, nbsubsample=nbsample,offset=off,adapt='kernel')
#%%
fs=30
f, axarr = pl.subplots(1, 5,figsize=(30,7))
newax = f.add_axes([0.15, 0, 0.32, 0.32], anchor='NW', zorder=1)
newax.imshow(img_mask)
newax.axis('off')
newax.set_title('mask')
axarr[0].imshow(img_source)
axarr[0].set_title('Source', fontsize=fs)
axarr[0].axis('off')
axarr[1].imshow(img_target)
axarr[1].set_title('target', fontsize=fs)
axarr[1].axis('off')
axarr[2].imshow(img_ret1)
axarr[2].set_title('[Perez 03]', fontsize=fs)
axarr[2].axis('off')
axarr[3].imshow(img_ret3)
axarr[3].set_title('Linear', fontsize=fs)
axarr[3].axis('off')
axarr[4].imshow(img_ret4)
axarr[4].set_title('Kernel', fontsize=fs)
axarr[4].axis('off')
pl.subplots_adjust(wspace=0.1)
pl.tight_layout()
pl.show()
<file_sep>/README.md
# Poisson Blending with adapted gradients
This library is a simple demonstration of using Optimal Transport Mapping Estimation [1]
in a context of seamless copy between images. See [1] for details over the method
## Installation
The Library has been tested on Linux and MacOSX. Among other classical dependencies, it requires the installation of POT, the Python Optimal Transport library (https://github.com/rflamary/POT)
- Numpy (>=1.11)
- Scipy (>=0.17)
- Matplotlib (>=1.5)
- Pyamg (>=3.1)
- POT (>=1.0)
If you want to execute the video demo, then you also need to have OpenCV for python installed.
## Examples
One notebook is provided as example of use:
* [Example](https://github.com/ncourty/PoissonGradient/blob/master/test.ipynb)
The video demo is available in the test_video.py file.
## References
[1] <NAME>, <NAME>, <NAME>, <NAME>, "Mapping estimation for discrete optimal transport", Neural Information Processing Systems (NIPS), 2016.
<file_sep>/demo_nips.py
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 31 08:24:30 2016
@author: rflamary
"""
import numpy as np
import cv2
import pylab as pl
import sys
import PIL.Image
cap = cv2.VideoCapture(0)
from poissonblending import blend
fname_mask='./data/joconde_0_mask.jpg'
fname_img='./data/joconde_0.jpg'
mask_list=['./data/joconde_0_mask.jpg',
'./data/monet_portrait_mask.png',
# './data/estree_mask.png',
'./data/firefly_mask.png',
'./data/vapnik_mask.png',
'./data/dorothy_mask.png']
img_list=['./data/joconde_0.jpg',
'./data/monet_portrait.png',
# './data/estree.png',
'./data/firefly.png',
'./data/vapnik.png',
'./data/dorothy.png']
adapt_list=['kernel',
'kernel',
'kernel',
'kernel',
'kernel',
'kernel']
nimg=len(img_list)
idimg=0
def load_images(fname_mask,fname_img):
img_mask = np.asarray(PIL.Image.open(fname_mask)).copy()
if len(img_mask.shape)<3:
img_mask = np.tile(img_mask[:,:,None],(1,1,3)) # remove alpha
img_mask = img_mask[:,:,:3]
img_mask.setflags(write=1)
#img_source = np.asarray(PIL.Image.open('./testimages/me_flipped.png'))
#img_source = img_source[:,:,:3]
#img_source.flags.writeable = True
img_target = np.asarray(PIL.Image.open(fname_img)).copy()
img_target = img_target[:,:,:3]
img_target.setflags(write=1)
#img_mask2=cv2.imread('testimages/mask_video.png')
#img_mask=img_mask2>0
mask2= np.maximum(cv2.Laplacian(img_mask,cv2.CV_64F),0)>20
return img_mask,img_target,mask2
img_mask,img_target,mask2=load_images(fname_mask,fname_img)
# nico : change the resolution of the video to match mask resolution
#cap.set(3,img_mask.shape[1])
#cap.set(4,img_mask.shape[0])
etape=0
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
#print(frame)
frame = cv2.resize(frame, (img_mask.shape[1],img_mask.shape[0]))
frame=frame[:,::-1,:]
# Our operations on the frame come here
if etape==0:
frame_mask=cv2.cvtColor(img_target, cv2.COLOR_BGR2RGB)
elif etape==1:
frame_mask=(img_mask>0)*frame+(img_mask==0)*cv2.cvtColor(img_target, cv2.COLOR_BGR2RGB)
k=cv2.waitKey(1) & 0xFF
if k in [ ord(' ')]:
if etape==1:
doit=True
break
else:
etape=1
if k in [ ord('q')]:
doit=False
break
if k in [ord('v')]:
etape=1
if k in [ord('i'),ord('m')]:
idimg=(idimg+1) % nimg
fname_mask=mask_list[idimg]
fname_img=img_list[idimg]
img_mask,img_target,mask2=load_images(fname_mask,fname_img)
# Display the resultinfname_maskg frame
cv2.imshow('frame',frame_mask)
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
I = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if doit:
nbsample=500
off = (0,0)
img_ret4 = blend(img_target, I, img_mask, reg=1, nbsubsample=nbsample,offset=off,adapt=adapt_list[idimg],verbose=True)
#%%
fs=30
f, axarr = pl.subplots(1, 3,figsize=(30,10))
newax = f.add_axes([0.15, 0, 0.32, 0.32], anchor='NW', zorder=1)
newax.imshow(img_mask)
newax.axis('off')
newax.set_title('mask')
axarr[0].imshow(I)
axarr[0].set_title('Source', fontsize=fs)
axarr[0].axis('off')
axarr[1].imshow(img_target)
axarr[1].set_title('target', fontsize=fs)
axarr[1].axis('off')
axarr[2].imshow(img_ret4)
axarr[2].set_title('Adapted', fontsize=fs)
axarr[2].axis('off')
pl.subplots_adjust(wspace=0.1)
pl.tight_layout()
if len(sys.argv)>1:
savename='./output/{}_{}.png'.format(sys.argv[1],idimg)
else:
savename='./output/{}_{}.png'.format('output',idimg)
pl.savefig(savename)
pl.show()
| f697b1224302980d47ea56d7c2a3665ad59d5199 | [
"Markdown",
"Python"
] | 4 | Markdown | ncourty/PoissonGradient | 97d1fec8dc331406146a63c330d65d410d8551d5 | a6b6b1cbc2c752a48f4bf2525f419651cd7cd89a |
refs/heads/master | <repo_name>pankajladhar/service-worker-demo<file_sep>/READ.md
# service-worker-demo
Sample code to demonstrate serviceworker.
1. How to register a serviceworker.
1. Serviceworker lifecyle method
1. Serviceworker event
| b017e7b6798ff255edc057493c69d509aaa025ca | [
"Markdown"
] | 1 | Markdown | pankajladhar/service-worker-demo | b0d0aae3bd9bea495e4c54173811f9a3299f55d9 | 4433e46fce4f1b8d347296154c9d6a7692b2ba11 |
refs/heads/master | <repo_name>sinejs/sine-router<file_sep>/src/router.js
class ActiveRoute {
constructor(route, matched, remaining, parameters) {
this.route = route;
this.matched = matched;
this.remaining = remaining;
this.parameters = parameters;
}
equals(activeRoute) {
return this.matched === activeRoute.matched;
}
}
@sine.decorator.service({
namespace: 'sine.router',
selector: '$router'
})
class RouterService extends sine.Service{
constructor(routes) {
super();
this.base = '/';
this.mode = 'history';
this.routes = [];
this.activeRoutes = [];
this.routeChange = new sine.Messenger();
}
config(routes, options) {
this.routes = routes;
this.mode = options && options.mode && options.mode === 'history' && !!(history.pushState) ? 'history' : 'hash';
this.base = options && options.base ? '/' + this.clearSlashes(options.base) + '/' : '/';
return this;
}
getFragment() {
var fragment = '';
if (this.mode === 'history') {
fragment = this.clearSlashes(decodeURI(location.pathname + location.search));
fragment = fragment.replace(/\?(.*)$/, '');
fragment = this.base !== '/' ? fragment.replace(this.base, '') : fragment;
}
else {
var match = window.location.href.match(/#(.*)$/);
fragment = match ? match[1] : '';
}
return this.clearSlashes(fragment);
}
clearSlashes(path) {
return path.toString().replace(/\/$/, '').replace(/^\//, '');
}
add(route) {
this.routes.push(route);
}
remove(route) {
sine.remove(this.routes, route);
}
flush() {
this.routes = [];
this.mode = null;
this.base = '/';
return this;
}
check(f) {
var fragment = f || this.getFragment(), activeRoutes = [];
this.matchRoute(this.routes, fragment, activeRoutes);
this.activeRoutes = activeRoutes;
this.routeChange.fire();
}
matchRoute(routes, fragment, activeRoutes) {
if (!routes) {
return;
}
var self = this;
routes.some(function (route) {
var activeRoute = self.matchPath(route, fragment);
if (activeRoute) {
if (self.activeRoutes.length > 0) {
var oldActiveRoute = self.activeRoutes.shift();
if (activeRoute.equals(oldActiveRoute)) {
activeRoutes.push(oldActiveRoute);
}
else {
activeRoutes.push(activeRoute);
}
}
else {
activeRoutes.push(activeRoute);
}
self.matchRoute(route.children, activeRoute.remaining, activeRoutes);
return true;
}
});
}
matchPath(route, fragment) {
var matches = [],
parameters = {},
pathItems = route.path.split('/'),
fragmentItems = fragment.split('/');
for (var i = 0; i < pathItems.length; i++) {
var pathItem = pathItems[i];
if (i >= fragmentItems.length) {
return null;
}
var fragmentItem = fragmentItems[i];
if (pathItem === fragmentItem) {
matches.push(fragmentItem);
}
else if (pathItem.startsWith(':')) {
matches.push(fragmentItem);
parameters[pathItem.substring(1)] = fragmentItem;
}
else {
return null;
}
}
return new ActiveRoute(route, matches.join('/'), fragmentItems.splice(pathItems.length).join('/'), parameters);
}
listen() {
var self = this;
var current = self.getFragment();
var fn = function () {
if (current !== self.getFragment()) {
current = self.getFragment();
self.check(current);
}
};
self.check(current);
clearInterval(this.interval);
this.interval = setInterval(fn, 50);
return this;
}
navigate(path) {
path = path ? path : '';
if (this.mode === 'history') {
history.pushState(null, null, this.base + this.clearSlashes(path));
}
else {
window.location.href = window.location.href.replace(/#(.*)$/, '') + '#' + path;
}
return this;
}
stop() {
clearInterval(this.interval);
}
}<file_sep>/src/index.js
export * from './router';
export * from './router-view';
export * from './router-link';<file_sep>/src/router-link.js
@sine.decorator.component({
namespace: 'sine.router',
selector: 'router-link',
template: '<span class="link" style="cursor: pointer;" @click="navigate()" *n-embed></span>',
inject: {
$router: '$router'
}
})
class RouterLinkComponent extends sine.Component {
constructor() {
super();
this.to = '';
}
navigate() {
this.$router.navigate(this.to);
}
}<file_sep>/README.md
# sine-router
front end router base on sinejs
| cfb52de2bb3eaaa429891a408ee4d6e4028e5d8f | [
"Markdown",
"JavaScript"
] | 4 | Markdown | sinejs/sine-router | 43d993545ac1060413a40637a0a212c04d6eb650 | 15b0bd250a4a7bb1a3d15d70886bd1b5b63dd43f |
refs/heads/master | <repo_name>ForeverHepburn/SwiftHistory<file_sep>/MyPlayground.playground/Pages/Collection Types.xcplaygroundpage/Contents.swift
//: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
//Array
var stringArray:[String] = [];
stringArray.append("1");
stringArray.append("2");
print(stringArray);
var value = stringArray[0];
if (value == "1") {
print(1);
}
var intArray = [1,2,3];
var commonArrayy = stringArray;
stringArray[0] = "111";
print(commonArrayy)
commonArrayy.insert("123", at: 0);
commonArrayy.insert("1111111", at: 0);
commonArrayy.remove(at: 0);
commonArrayy;
for obj in commonArrayy {
print(obj.appending(","));
}
for (index, value) in commonArrayy.enumerated() {
var str = value;
if index != (commonArrayy.count-1) {
str = str.appending(",")
}
print(str)
}
commonArrayy.removeLast()
commonArrayy.removeAll()
//Set
var letters = Set<Character>();
letters.count
letters.insert("a")
letters
letters.removeAll()
if letters.isEmpty {
print("set is empty")
}
var nonsSet : Set<String> = ["1","3","2"];
nonsSet.insert("wo");
nonsSet
for obj in nonsSet {
print(obj);
}
print("-------------")
for obj in nonsSet {
print(obj);
}
print("-------------")
for obj in nonsSet.sorted() {
print(obj);
}
var strSet1: Set<String> = ["1","2","3"];
var strSet2: Set<String> = ["1","4","5"];
var strSet3: Set<String> = ["1","3","6"];
//交集
let result1 = strSet1.intersection(strSet2).sorted()
result1
//除交集外的集合
let result2 = strSet1.symmetricDifference(strSet2).sorted()
result2
//两者集合
let result3 = strSet1.union(strSet2).sorted()
result3
//除交集外,set中余下的内容
let result4 = strSet1.subtracting(strSet2).sorted()
result4
//字典
var emptyDict = [Int: String]();
emptyDict
emptyDict[0] = "A"
emptyDict[1] = "B"
print(emptyDict)
emptyDict.count
//print(emptyDict.keys)
emptyDict.values
print("-----------------")
print(emptyDict.updateValue("C", forKey: 0))
emptyDict
<file_sep>/MyPlayground.playground/Pages/试运行01_20170518.xcplaygroundpage/Contents.swift
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
let name = "user"
print(name)
var swiftCode = "hello world"
print(name+" "+swiftCode)
print("Hello, world!")
let valueA = 10;
let valueB = 11;
//valueA += 10;
var value = 20;
value += valueA;
print(value);
let intValue = 90;
let doubleValue = 100;
print(intValue.description)
let floatValue: CGFloat = 100;
//print("%.2f",floatValue);
let label = "The width is";
let width:String = "94";
let widthLabel: String = label + width;
print(widthLabel);
let apples = 3;
let oranges = 5;
let appleSum = "I have \(apples) apples";
let orangeSum = "I have\(oranges) oranges";
print("I have no \(apples) in bag.");
var shopList = ["fish","orange","apple"];
print(shopList);
shopList[1] = "new fish";
print(shopList);
if intValue==90 {
print("1")
}
if apples<oranges {
print(1);
}
var optionalStr: String? = "hello"
var greeting = "world"
if let testStr = optionalStr {
greeting = "hello, \(greeting)"
}
//var optionalStr: String? = "str"
//
//var greeting = "world"
//if let testStr = optionalStr {
// greeting = "hello, \(greeting)"
//}<file_sep>/MyPlayground.playground/Pages/swift3.1_基础部分.xcplaygroundpage/Contents.swift
//: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
//常量和变量
//常量 let
let name = "liuweili"
//变量 var
var description = "description"
description = "new description"
//可以一次性创建多个变量、常量
let name1 = "lwlw",name2 = "lwl3"
var d1 = "d1",d2 = "d2"
print(d1,d2)
//类型标注 常量或变量名后面添加冒号及类型,如“name:String”
var welcomeMessage: String
welcomeMessage = "my message"
//也可以不写,有系统通过我们给的默认值推断
var message = "message" //是字符串
//可以一次定义多个同类型变量、常量,用逗号分开
var orages,apple,banana: String
//let 4Str = 4 //报错
let string4 = 5
let value = 1.25e2
print(value)
<file_sep>/MyPlayground.playground/Pages/试运行02_20170519.xcplaygroundpage/Contents.swift
//: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
//创建类及对象
//类
class Shape{
var numOfSides = 0
let length = 0
func simpleDescription() -> String {
return "A shape with \(numOfSides) sides."
}
func getLength(length: NSInteger) -> NSInteger {
return 4*length
}
}
var shape = Shape()
print(shape.simpleDescription())
print(shape.getLength(length: 4))
class NameShap{
var numberOfSides: Int = 0
var name:String
init(name:String) {
self.name = name;
}
func simpleDescription() -> String {
return "I will show you \(numberOfSides) answers."
}
}
//协议
protocol ExampleProtocol{
var simpleDescription: String{ get }
mutating func adjust()
}
class SimpleClass: ExampleProtocol{
var simpleDescription: String = "name"
func adjust() {
simpleDescription += "100"
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
//错误处理
enum PrinterError: Error{
case OutPaper
case NoToner
case OnFire
}
func send(job:Int, toPrinter printName: String) throws -> String{
if printName == "Never Has Toner" {
throw PrinterError.NoToner
}
return "Job sent"
}
print(try send(job: 404, toPrinter: "Never Has Toner"))
<file_sep>/README.md
# SwiftHistory
记录学习swift过程。
->试运行——20170518
->
| d11a5f644a928dfb18581b9bbcfa98cbf5a7b59b | [
"Swift",
"Markdown"
] | 5 | Swift | ForeverHepburn/SwiftHistory | 948274573af0927b2a0428b8ca763c059b67d1f4 | b66cbbc2b0d0f6017f9c5208074faf9329abebac |
refs/heads/master | <repo_name>jimmyting0710/readexcelFindComp<file_sep>/src/main/java/com/example/demo/FindCOMP.java
package com.example.demo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Stream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.monitorjbl.xlsx.StreamingReader;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FindCOMP {
private final static Logger logger = LoggerFactory.getLogger(FindCOMP.class);
static String copybookDirPath;//copybook位置
static List<String> queryColArray;// 要抓取的欄位
static String excelFolderPath; // excel資料夾位置
static String systemName; // excel檔名
static String sheetName; // 分頁名
static int col; // columns 位置
// (CellIndex,HeaderName)
static Map<Integer, String> HeaderName = new HashMap<Integer, String>();
// public static void main(String[] args) {
// test("D:/si1204/Desktop/writeY/all_copybook_20210820");
// }
/**
* 遞迴讀取某個目錄下的所有檔案
*
* @author 超越
* @Date 2016年12月5日,下午4:04:59
* @motto 人在一起叫聚會,心在一起叫團隊
* @Version 1.0
*/
public static void test() {
Properties pro = new Properties();
String config = "config.properties";
try {
pro.load(new FileInputStream(config));
excelFolderPath = pro.getProperty("excelDir");
queryColArray = Arrays.asList(pro.getProperty("queryColArray").split(","));
copybookDirPath=pro.getProperty("copybookDir");
logger.info("讀取config");
readfile(copybookDirPath);
logger.info("結束");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void readfile(String copybookDirPath) {
logger.info("尋找"+copybookDirPath+"全部檔案");
List<File> fileList = new ArrayList<File>();
File file = new File(copybookDirPath);
File[] files = file.listFiles();// 獲取目錄下的所有檔案或資料夾
if (files == null) {// 如果目錄為空,直接退出
return;
}
// 遍歷,目錄下的所有檔案
for (File f : files) {
if (f.isFile()) {
fileList.add(f);
} else if (f.isDirectory()) {
// System.out.println(f.getAbsolutePath());
readfile(f.getAbsolutePath());
}
}
for (File f1 : fileList) {
String copybookpath = file + "\\" + f1.getName();
String copybookname = f1.getName();
readcopybook(copybookpath, copybookname);
}
}
public static void readcopybook(String copybookpath, String copybookname) {
logger.info("讀取"+copybookname+"是否有COMP");
FileReader reader;
String str1 = null;
try {
reader = new FileReader(copybookpath);
BufferedReader br = new BufferedReader(reader);
//System.out.println(copybookpath);
// comp3的條件
while ((str1 = br.readLine()) != null) {
if (str1.contains("S9") && str1.contains("COMP")) {
// System.out.println(copybookpath + "11111111111111111111");
try {
logger.info(copybookname+"有COMP與S9");
readexcel(copybookname);
} catch (Exception e) {
e.printStackTrace();
}
break;
} else if (str1.contains("PIC 9") && str1.contains("COMP")) {
// System.out.println(copybookname + "22222222222222222222");
try {
logger.info(copybookname+"有COMP與PIC 9");
readexcel(copybookname);
} catch (Exception e) {
e.printStackTrace();
}
break;
} else if (str1.contains("PIC 9") && str1.contains("COMP")) {
// System.out.println(copybookname + "33333333333333333333");
try {
logger.info(copybookname+"有COMP與PIC 9");
readexcel(copybookname);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void readexcel(String copybookname) throws Exception {
logger.info("讀取excel:"+excelFolderPath);
// System.out.println(excelFolderPath);
File excelFolder = new File(excelFolderPath);
List<Map<String, String>> excelInfoList = null;
for (File file : excelFolder.listFiles()) {
Workbook wb = getExcelFile(file.getPath());
if (wb == null) {
throw new Exception("讀取失敗");
}
// 解析Excel to List
excelInfoList = parseExcel(wb);
// System.out.println(excelInfoList);
// excel檔名
systemName = file.getName();
wb.close();
}
writeexcel(excelInfoList, copybookname, excelFolderPath);
}
public static void writeexcel(List<Map<String, String>> excelInfoList, String copybookname,
String excelFolderPath) {
// System.out.println(copybookname);
logger.info("寫入excel");
for (Map<String, String> text : excelInfoList) {
// 路徑切割,比對
String lastItem = Stream.of(text.get("Copybook").split("/")).reduce((first, last) -> last).get();
if (lastItem.equals(copybookname)) {
// System.out.println(lastItem);
// System.out.println(text.get("rowindex"));
int rownum = Integer.valueOf(text.get("rowindex"));
logger.info(lastItem+"在excel第"+(rownum+1)+"行");
Workbook workbook;
try {
// 寫入EXCEL
workbook = new XSSFWorkbook(excelFolderPath + "\\" + systemName);
Sheet sheet1 = workbook.getSheet(sheetName);
Cell writeCell = sheet1.getRow(rownum).getCell(col);
if (writeCell == null) {
writeCell = sheet1.getRow(rownum).createCell(col);
}
writeCell.setCellValue("Y");
FileOutputStream fos = new FileOutputStream(excelFolderPath + "\\" + systemName, true);
workbook.write(fos);
logger.info("excel寫入完成");
workbook.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 讀取excel檔案
*
* Workbook(Excel本體)、Sheet(內部頁面)、Row(頁面之行(橫的))、Cell(行內的元素)
*
*
* @param path excel檔案路徑
* @return excel內容
*/
public static Workbook getExcelFile(String path) {
Workbook wb = null;
try {
if (path == null) {
return null;
}
String extString = path.substring(path.lastIndexOf(".")).toLowerCase();
FileInputStream in = new FileInputStream(path);
wb = StreamingReader.builder().rowCacheSize(100)// 存到記憶體行數,預設10行。
.bufferSize(2048)// 讀取到記憶體的上限,預設1024
.open(in);
} catch (FileNotFoundException e) {
logger.info(e.toString());
e.printStackTrace();
}
return wb;
}
public static List<Map<String, String>> parseExcel(Workbook workbook) {
// Sheet的資料
List<Map<String, String>> excelDataList = new ArrayList<>();
// 存放DNS欄位的欄位號
int dnsIndex = 0;
// 遍歷每一個sheet
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
Sheet sheet = workbook.getSheetAt(sheetNum);
boolean rowNum = true;
sheetName = sheet.getSheetName();
// 開始讀取sheet
for (Row row : sheet) {
// 先取header
if (rowNum) {
for (Cell cell : row) {
if (queryColArray.contains(cell.getStringCellValue())) {
HeaderName.put(cell.getColumnIndex(), cell.getStringCellValue());
// 給colums位置
if (cell.getStringCellValue().equals("Isbinary")) {
col = cell.getColumnIndex();
}
}
}
rowNum = false;
continue;
}
// 解析Row的資料
excelDataList.add(convertRowToData(row, dnsIndex));
}
}
return excelDataList;
}
/**
* 解析ROW
*
* @param row 資料行
* @param firstRow 標頭
* @param dnsIndex Dns的列數
* @return 整row的欄位
*/
public static Map<String, String> convertRowToData(Row row, int dnsIndex) {
Map<String, String> excelDateMap = new HashMap<String, String>();
for (Object key : HeaderName.keySet()) {
for (Cell cell : row) {
// 1.
int headerNameIndex = (int) key;
cell = row.getCell(headerNameIndex, MissingCellPolicy.CREATE_NULL_AS_BLANK);
if (cell == null) {
cell.setCellValue("Empty");
}
// 2.再去抓Header的欄位名稱
String firstRowName = HeaderName.get(key);
excelDateMap.put(firstRowName, cell.getStringCellValue());
excelDateMap.put("rowindex", String.valueOf(cell.getRowIndex()));
}
}
return excelDateMap;
}
}
<file_sep>/src/main/java/com/example/demo/ReadExcel.java
package com.example.demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;
import org.apache.poi.ss.formula.functions.Index;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.monitorjbl.xlsx.StreamingReader;
import java_cup.internal_error;
public class ReadExcel {
private final static Logger logger = LoggerFactory.getLogger(ReadExcel.class);
List<String> queryColArray;// 要抓取的欄位
String excelFolderPath; // excel資料夾位置
String destFileFolderPath; // output位置
String systemName;
String sheetName;
// (CellIndex,HeaderName)
Map<Integer, String> HeaderName = new HashMap<Integer, String>();
ReadExcel() {
Properties pro = new Properties();
String config = "config.properties";
logger.info(config);
try {
pro.load(new FileInputStream(config));
excelFolderPath = pro.getProperty("excelDir");
destFileFolderPath = pro.getProperty("destFile");
logger.info(" Excel資料夾位置:{}\n 輸出資料夾位置:{}", excelFolderPath, destFileFolderPath);
queryColArray = Arrays.asList(pro.getProperty("queryColArray").split(","));
logger.info("需要抓取的欄位 " + queryColArray);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readExcelStart() throws Exception {
// 取資料夾
File excelFolder = new File(excelFolderPath);
logger.info("excelDir:{} 有 {} 個Excel檔案", excelFolderPath, excelFolder.list().length);
List<Map<String, String>> excelInfoList = null;
for (File file : excelFolder.listFiles()) {
logger.info("開始讀取 " + file.getName());
Workbook wb = getExcelFile(file.getPath());
if (wb == null) {
logger.info(file.getPath() + "讀取失敗");
throw new Exception("讀取失敗");
}
logger.info(file.getName() + " 讀取完成");
// 解析Excel to List
logger.info("開始解析 " + file.getName());
excelInfoList = parseExcel(wb);
logger.info("解析 " + file.getName() + " 完成");
// excel檔名
// EX: excel檔名 帳務作業流程清單(BANK)_1090430 取 帳務作業流程清單(BANK)
systemName = file.getName();
logger.info("檔名 " + sheetName);
// System.out.println(excelInfoList);
logger.info(systemName + " 完成");
}
findPreviousAndNext(excelInfoList);
// System.out.println(excelInfoList);
}
public void findPreviousAndNext(List<Map<String, String>> excelInfoList) {
Scanner scanner = new Scanner(System.in);
System.out.println("輸入job name");
String keyjob = scanner.nextLine();
logger.info("要查詢的job name " + keyjob);
System.out.println("============往前找=======================");
for (Map<String, String> text : excelInfoList) {
// System.out.println(text);
if (text.get("JOB").equals(keyjob)) {
System.out.println("現在的AD NAME: " + text.get("AD") + '\t' + "PreviousJOB: " + text.get("PreviousJOB")
+ '\t' + "NextJOB: " + text.get("NextJOB"));
break;
} else {
System.out.println("前一筆的AD NAME: " + text.get("AD") + '\t' + "PreviousJOB: " + text.get("PreviousJOB")
+ '\t' + "NextJOB: " + text.get("NextJOB"));
}
}
System.out.println("============往後找=======================");
for (int i = 0; i < excelInfoList.size(); i++) {
if (excelInfoList.get(i).get("JOB").equals(keyjob)) {
System.out.println("現在的AD NAME: " + excelInfoList.get(i).get("AD") + '\t' + "PreviousJOB: "
+ excelInfoList.get(i).get("PreviousJOB") + '\t' + "NextJOB: "
+ excelInfoList.get(i).get("NextJOB"));
for (int j = i + 1; j < excelInfoList.size(); j++) {
System.out.println("下一個AD NAME: " + excelInfoList.get(j).get("AD") + '\t' + "PreviousJOB: "
+ excelInfoList.get(j).get("PreviousJOB") + '\t' + "NextJOB: "
+ excelInfoList.get(j).get("NextJOB"));
}
}
}
scanner.close();
}
/**
* 讀取excel檔案
*
* Workbook(Excel本體)、Sheet(內部頁面)、Row(頁面之行(橫的))、Cell(行內的元素)
*
*
* @param path excel檔案路徑
* @return excel內容
*/
public Workbook getExcelFile(String path) {
Workbook wb = null;
try {
if (path == null) {
return null;
}
String extString = path.substring(path.lastIndexOf(".")).toLowerCase();
FileInputStream in = new FileInputStream(path);
wb = StreamingReader.builder().rowCacheSize(100)// 存到記憶體行數,預設10行。
.bufferSize(2048)// 讀取到記憶體的上限,預設1024
.open(in);
} catch (FileNotFoundException e) {
logger.info(e.toString());
e.printStackTrace();
}
return wb;
}
/**
* 解析Sheet
*
* @param workbook Excel檔案
* @return 整個Sheet的資料
*/
public List<Map<String, String>> parseExcel(Workbook workbook) {
// Sheet的資料
List<Map<String, String>> excelDataList = new ArrayList<>();
// 存放DNS欄位的欄位號
int dnsIndex = 0;
// 遍歷每一個sheet
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
Sheet sheet = workbook.getSheetAt(sheetNum);
boolean rowNum = true;
sheetName = sheet.getSheetName();
// 開始讀取sheet
for (Row row : sheet) {
// 先取header
if (rowNum) {
for (Cell cell : row) {
if (queryColArray.contains(cell.getStringCellValue())) {
HeaderName.put(cell.getColumnIndex(), cell.getStringCellValue());
}
}
rowNum = false;
continue;
}
// 解析Row的資料
excelDataList.add(convertRowToData(row, dnsIndex));
}
}
return excelDataList;
}
/**
* 解析ROW
*
* @param row 資料行
* @param firstRow 標頭
* @param dnsIndex Dns的列數
* @return 整row的欄位
*/
public Map<String, String> convertRowToData(Row row, int dnsIndex) {
Map<String, String> excelDateMap = new HashMap<String, String>();
// Scanner scanner = new Scanner(System.in);
// System.out.println("輸入job name");
// String keyjob = scanner.nextLine();
for (Object key : HeaderName.keySet()) {
for (Cell cell : row) {
// 1.
int headerNameIndex = (int) key;
cell = row.getCell(headerNameIndex, MissingCellPolicy.CREATE_NULL_AS_BLANK);
if (cell == null) {
cell.setCellValue("Empty");
}
// 2.再去抓Header的欄位名稱
String firstRowName = HeaderName.get(key);
excelDateMap.put(firstRowName, cell.getStringCellValue());
excelDateMap.put(firstRowName, cell.getStringCellValue());
}
}
return excelDateMap;
}
}
<file_sep>/src/main/java/com/example/demo/ReadExcelApplication.java
package com.example.demo;
import java.util.Scanner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java_cup.internal_error;
import java_cup.simple_calc.scanner;
@SpringBootApplication
public class ReadExcelApplication {
public static void main(String[] args) {
SpringApplication.run(ReadExcelApplication.class, args);
// ReadExcel readExcel = new ReadExcel();
// readexcel2 re2= new readexcel2();
try {
// readExcel.readExcelStart();
// re2.readExcelStart();
FindCOMP.test();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 384f927b5197833a8da776664385009b11eee118 | [
"Java"
] | 3 | Java | jimmyting0710/readexcelFindComp | 58953303579202b4b7ab4f8eeb851761e807846f | 502d2b8e4c95c67babca2c13fa2e5a9f72e55b61 |
refs/heads/master | <file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Datetime from 'react-datetime';
import container from '../../../modules/container';
const Varsta = ({ varsta }) => ( varsta ?
<span>
<strong>{varsta}</strong>
</span> : <span>'-'</span>
);
export default container((props, onData) => {
const dataNastere = props.dataNastere;
if (dataNastere !== '' && typeof dataNastere !== 'undefined') {
let dataNastereArray = dataNastere.split('-');
dataNastereObj = new Date(dataNastereArray[2], dataNastereArray[1]-1, dataNastereArray[0], 0, 0, 0, 0);
let varsta = Datetime.moment().diff(dataNastereObj, 'years');
onData(null, { varsta });
}
}, Varsta);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { browserHistory } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import { Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import container from '../../modules/container';
import Orase from '../../api/orase/orase';
const logout = () => {
Object.keys(Session.keys).forEach(function(key){
Session.set(key, undefined);
});
Session.keys = {};
Meteor.logout();
browserHistory.push('/login');
};
const contulMeu = () => browserHistory.push('/contul-meu');
const userName = () => {
const user = Meteor.user();
const name = user && user.profile ? user.profile.name : '';
return user ? `${name.first} ${name.last}` : '';
};
const getIdOras = () => {
const user = Meteor.user();
return user ? `${user.profile.city}` : '';
};
const AuthenticatedNavigation = ( { numeOrasUser, linkOrasUser } ) => (
<div>
<Nav>
{Roles.userIsInRole(Meteor.userId(), 'admin') === false ?
<LinkContainer to={"/activitati-" + linkOrasUser}>
<NavItem eventKey={ 2.1 } href={"/activitati-" + linkOrasUser}>
{ numeOrasUser ?
'Activitati din ' + numeOrasUser : ''
}
</NavItem>
</LinkContainer>
:''
}
{Roles.userIsInRole(Meteor.userId(), 'admin') === false ?
<LinkContainer to="/adauga-activitate">
<NavItem eventKey={ 2.2 } href="/adauga-activitate">Adauga activitate</NavItem>
</LinkContainer>
:''
}
<LinkContainer to="/calendar-activitati">
<NavItem eventKey={ 2.3 } href="/calendar-activitati">Calendar activitati</NavItem>
</LinkContainer>
</Nav>
<Nav pullRight>
<NavDropdown eventKey={ 3 } title={ userName() } id="basic-nav-dropdown">
<MenuItem eventKey={ 3.1 } onClick={ contulMeu }>Contul meu</MenuItem>
<MenuItem eventKey={ 3.2 } onClick={ logout }>Logout</MenuItem>
</NavDropdown>
</Nav>
</div>
);
AuthenticatedNavigation.propTypes = {
numeOrasUser: PropTypes.string,
};
export default container((props, onData) => {
let numeOrasUser = '';
let linkOrasUser = '';
if (typeof Session.get('numeOrasUser') !== 'undefined') {
numeOrasUser = Session.get('numeOrasUser');
linkOrasUser = Session.get('linkOrasUser');
} else {
const subscription = Meteor.subscribe('orase.list');
if (subscription.ready()) {
const oras = Orase.findOne({_id: getIdOras()});
numeOrasUser = oras ? `${oras.nume}` : '';
linkOrasUser = oras ? `${oras.link}` : '';
let coordonateLatOrasUser = oras ? `${oras.coordonateLat}` : '';
let coordonateLngOrasUser = oras ? `${oras.coordonateLng}` : '';
Session.set('numeOrasUser', numeOrasUser);
Session.set('linkOrasUser', linkOrasUser);
Session.set('coordonateLatOrasUser', coordonateLatOrasUser);
Session.set('coordonateLngOrasUser', coordonateLngOrasUser);
}
}
onData(null, { numeOrasUser, linkOrasUser });
}, AuthenticatedNavigation);
<file_sep>import { Mongo } from 'meteor/mongo';
import SimpleSchema from 'simpl-schema';
//import { Factory } from 'meteor/dburles:factory';
const Activitati = new Mongo.Collection('activitati');
export default Activitati;
Activitati.allow({
insert: () => false,
update: () => false,
remove: () => false,
});
Activitati.deny({
insert: () => true,
update: () => true,
remove: () => true,
});
Activitati.schema = new SimpleSchema({
numeActivitate: {
type: String,
label: 'Numele activitatii',
},
descriereActivitate: {
type: String,
label: 'Descrierea activitatii',
},
idOras: {
type: String,
label: 'Orasul ales de utilizator',
},
idSport: {
type: String,
label: 'Sportul ales de utilizator',
},
nrmaxParticipanti: {
type: Number,
label: 'Numarul ales de paricipanti dorit',
},
limitaParticipanti: {
type: Boolean,
label: 'True daca nu are limita de participanti',
},
dataActivitate: {
type: Date,
label: 'Data de adaugare a activitatii',
},
dataActivitateadaugata: {
type: Date,
label: 'Data in care a fost adaugata activitatea',
},
idadminActivitate: {
type: String,
label: 'Id-ul persoanei care a creat activitatea',
},
anulata: {
type: Boolean,
label: 'Starea activitatii',
},
locatieLat: {
type: Number,
label: 'Coordonate locatie',
optional: true
},
locatieLng: {
type: Number,
label: 'Coordonate locatie',
optional: true
},
});
Activitati.attachSchema(Activitati.schema);
<file_sep>/* eslint-disable no-undef */
import { browserHistory } from 'react-router';
import { Accounts } from 'meteor/accounts-base';
import { Bert } from 'meteor/themeteorchef:bert';
import './validation.js';
let component;
const reseteaza = () => {
const oldPassword = document.querySelector('[name="oldPassword"]').value;
const newPassword = document.querySelector('[name="newPassword"]').value;
Accounts.changePassword(oldPassword, newPassword, (error) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
browserHistory.push('/');
Bert.alert('Password reset!', 'success');
}
});
};
const valideazaCampuri = () => {
$(component.formSchimbaParola).validate({
rules: {
oldPassword: {
required: true,
minlength: 6,
},
newPassword: {
required: true,
minlength: 6,
},
repeatNewPassword: {
required: true,
minlength: 6,
equalTo: '[name="newPassword"]',
},
},
messages: {
oldPassword: {
required: 'Introduceti parola curenta a contului.',
minlength: 'Use at least six characters, please.',
},
newPassword: {
required: 'Enter a new password, please.',
minlength: 'Use at least six characters, please.',
},
repeatNewPassword: {
required: 'Repeat your new password, please.',
equalTo: 'Hmm, your passwords don\'t match. Try again?',
},
},
submitHandler() { reseteaza(); },
});
};
export default function schimbaParola(options) {
component = options.component;
valideazaCampuri();
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import { Button } from 'react-bootstrap';
import { browserHistory } from 'react-router';
import container from '../../../modules/container';
const ButonEditareActivitate = props =>(
<span>
{(props.idadminActivitate === Meteor.userId()) || Roles.userIsInRole(Meteor.userId(), 'admin') === true ?
<span>
<Button onClick={ () => handleEdit(props.idActivitate) } bsStyle="primary">Edit <i className="fa fa-pencil-square-o" aria-hidden="true"></i></Button>
</span>
: ''
}
</span>
);
ButonEditareActivitate.propTypes = {
idActivitate: PropTypes.string,
idadminActivitate: PropTypes.string,
};
const handleEdit = (idActivitate) => {
browserHistory.push(`/activitati/${idActivitate}/edit`);
};
export default container((props, onData) => {
const idActivitate = props.idActivitate;
const idadminActivitate = props.idadminActivitate;
onData(null, { idActivitate, idadminActivitate });
}, ButonEditareActivitate);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Alert, Row, Col } from 'react-bootstrap';
import { Link } from 'react-router';
import { Meteor } from 'meteor/meteor';
import ParticipantiActivitati from '../../api/participanti_activitati/participanti_activitati';
import Activitati from '../../api/activitati/activitati';
import container from '../../modules/container';
import CardActivitate from './activitate/Card';
const ActivitatiUser = ({ activitati }) => (
<div>
{Roles.userIsInRole(Meteor.userId(), 'admin') === false ?
<Row className="show-grid">
<Col xs={12}>
<div className="page-header clearfix">
<h4 className="pull-left">Activități la care participi</h4>
</div>
<Row>
{activitati.length > 0 ?
activitati.map(({_id, numeActivitate, descriereActivitate, nrmaxParticipanti, idSport, dataActivitate, anulata}) => (
<CardActivitate
key={ _id }
idActivitate={ _id }
numeActivitate={ numeActivitate }
descriereActivitate={ descriereActivitate }
nrmaxParticipanti={ nrmaxParticipanti }
idSport={ idSport }
dataActivitate={ dataActivitate }
anulata={ anulata }
/>
))
:
<Col xs={12}>
<Alert bsStyle="warning">Nu participi la nicio activitate :(.</Alert>
</Col>
}
</Row>
</Col>
</Row>
:''
}
</div>
);
ActivitatiUser.propTypes = {
activitati: PropTypes.array,
};
export default container((props, onData) => {
const subscription = Meteor.subscribe('participanti_activitati.list');
let data = new Date();
if (subscription.ready()) {
const participantiActivitati = ParticipantiActivitati.find({idParticipant: Meteor.userId()}).fetch();
const idActivitati = [];
participantiActivitati.map(({_id, idActivitate}) => {
idActivitati.push(idActivitate);
});
const subscriptionActivitati = Meteor.subscribe('activitati.list');
if (subscriptionActivitati.ready()) {
const activitati = Activitati.find({ _id: { $in: idActivitati }, anulata: {$ne: true}, dataActivitate: {$gte: data} }, {sort: {dataActivitate: 1}, limit:4}).fetch();
onData(null, { activitati });
}
}
}, ActivitatiUser);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Row, Col } from 'react-bootstrap';
import { Link } from 'react-router';
import { Meteor } from 'meteor/meteor';
import container from '../../modules/container';
const Footer = (hasUser) => (
<Row>
<Col xs={12}>
Licenta @2017 - <NAME>
</Col>
</Row>
);
Footer.propTypes = {
hasUser: PropTypes.object,
};
export default container((props, onData) => {
onData(null, { hasUser: Meteor.user() });
}, Footer);
<file_sep>import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import Mesaje from '../mesaje';
Meteor.publish('mesaje.list', () => Mesaje.find());
Meteor.publish('mesaje.view', (_id) => {
check(_id, String);
return Mesaje.find(_id);
});
<file_sep>import React from 'react';
import { browserHistory, Link } from 'react-router';
import { Panel, ListGroup, ListGroupItem } from 'react-bootstrap';
const logout = () => Meteor.logout(() => browserHistory.push('/login'));
const MeniuContulMeu = () => (
<Panel collapsible defaultExpanded header="Contul meu">
<ListGroup fill>
<ListGroupItem>
<Link to="/contul-meu">Contul meu</Link>
</ListGroupItem>
<ListGroupItem>
<Link to="/activitatile-mele">Activitati adaugate</Link>
</ListGroupItem>
<ListGroupItem>
<Link to="/schimba-parola">Schimba parola</Link>
</ListGroupItem>
<ListGroupItem>
<a href="#" onClick={ logout }>Logout</a>
</ListGroupItem>
</ListGroup>
</Panel>
);
export default MeniuContulMeu;
<file_sep>import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import Activitati from './activitati';
import rateLimit from '../../modules/rate-limit.js';
export const adaugaActivitate = new ValidatedMethod({
name: 'activitati.upsert',
validate: new SimpleSchema({
_id: { type: String, optional: true },
numeActivitate: { type: String },
descriereActivitate: { type: String, optional: true },
idadminActivitate: { type: String },
idOras: { type: String },
idSport: { type: String },
anulata: { type: Boolean, optional: true },
nrmaxParticipanti: { type: Number, optional: true },
limitaParticipanti: { type: Boolean, optional: true },
dataActivitate: { type: Date },
dataActivitateadaugata: {type: Date},
locatieLat: { type: Number, optional: true },
locatieLng: { type: Number, optional: true },
}).validator(),
run(activitate) {
return Activitati.upsert({ _id: activitate._id }, { $set: activitate });
},
});
export const stergeActivitate = new ValidatedMethod({
name: 'activitati.remove',
validate: new SimpleSchema({
_id: { type: String },
}).validator(),
run({ _id }) {
Activitati.remove(_id);
},
});
export const anuleazaActivitate = new ValidatedMethod({
name: 'activitati.anuleaza',
validate: new SimpleSchema({
_id: { type: String },
anulata: { type: Boolean },
}).validator(),
run(activitate) {
return Activitati.update({ _id: activitate._id }, {
$set: { anulata: activitate.anulata }
}, { multi: true });
},
});
rateLimit({
methods: [
adaugaActivitate,
stergeActivitate,
anuleazaActivitate,
],
limit: 5,
timeRange: 1000,
});
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Alert, Row, Col } from 'react-bootstrap';
import { Link } from 'react-router';
import { Meteor } from 'meteor/meteor';
import Activitati from '../../api/activitati/activitati';
import container from '../../modules/container';
import CardActivitate from './activitate/Card';
const ActivitatiAdaugate = ({ activitati }) => (
<div>
<Row className="show-grid">
<Col xs={12}>
{activitati.length > 0 ?
activitati.map(({_id, numeActivitate, descriereActivitate, nrmaxParticipanti, idSport, dataActivitate, anulata}) => (
<CardActivitate
key={ _id }
idActivitate={ _id }
numeActivitate={ numeActivitate }
descriereActivitate={ descriereActivitate }
nrmaxParticipanti={ nrmaxParticipanti }
idSport={ idSport }
dataActivitate={ dataActivitate }
anulata={ anulata }
/>
))
:
<Alert bsStyle="warning">Nu ai adăugat nici o activitate :(.</Alert>
}
</Col>
</Row>
<Row>
<Col>
<Link to="/calendar-activitati" className="pull-right">Activități la care participi</Link>
</Col>
</Row>
</div>
);
ActivitatiAdaugate.propTypes = {
activitati: PropTypes.array,
};
export default container((props, onData) => {
const subscription = Meteor.subscribe('activitati.list');
if (subscription.ready()) {
const activitati = Activitati.find({idadminActivitate: Meteor.userId()}).fetch();
onData(null, { activitati });
}
}, ActivitatiAdaugate);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import { Image } from 'react-bootstrap';
import Sporturi from '../../../api/sporturi/sporturi';
import container from '../../../modules/container';
const ImgSport = ({ sport }) => (
sport ? <Image src={ '/img/' + sport.img } thumbnail responsive className="center-block" /> : ''
);
ImgSport.propTypes = {
sport: PropTypes.object,
};
export default container((props, onData) => {
const subscription = Meteor.subscribe('sporturi.list');
if (subscription.ready()) {
const sport = Sporturi.findOne({_id: props.id});
onData(null, { sport });
}
}, ImgSport);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { FormControl } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import Orase from '../../../api/orase/orase';
import container from '../../../modules/container';
const SelectOrase = ({ orase, selected }) => (
orase.length > 0 ? <FormControl name="oras" componentClass="select" defaultValue={selected} placeholder="Oras">
{orase.map(({ _id, nume }) => (
<option value={ _id } key={ _id }>
{ nume }
</option>
))}
</FormControl> : ''
);
SelectOrase.propTypes = {
orase: PropTypes.array,
selected: PropTypes.string,
};
export default container((props, onData) => {
const subscription = Meteor.subscribe('orase.list');
if (subscription.ready()) {
const orase = Orase.find().fetch();
let selected = '';
if (typeof props.selected !== 'undefined') {
selected = props.selected;
}
onData(null, { orase, selected });
}
}, SelectOrase);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Image } from 'react-bootstrap';
import container from '../../../modules/container';
const ImgOras = (props) => (
<Image src={ '/img/orase/' + props.img } thumbnail responsive />
);
ImgOras.propTypes = {
img: PropTypes.string,
};
export default container((props, onData) => {
let link = props.link;
const img = link + '.jpg';
onData(null, { img });
}, ImgOras);
<file_sep>.cardEveniment {
background-color: #f9f9f9;
margin: 5px 0px;
padding: 10px;
}
.detaliiActivitate {
margin: 0px 0px 10px 0px;
background: #f1f1f1;
padding: 5px;
border-radius: 5px;
}
.dataActivitate {
margin: 0px 0px 10px 0px;
text-align: center;
.fa {
margin-right: 5px;
color: #1d9a1d;
}
}
.numeActivitate {
text-align: center;
overflow: hidden;
height: 40px;
word-wrap: break-word;
}
<file_sep>import React from 'react';
import { Meteor } from 'meteor/meteor';
import { Row, Col, Image } from 'react-bootstrap';
import ActivitatiUser from '../components/ActivitatiUser';
import ActivitatiRecente from '../components/ActivitatiRecente';
import ListaOrase from '../components/oras/Lista';
const Index = () => (
<div>
<Row>
<Col xs={12} lg={12}>
<Image src={ '/img/extra/cover.png' } responsive thumbnail />
</Col>
</Row>
{Meteor.userId() ?
<ActivitatiUser />
: ''
}
<ActivitatiRecente />
<ListaOrase />
</div>
);
export default Index;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { browserHistory } from 'react-router';
import { Alert, Row, Col, Button } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import Activitati from '../../api/activitati/activitati';
import container from '../../modules/container';
import CardActivitate from './activitate/Card';
const handleNav = _id => browserHistory.push(`/activitati/${_id}`);
const ActivitatiRecente = ({ activitati }) => (
<Row className="show-grid">
<Col xs={12}>
<div className="page-header clearfix">
<h4 className="pull-left">Activităţi recent adăugate</h4>
</div>
{activitati.length > 0 ?
activitati.map(({_id, numeActivitate, descriereActivitate, nrmaxParticipanti, idSport, dataActivitate, anulata}) => (
<CardActivitate
key={ _id }
idActivitate={ _id }
numeActivitate={ numeActivitate }
descriereActivitate={ descriereActivitate }
nrmaxParticipanti={ nrmaxParticipanti }
idSport={ idSport }
dataActivitate={ dataActivitate }
anulata={ anulata }
/>
))
:
<Alert bsStyle="warning">Nu sunt activități adăugate.</Alert>
}
</Col>
</Row>
);
ActivitatiRecente.propTypes = {
activitati: PropTypes.array,
};
export default container((props, onData) => {
const subscription = Meteor.subscribe('activitati.list');
if (subscription.ready()) {
const activitati = Activitati.find({}, {sort: {dataActivitateadaugata : -1}, limit:4}).fetch();
onData(null, { activitati });
}
}, ActivitatiRecente);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import Orase from '../../../api/orase/orase';
import container from '../../../modules/container';
const OrasSelectat = ({numeOras}) => {
return numeOras ? <span><strong>{numeOras}</strong></span> : '';
};
const getIdOras = () => {
const user = Meteor.user();
return user ? `${user.profile.city}` : '';
};
OrasSelectat.propTypes = {
numeOras: PropTypes.string,
};
export default container((props, onData) => {
const subscription = Meteor.subscribe('orase.list');
if (subscription.ready()) {
const oras = Orase.findOne({ _id: getIdOras() });
onData(null, { numeOras: oras.nume });
}
}, OrasSelectat);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import { Button } from 'react-bootstrap';
import { browserHistory } from 'react-router';
import { stergeActivitate, anuleazaActivitate } from '../../../api/activitati/methods';
import ParticipantiActivitati from '../../../api/participanti_activitati/participanti_activitati';
import container from '../../../modules/container';
const ButonStergeActivitate = props =>(
<span>
{(props.idadminActivitate === Meteor.userId() && props.nrParticipanti === 0) || Roles.userIsInRole(Meteor.userId(), 'admin') === true ?
<span>
<Button onClick={ () => handleRemove(props.idActivitate) } bsStyle="danger"><i className="fa fa-trash-o" aria-hidden="true"></i> Sterge</Button>
</span>
: props.idadminActivitate === Meteor.userId() && props.anulata === false?
<span>
<Button onClick={ () => handleCancel(props.idActivitate) } bsStyle="default"><i className="fa fa-ban" aria-hidden="true"></i> Anuleaza</Button>
</span>
: (props.idadminActivitate === Meteor.userId() && props.anulata === true) ?
<span>
<Button disabled onClick={ () => handleCancel(props.idActivitate) } bsStyle="default"><i className="fa fa-ban" aria-hidden="true"></i> Activitate anulata</Button>
</span>
:''
}
</span>
);
ButonStergeActivitate.propTypes = {
idActivitate: PropTypes.string,
idadminActivitate: PropTypes.string,
nrParticipanti: PropTypes.number,
participantLogat: PropTypes.object,
anulata: PropTypes.bool,
};
const handleRemove = (idActivitate) => {
if (confirm('Esti sigur ca doresti stergerea acestei activitati?')) {
stergeActivitate.call({ _id: idActivitate }, (error) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
Bert.alert('Activitatea a fost stearsa! Activitatea poate fi reactivata daca o editezi', 'success');
browserHistory.push('/activitatile-mele');
}
});
}
};
const handleCancel = (idActivitate) => {
if (confirm('Esti sigur ca doresti sa anulezi activitatea?')) {
const activitate = {
_id: idActivitate,
anulata: true
};
anuleazaActivitate.call(activitate, (error) => {
if (error) {console.log(error);
Bert.alert(error.reason, 'danger');
} else {
Bert.alert('Activitatea a fost anulata!', 'success');
}
});
}
};
export default container((props, onData) => {
const idActivitate = props.idActivitate;
const idadminActivitate = props.idadminActivitate;
const anulata = props.anulata;
let nrParticipanti = ParticipantiActivitati.find({ idActivitate: idActivitate }).count();
let participantLogat = ParticipantiActivitati.findOne({ idActivitate: idActivitate, idParticipant: Meteor.userId() });
onData(null, { idActivitate, idadminActivitate, nrParticipanti, participantLogat, anulata });
}, ButonStergeActivitate);
<file_sep>/* eslint-disable no-undef */
import {browserHistory} from 'react-router';
import {Bert} from 'meteor/themeteorchef:bert';
import {adaugaActivitate} from '../api/activitati/methods.js';
import {adaugaParticipantActivitate} from '../api/participanti_activitati/methods.js';
import './validation.js';
let component;
const salveaza = () => {
const {activitate} = component.props;
const confirmation = activitate && activitate._id ? 'Activitate salvata!' : 'Activitate adaugata!';
let limitaParticipanti = false;
let anulata = false;
const dataActivitateadaugata = new Date();
if (document.querySelector('[name="limitaParticipanti"]:checked') !== null || document.querySelector('[name="nrmaxParticipanti"]').value.trim() === '') {
limitaParticipanti = true;
}
let nrmaxParticipanti = 0;
if (document.querySelector('[name="nrmaxParticipanti"]').value.trim() !== '' && limitaParticipanti === false) {
nrmaxParticipanti = parseInt(document.querySelector('[name="nrmaxParticipanti"]').value.trim());
if (nrmaxParticipanti < 0) {
nrmaxParticipanti = 0;
limitaParticipanti = true;
}
}
const activitateNoua = {
numeActivitate: document.querySelector('[name="numeActivitate"]').value.trim(),
descriereActivitate: document.querySelector('[name="descriereActivitate"]').value.trim(),
idadminActivitate: Meteor.userId(),
idOras: document.querySelector('[name="oras"]').value.trim(),
idSport: document.querySelector('[name="sport"]').value.trim(),
anulata: anulata,
nrmaxParticipanti: nrmaxParticipanti,
limitaParticipanti: limitaParticipanti,
dataActivitate: new Date(document.querySelector('[name="dataActivitate"]').value.trim()),
dataActivitateadaugata : dataActivitateadaugata,
};
let marker = component.state.marker;
if (marker.length > 0 && typeof marker[0].position !== 'undefined') {
if (typeof marker[0].position.lat !== 'function' && typeof marker[0].position.lng !== 'function') {
activitateNoua.locatieLat = parseFloat(marker[0].position.lat);
activitateNoua.locatieLng = parseFloat(marker[0].position.lng);
} else {
activitateNoua.locatieLat = parseFloat(marker[0].position.lat());
activitateNoua.locatieLng = parseFloat(marker[0].position.lng());
}
} else {
activitateNoua.locatieLat = null;
activitateNoua.locatieLng = null;
}
if (activitate && activitate._id) activitateNoua._id = activitate._id;
let idActivitate = null;
adaugaActivitate.call(activitateNoua, (error, response) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
idActivitate = response.insertedId;
if (!activitate && idActivitate !== null) {
adaugaParticipant(idActivitate);
}
component.editForm.reset();
Bert.alert(confirmation, 'success');
browserHistory.push(`/activitati/${idActivitate || activitate._id}`);
}
});
};
const adaugaParticipant = (idActivitate) => {
const participantActivitate = {
idActivitate: idActivitate,
idParticipant: Meteor.userId(),
data: new Date(),
};
adaugaParticipantActivitate.call(participantActivitate, (error, response) => {
if (error) {
Bert.alert('Eroare adaugare participant', 'danger');
}
});
};
const validate = () => {
$(component.editForm).validate({
rules: {
numeActivitate: {
required: true,
},
descriereActivitate: {
required: true,
},
idOras: {
required: true,
},
idSport: {
required: true,
},
dataActivitate: {
required: true,
},
},
messages: {
numeActivitate: {
required: 'Intraduce numele activitatii',
},
descriereActivitate: {
required: 'Descrie activitatea',
},
idOras: {
required: 'Alege orasul dorit',
},
idSport: {
required: 'Alege sportul dorit',
},
dataActivitate: {
required: 'Alege data si ora activitatii',
},
},
submitHandler() {
salveaza();
},
});
};
export default function modificaActivitate(options) {
component = options.component;
validate();
}
<file_sep>import { Mongo } from 'meteor/mongo';
import SimpleSchema from 'simpl-schema';
const Mesaje = new Mongo.Collection('mesaje');
export default Mesaje;
Mesaje.allow({
insert: () => false,
update: () => false,
remove: () => false,
});
Mesaje.deny({
insert: () => true,
update: () => true,
remove: () => true,
});
Mesaje.schema = new SimpleSchema({
mesaj: {
type: String,
label: 'Mesaj',
},
idActivitate: {
type: String,
label: 'Id-ul activitatii.',
},
idUser: {
type: String,
label: 'Id-ul userului.',
},
data: {
type: Date,
label: 'Data publicare mesaj.',
},
});
Mesaje.attachSchema(Mesaje.schema);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { browserHistory } from 'react-router';
import Datetime from "react-datetime";
import { Col, Button } from 'react-bootstrap';
import container from '../../../modules/container';
import NumeSport from '../sport/Nume';
import ImgSport from '../sport/Img';
import ParticipantiActivitati from '../../../api/participanti_activitati/participanti_activitati';
const handleNav = _id => browserHistory.push(`/activitati/${_id}`);
const Activitate = (props) => (
<Col xs={12} sm={4} md={3}>
<div className="cardEveniment">
<ImgSport id={ props.idSport } />
<h4 className="numeActivitate">{ props.numeActivitate }</h4>
<div className="detaliiActivitate">
<div><strong>Sport:</strong> <span className="label label-success"><NumeSport id={ props.idSport } /></span></div>
<div><strong>Locuri disponibile:</strong> <span className="label label-warning">
{props.nrmaxParticipanti === 0 ?
'Fără limită'
:
props.nrparticipantiRamasi
}
</span></div>
</div>
<div className="dataActivitate">
<i className="fa fa-calendar-check-o" aria-hidden="true"></i>
<strong>Dată activitate:</strong> { Datetime.moment(props.dataActivitate).format("DD-MM-YYYY") }
</div>
<div className="text-center">
{ props.anulata === false && props.dataActivitateStart > props.data ?
<Button onClick={ () => handleNav(props.idActivitate) } bsSize="small" bsStyle="primary"><i className="fa fa-eye" aria-hidden="true"></i> Detalii activitate</Button>
: props.anulata === false && props.dataActivitateStart < props.data ?
<Button onClick={ () => handleNav(props.idActivitate) } bsSize="small" bsStyle="danger"><i className="fa fa-exclamation-circle" aria-hidden="true"></i> Activitate expirată</Button>
: props.anulata === true ?
<Button onClick={ () => handleNav(props.idActivitate) } bsSize="small" bsStyle="default"><i className="fa fa-ban" aria-hidden="true"></i> Activitate anulată</Button>
:''
}
</div>
</div>
</Col>
);
Activitate.propTypes = {
idActivitate: PropTypes.string,
numeActivitate: PropTypes.string,
descriereActivitate: PropTypes.string,
nrmaxParticipanti: PropTypes.number,
idSport: PropTypes.string,
dataActivitate: PropTypes.instanceOf(Date),
anulata: PropTypes.bool,
nrParticipanti: PropTypes.number,
nrparticipantiRamasi: PropTypes.number,
data: PropTypes.instanceOf(Date),
dataActivitateStart: PropTypes.instanceOf(Date),
};
export default container((props, onData) => {
const idActivitate = props.idActivitate;
const numeActivitate = props.numeActivitate;
const descriereActivitate = props.descriereActivitate;
const nrmaxParticipanti = props.nrmaxParticipanti;
const idSport = props.idSport;
const dataActivitate = props.dataActivitate;
const dataActivitateStart = props.dataActivitate;
const anulata = props.anulata;
let data = new Date();
const subscription = Meteor.subscribe('participanti_activitati.view', idActivitate);
if (subscription.ready()) {
let nrParticipanti = ParticipantiActivitati.find({idActivitate: idActivitate}).count();
let nrparticipantiRamasi = nrmaxParticipanti - nrParticipanti;
onData(null, { data, idActivitate, nrmaxParticipanti, nrParticipanti, nrparticipantiRamasi, numeActivitate, descriereActivitate, idSport, dataActivitate, anulata, dataActivitateStart });
}
}, Activitate);
<file_sep>import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import Sporturi from '../sporturi';
Meteor.publish('sporturi.list', () => Sporturi.find());
Meteor.publish('sporturi.view', (_id) => {
check(_id, String);
return Sporturi.find(_id);
});
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Alert } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import Datetime from 'react-datetime';
import ParticipantiActivitati from '../../../api/participanti_activitati/participanti_activitati';
import container from '../../../modules/container';
import ParticipantActivitate from './ParticipantActivitate';
const ListaParticipanti = ({ participanti }) => (
participanti.length > 0 ?
<div className="lista-participanti">
<ul className="list-group">
{participanti.map(({ _id, idParticipant, data}) => (
<li key={ _id } className="list-group-item">
<ParticipantActivitate idParticipant={idParticipant}></ParticipantActivitate>
<div className="text-right data">{ Datetime.moment(data).format("DD-MM-YYYY hh-mm") }</div>
</li>
))}
</ul>
</div> :
<Alert bsStyle="warning">Nu sunt participanți adăugați.</Alert>
);
ListaParticipanti.propTypes = {
participanti: PropTypes.array,
};
export default container((props, onData) => {
const idActivitate = props.idActivitate;
const subscription = Meteor.subscribe('participanti_activitati.list');
if (subscription.ready()) {
const participanti = ParticipantiActivitati.find({idActivitate: idActivitate}).fetch();
onData(null, { participanti });
}
}, ListaParticipanti);
<file_sep>import React from 'react';
import { render } from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { Meteor } from 'meteor/meteor';
import App from '../../ui/layouts/App.js';
import Activitati from '../../ui/pages/Activitati.js';
import AdaugaActivitate from '../../ui/pages/AdaugaActivitate.js';
import EditActivitate from '../../ui/pages/EditActivitate.js';
import DetaliiActivitate from '../../ui/pages/DetaliiActivitate.js';
import Index from '../../ui/pages/Index.js';
import Login from '../../ui/pages/Login.js';
import NotFound from '../../ui/pages/NotFound.js';
import RecoverPassword from '../../ui/pages/RecoverPassword.js';
import ResetPassword from '../../ui/pages/ResetPassword.js';
import ContNou from '../../ui/pages/ContNou.js';
import ActivitatileMele from '../../ui/pages/ActivitatileMele.js';
import ContulMeu from '../../ui/pages/ContulMeu.js';
import SchimbaParola from '../../ui/pages/SchimbaParola.js';
import CalendarActivitati from '../../ui/pages/CalendarActivitati.js';
const authenticate = (nextState, replace) => {
if (!Meteor.loggingIn() && !Meteor.userId()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname },
});
}
};
Meteor.startup(() => {
render(
<Router history={ browserHistory }>
<Route path="/" component={ App }>
<IndexRoute name="index" component={ Index } />
<Route name="activitati-oras" path="/activitati-:linkOras" component={ Activitati } />
<Route name="calendar-activitati" path="/calendar-activitati" component={ CalendarActivitati } onEnter={ authenticate } />
<Route name="activitatile-mele" path="/activitatile-mele" component={ ActivitatileMele } onEnter={ authenticate } />
<Route name="adauga-activitate" path="/adauga-activitate" component={ AdaugaActivitate } onEnter={ authenticate } />
<Route name="edit-activitate" path="/activitati/:_id/edit" component={ EditActivitate } onEnter={ authenticate } />
<Route name="detalii-activitate" path="/activitati/:_id" component={ DetaliiActivitate } />
<Route name="login" path="/login" component={ Login } />
<Route name="recover-password" path="/recover-password" component={ RecoverPassword } />
<Route name="reset-password" path="/reset-password/:token" component={ ResetPassword } />
<Route name="cont-nou" path="/cont-nou" component={ ContNou } />
<Route name="contul-meu" path="/contul-meu" component={ ContulMeu } onEnter={ authenticate } />
<Route name="schimba-parola" path="/schimba-parola" component={ SchimbaParola } onEnter={ authenticate } />
<Route path="*" component={ NotFound } />
</Route>
</Router>,
document.getElementById('react-root'),
);
});
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Row, Col, FormGroup, ControlLabel, FormControl, Button, Checkbox } from 'react-bootstrap';
import Datetime from 'react-datetime';
import modificaActivitate from '../../modules/modifica-activitate.js';
import SelectOrase from '../components/oras/Select';
import SelectSporturi from './sport/Select';
import Locatie from './activitate/Locatie';
export default class ModificaActivitate extends React.Component {
componentDidMount() {
modificaActivitate({component: this});
setTimeout(() => {
document.querySelector('[name="numeActivitate"]').focus();
}, 0);
}
constructor(props) {
super();
this.faraLimitaParticipanti = this.faraLimitaParticipanti.bind(this);
this.handleMapClick = this.handleMapClick.bind(this);
this.handleMarkerRightClick = this.handleMarkerRightClick.bind(this);
const {activitate} = props;
this.state = {
limitaParticipanti: false,
marker: [],
};
if (activitate) {
this.state.limitaParticipanti = activitate.limitaParticipanti;
if (activitate.locatieLat && activitate.locatieLng) {
this.state.marker = [{
position: {
lat: activitate.locatieLat,
lng: activitate.locatieLng,
},
defaultAnimation: 2,
key: Date.now()
}];
}
}
}
faraLimitaParticipanti() {
this.setState({
limitaParticipanti: !this.state.limitaParticipanti
});
};
handleMapClick(event) {
const nextMarker = [{
position: event.latLng,
defaultAnimation: 2,
key: Date.now(), // Add a key property for: http://fb.me/react-warning-keys
}];
this.setState({
marker: nextMarker,
});
};
handleMarkerRightClick(targetMarker) {
this.setState({
marker: [],
});
};
render() {
const {activitate} = this.props;
const hidden = this.state.limitaParticipanti ? 'hidden' : '';
let yesterday = Datetime.moment().subtract(1, 'day');
let validDate = function( current ){
return current.isAfter(yesterday);
};
return (<form
ref={ form => (this.editForm = form) }
onSubmit={ event => event.preventDefault() }
>
<Row className="show-grid">
<Col md={10}>
<FormGroup>
<ControlLabel>Nume activitate</ControlLabel>
<FormControl
type="text"
name="numeActivitate"
defaultValue={ activitate && activitate.numeActivitate }
placeholder="Alege un nume pentru activitatea ta"
/>
</FormGroup>
</Col>
</Row>
<Row className="show-grid">
<Col md={6}>
<FormGroup>
<ControlLabel>Oras</ControlLabel>
<SelectOrase selected={ activitate && activitate.idOras } />
</FormGroup>
</Col>
</Row>
<Row className="show-grid">
<Col md={6}>
<FormGroup>
<ControlLabel>Alege sportul</ControlLabel>
<SelectSporturi selected={ activitate && activitate.idSport } />
</FormGroup>
</Col>
</Row>
<Row className="show-grid">
<Col md={12}>
<FormGroup>
<ControlLabel>Numar maxim de participanti</ControlLabel>
<FormControl className={`numar-participanti ${hidden}`} type="number" min="0" name="nrmaxParticipanti"
defaultValue={ activitate && activitate.nrmaxParticipanti }/>
<Checkbox checked={ this.state.limitaParticipanti } value="1" name="limitaParticipanti" onChange={ this.faraLimitaParticipanti }>
Fara limita de participanti
</Checkbox>
</FormGroup>
</Col>
</Row>
<Row className="show-grid">
<Col md={2}>
<FormGroup>
<ControlLabel>Data si ora</ControlLabel>
<Datetime isValidDate={ validDate } defaultValue={ activitate && activitate.dataActivitate } inputProps={{ name: 'dataActivitate' }} />
</FormGroup>
</Col>
</Row>
<Row className="show-grid">
<Col md={6}>
<FormGroup>
<ControlLabel>Locatie</ControlLabel>
<Locatie
googleMapURL="https://maps.googleapis.com/maps/api/js?key=<KEY>"
loadingElement={
<div style={{height: `250px`}}>
<i className="fa fa-spin 2s infinite linear"></i>
</div>
}
containerElement={
<div style={{height: `250px`}}/>
}
mapElement={
<div style={{height: `250px`}}/>
}
onMapClick={this.handleMapClick}
onMarkerRightClick={this.handleMarkerRightClick}
marker={this.state.marker}
/>
</FormGroup>
</Col>
</Row>
<Row className="show-grid">
<Col md={6}>
<FormGroup>
<ControlLabel>Detalii activitate</ControlLabel>
<FormControl
componentClass="textarea"
name="descriereActivitate"
defaultValue={ activitate && activitate.descriereActivitate }
placeholder="Locul de intalnire..."
/>
</FormGroup>
</Col>
</Row>
<Button type="submit" bsStyle="success">
{ activitate && activitate._id ? 'Save Changes' : 'Adauga activitate' }
</Button>
</form>);
}
}
ModificaActivitate.propTypes = {
activitate: PropTypes.object,
};
<file_sep>import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import ParticipantiActivitati from './participanti_activitati';
import rateLimit from '../../modules/rate-limit.js';
export const adaugaParticipantActivitate = new ValidatedMethod({
name: 'participanti_activitati.upsert',
validate: new SimpleSchema({
_id: { type: String, optional: true },
idActivitate: { type: String },
idParticipant: { type: String },
data: { type: Date },
}).validator(),
run(participantActivitate) {
return ParticipantiActivitati.upsert({ idActivitate: participantActivitate.idActivitate, idParticipant: participantActivitate.idParticipant }, { $set: participantActivitate });
},
});
export const stergeParticipantActivitate = new ValidatedMethod({
name: 'participanti_activitati.remove',
validate: new SimpleSchema({
_id: { type: String },
}).validator(),
run({ _id }) {
ParticipantiActivitati.remove(_id);
},
});
rateLimit({
methods: [
adaugaParticipantActivitate,
stergeParticipantActivitate,
],
limit: 5,
timeRange: 1000,
});
<file_sep>.activitate {
.butoane-activitate {
button {
margin-left: 5px;
}
}
@media screen and (min-width: 768px) {
.coloane {
display: flex;
}
.detalii-container {
padding-right: 0px !important;
display: flex;
}
.chat-container {
padding-left: 0px !important;
padding-right: 0px !important;
display: flex;
}
.participanti-container {
padding-left: 0px !important;
display: flex;
}
.detalii {
box-shadow: 4px 1px 5px -1px darken(#3D6599, 5%);
position: relative;
z-index: 2;
flex: 1;
}
.chat {
box-shadow: 4px 1px 5px -1px darken(#3D6599, 5%);
position: relative;
z-index: 1;
flex: 1;
}
.participanti {
flex: 1;
}
}
.detalii {
background-color: #3D6599;
color: #fff;
font-size: 15px;
font-weight: 300;
.data-activitate {
padding: 20px 10px;
}
.nume-sport {
padding: 10px 10px;
}
.locuri-participanti {
padding: 20px 10px;
}
.descriere {
padding: 20px 10px;
background-color: darken(#3D6599, 5%);
}
.titlu-sectiune {
font-weight: 500;
}
}
.chat {
background-color: lighten(#3D6599, 10%);
padding: 15px;
.mesaje {
color: #fff;
overflow: auto;
margin-bottom: 110px;
height: 440px;
.mesaj {
border-radius: 3px;
padding: 5px;
margin-bottom: 5px;
background-color: lighten(#3D6599, 20%);
.data {
font-size: 12px;
}
}
}
.adaugare-mesaj {
position: absolute;
bottom: 10px;
left: 10px;
right: 10px;
}
#formControlsTextarea {
margin-bottom: 10px;
}
}
.participanti {
background-color: lighten(#3D6599, 15%);
padding: 15px;
.lista-participanti {
height: 550px;
overflow: auto;
.data {
font-size: 12px;
}
}
}
.titlu-main {
font-size: 22px;
color: #fff;
margin-bottom: 10px;
}
.numar-participanti {
width: 80px !important;
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import ParticipantiActivitati from '../../../api/participanti_activitati/participanti_activitati';
import container from '../../../modules/container';
const NrMaxParticipanti = props =>(
<div className="locuri-participanti">
<div className="nr-max-participanti">
{props.nrmaxParticipanti > 0 ? (
<span>{props.nrmaxParticipanti}</span>
) : (
'Fără limită de participanți'
)
}
<div className="titlu-sectiune">
Număr maxim de participanți
</div>
</div>
{props.nrmaxParticipanti > 0 ? (
<div className="locuri-ramase">
{props.nrparticipantiRamasi}
<div className="titlu-sectiune">
Locuri disponibile
</div>
</div>
) : '' }
</div>
);
NrMaxParticipanti.propTypes = {
nrmaxParticipanti: PropTypes.number,
idActivitate: PropTypes.string,
nrParticipanti: PropTypes.number,
nrparticipantiRamasi: PropTypes.number,
};
export default container((props, onData) => {
const nrmaxParticipanti = props.nrmaxParticipanti;
const idActivitate = props.idActivitate;
const subscription = Meteor.subscribe('participanti_activitati.view', idActivitate);
if (subscription.ready()) {
let nrParticipanti = ParticipantiActivitati.find({idActivitate: idActivitate}).count();
let nrparticipantiRamasi = nrmaxParticipanti - nrParticipanti;
onData(null, { idActivitate, nrmaxParticipanti, nrParticipanti, nrparticipantiRamasi });
}
}, NrMaxParticipanti);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Alert, Row, Col } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import CardActivitate from './activitate/Card';
import Activitati from '../../api/activitati/activitati';
import Orase from '../../api/orase/orase';
import container from '../../modules/container';
const ListaActivitati = ({ activitati }) => (
activitati.length > 0 ?
<div>
<Row className="show-grid">
{activitati.map(({ _id, numeActivitate, descriereActivitate, nrmaxParticipanti, idSport, dataActivitate, anulata}) => (
<CardActivitate
key={ _id }
idActivitate={ _id }
numeActivitate={ numeActivitate }
descriereActivitate={ descriereActivitate }
nrmaxParticipanti={ nrmaxParticipanti }
idSport={ idSport }
dataActivitate={ dataActivitate }
anulata={ anulata }
/>
))}
</Row>
</div> :
<Alert bsStyle="warning">Nu sunt activitati adaugate.</Alert>
);
ListaActivitati.propTypes = {
activitati: PropTypes.array,
};
export default container((props, onData) => {
const linkOras = props.linkOras;
const sporturiSelectate = props.sporturiSelectate;
let data = new Date();
const subscriptionOras = Meteor.subscribe('orase.list');
if (subscriptionOras.ready()) {
const oras = Orase.findOne({ link: linkOras });
const idOras = oras._id;
const subscription = Meteor.subscribe('activitati.list');
if (subscription.ready()) {
if (sporturiSelectate.length > 0) {
const activitati = Activitati.find({idOras: idOras, anulata: {$ne: true}, idSport: {$in: sporturiSelectate}}, {sort: {dataActivitate: 1}}).fetch();
onData(null, { activitati });
} else {
const activitati = Activitati.find({idOras: idOras , anulata: {$ne: true}, dataActivitate: {$gte: data}}, {sort: {dataActivitate: 1}}).fetch();
onData(null, { activitati });
}
}
}
}, ListaActivitati);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import Sporturi from '../../../api/sporturi/sporturi';
import container from '../../../modules/container';
const NumeSport = ({ sport }) => (
sport ? <span>
{ sport.nume }
</span> : ''
);
NumeSport.propTypes = {
sport: PropTypes.object,
};
export default container((props, onData) => {
const subscription = Meteor.subscribe('sporturi.list');
if (subscription.ready()) {
const sport = Sporturi.findOne({_id: props.id});
onData(null, { sport });
}
}, NumeSport);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { FormGroup, Checkbox } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import Sporturi from '../../../api/sporturi/sporturi';
import container from '../../../modules/container';
const CheckboxesSporturi = ({ sporturi, sporturiSelectate }) => (
sporturi.length > 0 ? <FormGroup>
{sporturi.map(({ _id, nume }) => (
<Checkbox name="sporturi[]" value={ _id } key={ _id } defaultChecked={ typeof sporturiSelectate !== 'undefined' && sporturiSelectate.indexOf(_id) >= 0 } >
{nume}
</Checkbox>
))}
</FormGroup> : ''
);
CheckboxesSporturi.propTypes = {
sporturi: PropTypes.array,
sporturiSelectate: PropTypes.array,
};
export default container((props, onData) => {
const sporturiSelectate = props.sporturiSelectate;
const subscription = Meteor.subscribe('sporturi.list');
if (subscription.ready()) {
const sporturi = Sporturi.find().fetch();
onData(null, { sporturi, sporturiSelectate });
}
}, CheckboxesSporturi);
<file_sep>import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
const USER_FIELDS = {
profile: 1
};
Meteor.publish('detaliiUser', function (userId) {
check(userId, String);
return Meteor.users.find(userId, { fields: USER_FIELDS });
});
<file_sep>import React from 'react';
import { Meteor } from 'meteor/meteor';
import PropTypes from 'prop-types';
import Mesaje from '../../../api/mesaje/mesaje';
import { adaugaMesaj } from '../../../api/mesaje/methods';
import container from '../../../modules/container';
import NumeUser from '../user/Nume';
import Datetime from 'react-datetime';
import { FormControl, FormGroup, Button } from 'react-bootstrap';
const Chat = props =>(
<div>
<div className="mesaje">
{props.mesaje.map(({ _id, mesaj, data, idUser }) => (
<div className="mesaj" key={ _id }>
<div className="text-right"><strong>{ mesaj }</strong></div>
<div className="clearfix">
<div className="pull-left user"><NumeUser idUser={ idUser } /></div>
<div className="pull-right data">{ Datetime.moment(data).format("DD-MM-YYYY hh-mm") }</div>
</div>
</div>
))}
</div>
{Meteor.userId() ?
<div className="adaugare-mesaj">
<FormGroup controlId="formControlsTextarea">
<FormControl name="mesaj" componentClass="textarea" placeholder="Introduce mesaj" />
</FormGroup>
<Button onClick={() => {
adauga(props)
}} bsStyle="success" className="pull-right">Send</Button>
</div>
: ''
}
</div>
);
Chat.propTypes = {
idActivitate: PropTypes.string,
mesaje: PropTypes.array,
};
const adauga = (props) => {
//add mesaj - insert
const mesajObj = {
mesaj: document.querySelector('[name="mesaj"]').value.trim(),
idActivitate: props.idActivitate,
idUser: Meteor.userId(),
data: new Date(),
};
if (mesajObj.mesaj !== '') {
adaugaMesaj.call(mesajObj, (error, response) => {
if (error) {
Bert.alert('Eroare adaugare mesaj', 'danger');
} else {
document.querySelector('[name="mesaj"]').value = '';
}
});
}
};
export default container((props, onData) => {
const idActivitate = props.idActivitate;
const subscription = Meteor.subscribe('mesaje.list');
if (subscription.ready()) {
const mesaje = Mesaje.find({idActivitate: idActivitate}).fetch();
onData(null, { idActivitate, mesaje });
}
}, Chat);
<file_sep>import React from 'react';
import { Link } from 'react-router';
import { Row, Col, Button, OverlayTrigger, Popover } from 'react-bootstrap';
import CheckboxesSporturi from '../components/sport/Checkboxes';
import ListaActivitati from '../components/ListaActivitati';
export default class Activitati extends React.Component {
constructor(props) {
super();
this.state = {
linkOras: props.params.linkOras,
sporturiSelectate: [],
}
}
getChecked() {
let sporturiSelectate = [];
let checkboxes = document.querySelectorAll('[name="sporturi[]"]');
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked === true) {
sporturiSelectate.push(checkboxes[i].value.trim());
}
}
this.setState({
sporturiSelectate: sporturiSelectate
});
}
render() {
const popoverClickRootClose = (
<Popover id="popover-trigger-click-root-close" title="Alege sport">
{ this.state.sporturiSelectate.length > 0 ? (
<CheckboxesSporturi sporturiSelectate = {this.state.sporturiSelectate}/>
) : (
<CheckboxesSporturi />
)}
<Button onClick={() => { this.getChecked() }} bsStyle="primary">Filtreaza</Button>
</Popover>
);
return (
<div>
<Row>
<Col xs={ 12 }>
<div className="page-header clearfix">
<h4 className="pull-left">Activitati</h4>
<OverlayTrigger trigger="click" rootClose placement="bottom" overlay={popoverClickRootClose}>
<Button className="butonFiltrare">Filtrare</Button>
</OverlayTrigger>
<Link to="/adauga-activitate">
<Button
bsStyle="success"
className="pull-right"
>Adauga o activitate noua</Button>
</Link>
</div>
</Col>
</Row>
<ListaActivitati linkOras={ this.state.linkOras } sporturiSelectate={ this.state.sporturiSelectate }/>
</div>
)
};
}
<file_sep>import '../../api/activitati/methods.js';
import '../../api/activitati/server/publications.js';
import '../../api/participanti_activitati/methods.js';
import '../../api/participanti_activitati/server/publications.js';
import '../../api/mesaje/methods.js';
import '../../api/mesaje/server/publications.js';
import '../../api/orase/server/publications.js';
import '../../api/sporturi/server/publications.js';
import '../../api/users/server/publications.js';
<file_sep>import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import Sporturi from './Sporturi';
import rateLimit from '../../modules/rate-limit.js';
export const adaugaSport = new ValidatedMethod({
name: 'sporturi.upsert',
validate: new SimpleSchema({
nume: { type: String, optional: true },
link: { type: String, optional: true },
img: { type: String, optional: true },
}).validator(),
run(sporturi) {
return Sporturi.upsert({ nume: sporturi.nume }, { $set: sporturi });
},
});
/*export const updateOras = new ValidatedMethod({
name: 'oras.update',
validate: new SimpleSchema({
_id: { type: String },
}).validator(),
run({ _id }) {
Oras.update(_id);
},
});*/
rateLimit({
methods: [
adaugaSport,
//updateOras,
],
limit: 5,
timeRange: 1000,
});
/**
* Created by ionut on 13.05.2017.
*/
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Row, Col, FormGroup } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import { Bert } from 'meteor/themeteorchef:bert';
import Activitati from '../../api/activitati/activitati';
import NotFound from './NotFound';
import container from '../../modules/container';
import Locatie from '../components/activitate/Locatie';
import Datetime from 'react-datetime';
import NumeSport from '../components/sport/Nume';
import ListaParticipanti from '../components/activitate/ListaParticipanti';
import ButonParticipActivitate from '../components/activitate/ButonParticipActivitate';
import ButonEditareActivitate from '../components/activitate/ButonEditareActivitate';
import ButonStergeActivitate from '../components/activitate/ButonStergeActivitate';
import NrMaxParticipanti from '../components/activitate/NrMaxParticipanti';
import Chat from '../components/activitate/Chat';
const DetaliiActivitate = ({ activitate }) => {
if (activitate) {
if (activitate.locatieLat && activitate.locatieLng) {
this.state.marker = [{
position: {
lat: activitate.locatieLat,
lng: activitate.locatieLng,
},
defaultAnimation: 2,
key: Date.now()
}];
}
}
return activitate ? (
<div className="activitate">
<Row>
<Col xs={ 12 }>
<div className="page-header clearfix">
<h4 className="pull-left">{ activitate.numeActivitate }</h4>
<div className="butoane-activitate pull-right">
<ButonParticipActivitate className="pull-left" dataActivitate={ activitate.dataActivitate } anulata={activitate.anulata} idActivitate={activitate._id} nrmaxParticipanti={activitate.nrmaxParticipanti}/>
<ButonEditareActivitate className="pull-left" idActivitate={activitate._id} anulata={activitate.anulata} idadminActivitate={activitate.idadminActivitate}/>
<ButonStergeActivitate className="pull-left" idActivitate={activitate._id} anulata={activitate.anulata} idadminActivitate={activitate.idadminActivitate}/>
</div>
</div>
</Col>
</Row>
<Row className="coloane">
<Col xs={12} md={5} className="detalii-container">
<div className="detalii">
<Locatie
googleMapURL="https://maps.googleapis.com/maps/api/js?key=<KEY>"
loadingElement={
<div style={{height: `250px`}}>
<i className="fa fa-spin 2s infinite linear"></i>
</div>
}
containerElement={
<div style={{height: `250px`}}/>
}
mapElement={
<div style={{height: `250px`}}/>
}
marker={this.state.marker}
centerToMarker={true}
/>
<div className="data-activitate">
{ Datetime.moment(activitate.dataActivitate).format("DD-MM-YYYY hh-mm") }
<div className="titlu-sectiune">
Dată activitate
</div>
</div>
<div className="nume-sport">
<NumeSport id={activitate.idSport} />
<div className="titlu-sectiune">
Sport
</div>
</div>
<NrMaxParticipanti idActivitate={activitate._id} nrmaxParticipanti={activitate.nrmaxParticipanti}/>
<div className="descriere">
{ activitate.descriereActivitate }
</div>
</div>
</Col>
<Col xs={12} md={4} className="chat-container">
<div className="chat clearfix">
<div className="titlu-main">Chat</div>
<Chat idActivitate={activitate._id} />
</div>
</Col>
<Col xs={12} md={3} className="participanti-container">
<div className="participanti clearfix">
<div className="titlu-main">Participanți</div>
<ListaParticipanti idActivitate={activitate._id} />
</div>
</Col>
</Row>
</div>
) : <NotFound />;
};
DetaliiActivitate.propTypes = {
activitate: PropTypes.object,
};
export default container((props, onData) => {
const idActivitate = props.params._id;
const subscription = Meteor.subscribe('activitati.view', idActivitate);
if (subscription.ready()) {
const activitate = Activitati.findOne(idActivitate);
onData(null, { activitate });
}
const {activitate} = props;
this.state = {
marker: [],
};
if (activitate) {
if (activitate.locatieLat && activitate.locatieLng) {
this.state.marker = [{
position: {
lat: activitate.locatieLat,
lng: activitate.locatieLng,
},
defaultAnimation: 2,
key: Date.now()
}];
}
}
}, DetaliiActivitate);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Popover, Button, OverlayTrigger } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import container from '../../../modules/container';
import VarstaUser from '../../components/user/Varsta';
import OrasUser from '../../components/oras/Nume';
const ParticipantActivitate = ({ participant }) => (
<OverlayTrigger trigger={['hover', 'focus']} placement="bottom" overlay={popoverBottom(participant)}>
<strong>{participant.profile.name.first} {participant.profile.name.last}</strong>
</OverlayTrigger>
);
const popoverBottom = (participant) => (
<Popover id="popover-positioned-bottom" title="Detalii cont">
Oras: <OrasUser idOras={participant.profile.city} /> <br/><br/>
Varsta: <VarstaUser dataNastere={participant.profile.birthday} />
</Popover>
);
ParticipantActivitate.propTypes = {
participant: PropTypes.object,
};
export default container((props, onData) => {
const idParticipant = props.idParticipant;
const subscription = Meteor.subscribe('detaliiUser', idParticipant);
if (subscription.ready()) {
let participant = Meteor.users.findOne({ _id: idParticipant });
onData(null, { participant });
}
}, ParticipantActivitate);
<file_sep>import React from 'react';
import { Link } from 'react-router';
import { Row, Col, FormGroup, ControlLabel, FormControl, Button } from 'react-bootstrap';
import Datetime from 'react-datetime';
import handleSignup from '../../modules/signup';
import SelectOrase from '../components/oras/Select';
export default class ContNou extends React.Component {
componentDidMount() {
handleSignup({ component: this });
}
handleSubmit(event) {
event.preventDefault();
}
render() {
let data = Datetime.moment().subtract(15, 'years');
let validDate = function( current ){
return current.isBefore(data);
};
return (
<div className="Signup">
<Row>
<Col xs={ 12 } sm={ 6 } md={ 4 }>
<h4 className="page-header">Cont nou</h4>
<form
ref={ form => (this.signupForm = form) }
onSubmit={ this.handleSubmit }
>
<Row>
<Col xs={ 6 } sm={ 6 }>
<FormGroup>
<ControlLabel>Prenume</ControlLabel>
<FormControl
type="text"
ref="firstName"
name="firstName"
placeholder="<NAME>"
/>
</FormGroup>
</Col>
<Col xs={ 6 } sm={ 6 }>
<FormGroup>
<ControlLabel>Nume</ControlLabel>
<FormControl
type="text"
ref="lastName"
name="lastName"
placeholder="<NAME>"
/>
</FormGroup>
</Col>
</Row>
<FormGroup>
<ControlLabel>Oras</ControlLabel>
<SelectOrase />
</FormGroup>
<FormGroup>
<ControlLabel>Data nastere</ControlLabel>
<Datetime dateFormat="DD-MM-YYYY" isValidDate={ validDate } defaultValue={Datetime.moment().subtract(15, 'years')} timeFormat={false} inputProps={{ name: 'dataNastere' }} />
</FormGroup>
<FormGroup>
<ControlLabel>Adresa email</ControlLabel>
<FormControl
type="text"
ref="emailAddress"
name="emailAddress"
placeholder="Email Address"
/>
</FormGroup>
<FormGroup>
<ControlLabel>Parola</ControlLabel>
<FormControl
type="password"
ref="password"
name="password"
placeholder="<PASSWORD>"
/>
</FormGroup>
<Button type="submit" bsStyle="success">Creeaza cont</Button>
</form>
<p>Ai deja cont ? <Link to="/login">Log In</Link>.</p>
</Col>
</Row>
</div>
);
}
}
<file_sep># SportPlusPlus
I used Meteor and ReactJS for this project.
![Alt text](https://github.com/ionutciochinaru/SportPlusPlus/blob/master/poza1.jpg?raw=true "Optional Title")
![Alt text](https://github.com/ionutciochinaru/SportPlusPlus/blob/master/poza2.jpg?raw=true "Optional Title")
![Alt text](https://github.com/ionutciochinaru/SportPlusPlus/blob/master/poza3.jpg?raw=true "Optional Title")
<file_sep>import { Mongo } from 'meteor/mongo';
import SimpleSchema from 'simpl-schema';
const Sporturi = new Mongo.Collection('sporturi');
export default Sporturi;
Sporturi.allow({
insert: () => false,
update: () => false,
remove: () => false,
});
Sporturi.deny({
insert: () => true,
update: () => true,
remove: () => true,
});
Sporturi.schema = new SimpleSchema({
nume: {
type: String,
label: 'Numele sportului.',
},
link: {
type: String,
label: 'Linkul sportului.',
},
img: {
type: String,
label: 'Imaginea sportului',
},
});
Sporturi.attachSchema(Sporturi.schema);
if (Sporturi.find().count() === 0) {
const sporturi = [
{
nume: 'Alergare',
link: 'alergare',
img: 'alergare.gif'
},
{
nume: 'Ciclism',
link: 'ciclism',
img: 'ciclism.gif'
},
{
nume: 'Fotbal',
link: 'fotbal',
img: 'fotbal.gif'
},
{
nume: '<NAME>',
link: 'tenis-de-camp',
img: 'tenisdecamp.gif'
},
{
nume: 'Inot',
link: 'inot',
img: 'inot.gif'
},
{
nume: 'Baschet',
link: 'baschet',
img: 'baschet.gif'
}
];
sporturi.forEach(({nume, link, img}) => {
Sporturi.insert({nume, link, img});
});
}
<file_sep>import { BrowserPolicy } from 'meteor/browser-policy-common';
// e.g., BrowserPolicy.content.allowOriginForAll( 's3.amazonaws.com' );
BrowserPolicy.content.allowFontOrigin("data:");
BrowserPolicy.content.allowOriginForAll('*.googleapis.com');
BrowserPolicy.content.allowOriginForAll('*.gstatic.com');
BrowserPolicy.content.allowEval('https://ajax.googleapis.com');
<file_sep>import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import Mesaje from './mesaje';
import rateLimit from '../../modules/rate-limit.js';
export const adaugaMesaj = new ValidatedMethod({
name: 'mesaje.upsert',
validate: new SimpleSchema({
_id: { type: String, optional: true },
mesaj: { type: String },
idActivitate: { type: String },
idUser: { type: String },
data: { type: Date },
}).validator(),
run(mesaj) {
return Mesaje.upsert({ _id: mesaj._id }, { $set: mesaj });
},
});
rateLimit({
methods: [
adaugaMesaj,
],
limit: 50,
timeRange: 1000,
});
<file_sep>.detaliiActivitati_stanga{
background-color: darkslateblue;
}
<file_sep>import React from 'react';
import { Link } from 'react-router';
import PropTypes from 'prop-types';
import { Row, Col, Alert, FormGroup, ControlLabel, FormControl, Button, Panel, ListGroup, ListGroupItem } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import MeniuContulMeu from '../components/MeniuContulMeu.js';
import schimbaParola from '../../modules/schimba-parola';
export default class SchimbaParola extends React.Component {
componentDidMount() {
schimbaParola({ component: this });
}
handleSubmit(event) {
event.preventDefault();
}
render() {
return (
<div className="SchimbaProla">
<Row>
<Col xs={ 12 } sm={ 6 } md={ 4 }>
<MeniuContulMeu />
</Col>
<Col xs={ 12 } sm={ 6 } md={ 8 }>
<h4 className="page-header">Schimba parola</h4>
<Alert bsStyle="info">
Introduceti noua parola a contului.
</Alert>
<form
ref={ form => (this.formSchimbaParola = form) }
className="reset-password"
onSubmit={ this.handleSubmit }
>
<FormGroup>
<ControlLabel>Vechea parola</ControlLabel>
<FormControl
type="password"
ref="oldPassword"
name="oldPassword"
placeholder="<PASSWORD>"
/>
</FormGroup>
<FormGroup>
<ControlLabel>Noua parola</ControlLabel>
<FormControl
type="password"
ref="newPassword"
name="newPassword"
placeholder="<PASSWORD>"
/>
</FormGroup>
<FormGroup>
<ControlLabel>Retipareste parola</ControlLabel>
<FormControl
type="password"
ref="repeatNewPassword"
name="repeatNewPassword"
placeholder="<PASSWORD>"
/>
</FormGroup>
<Button type="submit" bsStyle="success">Schimba parola</Button>
</form>
</Col>
</Row>
</div>
);
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import { Row, Col } from 'react-bootstrap';
import Orase from '../../../api/orase/orase';
import CardOras from './Card';
import container from '../../../modules/container';
const ListaOrase = ({ orase }) => (
<Row className="show-grid">
<Col xs={12}>
<div className="page-header clearfix">
<h4 className="pull-left">Activități din alte orașe </h4>
</div>
<Row>
{orase.map(({ _id, nume, link }) => (
<CardOras
key={ _id }
idOras={ _id }
nume={ nume }
link={ link }
/>
))}
</Row>
</Col>
</Row>
);
ListaOrase.propTypes = {
orase: PropTypes.array,
};
export default container((props, onData) => {
const subscription = Meteor.subscribe('orase.list');
if (subscription.ready()) {
const orase = Orase.find({}, {sort: {nume: 1}}).fetch();
onData(null, { orase });
}
}, ListaOrase);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import container from '../../../modules/container';
const DataNastere = ({ user }) => ( user ?
<span>
<strong>{user.profile.birthday}</strong>
</span> : ''
);
DataNastere.propTypes = {
user: PropTypes.object,
};
export default container((props, onData) => {
const idUser = props.idUser;
const subscription = Meteor.subscribe('detaliiUser', idUser);
if (subscription.ready()) {
let user = Meteor.users.findOne({ _id: idUser });
onData(null, { user });
}
}, DataNastere);
| bd57041f2c3bdc7461508cd4afb26fed9db64bb0 | [
"Markdown",
"SCSS",
"JavaScript"
] | 48 | Markdown | ionutciochinaru/SportPlusPlus | 97666a23eae924259172af2badc737bb94da5df0 | 5ca872fab717bef49898d757c2675f4dafc3bc44 |
refs/heads/master | <repo_name>rvillars/bookapp-boot<file_sep>/bookapp-ui/src/js/books/books.resource.js
'use strict';
export default function (module) {
module.factory('Book', bookResource);
function bookResource ($resource) {
'ngInject';
return $resource('api/books/:bookId', {bookId: '@id'}, {
'query': {
url: 'api/books/:bookId?projection=inlineAuthor',
transformResponse: function (data, headers) {
try {
var embedded = JSON.parse(data)._embedded;
return embedded[Object.keys(embedded)[0]];
} catch(e) {
return null;
}
},
isArray: true
},
'update': {method: 'PUT'}
});
}
}
<file_sep>/settings.gradle
include 'bookapp-ui', 'bookapp-web';<file_sep>/bookapp-ui/src/js/books/books.controller.js
'use strict';
import utils from '../app.utils';
export default class BookController {
/*@ngInject;*/
constructor($http, Book, Author) {
this.$http = $http;
this.Book = Book;
this.Author = Author;
// properties
this.books = this.Book.query();
this.authors = this.Author.query();
this.currentBook = new this.Book();
this.currentBook.releasedate = new Date();
this.showId = false;
}
cancel() {
this.currentBook = new this.Book();
this.currentBook.releasedate = new Date();
};
save() {
var isNew = this.currentBook.id == null;
if (isNew) {
this.$http.get(this.currentBook.author).then(response => {
let savedBook = this.Book.save(this.currentBook);
savedBook.$promise.then(() => {
savedBook.author = response.data;
this.books.push(savedBook);
this.cancel();
});
});
} else {
this.$http.get(this.currentBook.author).then(response => {
let updatedBook = this.Book.update(this.currentBook);
updatedBook.$promise.then(() => {
updatedBook.author = response.data;
utils.replaceById(this.books, updatedBook);
this.cancel();
});
});
}
};
edit(book) {
this.currentBook = angular.copy(book);
this.currentBook.releasedate = new Date(book.releasedate);
this.currentBook.author = utils.filterById(this.authors, book.author.id)._links.self.href;
};
remove(index, id) {
this.books.splice(index, 1);
this.Book.remove({bookId: id});
};
openDatePicker($event) {
$event.preventDefault();
$event.stopPropagation();
this.opened = true;
};
}<file_sep>/bookapp-web/docker/Vagrantfile
Vagrant.configure("2") do |config|
config.vm.box = "chef/ubuntu-14.04"
config.vm.synced_folder "../build/libs", "/target", create: true
config.vm.synced_folder "log", "/log", create: true
config.vm.network "forwarded_port", guest: 8080, host: 8080
config.vm.provision "docker" do |d|
d.build_image "--tag=bookapp /vagrant"
d.run "bookapp",
args: "-p 8080:8080 -v /target:/target -v /log:/log"
end
end<file_sep>/bookapp-web/src/main/groovy/Application.groovy
package ch.bfh.swos.bookapp
import org.hibernate.annotations.GenericGenerator
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.builder.SpringApplicationBuilder
import org.springframework.boot.context.web.SpringBootServletInitializer
import org.springframework.context.annotation.Configuration
import org.springframework.data.repository.PagingAndSortingRepository
import org.springframework.data.rest.core.annotation.RepositoryRestResource
import org.springframework.data.rest.core.config.Projection
import org.springframework.data.rest.core.config.RepositoryRestConfiguration
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration
import org.springframework.format.annotation.DateTimeFormat
import javax.persistence.*
@EnableAutoConfiguration
class Application extends RepositoryRestMvcConfiguration {
@Override
protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setBasePath("/api")
config.exposeIdsFor(Book.class)
config.exposeIdsFor(Author.class)
config.setReturnBodyOnCreate(true)
config.setReturnBodyOnUpdate(true)
}
static void main(String[] args) {
SpringApplication.run Application, args
}
}
@Configuration
public class WebConfig extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
application.sources(Application.class)
return super.configure(application)
}
}
@RepositoryRestResource(path = "books") interface BookRepository extends PagingAndSortingRepository<Book, String> {}
@RepositoryRestResource(path = "authors") interface AuthorRepository extends PagingAndSortingRepository<Author, String> {}
@Projection(name = "inlineAuthor", types = Book.class) interface InlineAuthor {
String getId();
String getTitle();
Date getReleasedate();
Author getAuthor();
}
@Entity
class Book {
@Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid") String id
String title
@DateTimeFormat(iso=DateTimeFormat.ISO.DATE) Date releasedate
@ManyToOne @JoinColumn Author author
}
@Entity
class Author {
@Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid") String id
String firstname
String lastname
}<file_sep>/README.md
# Bookapp Spring Boot [![Build Status](https://travis-ci.org/rvillars/bookapp-boot.svg?branch=master)](https://travis-ci.org/rvillars/bookapp-boot)
<file_sep>/bookapp-ui/src/js/authors/authors.config.js
'use strict';
import template from './authors.tpl.html';
import controller from './authors.controller'
export default function config($stateProvider) {
'ngInject';
$stateProvider.state('authors', {
url: '/authors',
template: template,
controller: controller,
controllerAs: 'authorCtrl'
});
}<file_sep>/bookapp-ui/build.gradle
buildscript {
repositories {
mavenCentral()
jcenter()
}
}
plugins {
id 'com.moowork.node' version '0.9'
}
apply plugin: 'java'
jar.into('META-INF/resources') {
from('output')
}
node {
version = '0.12.2'
download = true
workDir = file("${project.buildDir}/nodejs")
}
npm_run_build.dependsOn npmInstall
build.dependsOn npm_run_build
check.dependsOn npm_run_build
<file_sep>/bookapp-ui/src/js/app.module.js
'use strict';
import 'bootstrap/dist/css/bootstrap.css';
import '../assets/books.png';
import angular from 'angular';
import ngResource from 'angular-resource';
import uiRouter from 'angular-ui-router';
import uiBootstrap from 'angular-ui-bootstrap';
import config from './app.config';
import bookConfig from './books/books.config'
import authorConfig from './authors/authors.config';
import bookResource from './books/books.resource';
import authorResource from './authors/authors.resource';
const bookapp = angular.module('bookapp', [
ngResource,
uiRouter,
uiBootstrap
]);
bookResource(bookapp);
authorResource(bookapp);
bookapp.config(config);
bookapp.config(bookConfig);
bookapp.config(authorConfig);<file_sep>/bookapp-ui/webpack.config.js
'use strict';
var webpack = require("webpack");
var HtmlWebpackPlugin = require('html-webpack-plugin-extra-files');
module.exports = {
entry: "./src/js/app.module.js",
output: {
path: '../bookapp-web/src/main/resources/static',
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.css$/,
loaders: [
'style',
'css'
]
},
{
test: /\.js$/,
exclude: /node_modules/,
loaders: [
'ng-annotate-loader',
'babel?presets[]=es2015'
]
},
{
test: /\.(woff2|woff|ttf|eot|svg)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loaders: [
'url-loader'
]
}, {
test: /\.(jpe?g|png|gif)$/i,
loaders: [
'url-loader?limit=10000'
]
},
{
test: /\.tpl\.html$/,
loaders: [
'html-loader?attrs[]=img:src&attrs[]=img:data-src'
]
}
]
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.tpl.html',
inject: 'body',
extraFiles: 'books.png'
})
],
devtool: 'cheap-source-map',
devServer: {
contentBase: '../bookapp-web/src/main/resources/static',
info: true,
hot: false,
inline: true,
port: 8081,
proxy: {
"*": "http://localhost:8080"
}
}
};<file_sep>/bookapp-ui/src/js/app.utils.js
'use strict';
var utils = {
filterById(array, id) {
return array.filter(object => {
return object.id == id;
})[0];
},
replaceById(array, replacement) {
array[array.indexOf(this.filterById(array,replacement.id))]=replacement;
}
};
export default utils; | d94e21d30cd3e27496c7d634fc37ee0e4ed2bd56 | [
"Markdown",
"Groovy",
"Ruby",
"Gradle",
"JavaScript"
] | 11 | Markdown | rvillars/bookapp-boot | 2ebb42bfdab1e375b5ca65e5bc6e9d70d5cb8922 | 723d6fe19ac11380d8e7cf1d86cc2e2b7fb7b13b |
refs/heads/master | <repo_name>renzhiyi/1704B-react-phone<file_sep>/README.md
# 1704B-react-phone | e037b44f3a42ea756ced806dfd1c79d976c477a3 | [
"Markdown"
] | 1 | Markdown | renzhiyi/1704B-react-phone | 52cd0fdb840224c9a2baf05d16afdeae378ee29a | c7a699e5c2a206630b6be24a4ba8fa3464dc3262 |
refs/heads/master | <file_sep># hello-world
First repository
Trying to master the art of coding
| aac3e543b8de72aea011f17e9b5a8e13c81d8643 | [
"Markdown"
] | 1 | Markdown | apurvashenoy/hello-world | a2db098661d9bf98ac24fa41190ac43be1de0087 | 73e013258910c9fd05d0a08d69001800cef6bb39 |
refs/heads/master | <file_sep>/**
* Created by student on 7.1.2016.
*/
$(document).ready(function(){
var canvasX, canvasY;
var pocPoliSirka = 10;
var pocPoliVyska = 10;
var velikostPole = 50;
var sirkaLinky = 1;
var arrayOfEllements = [];
var hrac = 0;
initArray(arrayOfEllements,pocPoliSirka, pocPoliVyska);
writeArray(arrayOfEllements, pocPoliSirka, pocPoliVyska);
vykresliPole(pocPoliSirka, pocPoliVyska, velikostPole)
$(canvas).click(function(event){
var pos;
pos = getMousePos(this, event);
canvasX = pos.x;
canvasY = pos.y;
var cells = getCellCoords(canvasX, canvasY, sirkaLinky, velikostPole);
var stred = getMiddleOfCell(cells.x, cells.y, velikostPole);
hrac = changePlayer(hrac);
if(arrayOfEllements[cells.x][cells.y] ==1 ){
alert(arrayOfEllements[cells.x][cells.y]);
}else{
arrayOfEllements[cells.x][cells.y] = 1;
}
});
});
/**
* funkce pro zmenu hrace
*
* @param hrac
* @returns {Number}
*/
function changePlayer(hrac){
hrac += 1;
hrac = hrac%2;
return hrac;
}
/**
* vykresleni pole
* @param arrayOfEllements
* @param pocPoliSirka
* @param pocPoliVyska
*/
function writeArray(arrayOfEllements, pocPoliSirka, pocPoliVyska){
var i,j;
for(i = 0; i < pocPoliSirka; i+=1){
for(j = 0; j < pocPoliVyska; j+=1){
console.log(i, arrayOfEllements[i][j]);
}
}
}
/**
* vytvoření prazdneho pole
* pole slouzi k zaznamenani do ktere bunky v canvasu uz bylo kliknuto
* ochrana pred prekreslovani bunek
*
* @param arrayOfEllements
* @param pocPoliSirka
* @param pocPoliVyska
*/
function initArray(arrayOfEllements, pocPoliSirka, pocPoliVyska){
var i,j;
for(i = 0; i < pocPoliSirka; i+=1){
arrayOfEllements.push(new Array);
for(j = 0; j < pocPoliVyska; j+=1){
arrayOfEllements[i].push(0);
}
}
}
/**
* vrací string, ktery obsahuje jeden radek do zaznamu
*/
function saveClick(){
// var save = "Click " + click + "bunka[" + y +" / " + x +"]";
}
/**
* vrati objekt se stredem bunky
* @param cellX
* @param cellY
*/
function getMiddleOfCell(cellX, cellY, velikostPole){
return {
stredX : velikostPole*cellX - velikostPole/2,
stredY : velikostPole*cellY - velikostPole/2
}
}
/**
* funkce pro ziskani souradnic bunek
* @param canX
* @param canY
* @param lineWidth
* @param cellWH
* @returns {*[]}
*/
function getCellCoords(canX, canY, lineWidth, cellWH){
var x, y;
x = 1 + Math.floor(canX / (cellWH+lineWidth));
y = 1 + Math.floor(canY / (cellWH+lineWidth));
return {
x : x,
y : y
};
}
/**
* funkce pro zjisteni x a y souradnic po kliknuti na canvas
*/
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
/**
* vykresli pole
* @param x
* @param y
* @param velP
*/
function vykresliPole(x, y, velP) {
var c = $("canvas");
var ctx = c[0].getContext("2d");
var i, k;
//sirka
for (i = 0; i <= x; i++) {
ctx.moveTo(0,i*velP); //x, y
ctx.lineTo(x*velP, i*velP); // odkud, kam
ctx.stroke();
}
//vyska
for (k = 0; k <= y; k++) {
ctx.moveTo(k*velP,0); //x, y
ctx.lineTo(k*velP, y*velP); // odkud, kam
ctx.stroke();
}
} | bb43e0d6097fc48288f37aba4fd448bc4f2bd840 | [
"JavaScript"
] | 1 | JavaScript | varhany/piskvorky | 2d80c93cdb833a606492f058dbb131e093f9d072 | 685b95773fa5be858bc7fe22a2e5c2519489a383 |
refs/heads/master | <file_sep># zentosam
Python code to transfer heldesk tickets from Zendesk to Samanage.
## Requirements
* [Python 3](https://www.python.org/)
* [Requests](http://docs.python-requests.org/en/latest/)
<file_sep>#!/usr/bin/python3
"""Python code to transfer helpdesk tickets from Zendesk to Samanage.
Tickets created on Samanage from tickets in Zendesk will have the name
of the ticket, who requested it, the priority of the ticket,
the assignee and the description. Comments from Zendesk
are added as comments to Samanage (The author of the comments on Samanage
will be the account whose Samanage account credentials are used in this code)."""
import json
import math
import sys
import time
import requests
class Samanage(object):
"""Class for Samanage API.
Samanage uses HTTP Digest for authentication
which takes username and password."""
def __init__(self, username, password):
self.uri = "https://api.samanage.com"
self.session = requests.Session()
self.session.auth = requests.auth.HTTPDigestAuth(username, password)
self.session.headers = {"Accept":"application/vnd.samanage.v1.1+json",
"Content-Type":"application/json"}
def incident(self, name, requester, priority, status, assignee, description):
"""Create an incident on Samanage. Name, requestor and priority
are requried fields."""
payload = {
"incident":{
"name": name,
"requester": {"email": requester},
"priority": priority,
"state": status,
"assignee":{"email": assignee},
"description": description
}
}
response = self.session.post(
"{0}/incidents.json".format(self.uri),
json=payload
)
return response.text
def comment(self, body, incident_id):
"""Create a comment on a Samanage incident."""
payload = {"comment":{"body":body, "is_private":"false"}}
response = self.session.post(
"{0}/incidents/{1}/comments.json".format(self.uri, incident_id),
json=payload
)
return response.status_code
def update_status(self, value, incident_id):
"""Update an incident's state on Samanage."""
payload = {"incident":{"state": value}}
response = self.session.put(
"{0}/incidents/{1}.json".format(self.uri, incident_id),
json=payload
)
return response.status_code
class Zendesk(object):
"""Class for Zendesk API.
Zendesk authentication will accept username with password
or api token. If using api token set token argument to True
when initalizing class.
Zendesk returns api calls in html. Responses are
read as binary instead and to prevent UnicodeDecodeError
are decoded with 'replace' argument."""
def __init__(self, username, password, org, token=False):
self.username = username
self.password = <PASSWORD>
self.token = token
self.uri = "https://{0}.zendesk.com/api/v2".format(org)
self.session = requests.Session()
if self.token:
self.session.auth = username+"/token", password
else:
self.session.auth = username, password
self.session.headers = {"Content-Type":"application/json"}
def http_call(self, request):
"""Make HTTP GET request to Zendesk.
Zendesk has rate-limits and will return a 429 Too Many Requests response
once its hit. This response is caught and the code will wait before
resending the request.
Zendesk rate-limits are listed at:
https://developer.zendesk.com/rest_api/docs/core/introduction#rate-limits
HTTP errors are raised to console."""
response = self.session.get(request)
attempts = 0
while response.status_code == 429:
if attempts > 5:
break
attempts = attempts + 1
time.sleep(30)
response = self.session.get(request)
response.raise_for_status()
return response
def ticket_range(self):
"""Zendesk returns 100 tickets at a time. With this request we
can calculate how many times we'd need to make a
self.get_list_of_tickets request."""
response = self.http_call("{0}/tickets.json".format(self.uri))
return math.ceil(response.json()["count"] / 100) + 1
def get_ticket(self, ticket_id):
"""Get a single ticket from Zendesk using the ticket id."""
response = self.http_call("{0}/tickets/{1}.json".format(self.uri, ticket_id))
return json.loads(response.content.decode(sys.stdout.encoding, "replace"))
def get_assignee_email(self, assignee_id):
"""Get an assignee email using the assignee id."""
response = self.http_call("{0}/users/{1}.json".format(self.uri, assignee_id))
return json.loads(response.content.decode(sys.stdout.encoding, "replace"))["user"]["email"]
def get_comments(self, ticket_id):
"""Get all the comments on a ticket using the ticket id."""
response = self.http_call("{0}/tickets/{1}/comments.json".format(self.uri, ticket_id))
return json.loads(response.content.decode(sys.stdout.encoding, "replace"))
def get_list_of_tickets(self, page=1):
"""Get a list of tickets up to 100. Page argument used to view next 100."""
response = self.http_call("{0}/tickets.json?page={1}".format(self.uri, page))
return json.loads(response.content.decode(sys.stdout.encoding, "replace"))
def get_comment_author(self, author_id):
"""Get the author of a comment using the author id."""
response = self.http_call("{0}/users/{1}.json".format(self.uri, author_id))
return json.loads(response.content.decode(sys.stdout.encoding, "replace"))["user"]["name"]
def get_many_tickets(self, tickets):
"""Get many tickets from zendesk. Up to 100."""
response = self.http_call("{0}/tickets/show_many.json?ids={1}".format(self.uri, tickets))
return json.loads(response.content.decode(sys.stdout.encoding, "replace"))
def get_all_ticket_ids(self):
""""Function to just get all the ticket ids on zendesk as a list"""
ticket_range = self.ticket_range()
all_ticket_ids = []
for i in range(1, ticket_range):
tickets = self.get_list_of_tickets(i)
for ticket in tickets["tickets"]:
all_ticket_ids.append(ticket["id"])
return all_ticket_ids
class Zentosam(object):
"""Class for functions to transfer tickets.
If samanage argument is given the initalized Samanage class
zendesk cards will be transfered to Samanage.
If tickets are going to be transfered to Samanage
the priority of the tickets needs to be given.
Priority is a requried field for Samanage tickets.
Likewise the default_requester needs to be given.
When a Zendesk ticket does not have a requester
the default_requester is used. Samanage requires
a requester in its tickets.
If dump argument is True a JSON dump of the information
that is transfered will be created as ticket_dump.json.
Both, either or neither (if you don't want to get any results)
of the samanage or dump arguments need to be set. Running the code
with just dump set can be used to get an idea of what will be
transfered to Samanage without actually transfering anything."""
def __init__(self, zendesk, samanage=False, priority=None, default_requester=None, dump=False):
self.zendesk = zendesk
self.samanage = samanage
self.priority = priority
self.default_requester = default_requester
if self.samanage and self.priority is None:
self.priority = input("Input Samanage priority: ")
if self.samanage and default_requester is None:
self.default_requester = input("Input Samanage default requester: ")
self.dump = dump
def batch_transfer(self):
"""Transfer all tickets from zendesk to samanage."""
ticket_range = self.zendesk.ticket_range()
for i in range(1, ticket_range):
tickets = self.zendesk.get_list_of_tickets(i)
for ticket in tickets["tickets"]:
ticket_id = ticket["id"]
self.transfer_ticket(ticket_id)
def transfer_ticket(self, ticket_id):
"""Transfer a ticket from zendesk
to samanage using the zendesk ticket id."""
ticket = self.zendesk.get_ticket(ticket_id)
subject = ticket["ticket"]["subject"]
status = ticket["ticket"]["status"]
description = ticket["ticket"]["description"]
if ticket["ticket"]["assignee_id"] is not None:
assignee_email = self.zendesk.get_assignee_email(ticket["ticket"]["assignee_id"])
try:
requester = ticket["ticket"]["via"]["source"]["from"]["address"]
except KeyError:
requester = self.default_requester
# Terms for the status of a ticket on Samanage differ from those on Zendesk
# When creating a ticket on Samanage through API only statuses allowed are Closed and New.
# After the ticket is created status can be changed.
if status in ("open", "pending"):
status = "New"
update_status = "Assigned"
if status in ("closed", "solved"):
status = "Closed"
update_status = "Closed"
# We can now make incident on Samanage
if self.samanage:
incident = self.samanage.incident(
subject, requester, self.priority, status, assignee_email, description
)
incident_id = json.loads(incident)["id"]
# Get all comments for a ticket on zendesk
comments = self.zendesk.get_comments(ticket_id)
comment_list = []
for comment in comments["comments"]:
author = self.zendesk.get_comment_author(comment["author_id"])
if self.dump:
comment_list.append({"author": author, "body": comment["body"]})
# Transfer comment(s) to Samanage
if self.samanage:
self.samanage.comment("From:{0}\n{1}".format(author, comment["body"]), incident_id)
# Adding comments to samanage ticket reopens it
# (re)update the status of the ticket on samanage to specified status
if self.samanage:
self.samanage.update_status(update_status, incident_id)
# JSON dump if initalized
if self.dump:
with open("ticket_dump.json", "a", errors='replace') as dump_file:
card_details = {ticket_id:{
"id": ticket_id,
"subject": subject,
"requester": requester,
"status": status,
"assignee": assignee_email,
"description": description,
"comments": comment_list}}
dump_file.write(json.dumps(card_details, ensure_ascii=False,
sort_keys=True, indent=4))
| 3914bb4d8d27acfd742fe8a545687b0f0d46a060 | [
"Markdown",
"Python"
] | 2 | Markdown | nimoon/zentosam | 425eb5d17a49af60bcb75206f5bdb26378afb4b4 | cc006013788f59f91235cc35c7258c0e0f215411 |
refs/heads/main | <repo_name>emilymmont/python-challenge<file_sep>/PyBank/main.py
import os
import csv
from pathlib import Path
csvpath = os.path.join("PyBank", "Resources", "budget_data.csv")
total_months = []
total_profit = []
monthly_profit_change = []
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader)
for row in csvreader:
total_months.append(row[0])
total_profit.append(int(row[1]))
for i in range(len(total_profit)-1):
monthly_profit_change.append(total_profit[i+1]-total_profit[i])
greatest_increase = max(monthly_profit_change)
greatest_decrease = min(monthly_profit_change)
greatest_increase_month = monthly_profit_change.index(max(monthly_profit_change)) + 1
greatest_decrease_month = monthly_profit_change.index(min(monthly_profit_change)) + 1
print("Financial Analysis")
print("----------------------------")
print(f"Total Months: {len(total_months)}")
print(f"Total: ${sum(total_profit)}")
print(f"Average Change: ${round(sum(monthly_profit_change)/len(monthly_profit_change),2)}")
print(f"Greatest Increase in Profits: {total_months[greatest_increase_month]} (${(str(greatest_increase))})")
print(f"Greatest Decrease in Profits: {total_months[greatest_decrease_month]} (${(str(greatest_decrease))})")
input_file = os.path.join("PyBank", "Resources", "budget_data.csv")
output_file = os.path.join("PyBank", "analysis", "Financial_Analysis.txt")
with open(output_file,"w") as file:
file.write("Financial Analysis")
file.write("\n")
file.write("----------------------------")
file.write("\n")
file.write(f"Total Months: {len(total_months)}")
file.write("\n")
file.write(f"Total: ${sum(total_profit)}")
file.write("\n")
file.write(f"Average Change: ${round(sum(monthly_profit_change)/len(monthly_profit_change),2)}")
file.write("\n")
file.write(f"Greatest Increase in Profits: {total_months[greatest_increase_month]} (${(str(greatest_increase))})")
file.write("\n")
file.write(f"Greatest Decrease in Profits: {total_months[greatest_decrease_month]} (${(str(greatest_decrease))})")<file_sep>/PyPoll/analysis/main.py
import os
import csv
from pathlib import Path
csvpath = os.path.join("PyPoll", "Resources", "election_data.csv")
total_votes = 0
khan_votes = 0
correy_votes = 0
li_votes = 0
otooley_votes = 0
with open(csvpath, newline="", encoding="utf-8") as elections:
csvreader = csv.reader(elections, delimiter=",")
header = next(csvreader)
for row in csvreader:
total_votes +=1
if row[2] == "Khan":
khan_votes +=1
elif row[2] == "Correy":
correy_votes +=1
elif row[2] == "Li":
li_votes +=1
elif row[2] == "O'Tooley":
otooley_votes +=1
candidates = ["Khan", "Correy", "Li", "O'Tooley"]
votes = [khan_votes, correy_votes, li_votes, otooley_votes]
dict_candidates_and_votes = dict(zip(candidates,votes))
key = max(dict_candidates_and_votes, key = dict_candidates_and_votes.get)
khan_percent = (khan_votes/total_votes) * 100
correy_percent = (correy_votes/total_votes) * 100
li_percent = (li_votes/total_votes) * 100
otooley_percent = (otooley_votes/total_votes) * 100
print("Election Results")
print("-------------------------")
print(f"Total Votes: {total_votes}")
print("-------------------------")
print(f"Khan: {khan_percent:.3f}% ({khan_votes})")
print(f"Correy: {correy_percent:.3f}% ({correy_votes})")
print(f"Li: {li_percent:.3f}% ({li_votes})")
print(f"O'Tooley: {otooley_percent:.3f}% ({otooley_votes})")
print("-------------------------")
print(f"Winner: {key}")
print("-------------------------")
input_file = os.path.join("PyPoll", "Resources", "election_data.csv")
output_file = os.path.join("PyPoll", "analysis", "Election_Results.txt")
with open(output_file,"w") as file:
file.write("Election Results")
file.write("\n")
file.write("-------------------------")
file.write("\n")
file.write(f"Total Votes: {total_votes}")
file.write("\n")
file.write("-------------------------")
file.write("\n")
file.write(f"Kahn: {khan_percent:.3f}% ({khan_votes})")
file.write("\n")
file.write(f"Correy: {correy_percent:.3f}% ({correy_votes})")
file.write("\n")
file.write(f"Li: {li_percent:.3f}% ({li_votes})")
file.write("\n")
file.write(f"O'Tooley: {otooley_percent:.3f}% ({otooley_votes})")
file.write("\n")
file.write("-------------------------")
file.write("\n")
file.write(f"Winner: {key}")
file.write("\n")
file.write("-------------------------")<file_sep>/README.md
# python-challenge
In this homework assignment, I used the concepts I've learned to complete the two Python Challenges, PyBank and PyPoll.
Both of these challenges encompass a real-world situation where I used my newfound Python scripting skills.
| 92d35d16908b4a515b062c8734d5ef50878fe34c | [
"Markdown",
"Python"
] | 3 | Markdown | emilymmont/python-challenge | 0a61181b05a1a8cde06b5a0309718e33a1e693f3 | ebbadd72f9abe082ff242d59e13dded1eaae5614 |
refs/heads/master | <repo_name>abdocmd/samples<file_sep>/box-node-lambda-sample/index.js
/**
* This sample demonstrates how to call Box APIs from an AWS Lambda function using the Box Node SDK.
*
* For step-by-step instructions on how to create and authorize a Box application, see box-node-lambda-sample in
* https://github.com/box/samples
*/
'use strict';
const BoxSDK = require('box-node-sdk');
const fs = require('fs');
// The private key can't be stored in an environment variable, so load the PEM file from the deployment package
// (You could also load it from an S3 bucket)
const privateKeyPath = `${process.env.LAMBDA_TASK_ROOT}/private_key.pem`;
const privateKey = fs.readFileSync(privateKeyPath);
// Load the application secrets from environment variables for security and configuration management
const sdk = new BoxSDK({
clientID: process.env.BOX_CLIENT_ID,
clientSecret: process.env.BOX_CLIENT_SECRET,
appAuth: {
keyID: process.env.BOX_PUBLIC_KEY_ID,
privateKey: privateKey,
passphrase: process.env.BOX_PRIVATE_KEY_PASSPHRASE,
},
});
/**
* Create a service account client that performs actions in the context of the specified enterprise.
* The app has a unique service account in each enterprise that authorizes the app.
* The service account contains any app-specific content for that enterprise.
* Depending on the scopes selected, it can also create and manage app users or managed users in that enterprise.
*
* The client will create and refresh the service account access token automatically.
*/
const client = sdk.getAppAuthClient('enterprise', process.env.BOX_ENTERPRISE_ID);
/**
* YOUR CODE GOES HERE!!!
*
* This sample function returns details of the current user (the service account)
*/
exports.handler = (event, context, callback) => {
console.log(`Event: ${JSON.stringify(event, null, 2)}`);
// Get details on the current user (the service account)
client.users.get(client.CURRENT_USER_ID, null, (err, result) => {
let response;
if (err) {
if (err.response && err.response.body) {
response = err.response.body;
} else {
response = err.toString();
}
} else {
response = result;
}
console.log(`Response: ${JSON.stringify(response, null, 2)}`);
callback(null, response);
});
};
<file_sep>/README.md
Box Samples
====================
This repo is dedicated to sharing code snippets and samples to demonstrate how to get the most out of the Box platform & API. It will include specific use cases, showcasing integrations and other creative uses of the Box API.
Index
-----
[box-node-lambda-sample](https://github.com/box/samples/tree/master/box-node-lambda-sample)
This sample demonstrates how to call Box APIs from an AWS Lambda function using the [Box Node SDK](https://github.com/box/box-node-sdk).
This lets you call Box from a Lambda function.
[box-node-webhook-to-lambda-sample](https://github.com/box/samples/tree/master/box-node-webhook-to-lambda-sample)
This sample shows how to connect a Box webhook to an AWS Lambda function via API Gateway.
This lets you call a Lambda function from Box.
Support
-------
Need to contact us directly? You can post to the
[Box Developer Forum](https://community.box.com/t5/Developer-Forum/bd-p/DeveloperForum).
Copyright and License
---------------------
Copyright 2016 Box, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
<file_sep>/box-node-lambda-sample/package.json
{
"name": "box-node-lambda-sample",
"version": "1.2.0",
"description": "This sample demonstrates how to call Box APIs from an AWS Lambda function using the Box Node SDK.",
"main": "index.js",
"dependencies": {
"box-node-sdk": "^1.3.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"genrsa": "openssl genrsa -aes256 -out private_key.pem 2048; openssl rsa -pubout -in private_key.pem -out public_key.pem",
"zip": "zip -rMM box-node-lambda-sample index.js private_key.pem node_modules",
"bp": "zip -rMM box-node-lambda-sample-bp index.js lambda.json node_modules",
"lint": "eslint index.js"
},
"author": "Box <<EMAIL>>",
"license": "Apache-2.0"
}
<file_sep>/box-node-lambda-sample/README.md
# box-node-lambda-sample
This sample demonstrates how to call Box APIs from an AWS Lambda function using the [Box Node SDK](https://github.com/box/box-node-sdk).
#### Step 1. Create a Box application
1. Log into the [Box Developer Console](https://developers.box.com) in your Box developer account
* Switch to the open beta of the new Developer Console, if needed
2. Select "Create New App"
* Select "Custom App" and press "Next"
* *You can also pick "Enterprise Integration" if your app will interact with existing Box enterprises*
* Select "Server Authentication" and press "Next"
* *This sample demonstrates a server-to-server integration*
* Name the application "Box Node Lambda Sample - YOUR NAME"
* *Application names must be unique across Box*
* Press "Create App" and then "View Your App"
* Check the "Manage users" scope and press "Save Changes"
* You'll need your "Client ID" and "Client Secret" later
#### Step 2. Generate your private and public keys
1. Generate a private key and a public key to use with Server Authentication
* In the `box-node-lambda-sample` directory, run the following commands:
```
openssl genrsa -aes256 -out private_key.pem 2048
openssl rsa -pubout -in private_key.pem -out public_key.pem
```
You'll need the passphrase for your private key later
2. Add the public key to the application
* Press "Add Public Key"
* You will need to set up 2-factor authentication, if you haven't already
* Copy the public key: `cat public_key.pem | pbcopy`
* Paste it into the "Public Key" field
* Press "Verify and Save"
* You will need to enter a 2-factor confirmation code
* You'll need the ID of your public key later
3. Your application is ready to go
#### Step 3. Authorize the application into your Box account
1. In a new tab, log into your Box developer account as an admin and go to the Admin Console
* *Applications that use Server Authentication must be authorized by the admin of the account*
2. Under the gear icon, go to Enterprise Settings (or Business Settings, depending on your account type)
* You'll need the "Enterprise ID" of your account later
3. Go to the Apps tab
3. Under "Custom Applications", press "Authorize New App"
4. Enter your "Client ID" from the developer console in the "API Key" field
* Your application is now authorized to access your Box account
#### Step 4. Create the AWS Lambda function
1. Build the deployment package for the Lambda function
* `cd` into the `box-node-lambda-sample` directory
* Run `npm install` to install the [Box Node SDK](https://github.com/box/box-node-sdk)
* Ensure that the `private_key.pem` file is in the directory
* Run `npm run zip` to create `box-node-lambda-sample.zip`
* The ZIP file includes the sample code in `index.js`, the private key in `private_key.pem`, plus the Box Node SDK
2. Log into the [AWS Management Console](https://aws.amazon.com/console) and go to the Lambda Management Console
3. Press "Create a Lambda function"
* Choose the "Blank Function" blueprint
* There is no need to configure a trigger for the Lambda function
* Press "Next"
4. Configure the lambda function
* Name = "box-node-lambda-sample"
* Description = "Demonstrates how to call Box APIs from an AWS Lambda function using the Box Node SDK"
* Runtime = "Node.js 4.3"
* Code entry type = "Upload a .ZIP file"
* Function package = Browse and select `box-node-lambda-sample.zip`
* Environment variables:
* *Storing the application secrets in environment variables makes them easier to secure and manage*
```
BOX_CLIENT_ID = Your Client ID
BOX_CLIENT_SECRET = Your Client Secret
BOX_PUBLIC_KEY_ID = Your Public Key ID
BOX_PRIVATE_KEY_PASSPHRASE = Your Private Key Passphrase
BOX_ENTERPRISE_ID = Your Enterprise ID
```
* Handler = "index.handler". This sets the entry point to be the `handler()` function of the `index.js` module
* Role = "Create new role from template"
* Role Name = "box-node-lambda-sample-role"
* Policy Templates = Leave blank
* Leave all of the advanced settings with default values
* Press "Next"
6. Press "Create function"
* Once the Lambda function is created, you will see the sample code from `index.js` that was uploaded in the ZIP file
* This first section initializes the Lambda function:
* First, it creates a `BoxSDK` object, initializing it with your application secrets from the environment variables
* Then, it creates a `BoxClient` object that obtains an access token for the Service Account in your Box enterprise
* The Lambda's `handler` function will be called each time the Lambda function is invoked:
* For this example, the `handler` function simply retrieves info about the Service Account user and returns it as the response
from the Lambda function
#### Step 5. Test the Lambda function
1. Press the "Test" button
* This Lambda function does not require any input, so just leave the sample test data as is and press "Save and test"
2. The result should be similar to the following JSON response:
```JSON
{
"type": "user",
"id": "12345678",
"name": "Box Node Lambda Sample",
"login": "<EMAIL>",
"created_at": "2017-01-25T15:39:38-08:00",
"modified_at": "2017-01-25T17:21:56-08:00",
"language": "en",
"timezone": "America/Los_Angeles",
"space_amount": 5368709120,
"space_used": 0,
"max_upload_size": 5368709120,
"status": "active",
"job_title": "",
"phone": "",
"address": "",
"avatar_url": "https://xyz.app.box.com/api/avatar/large/12345678"
}
```
3. Your Lambda function is sucessfully calling the Box API!
#### Next Steps
Now that you can call Box from your AWS Lambda function, modify the sample Lambda function to make other Box API calls
using the [Box Node SDK](https://github.com/box/box-node-sdk):
1. Create and view content owned by the service account
```Javascript
client.folders.create(0, 'Test Folder', (err, result) => {...});
client.folders.getItems(0, null, (err, result) => {...});
```
2. Create app users
* Add the "Manage users" scope to the application in the Developer Console
* Whenever you add scopes to your application, you need to re-authorize it in the Admin Console
```Javascript
client.enterprise.addUser(null, 'Test App User', {is_platform_access_only: true}, (err, result) => {...});
```
3. Make API calls using a user's account
* Add the "Generate User Access Tokens" scope to the application and re-authorize it in the Admin Console
* Create a user client that makes API calls as a specific user
```Javascript
const userClient = sdk.getAppAuthClient('user', user_id);
userClient.folders.create(0, 'User Folder', (err, result) => {...});
```
4. Alternatively, you can make API calls on behalf of a user using the service account client
* Add the "Perform Actions as Users" scope to the application and re-authorize it in the Admin Console
* Use the `asUser()` and `asSelf()` functions to make API calls as a specific user
```Javascript
client.asUser(user_id);
client.folders.create(0, 'User Folder', (err, result) => {...});
client.asSelf();
```
5. Use the AWS ["encryption helpers"](http://docs.aws.amazon.com/lambda/latest/dg/tutorial-env_console.html)
to encrypt the environment variables that hold the application secrets
* Modify the sample code to decrypt the secrets before creating the Box SDK and client objects
#### Troubleshooting
1. If your Client ID is wrong, you will get: `"Please check the 'iss' claim."`
2. If your Enterprise ID is wrong, you will get: `"Please check the 'sub' claim."`
3. If your Client Secret is wrong, you will get: `"The client credentials are invalid"`
4. If your Public Key ID is wrong, you will get: `"OpenSSL unable to verify data: "`
5. If your `private_key.pem` is wrong, you will get: `"OpenSSL unable to verify data: error:0906D06C:PEM routines:PEM_read_bio:no start line"`
6. If your Private Key Passphrase is wrong, you will get: `"Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt"`
7. If you pass an integer instead of a string for the `id` parameter of `getAppAuthClient()`, you wil get `"Please check the 'sub' claim."`
18. If you forgot to add your public key, you will get: `"This app is not configured properly. No public key(s) added"`
9. If you forgot to authorize the app, you wil get: `"This app is not authorized by the enterprise admin"`
10. If you didn't set the `BOX_CLIENT_ID` environment variable, you will get: `"clientID" must be set via init() before using the SDK.`
11. If you didn't set the `BOX_PRIVATE_KEY_PASSPHRASE` environment variable, you will get: `"Passphrase must be provided in app auth params"`
12. If you didn't set the `BOX_PUBLIC_KEY_ID` environment variable, you will get: `"Must provide app auth configuration to use JWT Grant"`
13. If you get `"Task timed out after 3.00 seconds"`, you may be getting a network error or Box server error.
Try increasing the "Timeout" value in "Advanced Settings" of the Lambda function's "Configuration" tab to 30 seconds in order
to see more details of the error
Support
-------
Need to contact us directly? You can post to the
[Box Developer Forum](https://community.box.com/t5/Developer-Forum/bd-p/DeveloperForum).
Copyright and License
---------------------
Copyright 2017 Box, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
<file_sep>/box-node-webhook-to-lambda-sample/README.md
# box-node-webhook-to-lambda-sample
This sample shows how to connect a Box webhook to an AWS Lambda function via API Gateway.
Each time an event occurs that triggers the webhook on Box, the Lambda function will be called with the details of the event.
The messages are secured with a message signature that is validated in the Lambda function.
There are several use cases for using Lambda functions with Box:
* **Trigger external systems.** Send an SMS when certain events occur in Box
* **Extend Box with external processing.** When an image file is uploaded to Box, use image analysis to extract information and add that as metadata to the file in Box
* **Build analytics.** Record events that happen in Box in an external analytics system
This sample gives step-by-step instructions to set up an AWS Lambda function and trigger it from a Box webhook.
#### Step 1. Create an AWS Lambda function
1. Log into the [AWS Management Console](https://aws.amazon.com/console) and go to the Lambda Management Console
2. Press "Create a Lambda function"
* Choose the "Blank Function" blueprint
3. Configure a trigger for the Lambda function by clicking in the gray outlined area
* Choose API Gateway
* Leave the API name and Deployment stage with default values
* Choose "Open" for Security. This enables the Box webhook to call the API externally
* Press Next
4. Create the deployment package for the Lambda function
* Run `npm install` to install the [Box Node SDK](https://github.com/box/box-node-sdk)
* Run `npm run zip` to create `box-node-webhook-to-lambda-sample.zip`
* The zip file includes the sample code in `index.js` plus the Box Node SDK
5. Configure the lambda function
* Name = "box-node-webhook-to-lambda-sample"
* Description = "Demonstrates connecting a Box webhook to an AWS Lambda function"
* Runtime = "Node.js"
* Code entry type = "Upload a .ZIP file"
* Function package = Browse and select `box-node-webhook-to-lambda-sample.zip`
* Environment variables:
```
BOX_WEBHOOK_PRIMARY_SIGNATURE_KEY = SamplePrimaryKey
BOX_WEBHOOK_SECONDARY_SIGNATURE_KEY = SampleSecondaryKey
```
* Handler = "index.handler". This sets the entry point to be the handler() function of the `index.js` file
* Role = "Create new role from template"
* Role Name = "box-node-webhook-to-lambda-sample-role"
* Policy Templates = Leave blank
* Leave all of the advanced settings with default values
* Press Next
6. Press "Create function"
#### Step 2. Test the Lambda function in the Lambda Console
1. Press the "Test" button and copy and paste the test data below (also in the file `lambda-test.json`):
```JSON
{
"headers": {
"box-delivery-id": "f96bb54b-ee16-4fc5-aa65-8c2d9e5b546f",
"box-delivery-timestamp": "2020-01-01T00:00:00-07:00",
"box-signature-algorithm": "HmacSHA256",
"box-signature-primary": "6TfeAW3A1PASkgboxxA5yqHNKOwFyMWuEXny/FPD5hI=",
"box-signature-secondary": "v+1CD1Jdo3muIcbpv5lxxgPglOqMfsNHPV899xWYydo=",
"box-signature-version": "1"
},
"body": "{\"type\":\"webhook_event\",\"webhook\":{\"id\":\"1234567890\"},\"trigger\":\"FILE.UPLOADED\",\"source\":{\"id\":\"1234567890\",\"type\":\"file\",\"name\":\"Test.txt\"}}"
}
```
This sample message has been signed with the keys `SamplePrimaryKey` and `SampleSecondaryKey`.
*Note that the API Gateway will pass the incoming HTTP request headers and body to the Lambda function as a JSON object.
See the [API Gateway documentation](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-input-format) for more information on the input and output formats for the Lambda Proxy Integration.*
2. The result should be the following JSON response:
```JSON
{
"statusCode": 200,
"body": "webhook=1234567890, trigger=FILE.UPLOADED, source=<file id=1234567890 name=Test.txt>"
}
```
3. Your Lambda function is working properly!
#### Step 3. Test the API Gateway API endpoint using curl
1. Find the URL for your API Gateway on the "Triggers" tab. It should look like:
```
https://xxxxxxxxxx.execute-api.us-west-2.amazonaws.com/prod/box-node-webhook-to-lambda-sample
```
2. Run the following `curl` command:
```
curl <YOUR_GATEWAY_API_URL> -d @curl-test.json \
-H "box-delivery-id: f96bb54b-ee16-4fc5-aa65-8c2d9e5b546f" \
-H "box-delivery-timestamp: 2020-01-01T00:00:00-07:00" \
-H "box-signature-algorithm: HmacSHA256" \
-H "box-signature-primary: 6TfeAW3A1PASkgboxxA5yqHNKOwFyMWuEXny/FPD5hI=" \
-H "box-signature-secondary: v+1CD1Jdo3muIcbpv5lxxgPglOqMfsNHPV899xWYydo=" \
-H "box-signature-version: 1"; echo
```
3. The file `curl-test.json` contains the following test data:
```JSON
{"type":"webhook_event","webhook":{"id":"1234567890"},"trigger":"FILE.UPLOADED","source":{"id":"1234567890","type":"file","name":"Test.txt"}}
```
4. This should return the following response message from the Lambda function:
```
webhook=1234567890, trigger=FILE.UPLOADED, source=<file id=1234567890 name="Test.txt">
```
*If you have trouble, try using `curl -v` to see the HTTP response code*
5. Your public API endpoint is working properly!
#### Step 4. Create a Box application and get a developer token
1. Log into the [Box Developer Console](https://developers.box.com)
* Switch to the open beta of the new Developer Console, if needed
2. Select "Create New App"
* Select "Enterprise Integration" and press "Next"
* Select "Server Authentication" and press "Next"
* Name the application "Box Webhook to Lambda Sample - YOUR NAME"
* *Application names must be unique across Box*
* Press "Create App" and then "View Your App"
* Check the "Manage users" and "Manage webhooks" scopes and press "Save Changes"
* This enables the application to create and use webhooks
* In the left navbar, switch to the "Webhooks" section
* Press "Generate Key" for both the "Primary Key" and "Secondary Key" to create keys for signing the events
* These are the keys that Box will use to sign events sent by your application's webhooks
* The events are signed using two separate keys to make it easier to [rotate your signing keys](https://docs.box.com/reference#section-rotating-signatures)
* Return to the "Configuration" section and get your "Developer Token"
* *The token is valid for an hour, but you can get another one if it expires*
#### Step 5. Create a Box webhook to call the Lambda function
Note: See [Getting Started with Webhooks V2](https://docs.box.com/v2.0/docs/getting-started-with-webhooks-v2) and [Overview of Webhooks V2](https://docs.box.com/reference#webhooks-v2) for more info.
1. Create a folder in your account on Box and record the "Folder ID"
* See these [instructions](https://docs.box.com/v2.0/docs/getting-started-with-webhooks-v2#section-3-create-a-webhook) for how to find the "Folder ID"
2. Create a webhook using `curl` to call the [Box webhook API](https://docs.box.com/reference#create-webhook):
```
curl https://api.box.com/2.0/webhooks \
-H "Authorization: Bearer <DEVELOPER_TOKEN>" \
-d '{"target": {"id": "<FOLDER_ID>", "type": "folder"}, "address": "<YOUR_GATEWAY_API_URL>", "triggers": ["FILE.UPLOADED"]}'; echo
```
*Note: You must use the API to create V2 webhooks -- there is no Web UI*
3. You should get a response confirming that the webhook has been created:
```
{"id":"<WEBHOOK_ID>","type":"webhook","target":{"id":"<FOLDER_ID>","type":"folder"},"created_by":<YOUR_USER_INFO>,"created_at":"2016-11-10T15:00:10-08:00","address":"<YOUR_GATEWAY_API_URL>","triggers":["FILE.UPLOADED"]}
```
* Note down the `<WEBHOOK_ID>` in case you need to modify or delete the webhook
4. The webhook will call the Lambda function each time a file is uploaded to the folder
* *See [here](https://docs.box.com/reference#section-retries) for details on how Box webhooks handle timeouts, retries, and exponential backoff*
#### Step 6. Update the Lambda function with your app's signing keys
1. In the Code tab of the Lambda Management Console, update the environment variables to the primary and secondary signing keys from the Box Developer Console
* *Storing the application secrets in environment variables makes them easier to secure and manage*
```
BOX_WEBHOOK_PRIMARY_SIGNATURE_KEY = <YOUR_PRIMARY_KEY>
BOX_WEBHOOK_SECONDARY_SIGNATURE_KEY = <YOUR_SECONDARY_KEY>
```
2. Press "Save and Test"
3. You should get an error response, because the sample test data is not signed with the keys you just added to the Lambda function
```JSON
{
"statusCode": 403,
"body": "Message authenticity not verified"
}
```
4. Publish the new version of your lambda function by selecting "Publish new version" in the "Actions" menu
#### Step 7. Test the webhook on Box
1. Upload a file to the Box folder that you specified when creating the webhook
2. In the Lambda Management Console, click on the Monitoring tab and click on "View Logs in Cloudwatch"
3. Click on the most recent log stream (the top one)
4. You should see a new set of events appear in Cloudwatch that include the console logs created by the Lambda function:
```JSON
{
"statusCode": 200,
"body": "webhook=386135, trigger=FILE.UPLOADED, source=<file id=99174057812 name=\"Electron 4.png\">"
}
```
*It may take a few seconds for the events to appear. Press the "Retry" link or scroll down to see new events*
5. Note that if your developer token expires, the webhook will no longer send events with a full payload. In that case, the event trigger will be `NO_ACTIVE_SESSION`
```JSON
{
"statusCode": 200,
"body": "webhook=386135, trigger=NO_ACTIVE_SESSION, source=<file id=99174057812 name=\"unknown\">"
}
```
6. To get the webhook to send the full payload again, generate a new developer token in the Box Developer Console
* *Note that you don't need to recreate the webhook with the new developer token -- there just needs to be a non-expired token associated with the user that created the webhook*
#### Next Steps
Now that you are successfully calling your AWS Lambda function from a Box webhook, here are some things you can try next:
1. Use the AWS "encryption helpers" to encrypt the environment variables that hold the application secrets
* Modify the sample code to decrypt the secrets
2. Modify the sample Lambda function to call an external service with the event data
3. Have the Lambda function download additional information from Box in response to the event (such as the contents of a newly uploaded file)
* See the documentation for the [Box Node SDK](https://github.com/box/box-node-sdk) for how to call Box APIs
4. [Rotate your app's signing keys](https://docs.box.com/reference#section-rotating-signatures)
* Generate a new primary key on Box
* Messages will continue to be validated using the secondary key
* Update you Lambda function with the new primary key
* Wait long enough for all in-flight messages to have been processed by the Lambda function
* Repeat the process, this time rotating the secondary key
#### Troubleshooting
1. Each app can only have one webhook for a given target. If you try to create a second one you will get an API error:
```JSON
{
"type": "error",
"status": 409,
"code": "conflict",
"context_info": {
"errors": [
{
"reason": "invalid_parameter",
"name": "existWebhookId",
"message": "Webhook:<WEBHOOK_ID> already exists on the specified target."
}]
}
,
"help_url": "http:\/\/developers.box.com\/docs\/#errors",
"message": "Bad Request",
"request_id": "87176267658a2217692375"
}
```
2. To inspect the webhook, use:
```
curl https://api.box.com/2.0/webhooks/<WEBHOOK_ID> -H "Authorization: Bearer <DEVELOPER_TOKEN>"
```
3. To delete the webhook when you are done, use:
```
curl https://api.box.com/2.0/webhooks/<WEBHOOK_ID> -H "Authorization: Bearer <DEVELOPER_TOKEN>" -X DELETE
```
Support
-------
Need to contact us directly? You can post to the
[Box Developer Forum](https://community.box.com/t5/Developer-Forum/bd-p/DeveloperForum).
Copyright and License
---------------------
Copyright 2016 Box, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| 707e6685b4b3c645fc4f186811da2bef5dc4c6ba | [
"Markdown",
"JavaScript",
"JSON"
] | 5 | Markdown | abdocmd/samples | 0c3f2dcb0afc27212cce935e6e9bf722ded596da | 3ad699ad6bbc61f821c98e0dbbafecd0385d0cea |
refs/heads/master | <file_sep>|以下のタスクを作成しました
ul
|i
|名称:
= @task.name
|i
|詳しい説明:
= simple_format(@task.description)<file_sep># Preview all emails at http://localhost:3000/rails/mailers/taskleaf
class TaskleafPreview < ActionMailer::Preview
end
<file_sep>class ChangeUsersName < ActiveRecord::Migration[5.2]
def up
change_column_null :users, :name, null: false
change_column_null :users, :email, null: false
change_column_null :users, :password_digest, null: false
end
end
| 37993fd0999d42448e296ebe7f51d11cf5afb272 | [
"Slim",
"Ruby"
] | 3 | Slim | mackey0209/taskleaf | 69f610c3989932ae464563127169c55b1b840404 | f51c92cb47960b81fba0a40d5503d80a603571d1 |
refs/heads/master | <file_sep>var User = require('../models/user.js');
var mongoose = require('mongoose');
var db = require('../config/db');
var userToSend;
//mongoose.connect(db.url);
module.exports = function(app){
var sess;
app.post('/newUser', function(req, res){
var newUser = new User({
firstName : req.body.firstName,
lastName : req.body.lastName,
username : req.body.username,
email : req.body.email,
password : <PASSWORD>
});
newUser.save(function(err){
if(err){
return res.redirect('/')
}
res.redirect('/');
});
});
app.post('/log', function(req, res){
var username = req.body.username;
var password = <PASSWORD>;
userToSend = User.findOne({username: username, password: <PASSWORD>}, function(err, user){
if(err){
return res.redirect();
}
if(!user){
return res.redirect('/');
}
sess = req.session;
sess.username = username;
res.redirect('/');
//res.render('index', {msg : username});
});
});
}<file_sep>// public/js/controllers/NerdCtrl.js
angular.module('LoginCtrl', []).controller('LoginController', function($scope, $http) {
$http.get('/username').then(function(response){
$scope.username = response.data;
if($scope.username !== ""){
document.getElementById("loginDiv").style.display="none";
document.getElementById("siginDiv").style.display="none";
document.getElementById("loginForm").style.display="none";
document.getElementById("logoutForm").style.display="block";
document.getElementById("homeDiv").style.display="block";
document.getElementById("scheduleDiv").style.display="block";
document.getElementById("myscheduleDiv").style.display="block";
}else{
document.getElementById("loginDiv").style.display="block";
document.getElementById("siginDiv").style.display="block";
document.getElementById("loginForm").style.display="block";
document.getElementById("logoutForm").style.display="none";
document.getElementById("homeDiv").style.display="none";
document.getElementById("scheduleDiv").style.display="none";
document.getElementById("myscheduleDiv").style.display="none";
}
})
});<file_sep>// public/js/controllers/NerdCtrl.js
angular.module('RegisterCtrl', []).controller('RegisterController', function($scope) {
});<file_sep>// public/js/controllers/NerdCtrl.js
angular.module('MatchCtrl', []).controller('MatchController', function($scope, $http) {
$http.get('/api/matches').then(function(response){
$scope.matches = response.data;
})
});<file_sep>module.exports = {
url : 'mongodb://diego:diego@ds033259.mlab.com:33259/jogadb'
}<file_sep>FROM node:boron
RUN mkdir -p /usr/src/jogaBonito
WORKDIR /usr/src/jogaBonito
COPY package.json /usr/src/jogaBonito/
RUN npm install
COPY . /usr/src/jogaBonito
EXPOSE 8080
CMD [ "npm", "start" ]<file_sep># JogaBonito
## Author
<NAME>
## Application
This is an application created to manage and organize some matches with other people that maybe we don't know who they are. We just have to log in to the app and choose the time in which we are going to go to the match, and our position. Here we can see who else is going to the match, and we can modify or delete our schedule.
This app was developed in MEAN framework (MongoDB, Express, Angular and Node) with the intention of deploy it in a virtual machine, docker and a PaaS (Platform as a Service).
## Prerequisites
### nodejs
A JavaScript runtime environment. There are a lot of ways to install it, here I put the way I used on Centos 7:
* sudo yum install epel-release.
* sudo yum install nodejs.
* node --version (To check that the installation was succesful).
### npm
It is the package manager for javaScript. To install it on centos 7 you just need to type:
* sudo yum install npm
## Download and installation
It is necesary to open a shell and type "git clone https://github.com/jocamp18/JogaBonito.git" (In this case you should install git) or just downloading it from the github https://github.com/jocamp18/JogaBonito.
All the modules are located in node_modules folder, so there is nothing else to install.
## Execution
To execute the server you have to go to JogaBonito folder (cd JogaBonito) and type:
* node server.js
After this you can type in the web browser localhost:8080 and you will see the app working.
## Development
To develop the application it is necesary to install some modules with npm package manager, so you should type:
* sudo npm install express mongojs body-parser mongoose method-override cookie-parser express-session consolidate ejs --save
With the save flag, packages will appear in our dependencies. There is a file call package.json that says which packages we will need in our development.
Now we have installed tools for the backend, and for the frontend we just need bower (A frontend tool to manager the frontend resources):
* sudo npm install -g bower
With the g flag, we will have access to bower globally on the system.
To use bower we will need two files:
* .bowerrc: Here we will say where to place our files.
* bower.json: It will tell Bower which packages are needed (It is similar to package.json).
After making these files we type "bower install", and we will have all the needed packages in the specified directory.
## Deployment
### Heroku
The app has been deployed on heroku (A cloud platform based on a managed container system). The url is "https://jogabonito-project1.herokuapp.com/".
### Virtual Machine
To deploy the app here, we need to clone the repo into the virtual machine and run the server as I explained before. But first, we have to stop and disable the firewall in the virtual machine, the way to do it on centos 7 is:
* sudo systemctl disable firewalld
* sudo systemctl stop firewalld
Now we can open a web browser in our local machine and type the ip address of the guest Operating System and the port 8080. Example:
http://192.168.1.58:8080/
### Docker
To run the app in docker, we need to create a Dockerfile that is located in the same folder than server.js. After that, we have to run those commands:
* sudo docker build -t jogabonito .
* sudo docker run -p 8080:8080 -d jogabonito
Now, we can go to http://localhost:8080/ and there it will be executing our app. To stop it, we can use the command:
* sudo docker stop $(sudo docker ps -q -f "name=$1")
## Application Structure
```
.
├── config
│ ├── db.js
├── models
│ ├── match.js
│ ├── user.js
├── node_modules
├── public
│ ├── css
│ │ ├── style.css
│ ├── js
│ │ ├── controllers
│ │ │ ├── LoginCtrl.js
│ │ │ ├── MainCtrl.js
│ │ │ ├── MatchCtrl.js
│ │ │ ├── MyMatchesCtrl.js
│ │ │ ├── RegisterCtrl.js
│ │ ├── app.js
│ │ ├── appRoutes.js
│ ├── libs
│ ├── views
│ │ ├── home.html
│ │ ├── login.html
│ │ ├── matches.html
│ │ ├── myMatches.html
│ │ ├── register.html
│ ├── index.html
├── routes
│ ├── Match.js
│ ├── User.js
├── README.md
├── bower.json
├── package.json
├── server.js
```
## Folders
### config
Here will be located the config files that the "server.js" file need to call.
### models
This will be all that is required to create records in our database.
### node_modules
The dependences that our app need to work without problems.
### public
The frontend part of the app.
### routes
This is used to separate parts of our application in our Node backend.
## Note.
There are some missing validations, like duplicated values in the DB or confirm passwords, this is because it wasn't enough time to do it (One week and a half), but it will be available in the next version.<file_sep>// public/js/controllers/MainCtrl.js
angular.module('MainCtrl', []).controller('MainController', function($scope, $http) {
$scope.positions = ['Goalkeper','Defender','Midfielder','Forward'];
$scope.times = ['12:00 - 14:00','14:00 - 16:00','16:00 - 18:00','18:00 - 20:00', '20:00 - 22:00'];
$scope.today = new Date();
$scope.newMatch = function(){
$http.post('/newMatch/' + $scope.position).then(function(response){
window.location.href = response.data;
})
}
});<file_sep><div>
{{username}}
<table>
<tr>
<th> Username </th>
<th> Position </th>
<th> Date </th>
<th> Time </th>
</tr>
<tr ng-repeat="match in matches">
<td>{{ match.username}}</td>
<td>{{ match.position }}</td>
<td>{{ match.date }}</td>
<td>{{ match.time }}</td>
</tr>
</table>
</div><file_sep>// app/routes.js
// grab the nerd model we just created
/*var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('mongodb://jocamp18:<EMAIL>:33259/jogadb',['matches']);
router.get('/matches',function(req, res, next){
db.matches.find(function(err, matches){
if(err){
res.send(err);
}
res.json(matches);
})
});*/
var Match = require('../models/match');
var mongoose = require('mongoose');
var db = require('../config/db');
mongoose.connect(db.url);
module.exports = function(app) {
// server routes ===========================================================
// handle things like api calls
// authentication routes
var sess;
app.post('/newMatch', function(req, res){
sess = req.session;
var username = sess.username;
console.log(req.body.position);
var newMatch = new Match({
username: username,
position: req.body.position,
date : req.body.date,
time : req.body.time1
});
newMatch.save(function(err){
if(err) throw err;
res.redirect('/');
});
});
app.get('/myMatches', function(req, res){
sess = req.session;
var username = sess.username;
if(username){
Match.find({username: username}, function(err, matches){
if(err){
res.send(err);
}
res.json(matches);
})
}
})
// sample api route
app.get('/api/matches', function(req, res) {
// use mongoose to get all nerds in the database
Match.find({},function(err, docs) {
if (err)
res.send(err);
res.json(docs);
//res.render('index', {matches: docs}); // return all nerds in JSON format
});
});
app.post('/deleteMatch/:id', function(req, res) {
var id = req.params.id;
Match.findOneAndRemove({"_id": id}, function (err) {
if(err) throw err;
})
Match.find({},function(err, docs) {
if (err)
res.send(err);
res.json(docs);
//res.render('index', {matches: docs}); // return all nerds in JSON format
});
})
app.post('/update', function(req, res){
var id = req.body.identifier;
Match.findOneAndUpdate({"_id": id},{position: req.body.position, date: req.body.date, time: req.body.time1}, function (err, result) {
res.redirect('/');
})
})
app.get('/logout', function(req, res) {
req.session.destroy(function(err){
res.redirect('/');
})
});
app.get('/username', function(req, res){
res.send(sess.username);
})
app.get('/username', function(req, res){
res.send(sess.username);
})
// route to handle creating goes here (app.post)
// route to handle delete goes here (app.delete)
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('../public/index.html'); // load our public/index.html file
});
}; | 3d79e59ec4c4ac68d570f284e75347da5ce15193 | [
"Markdown",
"HTML",
"JavaScript",
"Dockerfile"
] | 10 | Markdown | jocamp18/joga | 05001c120bc17149435722fb0ff772daa9c417af | 82311714afdb47ab39a907219b2253938d7b907f |
refs/heads/master | <repo_name>KorhanK/sda2test<file_sep>/README.md
# sda2test
Just an example :)
| 9d15f17bc823f723b482ef4d8989e2b4a5aaba84 | [
"Markdown"
] | 1 | Markdown | KorhanK/sda2test | ab2df76c96bc03e7c9eeb2c0782ca5e2fa8f5f50 | cce26ecdc4eab1996f69595a6e194cf889a327ef |
refs/heads/master | <file_sep><div id="neckpix4">
<div style="padding-left:12px;">
<div id="MainContent">
<table><tr><td></td><td></td> <td></td><td></td><td></td></tr></table>
<div style="margin-top:20px;">
<div class="rightImage" id="Div7">
<a class="fancybox" rel="group" href="images/bidz/LB 100.JPG">
<img src="images/bidz/LB 100.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:170px;" id="Div8" >
<a class="fancybox" rel="group" href="images/bidz/LB 101.JPG">
<img src="images/bidz/LB 101.JPG" width="155px" height="150px" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:340px;" id="Div8">
<a class="fancybox" rel="group" href="images/bidz/LB 102.JPG">
<img src="images/bidz/LB 102.JPG" width="155px" height="150px" alt="LB 0131.JPG" title="LB 0131.JPG"/>
</a></div>
<div class="rightImage" style="margin-left:510px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 103.JPG">
<img src="images/bidz/LB 103.JPG" width="155px" height="150px" alt="LB 0132.JPG"/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 104.JPG">
<img src="images/bidz/LB 104.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:850px;" id="Div9">
<a class="fancybox" rel="group" href="images/bidz/LB 105.JPG">
<img src="images/bidz/LB 105.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" id="Div10" >
<a class="fancybox" rel="group" href="images/bidz/LB 106.JPG">
<img src="images/bidz/LB 106.JPG" width="155px" height="150px" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:1190px;" id="Div8" >
<a class="fancybox" rel="group" href="images/bidz/LB 071.JPG">
<img src="images/bidz/LB 071.JPG" width="155px" height="150px" alt=""/></a>
</div>
</div>
<div style="margin-top:180px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 072.JPG">
<img src="images/bidz/LB 072.JPG" width="155px" height="150px" alt="LB 0131.JPG" title="LB 0131.JPG"/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 073.JPG">
<img src="images/bidz/LB 073.JPG" width="155px" height="150px" alt="LB 0132.JPG"/>
</a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 074.JPG">
<img src="images/bidz/LB 074.JPG" width="155px" height="150px" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:510px;" id="Div9">
<a class="fancybox" rel="group" href="images/bidz/LB 075.JPG">
<img src="images/bidz/LB 075.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="Div10" >
<a class="fancybox" rel="group" href="images/bidz/LB 076.jpg">
<img src="images/bidz/LB 076.jpg" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:850px;" id="Div10">
<a class="fancybox" rel="group" href="images/bidz/LB 032.JPG">
<img src="images/bidz/LB 032.JPG" width="155px" height="150px" title="LB 032" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:1020px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 033.JPG">
<img src="images/bidz/LB 033.JPG" width="155px" height="150px" title="LB 033" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 034.JPG">
<img src="images/bidz/LB 034.JPG" width="155px" height="150px" title="LB 034" alt=""/>
</a>
</div>
</div>
<div style="margin-top:340px;">
<div class="rightImage" id="Div5">
<a class="fancybox" rel="group" href="images/bidz/LB 035.JPG">
<img src="images/bidz/LB 035.JPG" width="155px" height="150px" title="LB 035" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:170px;" id="Div6" >
<a class="fancybox" rel="group" href="images/bidz/LB 036.JPG">
<img src="images/bidz/LB 036.JPG" width="155px" height="150px" title="LB 036" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:340px;" id="Div6">
<a class="fancybox" rel="group" href="images/bidz/LB 042.JPG">
<img src="images/bidz/LB 042.JPG" width="155px" height="150px" alt="LB 042.JPG" title="LB 042"/>
</a></div>
<div class="rightImage" style="margin-left:510px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 043.JPG">
<img src="images/bidz/LB 043.JPG" width="155px" height="150px" alt="LB 043.JPG" title="LB 043"/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="Div8" >
<a class="fancybox" rel="group" href="images/bidz/LB 041.JPG">
<img src="images/bidz/LB 041.JPG" width="155px" height="150px" title="LB 041" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:850px;" id="Div8" >
<a class="fancybox" rel="group" href="images/bidz/LB 037.jpg">
<img src="images/bidz/LB 037.JPG" width="155px" height="150px" title="LB 037" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:1020px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 038.jpg">
<img src="images/bidz/LB 038.JPG" width="155px" height="150px" title="LB 038" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:1190px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 039.jpg">
<img src="images/bidz/LB 039.JPG" width="155px" height="150px" title="LB 039" alt=""/>
</a>
</div>
</div>
<div class="clear">
</div>
</div>
</div>
<div class="button_holder"> <table width="100%"><tr><td width="30%" ALIGN="center"><form><a href="#" class="previous" onClick="rshow(4);">Previous</a></form></td><td width="40%" ALIGN="center"><form><a href="index.html" class="previous" onClick="">Home</a></form></td><td width="30%" align="center"><form><a href="#" class="next" onClick="">Next</a></td></tr></table> </div>
</div><file_sep><div id="neckpix1">
<div style="padding-left:12px;">
<div id="MainContent">
<table><tr><td></td><td></td> <td></td><td></td><td></td></tr></table>
<div style="margin-top:20px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/016.JPG">
<img src="images/bidz/016.JPG" width="155px" height="150px" title="016" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 001.JPG">
<img src="images/bidz/LB 001.JPG" width="155px" height="150px" title="LB 001" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 002.JPG">
<img src="images/bidz/LB 002.JPG" width="155px" height="150px" title="LB 002" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:510px;" id="l1r3">
<a class="fancybox" rel="group" href="images/bidz/LB 003.JPG">
<img src="images/bidz/LB 003.JPG" width="155px" height="150px" title="LB 003" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="l1r4" >
<a class="fancybox" rel="group" href="images/bidz/LB 004.JPG">
<img src="images/bidz/LB 004.JPG" width="155px" height="150px" title="LB 004" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:850px;" id="Div10" >
<a class="fancybox" rel="group" href="images/bidz/LB 016.JPG">
<img src="images/bidz/LB 016.JPG" width="155px" height="150px" title="LB 016" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:1020px;" id="Div9">
<a class="fancybox" rel="group" href="images/bidz/LB 015.JPG">
<img src="images/bidz/LB 015.JPG" width="155px" height="150px" title="LB 015" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 014.JPG">
<img src="images/bidz/LB 014.JPG" width="155px" height="150px" title="LB 014" alt=""/></a>
</div>
</div>
<div style="margin-top:180px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 005.JPG">
<img src="images/bidz/LB 005.JPG" width="155px" height="150px" title="LB 005" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 006.JPG">
<img src="images/bidz/LB 006.JPG" width="155px" height="150px" title="LB 006" alt=""/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 007.JPG">
<img src="images/bidz/LB 007.JPG" width="155px" height="150px" title="LB 007" alt=""/></a></div>
<div class="rightImage" style="margin-left:510px;" id="Div1">
<a class="fancybox" rel="group" href="images/bidz/LB 008.JPG">
<img src="images/bidz/LB 008.JPG" width="155px" height="150px" title="LB 008" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;">
<a class="fancybox" rel="group" href="images/bidz/LB 009.JPG">
<img src="images/bidz/LB 009.JPG" width="155px" height="150px" title="LB 009" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:850px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 0131.JPG">
<img src="images/bidz/LB 0131.JPG" width="155px" height="150px" alt="LB 0131.JPG" title="LB 0131"/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 0132.JPG">
<img src="images/bidz/LB 0132.JPG" width="155px" height="150px" alt="LB 0132.JPG" title="/LB 0132"/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 0129.jpg">
<img src="images/bidz/LB 0129.jpg" width="155px" height="150px" title="LB 0129" alt=""/>
</a>
</div>
</div>
<div style="margin-top:340px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 010.JPG">
<img src="images/bidz/LB 010.JPG" width="155px" height="150px" title="LB 010" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 011.JPG">
<img src="images/bidz/LB 011.JPG" width="155px" height="150px" title="LB 011" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 012.JPG">
<img src="images/bidz/LB 012.JPG" width="155px" height="150px" title="LB 012" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:510px;" id="Div3">
<a class="fancybox" rel="group" href="images/bidz/LB 0120.JPG">
<img src="images/bidz/LB 0120.JPG" width="155px" height="150px" title="LB 0120" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="Div4" >
<a class="fancybox" rel="group" href="images/bidz/LB 0121.JPG">
<img src="images/bidz/LB 0121.JPG" width="155px" height="150px" title="LB 0121" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:850px;" id="Div7">
<a class="fancybox" rel="group" href="images/bidz/LB 013.JPG">
<img src="images/bidz/LB 013.JPG" width="155px" height="150px" title="LB 013" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" id="Div8" >
<a class="fancybox" rel="group" href="images/bidz/LB 0130.JPG">
<img src="images/bidz/LB 0130.JPG" width="155px" height="150px" title="LB 0130" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:1190px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 0128.jpg">
<img src="images/bidz/LB 0128.jpg" width="155px" height="150px" title="LB 0128" alt=""/>
</a>
</div>
</div>
<div class="clear">
</div>
</div>
</div>
<div class="button_holder"> <table width="100%"><tr><td width="30%"></td><td width="40%" ALIGN="center"><form><a href="index.html" class="previous" onClick="">Home</a></form></td><td width="30%" align="center"><form><a href="#" class="next" onclick="show(2);" >Next</a></form></td></tr></table> </div>
</div>
<file_sep><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Weaves</title>
<link rel="shortcut icon" href="images/icons/laramii_favicon.jpg"/>
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<!-- Add jQuery library -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- Add mousewheel plugin (this is optional) -->
<script type="text/javascript" src="/fancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<!-- Add fancyBox -->
<link rel="stylesheet" href="/fancybox/source/jquery.fancybox.css?v=2.1.4" type="text/css" media="screen" />
<script type="text/javascript" src="/fancybox/source/jquery.fancybox.pack.js?v=2.1.4"></script>
<!-- Optionally add helpers - button, thumbnail and/or media -->
<link rel="stylesheet" href="/fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" />
<script type="text/javascript" src="/fancybox/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script>
<script type="text/javascript" src="/fancybox/source/helpers/jquery.fancybox-media.js?v=1.0.5"></script>
<link rel="stylesheet" href="/fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" />
<script type="text/javascript" src="/fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
openEffect : 'elastic',
closeEffect : 'elastic'
});})
</script>
<script type="text/javascript">
function show(box) {
for (var i = 1; i <= 4; i++) {
document.getElementById('content_' + i).style.display = (i == box ? 'block' : 'none');
}
}
</script>
<style type="text/css">
.rightImage
{
float:left;
position:absolute;
/* box-shadow:2px -2px 10px 3px #888, inset 2px -2px 10px 3px #888; */
}
/*.rightImage:hover img
{
height: 300px;
/* z-index:1; */
/* width:320px;
box-shadow:4px -4px 10px 3px #888, inset 4px -4px 10px 3px #888;
} */
</style>
</head>
<!-- THIS IS THE BEGGINING OF THE BODY OF THE SITE -->
<body>
<div id="background">
<img src="images/pink_backgrnd.jpg" class="stretch" alt="" />
</div>
<div class="page">
<div class="header">
<div class="title">
<?php
include 'logo.php';
?>
</div>
<!-- Navigation Bar is located here -->
<table><tr><td></td>
<td></td> <td></td><td></td><td></td></tr></table>
<?php
include_once 'navbar.php';
?>
</div>
<div id="neckpix1">
<div style="padding-left:12px;">
<div id="MainContent">
<table><tr><td></td><td></td> <td></td><td></td><td></td></tr></table>
<div style="margin-top:40px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/Hairstyles/weavon.jpg">
<img src="images/Hairstyles/weavon.jpg" width="155px" height="150px" title="weaveon 1" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/Hairstyles/weavon1.jpg">
<img src="images/Hairstyles/weavon1.jpg" width="155px" height="150px" title="weaveon 2" alt=""/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/Hairstyles/weavon2.jpg">
<img src="images/Hairstyles/weavon2.jpg" width="155px" height="150px" title="weaveon 3" alt=""/></a></div>
<div class="rightImage" style="margin-left:510px;" id="l1r3">
<a class="fancybox" rel="group" href="images/Hairstyles/weavon3.jpg">
<img src="images/Hairstyles/weavon3.jpg" width="155px" height="150px" title="weaveon 4" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="l1r4" >
<a class="fancybox" rel="group" href="images/Hairstyles/weavon5.jpg">
<img src="images/Hairstyles/weavon5.jpg" width="155px" height="150px" title="weavon 5" alt=""/></a>
</div>
</div>
<div class="clear">
</div>
</div>
</div>
<div class="button_holder"> <table width="100%"><tr><td width="30%"></td><td width="40%"></td><td width="30%" align="center"><form><a href="#" class="next" onclick="show(2);" >Next</a></form></td></tr></table> </div>
</div>
<?php
include_once "footer.php";
?>
</div>
</body>
</html>
<file_sep><div id="neckpix3">
<div style="padding-left:12px;">
<div id="MainContent">
<table><tr><td></td><td></td> <td></td><td></td><td></td></tr></table>
<div style="margin-top:20px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 047.JPG">
<img src="images/bidz/LB 047.JPG" width="155px" height="150px" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 048.JPG">
<img src="images/bidz/LB 048.JPG" width="155px" height="150px" alt=""/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 049.JPG">
<img src="images/bidz/LB 049.JPG" width="155px" height="150px" alt=""/></a></div>
<div class="rightImage" style="margin-left:510px;" id="l1r3">
<a class="fancybox" rel="group" href="images/bidz/LB 050.JPG">
<img src="images/bidz/LB 050.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="l1r4" >
<a class="fancybox" rel="group" href="images/bidz/LB 051.JPG">
<img src="images/bidz/LB 051.JPG" width="155px" height="150px" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:850px;">
<a class="fancybox" rel="group" href="images/bidz/LB 052.JPG">
<img src="images/bidz/LB 052.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 053.JPG">
<img src="images/bidz/LB 053.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 054.JPG">
<img src="images/bidz/LB 054.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
</div>
<div style="margin-top:180px;">
<div class="rightImage" id="Div1">
<a class="fancybox" rel="group" href="images/bidz/LB 055.JPG">
<img src="images/bidz/LB 055.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:170px;">
<a class="fancybox" rel="group" href="images/bidz/LB 056.JPG">
<img src="images/bidz/LB 056.JPG" width="155px" height="150px" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:340px;">
<a class="fancybox" rel="group" href="images/bidz/LB 057.JPG">
<img src="images/bidz/LB 057.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:510px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 058.JPG">
<img src="images/bidz/LB 058.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 059.JPG">
<img src="images/bidz/LB 059.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:850px;" id="Div3">
<a class="fancybox" rel="group" href="images/bidz/LB 060.JPG">
<img src="images/bidz/LB 060.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" id="Div4" >
<a class="fancybox" rel="group" href="images/bidz/LB 061.JPG">
<img src="images/bidz/LB 061.JPG" width="155px" height="150px" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:1190px;" id="Div4">
<a class="fancybox" rel="group" href="images/bidz/LB 062.JPG">
<img src="images/bidz/LB 062.JPG" width="155px" height="150px" alt=""/>
</a></div>
</div>
<div style="margin-top:340px;">
<div class="rightImage" >
<a class="fancybox" rel="group" href="images/bidz/LB 063.JPG">
<img src="images/bidz/LB 063.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 064.JPG">
<img src="images/bidz/LB 064.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:340px;" id="Div5">
<a class="fancybox" rel="group" href="images/bidz/LB 065.JPG">
<img src="images/bidz/LB 065.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:510px;" id="Div6" >
<a class="fancybox" rel="group" href="images/bidz/LB 066.JPG">
<img src="images/bidz/LB 066.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="Div6" >
<a class="fancybox" rel="group" href="images/bidz/LB 067.jpg">
<img src="images/bidz/LB 067.JPG" width="155px" height="150px" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:850px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 068.jpg">
<img src="images/bidz/LB 068.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 069.jpg">
<img src="images/bidz/LB 069.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" id="Div7">
<a class="fancybox" rel="group" href="images/bidz/LB 070.JPG">
<img src="images/bidz/LB 070.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
</div>
<div class="clear">
</div>
</div>
</div>
<div class="button_holder"> <table width="100%"><tr><td width="30%" ALIGN="center"><form><a href="#" class="previous" onClick="rshow(2);">Previous</a></form></td><td width="40%" ALIGN="center"><form><a href="index.html" class="previous" onClick="">Home</a></form></td><td width="30%" align="center"><form><a href="#" class="next" onclick="show(4);">Next</a></form></td></tr></table> </div>
</div>
<file_sep><div id="neckpix1">
<div style="padding-left:12px;">
<div id="MainContent">
<table><tr><td></td><td></td> <td></td><td></td><td></td></tr></table>
<div style="margin-top:20px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse1.jpg">
<img src="images/FashionClothes/skirtnblouse1.jpg" width="155px" height="200px" title="" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse2.jpg">
<img src="images/FashionClothes/skirtnblouse2.jpg" width="155px" height="200px" title="" alt=""/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse3.jpg">
<img src="images/FashionClothes/skirtnblouse3.jpg" width="155px" height="200px" title="" alt=""/></a></div>
<div class="rightImage" style="margin-left:510px;" id="l1r3">
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse4.jpg">
<img src="images/FashionClothes/skirtnblouse4.jpg" width="155px" height="200px" title="" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="l1r4" >
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse5.jpg">
<img src="images/FashionClothes/skirtnblouse5.jpg" width="155px" height="200px" title="LB 004" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:850px;" >
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse13.jpg">
<img src="images/FashionClothes/skirtnblouse13.jpg" width="155px" height="200px" title="LB 014" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" id="Div9">
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse14.jpg">
<img src="images/FashionClothes/skirtnblouse14.jpg" width="155px" height="200px" title="LB 015" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" id="Div10" >
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse15.jpg">
<img src="images/FashionClothes/skirtnblouse15.jpg" width="155px" height="200px" title="LB 016" alt=""/></a>
</div>
</div>
<div style="margin-top:230px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse6.jpg">
<img src="images/FashionClothes/skirtnblouse6.jpg" width="155px" height="200px" title="LB 005" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse7.jpg">
<img src="images/FashionClothes/skirtnblouse7.jpg" width="155px" height="200px" title="LB 006" alt=""/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse8.jpg">
<img src="images/FashionClothes/skirtnblouse8.jpg" width="155px" height="200px" title="LB 007" alt=""/></a></div>
<div class="rightImage" style="margin-left:510px;" id="Div1">
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse9.jpg">
<img src="images/FashionClothes/skirtnblouse9.jpg" width="155px" height="200px" title="LB 008" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;">
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse10.jpg">
<img src="images/FashionClothes/skirtnblouse10.jpg" width="155px" height="200px" title="LB 009" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:850px;">
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse11.jpg">
<img src="images/FashionClothes/skirtnblouse11.jpg" width="155px" height="200px" alt="LB 0131.JPG" title="LB 0131"/>
</a></div>
<div class="rightImage" style="margin-left:1020px;" >
<a class="fancybox" rel="group" href="images/FashionClothes/skirtnblouse12.jpg">
<img src="images/FashionClothes/skirtnblouse12.jpg" width="155px" height="200px" alt="LB 0132.JPG" title="LB 0132"/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" id="Div6" >
<a class="fancybox" rel="group" href="images/FashionClothes/dress_11.jpg">
<img src="images/FashionClothes/dress_11.jpg" width="155px" height="200px" title="LB 0126" alt=""/>
</a>
</div>
</div>
<div style="margin-top:440px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/FashionClothes/dress_12.jpg">
<img src="images/FashionClothes/dress_12.jpg" width="155px" height="200px" title="LB 010" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/FashionClothes/dress_3.jpg">
<img src="images/FashionClothes/dress_3.jpg" width="155px" height="200px" title="LB 011" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/FashionClothes/dress_4.jpg">
<img src="images/FashionClothes/dress_4.jpg" width="155px" height="200px" title="LB 012" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:510px;" id="Div3">
<a class="fancybox" rel="group" href="images/FashionClothes/dress_5.jpg">
<img src="images/FashionClothes/dress_5.jpg" width="155px" height="200px" title="LB 0120" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="Div4" >
<a class="fancybox" rel="group" href="images/FashionClothes/dress_6.jpg">
<img src="images/FashionClothes/dress_6.jpg" width="155px" height="200px" title="LB 0121" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:850px;">
<a class="fancybox" rel="group" href="images/FashionClothes/dress_7.jpg">
<img src="images/FashionClothes/dress_7.jpg" width="155px" height="200px" title="LB 0122" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" >
<a class="fancybox" rel="group" href="images/FashionClothes/dress_1.jpg">
<img src="images/FashionClothes/dress_1.jpg" width="155px" height="200px" title="LB 0123" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" >
<a class="fancybox" rel="group" href="images/FashionClothes/dress_9.jpg">
<img src="images/FashionClothes/dress_9.jpg" width="155px" height="200px" title="LB 0124" alt=""/>
</a>
</div>
</div>
<div class="clear">
</div>
</div>
</div>
<div class="button_holder"> <table width="100%"><tr><td width="30%"></td><td width="40%"></td><td width="30%" align="center"><form><a href="#" class="next" onclick="show(2);" >Next</a></form></td></tr></table> </div>
</div>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Skirts and Blouses</title>
<link rel="shortcut icon" href="images/laramii_favicon.jpg" type="image/x-icon"/>
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<!-- Apple iOS icons -->
<!—- iPhone 57x57 -->
<link rel=" apple-touch-icon-precomposed" href="images/laramii_favicon.jpg" />
<!—- iPad 72x72 -->
<link rel=" apple-touch-icon-precomposed" href="images/laramii_favicon.jpg" sizes="72x72" />
<!—- iPhone Retina Display 114x114 -->
<link rel=" apple-touch-icon-precomposed" href="images/laramii_favicon.jpg" sizes="114x114" />
<!—- iPad Retina Display 144x144 -->
<link rel=" apple-touch-icon-precomposed" href="images/laramii_favicon.jpg" sizes="144x144" />
<style type="text/css">
body{background-color:#400000; padding-top:3%;
padding-bottom: 0;}
#mainbody{margin: 0 auto;
width:1367px;
/* width:87%;*/
height:670px;
max-height:680px;
padding-left:5px;
padding-right:5px;
/* display: table-cell; */
background-color:#FFF}
.next, .previous { color:white;
font-family:"Comic Sans MS", cursive;
font-size:16px;
text-decoration:none;}
.rightImage
{
float:left;
position:absolute;
/* box-shadow:2px -2px 10px 3px #888, inset 2px -2px 10px 3px #888; */
}
a.tablin:active{
color: yellow;
}
a.tablin:link{
text-decoration:none;
color: #FFF;
padding-left:15px;
}
header{margin-left:5%; vertical-align: top; text-align: left; color:white; font-family:"Comic Sans MS", cursive; font-size:3em; }
.motto{margin-left:6%; vertical-align: top; text-align: left; color:white; font-family:"Comic Sans MS", cursive; font-size:1em;}
footer{ text-align: center; font-size:0.75em; color:white;bottom: 0; height: 100px; margin-top:100px; vertical-align: bottom; }
</style>
</head>
<!-- THIS IS THE BEGGINING OF THE BODY OF THE SITE -->
<body onLoad="MM_preloadImages('images/fontbeadshad.png')">
<header>
Laramii
</header>
<div class="motto">...giving you the best</div><br/>
<div role="tabpanel">
<!-- Nav tabs -->
<ul style="width:87%; padding-left:5px; margin: 0 auto; padding-bottom: 5px; margin-bottom:2%; ">
<li class="active" style="display:inline; ">
<a href="#home" class="tab" style="text-decoration:none; color:#400000 ; padding-left:5px;">
<div style="width: 100px; border-radius:20px; background: #FFF;padding: 5px 10px; float:left; text-align:center; ">African Design</div>
</a>
</li>
<li style="display:inline;">
<a class="tablin" href="#profile" style="text-decoration:none; color:#FFF; ">
<div style="width: 100px; border-radius:20px; background:#FF0000; ; padding: 5px 10px; float:left; text-align:center; margin-left:10px; clear: right;">African Cap</div>
</a>
</li>
</ul>
</div>
<div id="mainbody">
<!-- <div class="page"> -->
<div id="content_box">
<div id="content_1"><?php include 'skirtsnblouses1.php'; ?> </div>
<div id="content_2" style="display: none;"><?php include 'skirtsnblouses2.php'; ?></div>
</div>
</div>
<footer>
<p>Copyright© 2013 Laramii.com. All Right Reserved.</p>
</footer>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- Add mousewheel plugin (this is optional) -->
<script type="text/javascript" src="fancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<!-- Add fancyBox -->
<link rel="stylesheet" href="fancybox/source/jquery.fancybox.css?v=2.1.4" type="text/css" media="screen" />
<script type="text/javascript" src="fancybox/source/jquery.fancybox.pack.js?v=2.1.4"></script>
<!-- Optionally add helpers - button, thumbnail and/or media -->
<link rel="stylesheet" href="fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" />
<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script>
<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-media.js?v=1.0.5"></script>
<link rel="stylesheet" href="fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" />
<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
openEffect : 'elastic',
closeEffect : 'elastic'
});})
</script>
<script type="text/javascript">
function show(box) {
for (var i = 1; i <= 4; i++) {
document.getElementById('content_' + i).style.display = (i == box ? 'block' : 'none');
}
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
openEffect : 'elastic',
closeEffect : 'elastic'
});})
</script>
<script type="text/javascript">
function breadcrumbs($separator = ' » ', $home = 'Home') {
$path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
$base_url = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
$breadcrumbs = array("<a href=\"$base_url\">$home</a>");
$last = end(array_keys($path));
foreach ($path AS $x => $crumb) {
$title = ucwords(str_replace(array('.php', '_'), Array('', ' '), $crumb));
if ($x != $last){
$breadcrumbs[] = '<a href="$base_url$crumb">$title</a>';
}else{
$breadcrumbs[] = $title;
}
}
<nobr><a id="FALINK_3_0_2" class="FAtxtL" href="#">return</a></nobr> implode($separator, $breadcrumbs);
}
</script>
<script type="text/javascript">
function rshow(box) {
for (var i = 4; i >= 1; i--) {
document.getElementById('content_' + i).style.display = (i == box ? 'block' : 'none');
}
}
</script>
</body>
</html>
<file_sep><div id="neckpix4">
<div style="padding-left:12px;">
<div id="MainContent">
<table><tr><td></td><td></td> <td></td><td></td><td></td></tr></table>
<div style="margin-top:20px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 077 .JPG">
<img src="images/bidz/LB 077 .JPG" width="155px" height="150px" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 078.jpg">
<img src="images/bidz/LB 078.jpg" width="155px" height="150px" alt=""/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 079.JPG">
<img src="images/bidz/LB 079.JPG" width="155px" height="150px" alt=""/></a></div>
<div class="rightImage" style="margin-left:510px;" id="l1r3">
<a class="fancybox" rel="group" href="images/bidz/LB 080.JPG">
<img src="images/bidz/LB 080.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="l1r4" >
<a class="fancybox" rel="group" href="images/bidz/LB 081.jpg">
<img src="images/bidz/LB 081.jpg" width="155px" height="150px" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:850px;" id="l1r4" >
<a class="fancybox" rel="group" href="images/bidz/LB 082.JPG">
<img src="images/bidz/LB 082.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 083.JPG">
<img src="images/bidz/LB 083.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 084.JPG">
<img src="images/bidz/LB 084.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
</div>
<div style="margin-top:180px;">
<div class="rightImage" id="Div1">
<a class="fancybox" rel="group" href="images/bidz/LB 085.JPG">
<img src="images/bidz/LB 085.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:170px;">
<a class="fancybox" rel="group" href="images/bidz/LB 086.JPG">
<img src="images/bidz/LB 086.JPG" width="155px" height="150px" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 087.JPG">
<img src="images/bidz/LB 087.JPG" width="155px" height="150px" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:510px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 088.JPG">
<img src="images/bidz/LB 088.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 089.JPG">
<img src="images/bidz/LB 089.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:850px;" id="Div3">
<a class="fancybox" rel="group" href="images/bidz/LB 090.JPG">
<img src="images/bidz/LB 090.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" id="Div4" >
<a class="fancybox" rel="group" href="images/bidz/LB 091.JPG">
<img src="images/bidz/LB 091.JPG" width="155px" height="150px" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:1190px;" id="Div4" >
<a class="fancybox" rel="group" href="images/bidz/LB 092.JPG">
<img src="images/bidz/LB 092.JPG" width="155px" height="150px" alt=""/>
</a></div>
</div>
<div style="margin-top:340px;">
<div class="rightImage" >
<a class="fancybox" rel="group" href="images/bidz/LB 093.JPG">
<img src="images/bidz/LB 093.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 094.JPG">
<img src="images/bidz/LB 094.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:340px;" id="Div5">
<a class="fancybox" rel="group" href="images/bidz/LB 095.JPG">
<img src="images/bidz/LB 095.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:510px;" id="Div6" >
<a class="fancybox" rel="group" href="images/bidz/LB 096.JPG">
<img src="images/bidz/LB 096.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="Div6">
<a class="fancybox" rel="group" href="images/bidz/LB 097.JPG">
<img src="images/bidz/LB 097.JPG" width="155px" height="150px" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:850px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 098.JPG">
<img src="images/bidz/LB 098.JPG" width="155px" height="150px" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:1020px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 099.JPG">
<img src="images/bidz/LB 099.JPG" width="155px" height="150px" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" id="Div7">
<a class="fancybox" rel="group" href="images/bidz/LB 040.JPG">
<img src="images/bidz/LB 040.JPG" width="155px" height="150px" title="LB 040" alt=""/>
</a>
</div>
</div>
<div class="clear">
</div>
</div>
</div>
<div class="button_holder"> <table width="100%"><tr><td width="30%" ALIGN="center"><form><a href="#" class="previous" onClick="rshow(3);">Previous</a></form></td><td width="40%" ALIGN="center"><form><a href="index.html" class="previous" onClick="">Home</a></form></td><td width="30%" align="center"><form><a href="#" class="next" onClick="show(5);">Next</a></td></tr></table> </div>
</div><file_sep><div id="neckpix2">
<div style="padding-left:12px;">
<div id="MainContent">
<table><tr><td></td><td></td> <td></td><td></td><td></td></tr></table>
<div style="margin-top:20px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 017.JPG">
<img src="images/bidz/LB 017.JPG" width="155px" height="150px" title="LB 017" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 018.JPG">
<img src="images/bidz/LB 018.JPG" width="155px" height="150px" title="LB 018" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 019.JPG">
<img src="images/bidz/LB 019.JPG" width="155px" height="150px" title="LB 019" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:510px;" id="l1r3">
<a class="fancybox" rel="group" href="images/bidz/LB 020.JPG">
<img src="images/bidz/LB 020.JPG" width="155px" height="150px" title="LB 020" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="l1r4" >
<a class="fancybox" rel="group" href="images/bidz/LB 021.JPG">
<img src="images/bidz/LB 021.JPG" width="155px" height="150px" title="LB 021" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:850px;" id="l1r4">
<a class="fancybox" rel="group" href="images/bidz/LB 0127.jpg">
<img src="images/bidz/LB 0127.jpg" width="155px" height="150px" title="LB 0127" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" id="Div6" >
<a class="fancybox" rel="group" href="images/bidz/LB 0126.JPG">
<img src="images/bidz/LB 0126.JPG" width="155px" height="150px" title="LB 0126" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" id="Div5">
<a class="fancybox" rel="group" href="images/bidz/LB 0125.JPG">
<img src="images/bidz/LB 0125.JPG" width="155px" height="150px" title="LB 0125" alt=""/>
</a>
</div>
</div>
<div style="margin-top:180px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 022.JPG">
<img src="images/bidz/LB 022.JPG" width="155px" height="150px" title="LB 022" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 023.JPG">
<img src="images/bidz/LB 023.JPG" width="155px" height="150px" title="LB 023" alt=""/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 024.JPG">
<img src="images/bidz/LB 024.JPG" width="155px" height="150px" title="LB 024" alt=""/></a></div>
<div class="rightImage" style="margin-left:510px;" id="Div1">
<a class="fancybox" rel="group" href="images/bidz/LB 025.JPG">
<img src="images/bidz/LB 025.JPG" width="155px" height="150px" title="LB 025" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;">
<a class="fancybox" rel="group" href="images/bidz/LB 026.JPG">
<img src="images/bidz/LB 026.JPG" width="155px" height="150px" title="LB 026" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:850px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 0124.JPG">
<img src="images/bidz/LB 0124.JPG" width="155px" height="150px" title="LB 0124" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 0123.JPG">
<img src="images/bidz/LB 0123.JPG" width="155px" height="150px" title="LB 0123" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;">
<a class="fancybox" rel="group" href="images/bidz/LB 0122.JPG">
<img src="images/bidz/LB 0122.JPG" width="155px" height="150px" title="LB 0122" alt=""/>
</a></div>
</div>
<div style="margin-top:340px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 027.JPG">
<img src="images/bidz/LB 027.JPG" width="155px" height="150px" title="LB 027" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 028.JPG">
<img src="images/bidz/LB 028.JPG" width="155px" height="150px" title="LB 028" alt=""/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 029.JPG">
<img src="images/bidz/LB 029.JPG" width="155px" height="150px" title="LB 029" alt=""/></a></div>
<div class="rightImage" style="margin-left:510px;" id="Div3">
<a class="fancybox" rel="group" href="images/bidz/LB 030.JPG">
<img src="images/bidz/LB 030.JPG" width="155px" height="150px" title="LB 030" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="Div4" >
<a class="fancybox" rel="group" href="images/bidz/LB 031.JPG">
<img src="images/bidz/LB 031.JPG" width="155px" height="150px" title="LB 031" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:850px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 044.JPG">
<img src="images/bidz/LB 044.JPG" width="155px" height="150px" alt="" title="LB 044"/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" id="Div9">
<a class="fancybox" rel="group" href="images/bidz/LB 045.JPG">
<img src="images/bidz/LB 045.JPG" width="155px" height="150px" alt="" title="LB 045"/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" id="Div10" >
<a class="fancybox" rel="group" href="images/bidz/LB 046.JPG">
<img src="images/bidz/LB 046.JPG" width="155px" height="150px" alt="" title="LB 046"/></a>
</div>
</div>
<div class="clear">
</div>
</div>
</div>
<div class="button_holder"> <table width="100%"><tr><td width="30%" ALIGN="center"><form><a href="#" class="previous" onClick="rshow(1);">Previous</a></form></td><td width="40%" ALIGN="center"><form><a href="index.html" class="previous" onClick="">Home</a></form></td><td width="30%" align="center"><form><a href="#" class="next" onclick="show(3);">Next</a></form></td></tr></table> </div>
</div>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Necklaces And Earings</title>
<link rel="shortcut icon" href="images/laramii_favicon.jpg" type="image/x-icon"/>
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<!-- Apple iOS icons -->
<!—- iPhone 57x57 -->
<link rel=" apple-touch-icon-precomposed" href="images/laramii_favicon.jpg" />
<!—- iPad 72x72 -->
<link rel=" apple-touch-icon-precomposed" href="images/laramii_favicon.jpg" sizes="72x72" />
<!—- iPhone Retina Display 114x114 -->
<link rel=" apple-touch-icon-precomposed" href="images/laramii_favicon.jpg" sizes="114x114" />
<!—- iPad Retina Display 144x144 -->
<link rel=" apple-touch-icon-precomposed" href="images/laramii_favicon.jpg" sizes="144x144" />
<style type="text/css">
body{background-color:#400000; padding-top:3%;
padding-bottom: 0;}
#mainbody{margin: 0 auto;
width:87%;
height:520px;
max-height:520px;
padding-left:5px;
padding-right:5px;
clear:both;
/* display: table-cell; */
background-color:#FFF}
.next, .previous { color:white;
font-family:"Comic Sans MS", cursive;
font-size:16px;
text-decoration:none;}
.rightImage
{
float:left;
position:absolute;
/*width:11.2%;
padding-left:2%;*/
/* box-shadow:2px -2px 10px 3px #888, inset 2px -2px 10px 3px #888; */
}
header{margin-left:5%; vertical-align: top; text-align: left; color:white; font-family:"Comic Sans MS", cursive; font-size:3em; }
.motto{margin-left:6%; vertical-align: top; text-align: left; color:white; font-family:"Comic Sans MS", cursive; font-size:1em;}
footer{ text-align: center; font-size:0.75em; color:white; bottom: 0; margin-top:100px; vertical-align: bottom; position:relative; clear:both;}
</style>
</head>
<!-- THIS IS THE BEGGINING OF THE BODY OF THE SITE -->
<body>
<header>
Laramii
</header>
<div class="motto">...giving you the best</div><br/>
<div id="mainbody">
<!-- <div class="page"> -->
<div id="content_box">
<div id="content_1"><?php include 'NecklacesnEarings1.php'; ?> </div>
<div id="content_2" style="display: none;"><?php include 'NecklacesnEarings2.php'; ?></div>
<div id="content_3" style="display: none;"><?php include 'NecklacesnEarings3.php'; ?></div>
<div id="content_4" style="display: none;"><?php include 'NecklacesnEarings4.php'; ?></div>
<div id="content_5" style="display: none;"><?php include 'NecklacesnEarings5.php'; ?></div>
</div>
</div>
<footer>
<p>Copyright© 2013 Laramii.com. All Right Reserved.</p>
<!--<div class="copyright">
</div>
-->
</footer>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- Add mousewheel plugin (this is optional) -->
<script type="text/javascript" src="fancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<!-- Add fancyBox -->
<link rel="stylesheet" href="fancybox/source/jquery.fancybox.css?v=2.1.4" type="text/css" media="screen" />
<script type="text/javascript" src="fancybox/source/jquery.fancybox.pack.js?v=2.1.4"></script>
<!-- Optionally add helpers - button, thumbnail and/or media -->
<link rel="stylesheet" href="fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" />
<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script>
<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-media.js?v=1.0.5"></script>
<link rel="stylesheet" href="fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" />
<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
openEffect : 'elastic',
closeEffect : 'elastic'
});})
</script>
<script type="text/javascript">
function show(box) {
for (var i = 1; i <= 5; i++) {
document.getElementById('content_' + i).style.display = (i == box ? 'block' : 'none');
}
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
openEffect : 'elastic',
closeEffect : 'elastic'
});})
</script>
<script type="text/javascript">
function breadcrumbs($separator = ' » ', $home = 'Home') {
$path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
$base_url = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
$breadcrumbs = array("<a href=\"$base_url\">$home</a>");
$last = end(array_keys($path));
foreach ($path AS $x => $crumb) {
$title = ucwords(str_replace(array('.php', '_'), Array('', ' '), $crumb));
if ($x != $last){
$breadcrumbs[] = '<a href="$base_url$crumb">$title</a>';
}else{
$breadcrumbs[] = $title;
}
}
<nobr><a id="FALINK_3_0_2" class="FAtxtL" href="#">return</a></nobr> implode($separator, $breadcrumbs);
}
</script>
<script type="text/javascript">
function rshow(box) {
for (var i = 5; i >= 1; i--) {
document.getElementById('content_' + i).style.display = (i == box ? 'block' : 'none');
}
}
</script>
</body>
</html>
<file_sep><div id="neckpix2" >
<div style="padding-left:12px;">
<div id="MainContent">
<table><tr><td></td><td></td> <td></td><td></td><td></td></tr></table>
<div style="margin-top:40px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 017.JPG">
<img src="images/bidz/LB 017.JPG" width="155px" height="150px" title="LB 017" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 018.JPG">
<img src="images/bidz/LB 018.JPG" width="155px" height="150px" title="LB 018" alt=""/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 019.JPG">
<img src="images/bidz/LB 019.JPG" width="155px" height="150px" title="LB 019" alt=""/></a></div>
<div class="rightImage" style="margin-left:510px;" id="l1r3">
<a class="fancybox" rel="group" href="images/bidz/LB 020.JPG">
<img src="images/bidz/LB 020.JPG" width="155px" height="150px" title="LB 020" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="l1r4" >
<a class="fancybox" rel="group" href="images/bidz/LB 021.JPG">
<img src="images/bidz/LB 021.JPG" width="155px" height="150px" title="LB 021" alt=""/></a>
</div>
</div>
<div style="margin-top:200px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 022.JPG">
<img src="images/bidz/LB 022.JPG" width="155px" height="150px" title="LB 022" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 023.JPG">
<img src="images/bidz/LB 023.JPG" width="155px" height="150px" title="LB 023" alt=""/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 024.JPG">
<img src="images/bidz/LB 024.JPG" width="155px" height="150px" title="LB 024" alt=""/></a></div>
<div class="rightImage" style="margin-left:510px;" id="Div1">
<a class="fancybox" rel="group" href="images/bidz/LB 025.JPG">
<img src="images/bidz/LB 025.JPG" width="155px" height="150px" title="LB 025" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;">
<a class="fancybox" rel="group" href="images/bidz/LB 026.JPG">
<img src="images/bidz/LB 026.JPG" width="155px" height="150px" title="LB 026" alt=""/></a>
</div>
</div>
<div style="margin-top:360px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 027.JPG">
<img src="images/bidz/LB 027.JPG" width="155px" height="150px" title="LB 027" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 028.JPG">
<img src="images/bidz/LB 028.JPG" width="155px" height="150px" title="LB 028" alt=""/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 029.JPG">
<img src="images/bidz/LB 029.JPG" width="155px" height="150px" title="LB 029" alt=""/></a></div>
<div class="rightImage" style="margin-left:510px;" id="Div3">
<a class="fancybox" rel="group" href="images/bidz/LB 030.JPG">
<img src="images/bidz/LB 030.JPG" width="155px" height="150px" title="LB 030" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="Div4" >
<a class="fancybox" rel="group" href="images/bidz/LB 031.JPG">
<img src="images/bidz/LB 031.JPG" width="155px" height="150px" title="LB 031" alt=""/></a>
</div>
</div>
<div style="margin-top:520px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 032.JPG">
<img src="images/bidz/LB 032.JPG" width="155px" height="150px" title="LB 032" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 033.JPG">
<img src="images/bidz/LB 033.JPG" width="155px" height="150px" title="LB 033" alt=""/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 034.JPG">
<img src="images/bidz/LB 034.JPG" width="155px" height="150px" title="LB 034" alt=""/></a></div>
<div class="rightImage" style="margin-left:510px;" id="Div5">
<a class="fancybox" rel="group" href="images/bidz/LB 035.JPG">
<img src="images/bidz/LB 035.JPG" width="155px" height="150px" title="LB 035" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="Div6" >
<a class="fancybox" rel="group" href="images/bidz/LB 036.JPG">
<img src="images/bidz/LB 036.JPG" width="155px" height="150px" title="LB 036" alt=""/></a>
</div>
</div>
<div style="margin-top:680px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 037.jpg">
<img src="images/bidz/LB 037.JPG" width="155px" height="150px" title="LB 037" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 038.jpg">
<img src="images/bidz/LB 038.JPG" width="155px" height="150px" title="LB 038" alt=""/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 039.jpg">
<img src="images/bidz/LB 039.JPG" width="155px" height="150px" title="LB 039" alt=""/></a></div>
<div class="rightImage" style="margin-left:510px;" id="Div7">
<a class="fancybox" rel="group" href="images/bidz/LB 040.JPG">
<img src="images/bidz/LB 040.JPG" width="155px" height="150px" title="LB 040" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="Div8" >
<a class="fancybox" rel="group" href="images/bidz/LB 041.JPG">
<img src="images/bidz/LB 041.JPG" width="155px" height="150px" title="LB 041" alt=""/></a>
</div>
</div>
<div style="margin-top:840px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/bidz/LB 042.JPG">
<img src="images/bidz/LB 042.JPG" width="155px" height="150px" alt="LB 042.JPG" title="LB 042"/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 043.JPG">
<img src="images/bidz/LB 043.JPG" width="155px" height="150px" alt="LB 043.JPG" title="LB 043"/></a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/bidz/LB 044.JPG">
<img src="images/bidz/LB 044.JPG" width="155px" height="150px" alt="" title="LB 044"/></a></div>
<div class="rightImage" style="margin-left:510px;" id="Div9">
<a class="fancybox" rel="group" href="images/bidz/LB 045.JPG">
<img src="images/bidz/LB 045.JPG" width="155px" height="150px" alt="" title="LB 045"/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="Div10" >
<a class="fancybox" rel="group" href="images/bidz/LB 046.JPG">
<img src="images/bidz/LB 046.JPG" width="155px" height="150px" alt="" title="LB 046"/></a>
</div>
</div>
<div style="margin-top:670px;">
<div class="rightImage" id="Div5">
<a class="fancybox" rel="group" href="images/FashionClothes/dress_10.jpg">
<img src="images/FashionClothes/dress_10.jpg" width="155px" height="200px" title="LB 0125" alt=""/>
</a>
</div>
</div>
<div class="clear">
</div>
</div>
</div>
<div class="button_holder"> <table width="100%"><tr><td width="30%" ALIGN="center"><form><a href="#" class="previous" onClick="rshow(1);">Previous</a></form></td><td width="40%"></td><td width="30%" align="center"><form><a href="#" class="next" onclick="show(3);">Next</a></form></td></tr></table> </div>
</div>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Necklaces Jewelry</title>
<link rel="shortcut icon" href="images/laramii_favicon.jpg" type="image/x-icon"/>
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<!-- Apple iOS icons -->
<!—- iPhone 57x57 -->
<link rel=" apple-touch-icon-precomposed" href="images/laramii_favicon.jpg" />
<!—- iPad 72x72 -->
<link rel=" apple-touch-icon-precomposed" href="images/laramii_favicon.jpg" sizes="72x72" />
<!—- iPhone Retina Display 114x114 -->
<link rel=" apple-touch-icon-precomposed" href="images/laramii_favicon.jpg" sizes="114x114" />
<!—- iPad Retina Display 144x144 -->
<link rel=" apple-touch-icon-precomposed" href="images/laramii_favicon.jpg" sizes="144x144" />
<script type="text/javascript" src="/fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
openEffect : 'elastic',
closeEffect : 'elastic'
});})
</script>
<script type="text/javascript">
function show(box) {
for (var i = 1; i <= 4; i++) {
document.getElementById('content_' + i).style.display = (i == box ? 'block' : 'none');
}
}
</script>
<style type="text/css">
body{background-color:#400000; padding-top:3%;
padding-bottom: 0;}
#mainbody{margin: 0 auto;
width:87%;
height:370px;
max-height:480px;
padding-left:5px;
padding-right:5px;
/* display: table-cell; */
background-color:#FFF}
.next, .previous { color:white;
font-family:"Comic Sans MS", cursive;
font-size:16px;
text-decoration:none;}
.rightImage
{
float:left;
position:absolute;
/* box-shadow:2px -2px 10px 3px #888, inset 2px -2px 10px 3px #888; */
}
header{margin-left:5%; vertical-align: top; text-align: left; color:white; font-family:"Comic Sans MS", cursive; font-size:3em; }
.motto{margin-left:6%; vertical-align: top; text-align: left; color:white; font-family:"Comic Sans MS", cursive; font-size:1em;}
footer{ text-align: center; font-size:0.75em; color:white;bottom: 0; height: 100px; vertical-align: bottom; }
</style>
</head>
<!-- THIS IS THE BEGGINING OF THE BODY OF THE SITE -->
<body>
<header>
Laramii
</header>
<div class="motto">...giving you the best</div><br/>
<div id="mainbody">
<!-- <div class="page"> -->
<div id="content_box">
<div id="content_1">
<div id="neckpix1">
<div style="padding-left:12px;">
<div id="MainContent">
<table><tr><td></td><td></td> <td></td><td></td><td></td></tr></table>
<div style="margin-top:20px;">
<div class="rightImage">
<a class="fancybox" rel="group" href="images/Jewelry/necklaces1.jpg">
<img src="images/Jewelry/necklaces1.jpg" width="155px" height="150px" title="016" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:170px;" >
<a class="fancybox" rel="group" href="images/Jewelry/necklaces2.jpg">
<img src="images/Jewelry/necklaces2.jpg" width="155px" height="150px" title="LB 001" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/Jewelry/necklaces3.jpg">
<img src="images/Jewelry/necklaces3.jpg" width="155px" height="150px" title="LB 002" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:510px;" id="l1r3">
<a class="fancybox" rel="group" href="images/Jewelry/necklaces4.jpg">
<img src="images/Jewelry/necklaces4.jpg" width="155px" height="150px" title="LB 003" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="l1r4" >
<a class="fancybox" rel="group" href="images/Jewelry/necklaces5.jpg">
<img src="images/Jewelry/necklaces5.jpg" width="155px" height="150px" title="LB 004" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:850px;" >
<a class="fancybox" rel="group" href="images/Jewelry/earings1.jpg">
<img src="images/Jewelry/earings1.jpg" width="155px" height="150px" title="016" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" >
<a class="fancybox" rel="group" href="images/Jewelry/earings2.jpg">
<img src="images/Jewelry/earings2.jpg" width="155px" height="150px" title="LB 001" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" >
<a class="fancybox" rel="group" href="images/Jewelry/earings3.jpg">
<img src="images/Jewelry/earings3.jpg" width="155px" height="150px" title="LB 002" alt=""/>
</a>
</div>
</div>
<div style="margin-top:180px;">
<div class="rightImage" id="l1r3">
<a class="fancybox" rel="group" href="images/Jewelry/earings4.jpg">
<img src="images/Jewelry/earings4.jpg" width="155px" height="150px" title="LB 003" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:170px;" id="l1r4" >
<a class="fancybox" rel="group" href="images/Jewelry/earings5.jpg">
<img src="images/Jewelry/earings5.jpg" width="155px" height="150px" title="LB 004" alt=""/></a>
</div>
<div class="rightImage" style="margin-left:340px;" >
<a class="fancybox" rel="group" href="images/Jewelry/pendant1.jpg">
<img src="images/Jewelry/pendant1.jpg" width="155px" height="150px" title="LB 002" alt=""/>
</a></div>
<div class="rightImage" style="margin-left:510px;" id="l1r3">
<a class="fancybox" rel="group" href="images/Jewelry/pendant2.jpg">
<img src="images/Jewelry/pendant2.jpg" width="155px" height="150px" title="LB 003" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:680px;" id="l1r4" >
<a class="fancybox" rel="group" href="images/Jewelry/pendant3.jpg">
<img src="images/Jewelry/pendant3.jpg" width="155px" height="150px" title="LB 004" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:850px;" id="l1r3">
<a class="fancybox" rel="group" href="images/Jewelry/pendant4.jpg">
<img src="images/Jewelry/pendant4.jpg" width="155px" height="150px" title="LB 003" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1020px;" id="l1r4" >
<a class="fancybox" rel="group" href="images/Jewelry/pendant5.jpg">
<img src="images/Jewelry/pendant5.jpg" width="155px" height="150px" title="LB 004" alt=""/>
</a>
</div>
<div class="rightImage" style="margin-left:1190px;" id="l1r4" >
<a class="fancybox" rel="group" href="images/Jewelry/pendant6.jpg">
<img src="images/Jewelry/pendant6.jpg" width="155px" height="150px" title="LB 004" alt=""/>
</a>
</div>
</div>
<div class="clear">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="button_holder"> <table width="100%"><tr><td width="30%"></td><td width="40%"></td><td width="30%" align="center"><form><a href="#" class="next" onClick="show(2);" >Next</a></form></td></tr></table> </div>
</div>
</div>
<footer>
<p>Copyright© 2013 Laramii.com. All Right Reserved.</p>
</footer>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- Add mousewheel plugin (this is optional) -->
<script type="text/javascript" src="fancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<!-- Add fancyBox -->
<link rel="stylesheet" href="fancybox/source/jquery.fancybox.css?v=2.1.4" type="text/css" media="screen" />
<script type="text/javascript" src="fancybox/source/jquery.fancybox.pack.js?v=2.1.4"></script>
<!-- Optionally add helpers - button, thumbnail and/or media -->
<link rel="stylesheet" href="fancybox/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" />
<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script>
<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-media.js?v=1.0.5"></script>
<link rel="stylesheet" href="fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" />
<script type="text/javascript" src="fancybox/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
openEffect : 'elastic',
closeEffect : 'elastic'
});})
</script>
<script type="text/javascript">
function show(box) {
for (var i = 1; i <= 4; i++) {
document.getElementById('content_' + i).style.display = (i == box ? 'block' : 'none');
}
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
openEffect : 'elastic',
closeEffect : 'elastic'
});})
</script>
<script type="text/javascript">
function breadcrumbs($separator = ' » ', $home = 'Home') {
$path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
$base_url = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
$breadcrumbs = array("<a href=\"$base_url\">$home</a>");
$last = end(array_keys($path));
foreach ($path AS $x => $crumb) {
$title = ucwords(str_replace(array('.php', '_'), Array('', ' '), $crumb));
if ($x != $last){
$breadcrumbs[] = '<a href="$base_url$crumb">$title</a>';
}else{
$breadcrumbs[] = $title;
}
}
<nobr><a id="FALINK_3_0_2" class="FAtxtL" href="#">return</a></nobr> implode($separator, $breadcrumbs);
}
</script>
<script type="text/javascript">
function rshow(box) {
for (var i = 4; i >= 1; i--) {
document.getElementById('content_' + i).style.display = (i == box ? 'block' : 'none');
}
}
</script>
</body>
</html>
| df81a62bf94dd8a7d785b3cf07e2febd1e97954d | [
"Hack",
"PHP"
] | 11 | Hack | lazio1760/laramii | 974468f6a900395fe10a2bd9c875f1758856aa54 | 72c08db558405a348ae3060477eca085865548cf |
refs/heads/master | <repo_name>trevorba16/2020_1<file_sep>/os/project3/userprog/syscall.c
#include "userprog/syscall.h"
#include <stdio.h>
#include <syscall-nr.h>
#include "threads/interrupt.h"
#include "threads/thread.h"
#include "threads/vaddr.h"
typedef int pid_t;
//TODO Rename
struct proc_file
{
struct file* ptr;
int fd;
struct list_elem elem;
};
void (*syscall_handlers[20])(struct intr_frame *);
void* check_addr(const void *vaddr);
struct proc_file* list_search(struct list* files, int fd);
static void syscall_handler (struct intr_frame *f);
void sys_halt(struct intr_frame* f);
void sys_exit(struct intr_frame* f);
void sys_exec(struct intr_frame* f);
void sys_wait(struct intr_frame* f);
void sys_create(struct intr_frame* f);
void sys_remove(struct intr_frame* f);
void sys_open(struct intr_frame* f);
void sys_filesize(struct intr_frame* f);
void sys_read(struct intr_frame* f);
void sys_write(struct intr_frame* f);
void sys_seek(struct intr_frame* f);
void sys_tell(struct intr_frame* f);
void sys_close(struct intr_frame* f);
void halt();
void exit(int status);
int exec(char *filename);
int wait(pid_t pid);
bool create(const char *file, unsigned size);
bool remove(const char *file);
int open(const char *file);
int filesize(int fd);
int read(int fd, void *buffer, unsigned size);
int write(int fd, void* buffer, unsigned size);
void seek(int fd, int position);
unsigned tell(int fd);
void close(int fd);
void
syscall_init (void)
{
intr_register_int (0x30, 3, INTR_ON, syscall_handler, "syscall"); //registering handler for TRAP
syscall_handlers[SYS_HALT] = &sys_halt;
syscall_handlers[SYS_EXIT] = &sys_exit;
syscall_handlers[SYS_EXEC] = &sys_exec;
syscall_handlers[SYS_WAIT] = &sys_wait;
syscall_handlers[SYS_CREATE] = &sys_create;
syscall_handlers[SYS_REMOVE] = &sys_remove;
syscall_handlers[SYS_OPEN] = &sys_open;
syscall_handlers[SYS_FILESIZE] = &sys_filesize;
syscall_handlers[SYS_READ] = &sys_read;
syscall_handlers[SYS_WRITE] = &sys_write;
syscall_handlers[SYS_SEEK] = &sys_seek;
syscall_handlers[SYS_TELL] = &sys_tell;
syscall_handlers[SYS_CLOSE] = &sys_close;
}
void sys_halt(struct intr_frame* f)
{
shutdown_power_off();
};
void sys_exit(struct intr_frame* f)
{
uint32_t arg1;
uint32_t *user_esp = f->esp;
user_esp++;
check_addr(user_esp);
arg1 = (uint32_t)(*user_esp);
exit(arg1);
};
void sys_exec(struct intr_frame* f)
{
uint32_t arg1;
uint32_t *user_esp = f->esp;
user_esp++;
check_addr(user_esp);
arg1 = (uint32_t)(*user_esp);
check_addr(arg1);
f->eax = exec(arg1);
};
void sys_wait(struct intr_frame* f)
{
uint32_t arg1;
uint32_t *user_esp = f->esp;
user_esp++;
check_addr(user_esp);
arg1 = (uint32_t)(*user_esp);
f->eax = process_wait(arg1);
};
void sys_create(struct intr_frame* f)
{
uint32_t arg1, arg2;
uint32_t *user_esp = f->esp;
user_esp++;
check_addr(user_esp);
arg1 = (uint32_t)(*user_esp);
user_esp++;
check_addr(user_esp);
arg2 = (uint32_t)(*user_esp);
check_addr(arg1);
file_lock_acquire();
f->eax = filesys_create(arg1,arg2);
file_lock_release();
};
void sys_remove(struct intr_frame* f)
{
uint32_t arg1;
uint32_t *user_esp = f->esp;
user_esp++;
check_addr(user_esp);
arg1 = (uint32_t)(*user_esp);
file_lock_acquire();
f->eax = (filesys_remove(arg1) != NULL);
file_lock_release();
};
void sys_open(struct intr_frame* f)
{
uint32_t arg1;
uint32_t *user_esp = f->esp;
user_esp++;
check_addr(user_esp);
arg1 = (uint32_t)(*user_esp);
check_addr(arg1);
struct file* fptr;
file_lock_acquire();
fptr = filesys_open(arg1);
file_lock_release();
if (fptr == NULL)
{
f->eax = -1;
}
else
{
struct proc_file *pfile = malloc(sizeof(*pfile));
pfile->ptr = fptr;
pfile->fd = thread_current()->fd_count;
thread_current()->fd_count++;
list_push_back(&thread_current()->files, &pfile->elem);
f->eax = pfile->fd;
}
};
void sys_filesize(struct intr_frame* f)
{
uint32_t arg1;
uint32_t *user_esp = f->esp;
user_esp++;
check_addr(user_esp);
arg1 = (uint32_t)(*user_esp);
struct proc_file* file_result = list_search(&thread_current()->files, arg1);
file_lock_acquire();
f->eax = file_length(file_result->ptr);
file_lock_release();
};
void sys_read(struct intr_frame* f)
{
uint32_t arg1, arg2, arg3;
uint32_t *user_esp = f->esp;
user_esp++;
check_addr(user_esp);
arg1 = (uint32_t)(*user_esp);
user_esp++;
check_addr(user_esp);
arg2 = (uint32_t)(*user_esp);
check_addr(arg2);
user_esp++;
check_addr(user_esp);
arg3 = (uint32_t)(*user_esp);
file_lock_acquire();
f->eax = read((int)arg1, (char *)arg2, (unsigned)arg3);
file_lock_release();
};
void sys_write(struct intr_frame* f)
{
uint32_t arg1, arg2, arg3;
uint32_t *user_esp = f->esp;
user_esp++;
check_addr(user_esp);
arg1 = (uint32_t)(*user_esp);
user_esp++;
check_addr(user_esp);
arg2 = (uint32_t)(*user_esp);
check_addr(arg2);
user_esp++;
check_addr(user_esp);
arg3 = (uint32_t)(*user_esp);
file_lock_acquire();
f->eax = write((int)arg1, (char *)arg2, (unsigned)arg3);
file_lock_release();
};
void sys_seek(struct intr_frame* f)
{
uint32_t arg1, arg2;
uint32_t *user_esp = f->esp;
user_esp++;
check_addr(user_esp);
arg1 = (uint32_t)(*user_esp);
user_esp++;
check_addr(user_esp);
arg2 = (uint32_t)(*user_esp);
file_lock_acquire();
file_seek(list_search(&thread_current()->files, arg1)->ptr, arg2);
file_lock_release();
};
void sys_tell(struct intr_frame* f)
{
uint32_t arg1;
uint32_t *user_esp = f->esp;
user_esp++;
check_addr(user_esp);
arg1 = (uint32_t)(*user_esp);
file_lock_acquire();
f->eax = file_tell(list_search(&thread_current()->files, arg1)->ptr);
file_lock_release();
};
void sys_close(struct intr_frame* f)
{
uint32_t arg1;
uint32_t *user_esp = f->esp;
user_esp++;
check_addr(user_esp);
arg1 = (uint32_t)(*user_esp);
close(arg1);
};
static void
syscall_handler (struct intr_frame *f UNUSED)
{
check_addr(f->esp);
int callNo = * (int *)f->esp;
syscall_handlers[callNo](f);
}
int exec (char *filename)
{
file_lock_acquire();
int namelen = strlen(filename);
char *filename_copy = malloc(namelen + 1);
strlcpy(filename_copy, filename, namelen + 1);
char *filename_string;
filename_copy = strtok_r(filename_copy, " ", &filename_string);
struct file* f = filesys_open(filename_copy);
if (f == NULL)
{
file_lock_release();
return -1;
}
else
{
file_close(f);
file_lock_release();
return process_execute(filename);
}
}
int write (int fd, void *buffer, unsigned size)
{
if (fd == 1)
{
putbuf(buffer, size);
return size;
}
else
{
struct proc_file* fptr = list_search(&thread_current()->files, fd);
if (fptr == NULL)
{
return -1;
}
else
{
int ret = file_write(fptr->ptr, buffer, size);
return ret;
}
}
}
int read(int fd, void*buffer, unsigned size)
{
if (fd == 0)
{
for (int i = 0; i < size; i++)
{
buffer = input_getc();
}
return size;
}
else
{
struct proc_file* fptr = list_search(&thread_current()->files, fd);
if (fptr == NULL)
{
return -1;
}
else
{
return file_read(fptr->ptr, buffer, size);
}
}
}
void close(int fd)
{
struct list_elem *e;
struct list* files = &thread_current()->files;
for (e = list_begin(files); e != list_end(files); e = list_next(e))
{
struct proc_file *f = list_entry(e, struct proc_file, elem);
if(f->fd == fd)
{
file_close(f->ptr);
list_remove(e);
}
}
}
void exit(int status)
{
struct list_elem *e;
struct thread *curthread = thread_current();
for (e = list_begin (&curthread->parent->children); e != list_end (&thread_current()->parent->children);
e = list_next (e))
{
struct child_thread *chld = list_entry (e, struct child_thread, elem);
if(chld->tid == curthread->tid)
{
chld->used = true;
chld->exit_status = status;
}
}
curthread->exit_status = status;
lock_acquire(&curthread->parent->child_lock);
if(curthread->parent->wait_for_thread == curthread->tid)
{
cond_signal(&curthread->parent->child_condition,&curthread->parent->child_lock);
}
lock_release(&curthread->parent->child_lock);
printf("%s: exit(%d)\n", curthread->name, status);
thread_exit();
// struct thread *curthread = thread_current();
// curthread->exit_status = status;
// thread_current()->parent->ex = true;
// printf("%s: exit(%d)\n", curthread->name, status);
// thread_exit();
}
//TODO
void* check_addr(const void *vaddr)
{
if (!is_user_vaddr(vaddr))
{
exit(-1);
return 0;
}
void *ptr = pagedir_get_page(thread_current()->pagedir, vaddr);
if (!ptr)
{
exit(-1);
return 0;
}
return ptr;
}
//TODO
struct proc_file* list_search(struct list* files, int fd)
{
struct list_elem *e;
for (e = list_begin (files); e != list_end (files);
e = list_next (e))
{
struct proc_file *f = list_entry (e, struct proc_file, elem);
if(f->fd == fd)
return f;
}
return NULL;
}
void close_all_files(struct list* files)
{
struct list_elem *e;
for (e = list_begin (files); e != list_end (files); e = list_next (e))
{
struct proc_file *f = list_entry (e, struct proc_file, elem);
file_close(f->ptr);
list_remove(e);
}
}
/*
System Call: void halt (void)
Terminates Pintos by calling shutdown_power_off() (declared in "threads/init.h"). This should be seldom used, because you lose some information about possible deadlock situations, etc.
System Call: void exit (int status)
Terminates the current user program, returning status to the kernel. If the process's parent waits for it (see below), this is the status that will be returned. Conventionally, a status of 0 indicates success and nonzero values indicate errors.
System Call: pid_t exec (const char *cmd_line)
Runs the executable whose name is given in cmd_line, passing any given arguments, and returns the new process's program id (pid). Must return pid -1, which otherwise should not be a valid pid, if the program cannot load or run for any reason. Thus, the parent process cannot return from the exec until it knows whether the child process successfully loaded its executable. You must use appropriate synchronization to ensure this.
System Call: int wait (pid_t pid)
Waits for a child process pid and retrieves the child's exit status.
If pid is still alive, waits until it terminates. Then, returns the status that pid passed to exit. If pid did not call exit(), but was terminated by the kernel (e.g. killed due to an exception), wait(pid) must return -1. It is perfectly legal for a parent process to wait for child processes that have already terminated by the time the parent calls wait, but the kernel must still allow the parent to retrieve its child's exit status, or learn that the child was terminated by the kernel.
wait must fail and return -1 immediately if any of the following conditions is true:
pid does not refer to a direct child of the calling process. pid is a direct child of the calling process if and only if the calling process received pid as a return value from a successful call to exec.
Note that children are not inherited: if A spawns child B and B spawns child process C, then A cannot wait for C, even if B is dead. A call to wait(C) by process A must fail. Similarly, orphaned processes are not assigned to a new parent if their parent process exits before they do.
The process that calls wait has already called wait on pid. That is, a process may wait for any given child at most once.
Processes may spawn any number of children, wait for them in any order, and may even exit without having waited for some or all of their children. Your design should consider all the ways in which waits can occur. All of a process's resources, including its struct thread, must be freed whether its parent ever waits for it or not, and regardless of whether the child exits before or after its parent.
You must ensure that Pintos does not terminate until the initial process exits. The supplied Pintos code tries to do this by calling process_wait() (in "userprog/process.c") from main() (in "threads/init.c"). We suggest that you implement process_wait() according to the comment at the top of the function and then implement the wait system call in terms of process_wait().
Implementing this system call requires considerably more work than any of the rest.
System Call: bool create (const char *file, unsigned initial_size)
Creates a new file called file initially initial_size bytes in size. Returns true if successful, false otherwise. Creating a new file does not open it: opening the new file is a separate operation which would require a open system call.
System Call: bool remove (const char *file)
Deletes the file called file. Returns true if successful, false otherwise. A file may be removed regardless of whether it is open or closed, and removing an open file does not close it. See Removing an Open File, for details.
System Call: int open (const char *file)
Opens the file called file. Returns a nonnegative integer handle called a "file descriptor" (fd), or -1 if the file could not be opened.
File descriptors numbered 0 and 1 are reserved for the console: fd 0 (STDIN_FILENO) is standard input, fd 1 (STDOUT_FILENO) is standard output. The open system call will never return either of these file descriptors, which are valid as system call arguments only as explicitly described below.
Each process has an independent set of file descriptors. File descriptors are not inherited by child processes.
When a single file is opened more than once, whether by a single process or different processes, each open returns a new file descriptor. Different file descriptors for a single file are closed independently in separate calls to close and they do not share a file position.
System Call: int filesize (int fd)
Returns the size, in bytes, of the file open as fd.
System Call: int read (int fd, void *buffer, unsigned size)
Reads size bytes from the file open as fd into buffer. Returns the number of bytes actually read (0 at end of file), or -1 if the file could not be read (due to a condition other than end of file). Fd 0 reads from the keyboard using input_getc().
System Call: int write (int fd, const void *buffer, unsigned size)
Writes size bytes from buffer to the open file fd. Returns the number of bytes actually written, which may be less than size if some bytes could not be written.
Writing past end-of-file would normally extend the file, but file growth is not implemented by the basic file system. The expected behavior is to write as many bytes as possible up to end-of-file and return the actual number written, or 0 if no bytes could be written at all.
Fd 1 writes to the console. Your code to write to the console should write all of buffer in one call to putbuf(), at least as long as size is not bigger than a few hundred bytes. (It is reasonable to break up larger buffers.) Otherwise, lines of text output by different processes may end up interleaved on the console, confusing both human readers and our grading scripts.
System Call: void seek (int fd, unsigned position)
Changes the next byte to be read or written in open file fd to position, expressed in bytes from the beginning of the file. (Thus, a position of 0 is the file's start.)
A seek past the current end of a file is not an error. A later read obtains 0 bytes, indicating end of file. A later write extends the file, filling any unwritten gap with zeros. (However, in Pintos files have a fixed length until project 4 is complete, so writes past end of file will return an error.) These semantics are implemented in the file system and do not require any special effort in system call implementation.
System Call: unsigned tell (int fd)
Returns the position of the next byte to be read or written in open file fd, expressed in bytes from the beginning of the file.
System Call: void close (int fd)
Closes file descriptor fd. Exiting or terminating a process implicitly closes all its open file descriptors, as if by calling this function for each one.
*/<file_sep>/os/yashd/yashd.c
/**
* @file TCPServer-ex2.c
* @brief The program creates a TCP socket in
* the inet domain and listens for connections from TCPClients, accept clients
* into private sockets, and fork an echo process to ``serve'' the
* client. If [port] is not specified, the program uses any available
* port.
* Run as:
* TCPServer-ex2 <port>
*/
/*
NAME:
SYNOPSIS: TCPServer [port]
DESCRIPTION:
*/
#include <stdio.h>
/* socket(), bind(), recv, send */
#include <sys/types.h>
#include <sys/socket.h> /* sockaddr_in */
#include <netinet/in.h> /* inet_addr() */
#include <arpa/inet.h>
#include <sys/un.h>
#include <netdb.h> /* struct hostent */
#include <string.h> /* memset() */
#include <unistd.h> /* close() */
#include <stdlib.h> /* exit() */
#include <pthread.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/wait.h>
#include "server_thread.h"
#include <sys/stat.h>
#include <sys/file.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#define MAXHOSTNAME 80
#define NUM_THREADS 20
#define BUFSIZE 2000
#define PATHMAX 255
#pragma region STRUCTS
struct client_state
{
int in_use;
int running_pid;
int * pid_point;
struct job job_array[20];
};
typedef struct _client_thread_data
{
int psd;
int state_array_idx;
struct sockaddr_in from;
char * inString;
} client_thread_data;
typedef struct _job_thread_data
{
int state_array_idx;
int psd;
} job_thread_data;
typedef struct _recv_thread_data
{
int psd;
int state_array_idx;
struct sockaddr_in from;
} recv_thread_data;
#pragma endregion
#pragma region GLOBAL VARIABLES
struct client_state client_array[NUM_THREADS];
pthread_t client_thr[NUM_THREADS];
client_thread_data client_thr_data[NUM_THREADS];
pthread_mutex_t client_array_lock = PTHREAD_MUTEX_INITIALIZER;
recv_thread_data rtd[NUM_THREADS];
job_thread_data jtd[NUM_THREADS];
static char u_server_path[PATHMAX+1] = "/tmp"; /* default */
static char u_socket_path[PATHMAX+1];
static char u_log_path[PATHMAX+1];
static char u_pid_path[PATHMAX+1];
FILE * log_file;
#pragma endregion
#pragma region FUNCTION DECLARATIONS
int current_thread;
void reusePort(int sock);
void * ServeClient(void * arg);
void cleanup(char *buf);
void * StartJobsFromInput(void * arg);
void * ReceiveUserInput(void * arg);
int getOpenClientIndex();
void initializeClientArray();
int getLastProcess(int client_array_idx);
void daemon_init(const char * const path, uint mask);
#pragma endregion
#pragma region INITIALIZATION AND MEMORY
void initializeClientArray()
{
for (int i = 0; i < NUM_THREADS; i++)
{
client_array[i].in_use = 0;
initializeJobs(client_array[i].job_array);
}
}
void cleanup(char *buf)
{
int i;
for(i=0; i<BUFSIZE; i++) buf[i]='\0';
}
void reusePort(int s)
{
int one=1;
if ( setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *) &one,sizeof(one)) == -1 )
{
printf("error in setsockopt,SO_REUSEPORT \n");
exit(-1);
}
}
#pragma endregion
int main(int argc, char **argv ) {
int sd, psd;
struct sockaddr_in server;
struct hostent *hp, *gethostbyname();
struct sockaddr_in from;
int fromlen;
int length;
char ThisHost[80];
int pn;
current_thread = 0;
#pragma region DAEMONIZE
int listenfd;
/* Initialize path variables */
if (argc > 1)
strncpy(u_server_path, argv[1], PATHMAX); /* use argv[1] */
strncat(u_server_path, "/", PATHMAX-strlen(u_server_path));
strncat(u_server_path, argv[0], PATHMAX-strlen(u_server_path));
strcpy(u_socket_path, u_server_path);
strcpy(u_pid_path, u_server_path);
strncat(u_pid_path, ".pid", PATHMAX-strlen(u_pid_path));
strcpy(u_log_path, u_server_path);
strncat(u_log_path, ".log", PATHMAX-strlen(u_log_path));
daemon_init(u_server_path, 0); /* We stay in the u_server_path directory and file
creation is not restricted. */
#pragma endregion
#pragma region CONNECTION
/* get TCPServer1 Host information, NAME and INET ADDRESS */
gethostname(ThisHost, MAXHOSTNAME);
if ( (hp = gethostbyname(ThisHost)) == NULL ) {
fprintf(stderr, "Can't find host %s\n", argv[1]);
exit(-1);
}
bcopy ( hp->h_addr, &(server.sin_addr), hp->h_length);
/** Construct name of socket */
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
if (argc == 1)
server.sin_port = htons(3826);
else {
pn = htons(3826);
server.sin_port = pn;
}
/** Create socket on which to send and receive */
sd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sd<0) {
perror("opening stream socket");
exit(-1);
}
/** this allow the server to re-start quickly instead of waiting
for TIME_WAIT which can be as large as 2 minutes */
reusePort(sd);
if ( bind( sd, (struct sockaddr *) &server, sizeof(server) ) < 0 ) {
close(sd);
perror("binding name to stream socket");
exit(-1);
}
/** get port information and prints it out */
length = sizeof(server);
if ( getsockname (sd, (struct sockaddr *)&server,&length) ) {
perror("getting socket name");
exit(0);
}
#pragma endregion
/** accept TCP connections from clients and fork a process to serve each */
listen(sd,4);
fromlen = sizeof(from);
for(;;)
{
current_thread = getOpenClientIndex();
psd = accept(sd, (struct sockaddr *)&from, &fromlen);
client_thr_data[current_thread].from = from;
client_thr_data[current_thread].psd = psd;
client_thr_data[current_thread].state_array_idx = current_thread;
pthread_create(&client_thr[current_thread], NULL, ServeClient, &client_thr_data[current_thread]);
}
}
int getOpenClientIndex()
{
for (int i = 0; i < NUM_THREADS; i++)
{
if (client_array[i].in_use == 0)
return i;
}
}
static void sig_child(int signo)
{
pid_t pid;
int status;
for (int c = 0; c < NUM_THREADS; c++)
{
for (int i = 0; i < 20; i++)
{
if (client_array[c].job_array[i].job_order != -1 && client_array[c].job_array[i].run_status == 1 && client_array[c].job_array[i].is_background == 1)
{
pid = waitpid(client_array[c].job_array[i].pid, &status, WNOHANG | WUNTRACED);
if (WIFEXITED(status))
{
client_array[c].job_array[i].run_status = 2;
}
}
}
}
}
#pragma region CLIENT HANDLING
void * ServeClient(void * arg) {
client_thread_data *client_info = (client_thread_data *) arg;
pthread_t job_thread;
pthread_t recv_thread;
struct hostent *hp, *gethostbyname();
char inString[2000] = {0};
client_thr_data[client_info->state_array_idx].inString = inString;
client_array[client_info->state_array_idx].running_pid = -1;
client_array[client_info->state_array_idx].pid_point = &client_array[client_info->state_array_idx].running_pid;
if (signal(SIGCHLD, sig_child) == SIG_ERR)
printf("signal(SIGCHLD) error");
initializeJobs(client_array[client_info->state_array_idx].job_array);
if ((hp = gethostbyaddr((char *)&client_info->from.sin_addr.s_addr,
sizeof(client_info->from.sin_addr.s_addr),AF_INET)) == NULL)
{
fprintf(stderr, "Can't find host %s\n", inet_ntoa(client_info->from.sin_addr));
}
else
{
}
char * hash = "# ";
if (send(client_info->psd, hash, 2, 0) <0 )
perror("Couldn't send initial prompt");
struct sockaddr_in from = client_info->from;
int psd = client_info->psd;
int array_idx = client_info->state_array_idx;
/** get data from client and send it back */
jtd[array_idx].state_array_idx = array_idx;
jtd[array_idx].psd = psd;
pthread_create(&job_thread, NULL, StartJobsFromInput, &jtd[array_idx]);
rtd[array_idx].from = from;
rtd[array_idx].state_array_idx = array_idx;
rtd[array_idx].psd = psd;
pthread_create(&recv_thread, NULL, ReceiveUserInput, &rtd[array_idx]);
}
#pragma endregion
#pragma region START PROCESS
void * StartJobsFromInput(void * arg)
{
job_thread_data *thread_info = (job_thread_data *) arg;
int array_idx = thread_info->state_array_idx;
char process_output[BUFSIZE] = {0};
for (;;)
{
pthread_mutex_lock(&client_array_lock);
char c = client_thr_data[array_idx].inString[0];
pthread_mutex_unlock(&client_array_lock);
if (c == '\0')
{
}
else
{
int hours, minutes, seconds, day, month, year;
time_t now;
time(&now);
struct tm *local = localtime(&now);
hours = local->tm_hour; // get hours since midnight (0-23)
minutes = local->tm_min; // get minutes passed after the hour (0-59)
seconds = local->tm_sec; // get seconds passed after minute (0-59)
day = local->tm_mday; // get day of month (1 to 31)
month = local->tm_mon + 1; // get month of year (0 to 11)
year = local->tm_year + 1900; // get year since 1900
char mon[4] = {0};
mon[0] = ctime(&now)[4];
mon[1] = ctime(&now)[5];
mon[2] = ctime(&now)[6];
mon[3] = '\0';
log_file = fopen(u_log_path, "aw");
fprintf(log_file, "%s %d %02d:%02d:%02d yashd[%s:%d]: %s\n",
mon, day, hours, minutes, seconds,
inet_ntoa(client_thr_data[array_idx].from.sin_addr), ntohs(client_thr_data[array_idx].from.sin_port),
client_thr_data[array_idx].inString);
fclose(log_file);
processStarter(client_thr_data[array_idx].inString, client_array[thread_info->state_array_idx].job_array, process_output, client_array[array_idx].pid_point);
pthread_mutex_lock(&client_array_lock);
cleanup(client_thr_data[array_idx].inString);
pthread_mutex_unlock(&client_array_lock);
// printf("%d\n", 23);
int output_size = 0;
strcat(process_output, "\n# ");
for (int i = 0; i < sizeof(process_output); i++)
{
if (process_output[i] == '\0')
{
output_size = i;
break;
}
}
if (send(thread_info->psd, process_output, output_size, 0) <0 )
perror("sending stream message");
cleanup(process_output);
}
}
}
#pragma endregion
#pragma region RECEIVE INPUT
void * ReceiveUserInput(void * arg)
{
recv_thread_data * thread_info = (recv_thread_data *) arg;
int array_idx = thread_info->state_array_idx;
int rc = -1;
char buf[BUFSIZE];
int psd = thread_info->psd;
struct hostent *hp, *gethostbyname();
if ((hp = gethostbyaddr((char *)&thread_info->from.sin_addr.s_addr,
sizeof(thread_info->from.sin_addr.s_addr),AF_INET)) == NULL)
{
fprintf(stderr, "Can't find host %s\n", inet_ntoa(thread_info->from.sin_addr));
}
else
{
}
for(;;){
if( (rc=recv(psd, buf, sizeof(buf), 0)) < 0){
perror("receiving stream message");
exit(-1);
}
if (rc > 0){
pthread_mutex_lock(&client_array_lock);
if (buf[4] == '\n')
{
client_thr_data[array_idx].inString[0] = '\n';
client_thr_data[array_idx].inString[1] = '\0';
}
else if (buf[0] == 'C' && buf[1] == 'M' && buf[2] == 'D')
{
buf[rc - 1]='\0';
int c = 0;
while (c < rc) {
client_thr_data[array_idx].inString[c] = buf[4+c];
c++;
}
client_thr_data[array_idx].inString[c] = '\0';
}
else if (buf[0] == 'C' && buf[1] == 'T' && buf[2] == 'L')
{
buf[rc - 1]='\0';
if (buf[4] == 'C')
{
if (client_array[array_idx].running_pid != 0)
{
kill(client_array[array_idx].running_pid, SIGINT);
client_array[array_idx].running_pid = 0;
int kill_job_idx = -1;
for (int i = 0; i < 20; i++)
{
if (client_array[array_idx].job_array[kill_job_idx].pid == client_array[array_idx].running_pid)
kill_job_idx = i;
}
if (kill_job_idx != -1)
{
memset(job_array[kill_job_idx].args, 0, 2000);
client_array[array_idx].job_array[kill_job_idx].job_order = -1;
client_array[array_idx].job_array[kill_job_idx].pid = -1;
client_array[array_idx].job_array[kill_job_idx].run_status = -1;
client_array[array_idx].job_array[kill_job_idx].is_background = -1;
}
}
else
{
client_thr_data[array_idx].inString[0] = ' ';
}
client_thr_data[array_idx].inString[1] = '\0';
}
else if (buf[4] == 'Z')
{
if (client_array[array_idx].running_pid != 0)
{
kill(client_array[array_idx].running_pid, SIGTSTP);
client_array[array_idx].running_pid = 0;
}
}
else if (buf[4] == 'D')
{
exit(0);
}
}
pthread_mutex_unlock(&client_array_lock);
rc = 0;
cleanup(buf);
}
else {
}
}
}
int getLastProcess(int client_array_idx)
{
int max_process = -1;
int max_job_order = -1;
int max_index = -1;
for (int i = 0; i < 20; i++)
{
if (client_array[client_array_idx].job_array[i].job_order != -1
&& client_array[client_array_idx].job_array[i].pid != -1
&& client_array[client_array_idx].job_array[i].run_status != -1)
{
struct job j = client_array[client_array_idx].job_array[i];
if (j.job_order > max_job_order && j.run_status == 1)
{
max_job_order = j.job_order;
max_index = i;
}
}
}
return max_index;
}
#pragma endregion
#pragma region DAEMON INIT
/**
* @brief If we are waiting reading from a pipe and
* the interlocutor dies abruptly (say because
* of ^C or kill -9), then we receive a SIGPIPE
* signal. Here we handle that.
*/
void sig_pipe(int n)
{
perror("Broken pipe signal");
}
/**
* @brief Handler for SIGCHLD signal
*/
void sig_chld(int n)
{
int status;
fprintf(stderr, "Child terminated\n");
wait(&status); /* So no zombies */
}
/**
* @brief Initializes the current program as a daemon, by changing working
* directory, umask, and eliminating control terminal,
* setting signal handlers, saving pid, making sure that only
* one daemon is running. Modified from R.Stevens.
* @param[in] path is where the daemon eventually operates
* @param[in] mask is the umask typically set to 0
*/
void daemon_init(const char * const path, uint mask)
{
pid_t pid;
char buff[256];
int fd;
int k;
/* put server in background (with init as parent) */
if ( ( pid = fork() ) < 0 ) {
perror("daemon_init: cannot fork");
exit(0);
} else if (pid > 0) /* The parent */
exit(0);
/* the child */
/* Close all file descriptors that are open */
for (k = getdtablesize()-1; k>0; k--)
close(k);
/* Redirecting stdin and stdout to /dev/null */
if ( (fd = open("/dev/null", O_RDWR)) < 0) {
perror("Open");
exit(0);
}
dup2(fd, STDIN_FILENO); /* detach stdin */
dup2(fd, STDOUT_FILENO); /* detach stdout */
close (fd);
/* From this point on printf and scanf have no effect */
/* Redirecting stderr to u_log_path */
log_file = fopen(u_log_path, "aw"); /* attach stderr to u_log_path */
/* From this point on printing to stderr will go to /tmp/u-echod.log */
/* Establish handlers for signals */
if ( signal(SIGCHLD, sig_chld) < 0 ) {
perror("Signal SIGCHLD");
exit(1);
}
if ( signal(SIGPIPE, sig_pipe) < 0 ) {
perror("Signal SIGPIPE");
exit(1);
}
/* Change directory to specified directory */
chdir(path);
/* Set umask to mask (usually 0) */
umask(mask);
/* Detach controlling terminal by becoming sesion leader */
setsid();
/* Put self in a new process group */
pid = getpid();
setpgrp(); /* GPI: modified for linux */
/* Make sure only one server is running */
if ( ( k = open(u_pid_path, O_RDWR | O_CREAT, 0666) ) < 0 )
{
perror("Cannot start yashd daemon, other instance already running");
exit(1);
}
if ( lockf(k, F_TLOCK, 0) != 0)
exit(0);
/* Save server's pid without closing file (so lock remains)*/
sprintf(buff, "%6d", pid);
write(k, buff, strlen(buff));
return;
}
#pragma endregion<file_sep>/os/code_samples/pdfexec.c
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
/* pipe dup fork and exec Example */
/* runs as: ./pdfexec date wc */
/* Runs the shell equivalent of date | wc */
int main(int argc, char *argv[])
{
int pipefd[2], status, done=0;
pid_t cpid;
pipe(pipefd);
cpid = fork();
if (cpid == 0) { /* left child (for date) */
close(pipefd[0]); /* Close unused read end */
dup2(pipefd[1],STDOUT_FILENO); /* Make output go to pipe */
execlp(argv[1], argv[1], (char *) NULL);
}
cpid = fork();
if (cpid == 0) { /* right child (for wc */
close(pipefd[1]); /* Close unused write end */
dup2(pipefd[0],STDIN_FILENO); /* Get input from pipe */
execlp(argv[2], argv[2], (char *) NULL);
}
close(pipefd[0]); /* close pipes so EOF can work */
close(pipefd[1]); /* This is a subtle but important step. The second child
will not receive a EOF to trigger it to terminate while
at least one other process (the parent) has the write
end open */
/* Parent reaps children exits */
waitpid(-1,&status, 0);
waitpid(-1,&status, 0);
}
<file_sep>/os/yashd/Makefile
all: client server
#client
client: yash.c
gcc -g -o yash yash.c -lreadline
#server
server: yash.c
gcc -g -o yashd yashd.c server_thread.c -lpthread<file_sep>/os/yashd/yash.c
#include <stdio.h>
/* socket(), bind(), recv, send */
#include <sys/types.h>
#include <sys/socket.h> /* sockaddr_in */
#include <netinet/in.h> /* inet_addr() */
#include <arpa/inet.h>
#include <netdb.h> /* struct hostent */
#include <string.h> /* memset() */
#include <unistd.h> /* close() */
#include <stdlib.h> /* exit() */
#include <signal.h>
#include <readline/readline.h>
#define MAXHOSTNAME 80
#define BUFSIZE 2000
char buf[BUFSIZE];
char rbuf[BUFSIZE];
void GetUserInput();
void cleanup(char *buf);
int rc, cc;
int sd;
int childpid;
char mod_buf[BUFSIZE] = {0};
char * inString;
static void sig_ignore(int signo)
{
}
static void sig_int(int signo)
{
if (send(sd, "CTL C", sizeof("CTL C"), 0) <0 )
perror("sending stream message");
}
static void sig_tstp(int signo)
{
if (send(sd, "CTL Z", sizeof("CTL Z"), 0) <0 )
perror("sending stream message");
cleanup(mod_buf);
cleanup(buf);
}
int main(int argc, char **argv ) {
struct sockaddr_in server;
struct sockaddr_in client;
struct hostent *hp, *gethostbyname();
struct sockaddr_in from;
struct sockaddr_in addr;
int fromlen;
int length;
char ThisHost[80];
#pragma region CONNECT
gethostname(ThisHost, MAXHOSTNAME);
if ( (hp = gethostbyname(ThisHost)) == NULL ) {
fprintf(stderr, "Can't find host %s\n", argv[1]);
exit(-1);
}
bcopy ( hp->h_addr, &(server.sin_addr), hp->h_length);
/** get TCPServer-ex2 Host information, NAME and INET ADDRESS */
if ( (hp = gethostbyname(argv[1])) == NULL ) {
addr.sin_addr.s_addr = inet_addr(argv[1]);
if ((hp = gethostbyaddr((char *) &addr.sin_addr.s_addr,
sizeof(addr.sin_addr.s_addr),AF_INET)) == NULL) {
fprintf(stderr, "Can't find host %s\n", argv[1]);
exit(-1);
}
}
bcopy ( hp->h_addr, &(server.sin_addr), hp->h_length);
/* Construct name of socket to send to. */
server.sin_family = AF_INET; \
server.sin_port = htons(3826);
/* Create socket on which to send and receive */
sd = socket (AF_INET,SOCK_STREAM,0);
if (sd<0) {
perror("opening stream socket");
exit(-1);
}
/** Connect to TCPServer-ex2 */
if ( connect(sd, (struct sockaddr *) &server, sizeof(server)) < 0 ) {
close(sd);
perror("connecting stream socket");
exit(0);
}
fromlen = sizeof(from);
if (getpeername(sd,(struct sockaddr *)&from,&fromlen)<0){
perror("could't get peername\n");
exit(1);
}
#pragma endregion
printf("%s:%d\n", inet_ntoa(from.sin_addr),
ntohs(from.sin_port));
if ((hp = gethostbyaddr((char *) &from.sin_addr.s_addr,
sizeof(from.sin_addr.s_addr),AF_INET)) == NULL)
fprintf(stderr, "Can't find host %s\n", inet_ntoa(from.sin_addr));
else
if (signal(SIGINT, sig_int) == SIG_ERR)
printf("signal(SIGINT) error");
if (signal(SIGTSTP, sig_tstp) == SIG_ERR)
printf("signal(SIGTSTP) error");
childpid = fork();
if (childpid == 0) {
GetUserInput();
}
else
/* get data from USER, send it SERVER,
receive it from SERVER, display it back to USER */
for(;;)
{
fflush(stdout);
cleanup(rbuf);
if( (rc=recv(sd, rbuf, sizeof(buf), 0)) < 0){
perror("receiving stream message");
exit(-1);
}
if (rc > 0){
rbuf[rc]='\0';
printf("%s", rbuf);
rc = 0;
fflush(stdout);
} else {
close (sd);
exit(0);
}
}
}
void cleanup(char *buf)
{
int i;
for(i=0; i<BUFSIZE; i++) buf[i]='\0';
}
void GetUserInput()
{
while(inString = readline(""))
{
cleanup(buf);
cleanup(mod_buf);
for (int i = 0; i < BUFSIZE; i++)
{
if (inString[i] == '\0')
{
rc = i + 1;
break;
}
}
strcat(mod_buf, "CMD ");
strcat(mod_buf, inString);
if (send(sd, mod_buf, rc + 4, 0) <0 )
perror("sending stream message");
cleanup(mod_buf);
inString = "";
}
close(sd);
kill(getppid(), 9);
exit (0);
}
<file_sep>/sw_testing/ps1/src/pset1/EqualsTester.java
package pset1;
import static org.junit.Assert.*;
import org.junit.Test;
public class EqualsTester
{ /* * P1: For any non-null reference value x, x.equals(null) should return false. */
@Test public void t0()
{
assertFalse(new Object().equals(null));
}
// your test methods for P1 go here
@Test public void t1()
{
assertFalse(new C(0).equals(null));
}
@Test public void t2()
{
assertFalse(new D(0,0).equals(null));
}
/* P2: It is reflexive: for any non-null reference value x, x.equals(x)
* should return true.
*/
@Test public void p2_t0()
{
Object o = new Object();
assertTrue(o.equals(o));
}
@Test public void p2_t1()
{
C c = new C(0);
assertTrue(c.equals(c));
}
@Test public void p2_t2()
{
D d = new D(0,0);
assertTrue(d.equals(d));
}
/*
* P3: It is symmetric: for any non-null reference values x and y, x.equals(y)
* should return true if and only if y.equals(x) returns true.
*/
@Test public void p3_t0()
{
Object o = new Object();
Object o1 = new Object();
assertTrue(o.equals(o1) == o1.equals(o));
}
@Test public void p3_t1()
{
Object o = new Object();
C c1 = new C(0);
assertTrue(o.equals(c1) == c1.equals(o));
}
// your test methods for P1 go here
@Test public void p3_t2()
{
Object o = new Object();
D d1 = new D(0,0);
assertTrue(o.equals(d1) == d1.equals(o));
}
@Test public void p3_t3()
{
C c = new C(0);
C c1 = new C(0);
assertTrue(c.equals(c1) == c1.equals(c));
}
@Test public void p3_t4()
{
C c = new C(0);
Object o1 = new Object();
assertTrue(c.equals(o1) == o1.equals(c));
}
@Test public void p3_t5()
{
C c = new C(0);
D d1 = new D(0,0);
assertTrue(c.equals(d1) == d1.equals(c));
}
@Test public void p3_t6()
{
D d = new D(0,0);
D d1 = new D(0,0);
assertTrue(d.equals(d1) == d1.equals(d));
}
@Test public void p3_t7()
{
D d = new D(0,0);
Object o1 = new Object();
assertTrue(d.equals(o1) == o1.equals(d));
}
@Test public void p3_t8()
{
D d = new D(0, 0);
C c1 = new C(0);
assertTrue(d.equals(c1) == c1.equals(d));
}
/* P4: It is transitive: for any non-null reference values x, y, and z,
* if x.equals(y) returns true and y.equals(z) returns true, then
* x.equals(z) should return true. */
// you do not need to write tests for P4
}<file_sep>/os/project3/userprog/og/syscall.c
#include "userprog/syscall.h"
#include <stdio.h>
#include <syscall-nr.h>
#include "threads/interrupt.h"
#include "threads/thread.h"
#include "threads/vaddr.h"
typedef int pid_t;
void (*syscall_handlers[20])(struct intr_frame *);
static void syscall_handler (struct intr_frame *f);
void sys_halt(struct intr_frame* f);
void sys_exit(struct intr_frame* f);
void sys_exec(struct intr_frame* f);
void sys_wait(struct intr_frame* f);
void sys_create(struct intr_frame* f);
void sys_remove(struct intr_frame* f);
void sys_open(struct intr_frame* f);
void sys_filesize(struct intr_frame* f);
void sys_read(struct intr_frame* f);
void sys_write(struct intr_frame* f);
void sys_seek(struct intr_frame* f);
void sys_tell(struct intr_frame* f);
void sys_close(struct intr_frame* f);
void halt();
void exit(int status);
pid_t exec(const char *file);
int wait(pid_t pid);
bool create(const char *file, unsigned size);
bool remove(const char *file);
int open(const char *file);
int filesize(int fd);
int read(int fd, void *buffer, unsigned size);
int write(int fd, void* buffer, unsigned size);
void seek(int fd, int position);
unsigned tell(int fd);
void close(int fd);
bool is_valid_pointer(uint32_t* esp,uint8_t argc);
void
syscall_init (void)
{
intr_register_int (0x30, 3, INTR_ON, syscall_handler, "syscall"); //registering handler for TRAP
syscall_handlers[SYS_HALT] = &sys_halt;
syscall_handlers[SYS_EXIT] = &sys_exit;
syscall_handlers[SYS_WAIT] = &sys_wait;
syscall_handlers[SYS_CREATE] = &sys_create;
syscall_handlers[SYS_REMOVE] = &sys_remove;
syscall_handlers[SYS_OPEN] = &sys_open;
syscall_handlers[SYS_WRITE] = &sys_write;
syscall_handlers[SYS_SEEK] = &sys_seek;
syscall_handlers[SYS_TELL] = &sys_tell;
syscall_handlers[SYS_CLOSE] = &sys_close;
}
void sys_halt(struct intr_frame* f)
{
shutdown_power_off();
};
void sys_exit(struct intr_frame* f)
{
uint32_t arg1;
uint32_t *user_esp = f->esp;
user_esp++;
arg1 = (uint32_t)(*user_esp);
exit(arg1);
};
void sys_exec(struct intr_frame* f){};
void sys_wait(struct intr_frame* f){};
void sys_create(struct intr_frame* f){};
void sys_remove(struct intr_frame* f){};
void sys_open(struct intr_frame* f){};
void sys_filesize(struct intr_frame* f){};
void sys_read(struct intr_frame* f){};
void sys_write(struct intr_frame* f)
{
uint32_t arg1, arg2, arg3;
uint32_t *user_esp = f->esp;
user_esp++;
arg1 = (uint32_t)(*user_esp);
user_esp++;
arg2 = (uint32_t)(*user_esp);
user_esp++;
arg3 = (uint32_t)(*user_esp);
f->eax = write((int)arg1, (char *)arg2, (unsigned)arg3);
};
void sys_seek(struct intr_frame* f){};
void sys_tell(struct intr_frame* f){};
void sys_close(struct intr_frame* f){};
static void
syscall_handler (struct intr_frame *f UNUSED)
{
int callNo = * (int *)f->esp;
syscall_handlers[callNo](f);
// thread_exit();
}
int write (int fd, void *buffer, unsigned size)
{
if (fd == 1) // STDOUT
{
putbuf(buffer, size);
return size;
}
}
void exit(int status)
{
struct thread *curthread = thread_current();
curthread->parent->ex = true;
printf("%s: exit(%d)\n", curthread->name, status);
thread_exit();
}
/*
System Call: void halt (void)
Terminates Pintos by calling shutdown_power_off() (declared in "threads/init.h"). This should be seldom used, because you lose some information about possible deadlock situations, etc.
System Call: void exit (int status)
Terminates the current user program, returning status to the kernel. If the process's parent waits for it (see below), this is the status that will be returned. Conventionally, a status of 0 indicates success and nonzero values indicate errors.
System Call: pid_t exec (const char *cmd_line)
Runs the executable whose name is given in cmd_line, passing any given arguments, and returns the new process's program id (pid). Must return pid -1, which otherwise should not be a valid pid, if the program cannot load or run for any reason. Thus, the parent process cannot return from the exec until it knows whether the child process successfully loaded its executable. You must use appropriate synchronization to ensure this.
System Call: int wait (pid_t pid)
Waits for a child process pid and retrieves the child's exit status.
If pid is still alive, waits until it terminates. Then, returns the status that pid passed to exit. If pid did not call exit(), but was terminated by the kernel (e.g. killed due to an exception), wait(pid) must return -1. It is perfectly legal for a parent process to wait for child processes that have already terminated by the time the parent calls wait, but the kernel must still allow the parent to retrieve its child's exit status, or learn that the child was terminated by the kernel.
wait must fail and return -1 immediately if any of the following conditions is true:
pid does not refer to a direct child of the calling process. pid is a direct child of the calling process if and only if the calling process received pid as a return value from a successful call to exec.
Note that children are not inherited: if A spawns child B and B spawns child process C, then A cannot wait for C, even if B is dead. A call to wait(C) by process A must fail. Similarly, orphaned processes are not assigned to a new parent if their parent process exits before they do.
The process that calls wait has already called wait on pid. That is, a process may wait for any given child at most once.
Processes may spawn any number of children, wait for them in any order, and may even exit without having waited for some or all of their children. Your design should consider all the ways in which waits can occur. All of a process's resources, including its struct thread, must be freed whether its parent ever waits for it or not, and regardless of whether the child exits before or after its parent.
You must ensure that Pintos does not terminate until the initial process exits. The supplied Pintos code tries to do this by calling process_wait() (in "userprog/process.c") from main() (in "threads/init.c"). We suggest that you implement process_wait() according to the comment at the top of the function and then implement the wait system call in terms of process_wait().
Implementing this system call requires considerably more work than any of the rest.
System Call: bool create (const char *file, unsigned initial_size)
Creates a new file called file initially initial_size bytes in size. Returns true if successful, false otherwise. Creating a new file does not open it: opening the new file is a separate operation which would require a open system call.
System Call: bool remove (const char *file)
Deletes the file called file. Returns true if successful, false otherwise. A file may be removed regardless of whether it is open or closed, and removing an open file does not close it. See Removing an Open File, for details.
System Call: int open (const char *file)
Opens the file called file. Returns a nonnegative integer handle called a "file descriptor" (fd), or -1 if the file could not be opened.
File descriptors numbered 0 and 1 are reserved for the console: fd 0 (STDIN_FILENO) is standard input, fd 1 (STDOUT_FILENO) is standard output. The open system call will never return either of these file descriptors, which are valid as system call arguments only as explicitly described below.
Each process has an independent set of file descriptors. File descriptors are not inherited by child processes.
When a single file is opened more than once, whether by a single process or different processes, each open returns a new file descriptor. Different file descriptors for a single file are closed independently in separate calls to close and they do not share a file position.
System Call: int filesize (int fd)
Returns the size, in bytes, of the file open as fd.
System Call: int read (int fd, void *buffer, unsigned size)
Reads size bytes from the file open as fd into buffer. Returns the number of bytes actually read (0 at end of file), or -1 if the file could not be read (due to a condition other than end of file). Fd 0 reads from the keyboard using input_getc().
System Call: int write (int fd, const void *buffer, unsigned size)
Writes size bytes from buffer to the open file fd. Returns the number of bytes actually written, which may be less than size if some bytes could not be written.
Writing past end-of-file would normally extend the file, but file growth is not implemented by the basic file system. The expected behavior is to write as many bytes as possible up to end-of-file and return the actual number written, or 0 if no bytes could be written at all.
Fd 1 writes to the console. Your code to write to the console should write all of buffer in one call to putbuf(), at least as long as size is not bigger than a few hundred bytes. (It is reasonable to break up larger buffers.) Otherwise, lines of text output by different processes may end up interleaved on the console, confusing both human readers and our grading scripts.
System Call: void seek (int fd, unsigned position)
Changes the next byte to be read or written in open file fd to position, expressed in bytes from the beginning of the file. (Thus, a position of 0 is the file's start.)
A seek past the current end of a file is not an error. A later read obtains 0 bytes, indicating end of file. A later write extends the file, filling any unwritten gap with zeros. (However, in Pintos files have a fixed length until project 4 is complete, so writes past end of file will return an error.) These semantics are implemented in the file system and do not require any special effort in system call implementation.
System Call: unsigned tell (int fd)
Returns the position of the next byte to be read or written in open file fd, expressed in bytes from the beginning of the file.
System Call: void close (int fd)
Closes file descriptor fd. Exiting or terminating a process implicitly closes all its open file descriptors, as if by calling this function for each one.
*/
bool is_valid_pointer(uint32_t* esp,uint8_t argc){
for (int i = 0; i < argc; ++i)
{
if((!is_user_vaddr(esp))||(pagedir_get_page(thread_current()->pagedir,esp)==NULL))
{
return false;
}
}
return true;
}<file_sep>/sw_testing/ps3/settings.gradle
rootProject.name = 'ps3'
include 'ps3'
<file_sep>/os/code_samples/daemons/Makefile
# The program we want to build, what it depends on
# and how to build it
# build all
all: u-echo u-echod
#client
u-echo : u-echo.c
gcc -g -o u-echo u-echo.c
#server
u-echod : u-echod.c
gcc -g -o u-echod u-echod.c
# What to do if make is run as:
# make clean
# remove all executables
clean:
rm u-echo u-echod
<file_sep>/os/code_samples/pipe_ex2.c
/* Example demonstrates use of a pipe that mimics the use of pipes in a shell
Takes the name of the file you want to view using a pager program
like "more" or "less"; Displays the file's contents by: Creating a
child process that execs the pager. The parent passes the name of
the file to the child
Original Source: Advanced Programming in the Unix Enviroment, by <NAME>
http://www.apuebook.com/apue3e.html
Annotated by: <NAME>
System Calls used: fork, exec, wait, pipe, dup2
*/
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define MAXLINE 4096 /* max line length */
#define DEF_PAGER "/bin/more" /* default pager program */
int
main(int argc, char *argv[])
{
int n;
int pipefd[2];
pid_t cpid;
char *pager, *argv0;
char line[MAXLINE];
FILE *fp;
if (argc != 2) {
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
exit(EXIT_FAILURE);
}
if ((fp = fopen(argv[1], "r")) == NULL)
{
fprintf(stderr,"can't open %s", argv[1]);
}
if (pipe(pipefd) < 0)
{
fprintf(stderr,"pipe error");
}
cpid = fork();
if (cpid < 0) {
fprintf(stderr,"fork error");
}
else if (cpid > 0) {/* parent */
close(pipefd[0]); /* close read end */
// /* parent copies contents of file given in argv[1] to pipe */
// while (fgets(line, MAXLINE, fp) != NULL) {
// n = strlen(line);
// if (write(pipefd[1], line, n) != n)
// fprintf(stderr,"write error to pipe");
// }
write(pipefd[1], )
if (ferror(fp))
fprintf(stderr,"fgets error");
close(pipefd[1]); /* close write end of pipe for reader */
if (waitpid(pid, NULL, 0) < 0)
fprintf(stderr,"waitpid error");
exit(0);
}
else {
/*
*
* child
*
*/
close(pipefd[1]); /* close write end */
if (pipefd[0] != STDIN_FILENO) {
if (dup2(pipefd[0], STDIN_FILENO) != STDIN_FILENO)
fprintf(stderr,"dup2 error to stdin");
close(pipefd[0]); /* don't need this after dup2 */
}
/* get arguments for execl() */
if ((pager = getenv("PAGER")) == NULL)
pager = DEF_PAGER;
if ((argv0 = strrchr(pager, '/')) != NULL)
argv0++; /* step past rightmost slash */
else
argv0 = pager; /* no slash in pager */
printf("Pager: %s\n", pager);
printf("Argv0: %s\n", argv0);
if (execl(pager, argv0, (char *)0) < 0)
fprintf(stderr,"execl error for %s", pager);
}
exit(0);
}
<file_sep>/os/yashd/server_thread.h
#pragma region GLOBAL VARIABLES
struct job
{
int pid;
int run_status; // 1 is running, 0 is stopped // 2 is done
int job_order;
int is_background;
char args[2000];
};
int pid_ch1, pid_ch2, ppid, job_num, status;
struct job job_array[20];
char *inString;
#pragma endregion
#pragma region FUNCTION DECLARATIONS
void setjobAsBackground(int pid);
void removeJobFromLog(int rem_index);
static void sig_ignore(int signo);
static void sig_int(int signo);
static void sig_tstp(int signo);
static void sig_int(int signo);
int addJobToLog(int is_background);
void executeChildProcess(char** args, int argc, int input_index, int output_index, int error_index, int background_index);
void processSingleCommand(char** args, int argc, int input_index, int output_index, int error_index, int background_index, char* output_content, int *running_pid);
void processPipeCommand(char** init_args, int argc, int pipe_index, int background_index, char * output_content, int *running_pid);
int getMostRecentBackground(int is_background);
void processForegroundCommand(char * output_content, int *running_pid);
void processBackgroundCommand(char * output_content);
void processJobsCommand(char * output_content);
void printJob(int index, int is_bg, char * output_content);
void findAndPrintCompletedJobs(char * output_content);
void processStarter(char * inString, struct job job_array[], char * process_output, int *running_pid);
void initializeJobs(struct job job_array[]);
void copy_arrays(struct job main_arr[], struct job to_copy_arr[]);
#pragma endregion
<file_sep>/os/code_samples/daemons/u-echo.c
/**
* @file u-echo.c
* @brief u-echo.c - Communicate with the u-echod server
* through a Unix socket associated with a file pathname
* [passed either as argv[1] or by default /tmp/u-echod]
* In a loop the user is prompted to enter a line of text
* and this data is sent to the server; the reply (echo) is printed
* out. The loop terminates when we enter a null line.
* This example is from <NAME>'s Unix Programming Course
* at Temple University
* (https://cis.temple.edu/~ingargio/cis307/readings/daemon.html)
* I modified it a little bit and annotated it with explanations
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
char u_echo_path[256] = "/tmp/u-echod"; /* default */
int
main(int argc, char **argv)
{
int sockfd;
struct sockaddr_un servaddr;
if ( (sockfd = socket(AF_UNIX, SOCK_STREAM, 0) ) < 0 ) {
perror("Socket");
exit (1);
}
bzero((void *)&servaddr, sizeof(servaddr));
servaddr.sun_family = AF_UNIX;
strcpy(servaddr.sun_path, u_echo_path);
if ( connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0 ) {
perror("Connect");
exit (1);
}
for ( ; ; ) {
int n;
char c;
/* Read a line from user and write it to socket */
n = 0;
printf("Enter a line: ");
for (;;) {
c = getchar();
write(sockfd, &c, 1);
if (c == '\n') break;
n++;
}
/* Read a line from the socket */
for (;;) {
read(sockfd, &c, 1);
putchar(c);
if (c == '\n') break;
}
if (n == 0) break; /* The line entered by user was null */
}
exit(0);
}
<file_sep>/os/yashd/server_thread.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <fcntl.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "server_thread.h"
#define MAXLINE 4096
#define MAX_JOBS 20
#define BUFSIZE 2000
#pragma region SIGNAL HANDLING
static void sig_ignore(int signo)
{
}
static void sig_int(int signo)
{
for (int i = 0; i < MAX_JOBS; i++)
{
if (job_array[i].pid == pid_ch1)
{
removeJobFromLog(i);
break;
}
}
kill(pid_ch1,SIGINT);
}
static void sig_tstp(int signo)
{
kill(pid_ch1,SIGTSTP);
for (int i = 0; i < MAX_JOBS; i++)
{
if (job_array[i].pid == pid_ch1)
{
job_array[i].run_status = 0;
break;
}
}
}
static void sig_child(int signo)
{
pid_t pid;
int status;
for (int i = 0; i < MAX_JOBS; i++)
{
if (job_array[i].job_order != -1 && job_array[i].run_status == 1 && job_array[i].is_background == 1)
{
pid = waitpid(job_array[i].pid, &status, WNOHANG | WUNTRACED);
if (WIFEXITED(status))
{
job_array[i].run_status = 2;
}
}
}
}
#pragma endregion
#pragma region JOB LOG MANAGEMENT
int addJobToLog(int is_background)
{
struct job new_job;
new_job.pid = pid_ch1;
new_job.run_status = 1;
new_job.job_order = ++job_num;
// printf("process_num: %d\n", pid_ch1);
new_job.is_background = is_background;
strcpy(new_job.args, inString);
for (int i = 0; i < MAX_JOBS; i++)
{
if (job_array[i].job_order == -1
&& job_array[i].pid == -1
&& job_array[i].run_status == -1)
{
job_array[i] = new_job;
return i;
}
}
// printf("added to job log\n");
}
void removeJobFromLog(int rem_index)
{
memset(job_array[rem_index].args, 0, 2000);
job_array[rem_index].job_order = -1;
job_array[rem_index].pid = -1;
job_array[rem_index].run_status = -1;
job_array[rem_index].is_background = -1;
}
void setjobAsBackground(int pid)
{
for (int i = 0; i < MAX_JOBS; i++)
{
if (job_array[i].pid == pid)
job_array[i].is_background = 1;
}
}
int getMostRecentBackground(int is_background)
{
int max_process = -1;
int max_job_order = -1;
int max_index = -1;
for (int i = 0; i < MAX_JOBS; i++)
{
if (job_array[i].job_order != -1
&& job_array[i].pid != -1
&& job_array[i].run_status != -1)
{
struct job j = job_array[i];
if (is_background == 1)
{
if (j.run_status == 0 && j.job_order > max_job_order)
{
max_job_order = j.job_order;
max_index = i;
}
}
else if (is_background == 2)
{
if ((j.is_background == 1 || j.run_status == 0) && j.job_order > max_job_order)
{
max_job_order = j.job_order;
max_index = i;
}
}
else
{
if (j.job_order > max_job_order)
{
max_job_order = j.job_order;
max_index = i;
}
}
}
}
return max_index;
}
#pragma endregion
#pragma region DEFAULT COMMAND EXECUTION
void executeChildProcess(char** args, int argc, int input_index, int output_index, int error_index, int background_index)
{
args[argc] = NULL;
pid_t pid = getpid();
setpgid(pid, pid);
if (input_index != -1) {
args[input_index] = NULL;
char* input_string = args[input_index + 1];
int ofd;
ofd = open(input_string, 0644);
dup2(ofd, STDIN_FILENO);
}
if (output_index != -1) {
args[output_index] = NULL;
char* output_string = args[output_index + 1];
int ofd;
ofd = creat(output_string, 0644);
dup2(ofd, STDOUT_FILENO);
}
if (error_index != -1) {
args[error_index] = NULL;
char* error_string = args[error_index + 1];
int ofd;
ofd = creat(error_string, 0644);
dup2(ofd, STDERR_FILENO);
}
if (background_index != -1)
{
args[background_index] = NULL;
}
execvp(args[0], args);
exit(0);
}
void processSingleCommand(char** args, int argc, int input_index, int output_index, int error_index, int background_index, char* output_content, int *running_pid)
{
int filedes[2];
int is_background = 0;
if (background_index != -1)
is_background = 1;
if (pipe(filedes) == -1) {
perror("pipe had an error");
}
pid_ch1 = fork();
if (pid_ch1 > 0)
{
// Parent
close(filedes[1]);
int job_idx = addJobToLog(is_background);
*running_pid = pid_ch1;
// printf("pid is now %p\n", running_pid);
if (background_index != -1) {
kill(pid_ch1, SIGTSTP);
kill(pid_ch1, SIGCONT);
}
else {
// printf("%d\n", 1);
setpgid(pid_ch1, pid_ch1);
// if (signal(SIGINT, sig_int) == SIG_ERR)
// printf("signal(SIGINT) error");
// if (signal(SIGTSTP, sig_tstp) == SIG_ERR)
// printf("signal(SIGTSTP) error");
// if (signal(SIGCHLD, sig_child) == SIG_ERR)
// printf("signal(SIGCHLD) error");
// printf("%d\n", 2);
int count = 0;
while (count < 1)
{
// printf("%d\n", 3);
ppid = waitpid(pid_ch1, &status, WUNTRACED);
// printf("waiting for %d\n", pid_ch1);
if (ppid == -1)
{
perror("waitpid");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status))
{
// printf("Exited\n");
removeJobFromLog(job_idx);
//printf("child %d exited, status=%d\n", ppid, WEXITSTATUS(status));
count++;
char buffer[BUFSIZE];
while (1)
{
ssize_t count = read(filedes[0], buffer, sizeof(buffer));
// printf("Count from read: %zu\n", count);
if (count == -1) {
perror("waitpid");
exit(EXIT_FAILURE);
} else if (count == 0) {
break;
} else {
// printf("Got this in parent: %s\n", buffer);
for (int i = 0; i < count; i++)
{
output_content[i] = buffer[i];
}
}
}
}
else if (WIFSIGNALED(status))
{
// printf("Signaled\n");
removeJobFromLog(job_idx);
//printf("child %d exited, status=%d\n", ppid, WEXITSTATUS(status));
count++;
// char buffer[BUFSIZE];
// printf("Signaled\n");
}
else if (WIFSTOPPED(status)) {
// printf("Stopped\n");
job_array[job_idx].run_status = 0;
count++;
} else if (WIFCONTINUED(status)) {
}
}
}
}
else if (pid_ch1 == 0) {
// Child
close(filedes[0]);
dup2(filedes[1], STDOUT_FILENO);
close(filedes[1]);
executeChildProcess(args, argc, input_index, output_index, error_index, background_index);
}
}
void processPipeCommand(char** init_args, int argc, int pipe_index, int background_index, char * output_content, int *running_pid)
{
char **args_left = malloc((argc) * sizeof(char *));
char **args_right = malloc((argc) * sizeof(char *));
int left_input = -1;
int left_output = -1;
int left_error = -1;
int right_input = -1;
int right_output = -1;
int right_error = -1;
int right_background = -1;
#pragma region Split Commands
for (int i = 0; i < pipe_index; i++) {
args_left[i] = init_args[i];
if (args_left[i][0] == '>') {
left_output = i;
}
else if (args_left[i][0] == '<') {
left_input = i;
}
else if (args_left[i][0] == '2' && args_left[i][1] == '>') {
left_error = i;
}
}
args_left[pipe_index] = NULL;
for (int i = 0; i < (argc - pipe_index) - 1; i++) {
args_right[i] = init_args[pipe_index + i + 1];
if (args_right[i][0] == '>') {
right_output = i;
}
else if (args_right[i][0] == '<') {
right_input = i;
}
else if (args_right[i][0] == '2' && args_right[i][1] == '>') {
right_error = i;
}
else if (args_right[i][0] == '&')
{
right_background = i;
}
}
args_right[(argc - pipe_index) - 1] = NULL;
#pragma endregion
int pipeLtoR[2];
char buf;
if (pipe(pipeLtoR) == -1) {
perror("pipe had an error");
}
pid_ch1 = fork();
if (pid_ch1 == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid_ch1 == 0)
{
/*
*
* WRITE SIDE / Child 1
*
* */
close(pipeLtoR[0]);
dup2(pipeLtoR[1], STDOUT_FILENO);
close(pipeLtoR[1]);
if (left_input != -1) {
args_left[left_input] = NULL;
char* input_string = args_left[left_input + 1];
int ofd;
ofd = open(input_string, 0644);
dup2(ofd, STDIN_FILENO);
}
if (left_output != -1) {
args_left[left_output] = NULL;
char* output_string = args_left[left_output + 1];
int ofd;
ofd = creat(output_string, 0644);
dup2(ofd, STDOUT_FILENO);
}
if (left_error != -1) {
args_left[left_error] = NULL;
char* error_string = args_left[left_error + 1];
int ofd;
ofd = creat(error_string, 0644);
dup2(ofd, STDERR_FILENO);
}
execvp(args_left[0], args_left);
exit(0);
}
else
{
/*
*
* READ SIDE AND PARENT
*
* */
int pipeRtoP[2];
if (pipe(pipeRtoP) == -1) {
perror("pipe had an error");
}
pid_ch2 = fork();
if (pid_ch2 == -1) {
perror("Child 2 had a problem");
exit(EXIT_FAILURE);
}
if (pid_ch2 == 0) {
// READ CHILD AND OUTPUT TO PARENT PIPE
setpgid(pid_ch1, pid_ch1);
close(pipeRtoP[0]); // read end
close(pipeLtoR[1]); // write end
dup2(pipeLtoR[0], STDIN_FILENO);
dup2(pipeRtoP[1], STDOUT_FILENO);
close(pipeLtoR[0]);
close(pipeRtoP[1]);
if (right_input != -1) {
args_right[right_input] = NULL;
char* input_string = args_right[right_input + 1];
int ofd;
ofd = open(input_string, 0644);
dup2(ofd, STDIN_FILENO);
}
if (right_output != -1) {
args_right[right_output] = NULL;
char* output_string = args_right[right_output + 1];
int ofd;
ofd = creat(output_string, 0644);
dup2(ofd, STDOUT_FILENO);
}
if (right_error != -1) {
args_right[right_error] = NULL;
char* error_string = args_right[right_error + 1];
int ofd;
ofd = creat(error_string, 0644);
dup2(ofd, STDERR_FILENO);
}
if (background_index != -1)
{
args_right[background_index] = NULL;
}
execvp(args_right[0], args_right);
exit(0);
}
else {
// Parent
close(pipeRtoP[1]);
close(pipeLtoR[1]);
close(pipeLtoR[1]);
setpgid(pid_ch1, pid_ch1);
setpgid(pid_ch2, pid_ch1);
int is_background = 0;
if (background_index != -1)
{
is_background = 1;
}
int job_idx = addJobToLog(is_background);
// running_pid = pid_ch1;
if (background_index != -1)
{
kill(pid_ch1, SIGTSTP);
kill(pid_ch1, SIGCONT);
}
else
{
int count = 0;
while (count < 1)
{
ppid = waitpid(pid_ch1, &status, WUNTRACED | WNOHANG);
if (ppid == -1)
{
perror("waitpid");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status))
{
removeJobFromLog(job_idx);
char buffer[BUFSIZE];
while (1)
{
ssize_t count = read(pipeRtoP[0], buffer, sizeof(buffer));
if (count == -1) {
perror("waitpid");
exit(EXIT_FAILURE);
} else if (count == 0) {
break;
} else {
for (int i = 0; i < count; i++)
{
output_content[i] = buffer[i];
}
}
}
close(pipeRtoP[0]);
count++;
}
else if (WIFSIGNALED(status))
{
count++;
}
else if (WIFSTOPPED(status)) {
count++;
} else if (WIFCONTINUED(status)) {
}
}
}
}
}
}
#pragma endregion
#pragma region CUSTOM JOB COMMANDS
void processForegroundCommand(char * output_content, int *running_pid)
{
int max_index = getMostRecentBackground(2);
int max_pid = job_array[max_index].pid;
setpgid(max_pid, max_pid);
int count = 0;
if (job_array[max_index].run_status == 1)
{
while (count < 1)
{
ppid = waitpid(max_pid, &status, WNOHANG | WUNTRACED | WCONTINUED);
if (ppid == -1)
{
perror("waitpid");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status))
{
removeJobFromLog(max_index);
count++;
}
else if (WIFSIGNALED(status))
{
count++;
}
else if (WIFSTOPPED(status)) {
count++;
} else if (WIFCONTINUED(status)) {
}
}
}
else {
int first_stop = 0;
while (count < 2)
{
ppid = waitpid(max_pid, &status, WNOHANG | WUNTRACED | WCONTINUED);
if (ppid == -1)
{
perror("waitpid");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status))
{
removeJobFromLog(max_index);
count++;
}
else if (WIFSIGNALED(status))
{
count++;
}
else if (WIFSTOPPED(status)) {
if (first_stop == 0) {
pid_ch1 = max_pid;
strcat(output_content, job_array[max_index].args);
kill(max_pid, SIGCONT);
job_array[max_index].run_status = 1;
first_stop++;
}
count++;
} else if (WIFCONTINUED(status)) {
}
}
}
}
void processBackgroundCommand(char * output_content)
{
int max_index = getMostRecentBackground(1);
int max_pid = job_array[max_index].pid;
printJob(max_index, 1, output_content);
setpgid(max_pid, max_pid);
kill(max_pid, SIGCONT);
job_array[max_index].run_status = 1;
job_array[max_index].is_background = 1;
}
void processJobsCommand(char * output_content)
{
findAndPrintCompletedJobs(output_content);
int index_order[20];
for (int i = 0; i < MAX_JOBS; i++)
{
for (int j = i + 1; j < MAX_JOBS; ++j)
{
if (job_array[i].job_order > job_array[j].job_order)
{
struct job temp_job = job_array[i];
job_array[i] = job_array[j];
job_array[j] = temp_job;
}
}
}
for (int i = 0; i < MAX_JOBS; i++)
{
if (job_array[i].job_order != -1)
{
printJob(i, 0, output_content);
}
}
}
#pragma endregion
#pragma region PRINTING
void printJob(int index, int is_bg, char * output_content)
{
int rec_idx = getMostRecentBackground(0);
strcat(output_content, "[");
char buffer[3];
sprintf(buffer, "%d", job_array[index].job_order);
strcat(output_content, buffer);
strcat(output_content, "]");
// printf("[%d]", job_array[index].job_order);
if (index == rec_idx)
{
strcat(output_content, "+ ");
// printf("+ ");
}
else
{
strcat(output_content, "- ");
// printf("- ");
}
if (is_bg == 0)
{
if (job_array[index].run_status == 0)
{
strcat(output_content, "Stopped\t\t");
// printf("Stopped\t\t");
}
else if (job_array[index].run_status == 1)
{
strcat(output_content, "Running\t\t");
// printf("Running\t\t");
}
else if (job_array[index].run_status == 2)
{
strcat(output_content, "Done\t\t");
// printf("Done\t\t");
}
}
strcat(output_content, job_array[index].args);
// printf("%s", job_array[index].args);
if (is_bg == 1)
{
strcat(output_content, " &");
// printf(" &");
}
strcat(output_content, "\n");
// printf("\n");
}
void findAndPrintCompletedJobs(char * output_content)
{
int max_order = 0;
for (int i = 0; i < MAX_JOBS; i++)
{
if (job_array[i].run_status == 2)
{
printJob(i, 0, output_content);
removeJobFromLog(i);
}
else if (job_array[i].job_order > max_order)
{
// printf("Reassign to %d\n", job_array[i].job_order);
max_order = job_array[i].job_order;
}
}
// printf("max_order: %d\n", max_order);
job_num = max_order;
}
#pragma endregion
void initializeJobs(struct job client_jobs[])
{
for (int i = 0; i < MAX_JOBS; i++)
{
removeJobFromLog(i);
}
job_num = 0;
copy_arrays(job_array, client_jobs);
}
void copy_arrays(struct job main_arr[], struct job to_copy_arr[])
{
for (int i = 0; i < MAX_JOBS; i++)
{
to_copy_arr[i] = main_arr[i];
}
}
void processStarter(char * client_inString, struct job client_jobs[], char * process_output, int * running_pid)
{
inString = client_inString;
copy_arrays(client_jobs, job_array);
pid_ch1 = -1;
pid_ch2 = -1;
int input_length = strlen(inString);
int pipe_index = -1;
int input_index = -1;
int output_index = -1;
int error_index = -1;
int background_index = -1;
char argv[100][50];
int j,ctr;
#pragma region PARSE INSTRING
j=0; ctr=0;
for(int i=0;i<=(strlen(inString));i++) {
if(inString[i] == '|')
{
pipe_index = ctr;
}
if(inString[i] == '<')
{
input_index = ctr;
}
if(inString[i] == '>')
{
if (inString[i-1] == '2')
{
error_index = ctr;
}
else {
output_index = ctr;
}
}
if(inString[i] == '&')
{
background_index = ctr;
}
// if space or NULL found, assign NULL into newString[ctr]
if(inString[i]==' '||inString[i]=='\0')
{
argv[ctr][j]='\0';
ctr++; //for next word
j=0; //for next word, init index to 0
}
else
{
argv[ctr][j]=inString[i];
j++;
}
}
#pragma endregion
#pragma region CHECK FOR CUSTOM COMMANDS
int foreground = 0;
int background = 0;
int jobs = 0;
char **args = malloc((ctr + 1)* sizeof(char *));
for (int i = 0; i < ctr; i++)
{
args[i] = argv[i];
if (strcmp(argv[i],"fg") == 0)
{
foreground = 1;
}
else if (strcmp(argv[i],"bg") == 0)
{
background = 1;
}
else if (strcmp(argv[i],"jobs") == 0)
{
jobs = 1;
}
}
#pragma endregion
#pragma region EXECUTE COMMANDS
if (foreground == 1)
{
processForegroundCommand(process_output, running_pid);
}
else if (background == 1)
{
processBackgroundCommand(process_output);
}
else if (jobs == 1)
{
processJobsCommand(process_output);
}
else
{
if (pipe_index != -1)
{
processPipeCommand(args, ctr, pipe_index, background_index, process_output, running_pid);
}
else
{
processSingleCommand(args, ctr, input_index, output_index, error_index, background_index, process_output, running_pid);
}
}
#pragma endregion
findAndPrintCompletedJobs(process_output);
copy_arrays(job_array, client_jobs);
}<file_sep>/os/project3/userprog/og/o_process.h
#ifndef USERPROG_PROCESS_H
#define USERPROG_PROCESS_H
#include "threads/thread.h"
tid_t process_execute (const char *file_name);
int process_wait (tid_t);
void process_exit (void);
void process_activate (void);
struct file_descriptor{
int fd;
struct list_elem elem;
struct file* file;
};
struct process {
struct list_elem elem;
struct thread *thread;
}
#endif /* userprog/process.h */
<file_sep>/os/code_samples/sig_ex2.c
/* file: sig_ex2.c
Author: <NAME>
This is a more complex example of signals
Create a child process and communicate with it using a pipe
The parent writes to the pipe and child reads from the pipe.
What the parent writes is what the user is typing on the keyboard
when the child read two identical characters in a row
it sends a SIGUSR1 signal to the parent. The parent acknowleges
the signal and quits
*/
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
static void sig_handler(int signo) {
printf("doh\n");
exit(0);
}
int main(void) {
int pipefd[2], status;
char ch[2]={0,0},pch=128;
if (pipe(pipefd) == -1) {
perror("pipe");
exit(-1);
}
int ret = fork();
if (ret > 0){
// Parent
if (signal(SIGUSR1, sig_handler) == SIG_ERR)
printf("signal(SIGUSR1) error");
close(pipefd[0]); //close read
while (read(STDIN_FILENO,ch,1) != 0){
write(pipefd[1],ch,1);
}
wait(&status);
}else {
// Child
close(pipefd[1]); // close the write end
while (read(pipefd[0],ch,1) != 0){
printf("%c",ch[0]);sync();
if (pch == ch[0]){
//printf("sending SIGUSR1 to parent\n");
kill(getppid(),SIGUSR1);
exit(0);
}
pch = ch[0];
}
}
}
<file_sep>/os/code_samples/pipe_ex.c
/* Example demonstrates a simple use of a Pipe to communicate between a parent and a child
A pipe is a uni-directional communication mechanism.
Here the parent writes a string to the child, which the child prints to the screen
Original Source: Advanced Programming in the Unix Enviroment, by <NAME>
http://www.apuebook.com/apue3e.html
Annotated by: <NAME>
System Calls used: fork, wait, pipe
*/
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int
main(int argc, char *argv[])
{
int pipefd[2];
pid_t cpid;
char buf;
if (argc != 2) {
fprintf(stderr, "Usage: %s <string>\n", argv[0]);
exit(EXIT_FAILURE);
}
// pipe takes a pointer to a 2-element array (pipefd[2]) as input and returns the
// the read and write end of the pipe in pipefd[0] and write end in pipefd[1]
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child reads from pipe */
close(pipefd[1]); /* Closes unused write end */
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */
close(pipefd[0]); /* Close unused read end */
write(pipefd[1], argv[1], strlen(argv[1]));
close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}
<file_sep>/os/code_samples/pthreads/Makefile
all: threads passing
threads: threads.c
gcc -o threads threads.c -lpthread
passing: passing.c
gcc -o passing passing.c -lpthread
clean:
rm passing threads
<file_sep>/os/yash/Makefile
yash :
gcc -g -o yash yash.c -lreadline
clean :
rm *.o yash | 682917cf9a57ad77303cde18a949fc073317401a | [
"Makefile",
"Java",
"Gradle",
"C"
] | 18 | Makefile | trevorba16/2020_1 | 248878a236925cd149fddde187ff8ca1bab2138e | 1326c40f03d87ed313f28f9da054b5b4582a6365 |
refs/heads/master | <file_sep>/*
* Copyright (c) 2018 OpenSourceDevTeam
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.opensdt.dense.pipeline;
import com.opensdt.dense.pipeline.handler.DnsChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.DatagramChannel;
import io.netty.handler.codec.dns.DatagramDnsQueryDecoder;
import io.netty.handler.codec.dns.DatagramDnsResponseEncoder;
public class DenseChannelInitializer extends ChannelInitializer<DatagramChannel> {
@Override
protected void initChannel(DatagramChannel ch) throws Exception {
ch.pipeline()
.addLast(new DatagramDnsQueryDecoder())
.addLast(new DatagramDnsResponseEncoder())
.addLast(new DnsChannelHandler());
}
}
<file_sep>/*
* Copyright (c) 2018 OpenSourceDevTeam
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.opensdt.dense;
import com.opensdt.dense.channel.ChannelUtils;
import com.opensdt.dense.pipeline.DenseChannelInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.EventLoopGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DenseBootstrap {
private static Logger logger = LoggerFactory.getLogger(DenseBootstrap.class);
public static void main(String[] args) {
logger.info("Bootstrapping dense DNS Server");
EventLoopGroup boss = ChannelUtils.getEventLoopGroup(1);
try {
new Bootstrap()
.group(boss)
.channel(ChannelUtils.getChannel())
.handler(new DenseChannelInitializer())
// TODO: Configurable bind IP
.bind(53)
.sync()
.channel()
.closeFuture()
.sync();
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
boss.shutdownGracefully();
}
}
}
| dfb98a5869b18bb0b1918734757c02bbb41c2594 | [
"Java"
] | 2 | Java | OpenSourceDevTeam/dns-server | 1e9216107cc7a055929098d2fc6f4e4f04a86303 | 5adccacd5ea0c03fbb480eee53361bd7a106125f |
refs/heads/develop | <repo_name>YJeongKim/murmul-er_app<file_sep>/README.md
# Murmul-er Android Application
<br>
### Murmul-er Web Version : https://github.com/YJeongKim/murmul-er
<br>
### App 소개
- 머물러 회원을 위한 안드로이드 애플리케이션
- 하이브리드 앱 방식
- 방 매물 검색/상세정보 서비스 제공
- 방 매물 관심목록 서비스 제공
<br>
### App 구성
<p align="center">
<img src="https://user-images.githubusercontent.com/33328991/74097820-ee43a200-4b53-11ea-8d2d-50ce039ba894.png" alt="app1" />
</p>
<br>
<p align="center">
<img src="https://user-images.githubusercontent.com/33328991/74097821-eedc3880-4b53-11ea-93f4-780b9915d1e9.png" alt="app2" />
</p>
<br>
##### ▷ 프로젝트 정보
###### - 프로젝트 기간 : 총 6주 중 1주 (19.08.19 ~ 19.08.26)
###### - 개발 인원 : 5인
###### - 개발 환경 : Android(Java), MySQL
<br>
------
<p align="center">Copyright© 2019. Organic Stack. All rights reserved.</p><file_sep>/app/src/main/java/com/murmuler/organicstack/adapter/RoomSummaryViewAdapter.java
package com.murmuler.organicstack.adapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.murmuler.organicstack.DetailActivity;
import com.murmuler.organicstack.MainActivity;
import com.murmuler.organicstack.R;
import com.murmuler.organicstack.util.Constants;
import com.murmuler.organicstack.vo.RoomSummaryViewVO;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class RoomSummaryViewAdapter extends BaseAdapter {
Context context;
List<RoomSummaryViewVO> roomList;
LayoutInflater layoutInflater;
Bitmap bitmap = null;
public RoomSummaryViewAdapter(Context context, List<RoomSummaryViewVO> roomList) {
this.context = context;
this.roomList = roomList;
this.layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return roomList.size();
}
@Override
public Object getItem(int position) {
return roomList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemLayout = convertView;
if(itemLayout == null)
itemLayout = layoutInflater.inflate(R.layout.room_detail_list_item, parent, false);
RoomSummaryViewVO room = roomList.get(position);
ImageView imageView = itemLayout.findViewById(R.id.imageView);
Thread mThread = new Thread() {
@Override
public void run() {
InputStream is = null;
try {
URL url = new URL(Constants.ROOT_CONTEXT +"/manage/download?middlePath=/room/roomId_" + room.getRoomId() + "&imageFileName=" + room.getRoomImg());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
mThread.start();
try {
mThread.join();
imageView.setImageBitmap(bitmap);
} catch (InterruptedException e) {
e.printStackTrace();
}
TextView title = itemLayout.findViewById(R.id.title);
String titleText = room.getTitle();
if(titleText.length() >= 14) titleText = titleText.substring(0,12) + "...";
title.setText(titleText);
// ImageButton likeButton = itemLayout.findViewById(R.id.likeButton);
// likeButton.setImageResource(R.drawable.heart_custom);
TextView address = itemLayout.findViewById(R.id.address);
String addressText = room.getSido() + " " + room.getSigungu() + " " + room.getRoadname();
address.setText(addressText);
TextView detail = itemLayout.findViewById(R.id.detail);
String deposit = room.getDeposit();
String pyeong = (int)(room.getArea() / 3.3) + "";
String cost = room.getMonthlyCost().equals("없음") ? "" : " / 월세 " + room.getMonthlyCost();
String manageCost = room.getManageCost().equals("없음") ? "없음" : room.getManageCost();
String detailText = "[" + room.getRentType() + "] 보증금 " + deposit + cost + "\n"
+ room.getRoomType() + " " + pyeong + "평 / 관리비 " + manageCost;
detail.setText(detailText);
itemLayout.setId(room.getRoomId());
itemLayout.setOnClickListener(v -> {
Log.i("아이템 클릭", "roomId("+roomList.get(position).getRoomId()+")");
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("roomId", v.getId()+"");
context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
});
ViewGroup.LayoutParams param = itemLayout.getLayoutParams();
if(param == null) {
param = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
param.height = 300;
itemLayout.setLayoutParams(param);
return itemLayout;
}
}
<file_sep>/app/src/main/java/com/murmuler/organicstack/MainActivity.java
package com.murmuler.organicstack;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.widget.CompoundButtonCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.maps.CameraUpdate;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.murmuler.organicstack.util.Constants;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.murmuler.organicstack.vo.RoomSummaryViewVO;
import com.murmuler.organicstack.adapter.RoomSummaryViewAdapter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback, NavigationView.OnNavigationItemSelectedListener {
private GoogleMap mMap;
private ArrayList<Marker> currentMarker;
private static final String ROOT_CONTEXT = Constants.ROOT_CONTEXT;
private static RequestQueue requestQueue;
private static final int GPS_ENABLE_REQUEST_CODE = 2001;
private static final int PERMISSIONS_REQUEST_CODE = 100;
// private static final int UPDATE_INTERVAL_MS = 1000;
// private static final int FASTEST_UPDATE_INTERVAL_MS = 500;
// private static final int PLACE_PICKER_REQUEST=1;
boolean needRequest = false;
String[] REQUIRED_PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
private LatLng currentPosition;
private FusedLocationProviderClient mFusedLocationClient;
private LocationRequest locationRequest;
private Location location;
private String memberId;
private String nickname;
private String popupStatus = "COLLAPSED";
private TableLayout filterOption;
private ArrayList<CheckBox> checkBoxList;
private ArrayList<String> curCheckBoxArray;
private ArrayList<String> confirmArray;
private ArrayList<Integer> selectedBT;
private int depositProgress = -1;
private int monthlyCostProgress = -1;
private int periodValue = -1;
@BindView(R.id.layout_main)
View mLayout;
@BindView(R.id.editText)
EditText editSearch;
@BindView(R.id.btnSearch)
ImageButton btnSearch;
@BindView(R.id.btnSlide)
ImageButton btnSlide;
@BindView(R.id.popupLayout)
LinearLayout popupLayout;
@BindView(R.id.btnBuildingType)
Button btnBuildingType;
@BindView(R.id.listView)
ListView listView;
@BindView(R.id.btnPeriod)
Button btnPeriod;
@BindView(R.id.btnDeposit)
Button btnDeposit;
@BindView(R.id.btnMonthlyCost)
Button btnMonthlyCost;
@BindView(R.id.btnOption)
Button btnOption;
@BindView(R.id.searchBar)
LinearLayout searchBar;
@BindView(R.id.botMain)
ImageButton botMain;
@BindView(R.id.botSearch)
ImageButton botSearch;
@BindView(R.id.botLike)
ImageButton botLike;
@BindView(R.id.botMore)
ImageButton botMore;
@BindView(R.id.nav_view)
NavigationView navigationView;
@BindView(R.id.drawerLayout)
DrawerLayout drawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Glide.with(this).load(R.drawable.bottom_main).into(botMain);
Glide.with(this).load(R.drawable.bottom_search_on).into(botSearch);
Glide.with(this).load(R.drawable.bottom_like).into(botLike);
Glide.with(this).load(R.drawable.bottom_more).into(botMore);
currentMarker = new ArrayList<>();
selectedBT = new ArrayList<>();
selectedBT.add(Constants.BUILDING_AP);
selectedBT.add(Constants.BUILDING_OF);
selectedBT.add(Constants.BUILDING_OR);
selectedBT.add(Constants.BUILDING_TR);
selectedBT.add(Constants.BUILDING_VI);
// 주기적으로 위치값을 받아서 현재 위치를 Setting 해주어야 할 경우 주석을 풀 것
locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// .setInterval(FASTEST_UPDATE_INTERVAL_MS)
// .setFastestInterval(FASTEST_UPDATE_INTERVAL_MS);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
editSearch.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
btnSearch.callOnClick();
return true;
}
return false;
}
});
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
Geocoder geocoder = new Geocoder(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String keyword = intent.getExtras().getString("keyword");
if (keyword != null) {
Log.i("키워드값", keyword);
editSearch.setText(keyword);
}
memberId = intent.getExtras().getString("memberId");
nickname = intent.getExtras().getString("nickname");
View headerView = navigationView.getHeaderView(0);
TextView userName = headerView.findViewById(R.id.loginId);
userName.setText(nickname);
navigationView.setNavigationItemSelectedListener(this);
curCheckBoxArray = new ArrayList<>();
setSlideMenuEvent();
}
private void setSlideMenuEvent() {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // 슬라이드 메뉴에서 아이템이 클릭됐을 때
// System.out.println(view.toString());
Log.i("parent", parent.toString());
Log.i("view", view.toString());
Log.i("position", position + "");
Log.i("id", id + "");
// AppCompatTextView tv = (AppCompatTextView)view;
// Toast.makeText(MainActivity.this, tv.getText(), Toast.LENGTH_SHORT).show();
}
});
((SlidingUpPanelLayout) mLayout).addPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {
@Override
public void onPanelSlide(View panel, float slideOffset) {
}
@Override
public void onPanelStateChanged(View panel, SlidingUpPanelLayout.PanelState previousState, SlidingUpPanelLayout.PanelState newState) {
Log.i("상태변경", "onPanelStateChanged " + newState);
switch (newState.toString()) {
case "EXPANDED":
Glide.with(MainActivity.this).load(R.drawable.angle_down_custom).into(btnSlide);
popupStatus = "EXPANDED";
break;
case "COLLAPSED":
Glide.with(MainActivity.this).load(R.drawable.angle_up_custom).into(btnSlide);
popupStatus = "COLLAPSED";
break;
case "DRAGGING":
if (popupStatus.equals("COLLAPSED") && popupLayout.getChildCount() == 1) {
allSelectedFalse();
popupLayout.removeAllViews();
searchBar.setVisibility(View.VISIBLE);
}
break;
}
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setDefaultLocation();
// 위치 퍼미션을 가지고 있는지 Check
int hasFineLocationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
int hasCoarseLocationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED &&
hasCoarseLocationPermission == PackageManager.PERMISSION_GRANTED) {
startLocationUpdates();
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, REQUIRED_PERMISSIONS[0])) {
// 사용자에게 퍼미션을 요청
Snackbar.make(mLayout, "이 앱을 실행하려면 위치 접근 권한이 필요합니다.", Snackbar.LENGTH_INDEFINITE).setAction("확인", new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCompat.requestPermissions(MainActivity.this, REQUIRED_PERMISSIONS, PERMISSIONS_REQUEST_CODE);
}
}).show();
} else {
// 사용자가 퍼미션 거부를 한적이 없는 경우에는 퍼미션 요청을 바로 함
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, PERMISSIONS_REQUEST_CODE);
}
}
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
@Override
public void onCameraIdle() {
showRoomList(mMap.getProjection().getVisibleRegion().latLngBounds);
}
});
}
LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
location = locationList.get(locationList.size() - 1);
currentPosition = new LatLng(location.getLatitude(), location.getLongitude());
String markerTitle = getCurrentAddress(currentPosition);
String markerSnippet = "위도 : " + location.getLatitude() + ", 경도 : " + location.getLongitude();
setCurrentLocation(location, markerTitle, markerSnippet);
if (!editSearch.getText().equals("")) {
btnSearch.performClick();
Log.i("검색", "버튼눌렀다");
}
}
}
};
private void startLocationUpdates() {
if (!checkLocationServicesStatus()) {
showDialogForLocationServiceSetting();
} else {
int hasFineLocationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
int hasCoarseLocationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (hasFineLocationPermission != PackageManager.PERMISSION_GRANTED || hasCoarseLocationPermission != PackageManager.PERMISSION_GRANTED) {
return;
}
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
if (checkPermission()) {
mMap.setMyLocationEnabled(true);
}
}
}
;
@Override
protected void onStart() {
super.onStart();
if (checkPermission()) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
}
}
@Override
protected void onStop() {
super.onStop();
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(locationCallback);
}
}
public void searchLocation(View view) {
String keyword = editSearch.getText().toString();
Log.i("검색 키워드", keyword);
LatLng searchLatLng = getAddressCoordinate(keyword);
if (searchLatLng != null) {
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(searchLatLng);
mMap.moveCamera(cameraUpdate);
if (currentMarker != null) {
clearMarker();
}
showRoomList(mMap.getProjection().getVisibleRegion().latLngBounds);
}
}
public String getCurrentAddress(LatLng latlng) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(
latlng.latitude,
latlng.longitude,
1
);
} catch (IOException ioException) {
// Toast.makeText(this, "지오코더 서비스 사용불가", Toast.LENGTH_LONG).show();
return "지오코더 서비스 사용불가";
} catch (IllegalArgumentException illegalArgumentException) {
Toast.makeText(this, "잘못된 GPS 좌표", Toast.LENGTH_LONG).show();
return "잘못된 GPS 좌표";
}
if (addresses == null || addresses.size() == 0) {
// Toast.makeText(this, "주소 미발견", Toast.LENGTH_LONG).show();
return "주소 미발견";
} else {
Address address = addresses.get(0);
return address.getAddressLine(0).toString();
}
}
public LatLng getAddressCoordinate(String strAddress) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
LatLng latLng = null;
try {
addresses = geocoder.getFromLocationName(
strAddress,
1
);
} catch (IOException ioException) {
// Toast.makeText(this, "지오코더 서비스 사용불가", Toast.LENGTH_LONG).show();
} catch (IllegalArgumentException illegalArgumentException) {
Toast.makeText(this, "잘못된 GPS 좌표", Toast.LENGTH_LONG).show();
}
if (addresses == null || addresses.size() == 0) {
// Toast.makeText(this, "주소 미발견", Toast.LENGTH_LONG).show();
} else {
Address address = addresses.get(0);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
}
return latLng;
}
public boolean checkLocationServicesStatus() {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void setCurrentLocation(Location location, String markerTitle, String markerSnippet) {
if (currentMarker != null) {
clearMarker();
}
LatLng currentLatLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(currentLatLng);
mMap.moveCamera(cameraUpdate);
}
public void setDefaultLocation() {
LatLng DEFAULT_LOCATION = new LatLng(37.4839778342191, 126.955578840377);
String markerTitle = "위치정보 가져올 수 없음";
String markerSnippet = "위치 퍼미션과 GPS 활성 여부를 확인하세요.";
if (currentMarker != null) {
clearMarker();
}
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(DEFAULT_LOCATION);
markerOptions.title(markerTitle);
markerOptions.snippet(markerSnippet);
markerOptions.draggable(false);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
currentMarker.add(mMap.addMarker(markerOptions));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(DEFAULT_LOCATION, 15);
mMap.moveCamera(cameraUpdate);
}
private boolean checkPermission() {
int hasFineLocationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
int hasCoarseLocationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED &&
hasCoarseLocationPermission == PackageManager.PERMISSION_GRANTED) {
return true;
}
return false;
}
/*
* ActivityCompat.requestPermissions를 사용한 퍼미션 요청의 결과를 리턴받는 메소드입니다.
*/
@Override
public void onRequestPermissionsResult(int permsRequestCode,
@NonNull String[] permissions,
@NonNull int[] grandResults) {
if (permsRequestCode == PERMISSIONS_REQUEST_CODE &&
grandResults.length == REQUIRED_PERMISSIONS.length) {
// 요청 코드가 PERMISSIONS_REQUEST_CODE 이고, 요청한 퍼미션 개수만큼 수신되었다면
boolean checkResult = true;
// 모든 퍼미션을 허용했는지 체크합니다.
for (int result : grandResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
checkResult = false;
break;
}
}
if (checkResult) {
startLocationUpdates();
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, REQUIRED_PERMISSIONS[0])
|| ActivityCompat.shouldShowRequestPermissionRationale(this, REQUIRED_PERMISSIONS[1])) {
// 사용자가 거부만 선택한 경우에는 앱을 다시 실행하여 허용을 선택하면 앱을 사용할 수 있습니다.
Snackbar.make(mLayout, "퍼미션이 거부되었습니다. 앱을 다시 실행하여 퍼미션을 허용해주세요. ",
Snackbar.LENGTH_INDEFINITE).setAction("확인", new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
}).show();
} else {
// "다시 묻지 않음"을 사용자가 체크하고 거부를 선택한 경우에는 설정(앱 정보)에서 퍼미션을 허용해야 앱을 사용할 수 있습니다.
Snackbar.make(mLayout, "퍼미션이 거부되었습니다. 설정(앱 정보)에서 퍼미션을 허용해야 합니다. ",
Snackbar.LENGTH_INDEFINITE).setAction("확인", new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
}).show();
}
}
}
}
// GPS 활성화를 위한 메서드
private void showDialogForLocationServiceSetting() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("위치 서비스 비활성화");
builder.setMessage("앱을 사용하기 위해서는 위치 서비스가 필요합니다.\n"
+ "위치 설정을 수정하실래요?");
builder.setCancelable(true);
builder.setPositiveButton("설정", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent
= new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(callGPSSettingIntent, GPS_ENABLE_REQUEST_CODE);
}
});
builder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case GPS_ENABLE_REQUEST_CODE:
//사용자가 GPS 활성 시켰는지 검사
if (checkLocationServicesStatus()) {
if (checkLocationServicesStatus()) {
needRequest = true;
return;
}
}
break;
}
}
public void showRoomList(LatLngBounds latLngBounds) {
String[] southWestSpl = latLngBounds.southwest.toString().substring(9).split(",");
String southWest = southWestSpl[0] + ", " + southWestSpl[1];
String[] northEastSpl = latLngBounds.northeast.toString().substring(9).split(",");
String northEast = northEastSpl[0] + ", " + northEastSpl[1];
String url = ROOT_CONTEXT + "/searchRoom/search?southWest=" + southWest + "&northEast=" + northEast;
StringRequest request = new Utf8StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
List<RoomSummaryViewVO> roomList = getRoomList(response);
System.out.println(roomList.size());
if (roomList == null || roomList.size() == 0) {
clearMarker();
Toast.makeText(getApplicationContext(), "검색 된 매물이 없습니다.", Toast.LENGTH_LONG).show();
return;
}
if (currentMarker != null) {
clearMarker();
for (RoomSummaryViewVO room : roomList) {
if (room.getPostType().equals("게시중")) {
LatLng position = new LatLng(room.getLatitude().doubleValue(), room.getLongitude().doubleValue());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(position);
markerOptions.title(room.getSido() + " " + room.getSigungu() + " " + room.getRoadname());
markerOptions.snippet("[" + room.getRoomType() + "] " + room.getTitle());
markerOptions.draggable(false);
switch (room.getRoomType()) {
case "아파트":
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(resizeMarker(R.drawable.mk_ap)));
break;
case "오피스텔":
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(resizeMarker(R.drawable.mk_of)));
break;
case "원룸":
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(resizeMarker(R.drawable.mk_or)));
break;
case "투룸":
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(resizeMarker(R.drawable.mk_tr)));
break;
case "빌라":
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(resizeMarker(R.drawable.mk_vi)));
break;
}
currentMarker.add(mMap.addMarker(markerOptions));
}
}
listView.removeAllViewsInLayout();
listView.setAdapter(new RoomSummaryViewAdapter(getApplicationContext(), roomList));
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error: " + error.getMessage());
}
}
) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
request.setShouldCache(false);
requestQueue.add(request);
}
public Bitmap resizeMarker(int id) {
Bitmap bitmap;
bitmap = ((BitmapDrawable) getResources().getDrawable(id)).getBitmap();
return Bitmap.createScaledBitmap(bitmap, 150, 180, false);
}
class Utf8StringRequest extends StringRequest {
public Utf8StringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(method, url, listener, errorListener);
}
public Utf8StringRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(url, listener, errorListener);
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
String utf8String = new String(response.data, "UTF-8");
return Response.success(utf8String, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
}
public List<RoomSummaryViewVO> getRoomList(String response) {
List<RoomSummaryViewVO> roomList = new ArrayList<>();
JsonParser jsonParser = new JsonParser();
Object obj = jsonParser.parse(response);
JsonObject jsonObj = (JsonObject) obj;
int check = 0;
for (int i = 0; i < jsonObj.size(); i++) {
String temp = jsonObj.get("item" + i).toString();
Object object = jsonParser.parse(temp.substring(3, temp.length() - 3).replace("\\\"", "\""));
JsonObject jsonObject = (JsonObject) object;
RoomSummaryViewVO roomSummaryViewVO = new RoomSummaryViewVO();
List<String> roomOptions = new ArrayList<>();
roomSummaryViewVO.setRoomId(Integer.parseInt(jsonObject.get("roomId").getAsString()));
roomSummaryViewVO.setLatitude(jsonObject.get("latitude").getAsBigDecimal());
roomSummaryViewVO.setLongitude(jsonObject.get("longitude").getAsBigDecimal());
roomSummaryViewVO.setPostType(jsonObject.get("postType").getAsString());
roomSummaryViewVO.setTitle(jsonObject.get("title").getAsString());
String[] address = (jsonObject.get("address").getAsString().split(" "));
roomSummaryViewVO.setSido(address[0]);
roomSummaryViewVO.setSigungu(address[1]);
roomSummaryViewVO.setRoadname(address[2]);
roomSummaryViewVO.setPeriodNum(Integer.parseInt(jsonObject.get("period").getAsString().replaceAll("[^0-9]", "")));
roomSummaryViewVO.setPeriodUnit(jsonObject.get("period").getAsString().replaceAll("[0-9]", ""));
roomSummaryViewVO.setPostType(jsonObject.get("postType").getAsString());
roomSummaryViewVO.setRoomType(jsonObject.get("roomType").getAsString());
roomSummaryViewVO.setRentType(jsonObject.get("rentType").getAsString());
roomSummaryViewVO.setArea(jsonObject.get("area").getAsDouble());
roomSummaryViewVO.setDeposit(jsonObject.get("deposit").getAsString());
roomSummaryViewVO.setMonthlyCost(jsonObject.get("monthlyCost").getAsString());
roomSummaryViewVO.setManageCost(jsonObject.get("manageCost").getAsString());
roomSummaryViewVO.setWriteDate(Date.valueOf(jsonObject.get("writeDate").getAsString()));
roomSummaryViewVO.setViews(jsonObject.get("views").getAsInt());
roomSummaryViewVO.setRoomImg(jsonObject.get("roomImg").getAsString());
for (JsonElement e : jsonObject.get("roomOptions").getAsJsonArray()) {
roomOptions.add(e.getAsString());
}
if (selectedBT.size() != Constants.BUILDING_TYPE_SIZE) {
boolean isContains = isBuildingTypeChecked(roomSummaryViewVO.getRoomType());
if (!isContains)
continue;
}
int depositRange;
switch (depositProgress) {
case 0:
depositRange = 0;
break;
case 1:
depositRange = 300;
break;
case 2:
depositRange = 500;
break;
case 3:
depositRange = 1000;
break;
case 4:
depositRange = 99999999;
break;
default:
depositRange = 99999999;
break;
}
String d = jsonObject.get("deposit").getAsString().replaceAll("[^0-9]", "");
if (!d.equals("")) {
if (Integer.parseInt(d) > depositRange) {
continue;
}
}
int monthlyCostRange;
switch (monthlyCostProgress) {
case 0:
monthlyCostRange = 0;
break;
case 1:
monthlyCostRange = 30;
break;
case 2:
monthlyCostRange = 50;
break;
case 3:
monthlyCostRange = 100;
break;
case 4:
monthlyCostRange = 99999;
break;
default:
monthlyCostRange = 99999;
break;
}
String m = jsonObject.get("monthlyCost").getAsString().replaceAll("[^0-9]", "");
if (!m.equals("")) {
if (Integer.parseInt(m) > monthlyCostRange) {
continue;
}
}
int periodNum = roomSummaryViewVO.getPeriodNum();
int rentD = 1;
int rentRange = 99999;
switch(periodValue) {
case 0: rentRange = 0; break;
case 1: rentRange = 30; break;
case 2: rentRange = 180; break;
case 3: rentRange = 365; break;
case 4: rentRange = 99999; break;
}
switch(roomSummaryViewVO.getPeriodUnit()) {
case "주": rentD = periodNum * 7; break;
case "개월": rentD = periodNum * 30; break;
case "년": rentD = periodNum * 365; break;
}
if (rentD > rentRange) {
continue;
}
if(curCheckBoxArray != null){
if (roomOptions.size() < curCheckBoxArray.size()){
continue;
}
for (int j=0; j<curCheckBoxArray.size(); j++){
if (roomOptions.contains(curCheckBoxArray.get(j)) == false){
check = 1;
break;
}
}
if(check == 0){
roomSummaryViewVO.setRoomOptions(roomOptions);
roomList.add(roomSummaryViewVO);
} else{
check = 0;
}
} else{
roomSummaryViewVO.setRoomOptions(roomOptions);
roomList.add(roomSummaryViewVO);
}
}
return roomList;
}
private boolean isBuildingTypeChecked(String roomType) {
boolean isContains = false;
switch (roomType) {
case "아파트" :
if (selectedBT.contains(Constants.BUILDING_AP))
isContains = true;
break;
case "빌라" :
if (selectedBT.contains(Constants.BUILDING_VI))
isContains = true;
break;
case "오피스텔" :
if (selectedBT.contains(Constants.BUILDING_OF))
isContains = true;
break;
case "투룸" :
if (selectedBT.contains(Constants.BUILDING_TR))
isContains = true;
break;
case "원룸" :
if (selectedBT.contains(Constants.BUILDING_OR))
isContains = true;
break;
}
return isContains;
}
public void clearMarker() {
int i = 0;
while (currentMarker.size() > i) {
if (currentMarker.get(i).isInfoWindowShown() == false) {
currentMarker.get(i).remove();
currentMarker.remove(i);
continue;
}
i++;
}
}
public void clickSlide(View view) {
SlidingUpPanelLayout slidingPanel = (SlidingUpPanelLayout)mLayout;
switch (slidingPanel.getPanelState().toString()) {
case "EXPANDED" :
slidingPanel.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
Glide.with(MainActivity.this).load(R.drawable.angle_up_custom).into(btnSlide);
break;
case "COLLAPSED" :
if(popupLayout.getChildCount()==1) {
allSelectedFalse();
popupLayout.removeAllViews();
searchBar.setVisibility(View.VISIBLE);
}
slidingPanel.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
Glide.with(MainActivity.this).load(R.drawable.angle_down_custom).into(btnSlide);
break;
}
}
public void clickFilter(View view) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Button button = findViewById(view.getId());
int layoutId = popupLayout.getId();
SlidingUpPanelLayout slidingPanel = (SlidingUpPanelLayout)mLayout;
switch (view.getId()) {
case R.id.btnBuildingType:
layoutId = R.layout.popup_building;
break;
case R.id.btnPeriod:
layoutId = R.layout.popup_period;
break;
case R.id.btnDeposit:
layoutId = R.layout.popup_deposit;
break;
case R.id.btnMonthlyCost:
layoutId = R.layout.popup_monthly;
break;
case R.id.btnOption:
layoutId = R.layout.popup_option;
break;
}
if (slidingPanel.getPanelState().toString().equals("EXPANDED")) {
slidingPanel.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
Glide.with(MainActivity.this).load(R.drawable.angle_up_custom).into(btnSlide);
}
if(button.isSelected()) {
popupLayout.removeAllViews();
searchBar.setVisibility(View.VISIBLE);
button.setSelected(false);
}
else {
allSelectedFalse();
popupLayout.removeAllViews();
popupLayout.addView(inflater.inflate(layoutId, null));
searchBar.setVisibility(View.GONE);
switch (button.getId()) {
case R.id.btnBuildingType:
initBuildingType();
break;
case R.id.btnPeriod:
if (periodValue < 0) periodValue = 4;
((SeekBar) findViewById(R.id.periodSeekBar)).setProgress(periodValue);
break;
case R.id.btnDeposit:
if (depositProgress < 0) depositProgress = 4;
((SeekBar) findViewById(R.id.depositBar)).setProgress(depositProgress);
break;
case R.id.btnMonthlyCost:
if (monthlyCostProgress < 0) monthlyCostProgress = 4;
((SeekBar) findViewById(R.id.monthlyCostBar)).setProgress(monthlyCostProgress);
break;
case R.id.btnOption:
optionList();
break;
}
button.setSelected(true);
}
}
private void initBuildingType() {
for (int buildingType : selectedBT) {
switch (buildingType) {
case Constants.BUILDING_AP:
Button AP = findViewById(R.id.AP);
AP.setSelected(true);
break;
case Constants.BUILDING_OF:
Button OF = findViewById(R.id.OF);
OF.setSelected(true);
break;
case Constants.BUILDING_VI:
Button VI = findViewById(R.id.VI);
VI.setSelected(true);
break;
case Constants.BUILDING_TR:
Button TR = findViewById(R.id.TR);
TR.setSelected(true);
break;
case Constants.BUILDING_OR:
Button OR = findViewById(R.id.OR);
OR.setSelected(true);
break;
}
}
}
public void clickCancel(View view) {
allSelectedFalse();
popupLayout.removeAllViews();
searchBar.setVisibility(View.VISIBLE);
}
public void clickApply(View view) {
allSelectedFalse();
popupLayout.removeAllViews();
showRoomList(mMap.getProjection().getVisibleRegion().latLngBounds);
searchBar.setVisibility(View.VISIBLE);
}
public void periodApply(View view){
if(periodValue > -1) {
periodValue = ((SeekBar) findViewById(R.id.periodSeekBar)).getProgress();
}
allSelectedFalse();
popupLayout.removeAllViews();
showRoomList(mMap.getProjection().getVisibleRegion().latLngBounds);
searchBar.setVisibility(View.VISIBLE);
}
public void depositApply(View view) {
if (depositProgress > -1) {
depositProgress = ((SeekBar) findViewById(R.id.depositBar)).getProgress();
}
allSelectedFalse();
popupLayout.removeAllViews();
showRoomList(mMap.getProjection().getVisibleRegion().latLngBounds);
searchBar.setVisibility(View.VISIBLE);
}
public void monthlyCostApply(View view) {
if (monthlyCostProgress > -1) {
monthlyCostProgress = ((SeekBar) findViewById(R.id.monthlyCostBar)).getProgress();
}
allSelectedFalse();
popupLayout.removeAllViews();
showRoomList(mMap.getProjection().getVisibleRegion().latLngBounds);
searchBar.setVisibility(View.VISIBLE);
}
public void allSelectedFalse() {
btnBuildingType.setSelected(false);
btnPeriod.setSelected(false);
btnDeposit.setSelected(false);
btnMonthlyCost.setSelected(false);
btnOption.setSelected(false);
}
public void changeBtnColor(View view) {
Button thisBtn = (Button)view;
if (thisBtn.isSelected()) {
thisBtn.setSelected(false);
} else {
thisBtn.setSelected(true);
}
}
public void clickApplyBT(View view) {
selectedBT.clear();
int[] btnIds = { R.id.AP, R.id.VI, R.id.OF, R.id.TR, R.id.OR };
for (int i = 0; i < btnIds.length; i++) {
Button btn = findViewById(btnIds[i]);
if (btn.isSelected()) {
selectedBT.add(Constants.BUILDING_AP + i);
}
}
clickApply(view);
showRoomList(mMap.getProjection().getVisibleRegion().latLngBounds);
}
public void optionList(){
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
checkBoxList = new ArrayList<>();
String url = ROOT_CONTEXT + "/mobile/search";
StringRequest request = new Utf8StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
String result = createOptionList(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error: " + error.getMessage());
}
}
) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
request.setShouldCache(false);
requestQueue.add(request);
}
public String createOptionList(String response) {
JsonParser jsonParser = new JsonParser();
JsonObject jsonObj = (JsonObject) jsonParser.parse(response);
JsonArray optionList = jsonObj.get("options").getAsJsonArray();
int size = optionList.size();
JsonObject jsonOption;
String option;
for(int i=0; i<size; i=i+2){
TableRow tr = new TableRow(this);
for(int j=i; j<=i+1; j++){
if(j == size){
break;
}
jsonOption = optionList.get(j).getAsJsonObject();
option = jsonOption.get(j+1+"").getAsString();
CheckBox checkBox = new CheckBox(this);
checkBox.setText(option);
if(curCheckBoxArray.contains(option) == true){
checkBox.setChecked(true);
}
checkBox.setOnClickListener(new CheckBox.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println(((CheckBox)v).getText() + "클릭");
if (((CheckBox)v).isChecked()) {
curCheckBoxArray.add(((CheckBox)v).getText()+"");
} else {
curCheckBoxArray.remove(((CheckBox)v).getText()+"");
}
System.out.println("현재 체크 된 값 : " + curCheckBoxArray);
}
}) ;
int states[][] = {{android.R.attr.state_checked}, {}};
int colors[] = {Color.rgb(182, 226, 248), Color.GRAY};
CompoundButtonCompat.setButtonTintList(checkBox, new ColorStateList(states, colors));
float scale = getResources().getDisplayMetrics().density;
checkBox.setPadding(checkBox.getPaddingLeft() + (int)(30.0f * scale + 0.5f),
checkBox.getPaddingTop(),
checkBox.getPaddingRight(),
checkBox.getPaddingBottom());
checkBoxList.add(checkBox);
tr.addView(checkBox);
}
filterOption = findViewById(R.id.filterOption);
filterOption.addView(tr);
}
return "SUCCESS";
}
public void clickCancelOption(View view) {
curCheckBoxArray.clear();
if(confirmArray != null){
curCheckBoxArray = new ArrayList<>(confirmArray);
}
mLayout.setEnabled(true);
allSelectedFalse();
popupLayout.removeAllViews();
searchBar.setVisibility(View.VISIBLE);
}
public void clickApplyOption(View view) {
confirmArray = new ArrayList<>(curCheckBoxArray);
mLayout.setEnabled(true);
allSelectedFalse();
popupLayout.removeAllViews();
showRoomList(mMap.getProjection().getVisibleRegion().latLngBounds);
searchBar.setVisibility(View.VISIBLE);
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Log.i("NavigatinoItemSeleted", "selected " + id);
switch (id) {
case R.id.nav_search :
break;
case R.id.nav_like :
Intent intent = new Intent(MainActivity.this, MainViewActivity.class);
intent.putExtra("nickname", nickname);
intent.putExtra("memberId", memberId);
intent.putExtra("isLike", "true");
startActivity(intent);
finish();
break;
}
drawerLayout.closeDrawer(navigationView);
return true;
}
@OnClick(R.id.botMain)
public void clickMain(View v) {
Intent intent = new Intent(MainActivity.this, MainViewActivity.class);
intent.putExtra("nickname", nickname);
intent.putExtra("memberId", memberId);
startActivity(intent);
finish();
}
@OnClick(R.id.botSearch)
public void clickSearch(View v) {
}
@OnClick(R.id.botLike)
public void clickLike(View v) {
Intent intent = new Intent(MainActivity.this, MainViewActivity.class);
intent.putExtra("nickname", nickname);
intent.putExtra("memberId", memberId);
intent.putExtra("isLike", "true");
startActivity(intent);
finish();
}
@OnClick(R.id.botMore)
public void clickMore(View v) {
drawerLayout.openDrawer(navigationView);
}
}<file_sep>/app/src/main/java/com/murmuler/organicstack/vo/RoomSummaryViewVO.java
package com.murmuler.organicstack.vo;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.List;
public class RoomSummaryViewVO {
private int roomId;
private BigDecimal latitude;
private BigDecimal longitude;
private String postType;
private String title;
private String sido;
private String sigungu;
private String roadname;
private int periodNum;
private String periodUnit;
private String roomType;
private String rentType;
private double area;
private String deposit;
private String monthlyCost;
private String manageCost;
private Date writeDate;
private int views;
private String roomImg;
private List<String> roomOptions;
public RoomSummaryViewVO() { }
public RoomSummaryViewVO(int roomId, BigDecimal latitude, BigDecimal longitude, String postType, String title, String sido, String sigungu, String roadname, int periodNum, String periodUnit, String roomType, String rentType, double area, String deposit, String monthlyCost, String manageCost, Date writeDate, int views, String roomImg, List<String> roomOptions) {
this.roomId = roomId;
this.latitude = latitude;
this.longitude = longitude;
this.postType = postType;
this.title = title;
this.sido = sido;
this.sigungu = sigungu;
this.roadname = roadname;
this.periodNum = periodNum;
this.periodUnit = periodUnit;
this.roomType = roomType;
this.rentType = rentType;
this.area = area;
this.deposit = deposit;
this.monthlyCost = monthlyCost;
this.manageCost = manageCost;
this.writeDate = writeDate;
this.views = views;
this.roomImg = roomImg;
this.roomOptions = roomOptions;
}
public int getRoomId() {
return roomId;
}
public void setRoomId(int roomId) {
this.roomId = roomId;
}
public BigDecimal getLatitude() {
return latitude;
}
public void setLatitude(BigDecimal latitude) {
this.latitude = latitude;
}
public BigDecimal getLongitude() {
return longitude;
}
public void setLongitude(BigDecimal longitude) {
this.longitude = longitude;
}
public String getPostType() {
return postType;
}
public void setPostType(String postType) {
this.postType = postType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSido() {
return sido;
}
public void setSido(String sido) {
this.sido = sido;
}
public String getSigungu() {
return sigungu;
}
public void setSigungu(String sigungu) {
this.sigungu = sigungu;
}
public String getRoadname() {
return roadname;
}
public void setRoadname(String roadname) {
this.roadname = roadname;
}
public int getPeriodNum() {
return periodNum;
}
public void setPeriodNum(int periodNum) {
this.periodNum = periodNum;
}
public String getPeriodUnit() {
return periodUnit;
}
public void setPeriodUnit(String periodUnit) {
this.periodUnit = periodUnit;
}
public String getRoomType() {
return roomType;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
public String getRentType() {
return rentType;
}
public void setRentType(String rentType) {
this.rentType = rentType;
}
public double getArea() {
return area;
}
public void setArea(double area) {
this.area = area;
}
public String getDeposit() {
return deposit;
}
public void setDeposit(String deposit) {
this.deposit = deposit;
}
public String getMonthlyCost() {
return monthlyCost;
}
public void setMonthlyCost(String monthlyCost) {
this.monthlyCost = monthlyCost;
}
public String getManageCost() {
return manageCost;
}
public void setManageCost(String manageCost) {
this.manageCost = manageCost;
}
public Date getWriteDate() {
return writeDate;
}
public void setWriteDate(Date writeDate) {
this.writeDate = writeDate;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
public String getRoomImg() {
return roomImg;
}
public void setRoomImg(String roomImg) {
this.roomImg = roomImg;
}
public List<String> getRoomOptions() {
return roomOptions;
}
public void setRoomOptions(List<String> roomOptions) {
this.roomOptions = roomOptions;
}
@Override
public String toString() {
return "RoomSummaryViewVO{" +
"roomId=" + roomId +
", latitude=" + latitude +
", longitude=" + longitude +
", postType='" + postType + '\'' +
", title='" + title + '\'' +
", sido='" + sido + '\'' +
", sigungu='" + sigungu + '\'' +
", roadname='" + roadname + '\'' +
", periodNum=" + periodNum +
", periodUnit='" + periodUnit + '\'' +
", roomType='" + roomType + '\'' +
", rentType='" + rentType + '\'' +
", area=" + area +
", deposit=" + deposit +
", monthlyCost=" + monthlyCost +
", manageCost=" + manageCost +
", writeDate=" + writeDate +
", views=" + views +
", roomImg='" + roomImg + '\'' +
", roomOptions=" + roomOptions +
'}';
}
}
| cc3715581f25053a941ec8ccf1efba3ae2febd24 | [
"Java",
"Markdown"
] | 4 | Java | YJeongKim/murmul-er_app | 4bfbaee8db749365aeb6373ef3a1956a0b54726f | 2911ddad6be08e596036d388808d4a3231e6f85e |
refs/heads/main | <repo_name>rookie0806/testtesttest<file_sep>/autotrade.py
import requests
import pandas as pd
import time
import webbrowser
import numpy
import time
import sys
import telegram
import pandas as pd
import requests
import pandas as pd
import sys
import time
from bs4 import BeautifulSoup
import telegram
from urllib.parse import urlencode
import os
import jwt
import uuid
import hashlib
import datetime
import requests
import requests
import datetime
import time
import sys
import numpy
import readchar
import pandas
import pyupbit
access_key = '<KEY>'
secret_key = '<KEY>'
server_url = 'https://api.upbit.com'
upbit = pyupbit.Upbit(access_key, secret_key)
#code = ["XRP","DAWN","DOGE","STRK","ETC","SRM","WAVES","BTG","NEO","QTUM","EOS","SC","CBK","PUNDIX","GAS","MLK","SBD","AXS","ONT","OBSR","MVL","FLOW","ARK","MTL","TON","STX","MBL","TSHP","STRAX","ADA","STMX","PCI","CRE","IOST","SXP","DOT","MANA","STEEM","STPT","LINK","QTCON","DMT","RFR","LTC","MFT","LAMB","GRS","EDR","AERGO","BCHA","AQT","BSV","TT","KNC","IQ","QKC","STORJ","ICX","AHT","ZRX","LSK","ONG","XTZ","KAVA","THETA","ENJ","OMG","REP","ATOM","BAT","ADX","IOTA"]
#code = ["ETH","QTUM","BTC","XRP","EOS","BCH","BTT","ADA","LTC","KMD","EOS","SC","CBK","PUNDIX","GAS","MLK","SBD","AXS","ONT","OBSR","MVL","FLOW","ARK","MTL","TON","STX","MBL","TSHP","STRAX","ADA","STMX","PCI","CRE","IOST","SXP","DOT","MANA","STEEM","STPT","LINK","QTCON","DMT","RFR","LTC","MFT","LAMB","GRS","EDR","AERGO","BCHA","AQT","BSV","TT","KNC","IQ","QKC","STORJ","ICX","AHT","ZRX","LSK","ONG","XTZ","KAVA","THETA","ENJ","OMG","REP","ATOM","BAT","ADX","IOTA"]
#code = ["BTT","MBL","AHT","TT","MFT","CRE","RFR","TSHP","IQ","MVL","OBSR","QKC","SC","STMX","EDR","IOST","QTCON","LAMB","STPT"]
code = ["BTC","ETH","BCH","LTC","BSV","ETC","BTG","NEO","STRK","LINK","REP","DOT","BCHA","WAVES","ATOM","FLOW","QTUM","SBD","GAS"]
buyflag = []
telegram_token = '<PASSWORD>:<PASSWORD>'
bot = telegram.Bot(token = telegram_token)
hap = 0
money = 20000000
cnt = 0
def buy(coin,volume,price):
query = {
'market': 'KRW-'+coin,
'side': 'bid',
'price': price,
'volume': '',
'ord_type': 'price',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
print(res.text)
if(res.status_code==201):
return True
else:
return False
def sell(coin,volume,price):
query = {
'market': 'KRW-'+coin,
'side': 'ask',
'price': '',
'volume': volume,
'ord_type': 'market',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
print(res.text)
if(res.status_code==201):
#return float(res.json()["price"])
return 1
else:
return 0
def get_my_value(coin):
query = {
'market': 'KRW-'+coin,
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.get(server_url + "/v1/orders/chance", params=query, headers=headers)
balance = float(res.json()["ask_account"]["balance"])
avg_buy_price = float(res.json()["ask_account"]["avg_buy_price"])
return balance,avg_buy_price
def get_my_KRW():
m = hashlib.sha512()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.get(server_url + "/v1/accounts", headers=headers)
print(float(res.json()[0]["balance"]))
return float(res.json()[0]["balance"])
for j in range(0,len(code)):
buyflag.append(True)
buymoney = 0
nowcode = ''
sonik = 0
flag = False
while True:
if(flag == False):
for i in range(0,len(code)):
url = "https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/3?code=CRIX.UPBIT.KRW-"+code[i]+"&count=400"
response = requests.request("GET", url)
data = response.json()
df = pd.DataFrame(data)
now = time.localtime()
#print(df.iloc[0]["tradePrice"])
if(df.iloc[0]["highPrice"] > df.iloc[1]["highPrice"] and df.iloc[0]["tradePrice"] < df.iloc[1]["highPrice"] and df.iloc[2]["tradePrice"] > df.iloc[1]["tradePrice"] and df.iloc[3]["tradePrice"] > df.iloc[2]["tradePrice"] ):
print(code[i],df.iloc[0]["tradePrice"],"구매")
ret = upbit.buy_limit_order("KRW-"+code[i], df.iloc[0]["tradePrice"], (get_my_KRW()-300)/df.iloc[0]["tradePrice"])
print(ret)
try:
cancelcode =ret['uuid']
time.sleep(3)
ret = upbit.cancel_order(cancelcode)
try:
if(ret["error"]):
nowcode = code[i]
flag = True
time.sleep(5)
break
except:
pass
except:
pass
#bot.sendMessa ge(chat_id = '1780594186', text="["+code[j]+"] 구매시도")
time.sleep(1)
else:
mybal,my_avg_price = get_my_value(nowcode)
url = "https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/3?code=CRIX.UPBIT.KRW-"+nowcode+"&count=1"
response = requests.request("GET", url)
data = response.json()
if(mybal!=0):
if(my_avg_price * 1.006 <= data[0]["tradePrice"]):
#sell(nowcode,mybal,mybal)
print(nowcode,data[0]["tradePrice"],"판매")
ret = upbit.sell_limit_order("KRW-"+nowcode, data[0]["tradePrice"], mybal)
print(ret)
try:
cancelcode =ret['uuid']
time.sleep(1)
ret = upbit.cancel_order(cancelcode)
try:
if(ret["error"]):
flag = False
bot.sendMessage(chat_id = '1780594186', text="["+get_my_KRW()+"]")
time.sleep(10)
except:
time.sleep(0.1)
except:
pass
if(my_avg_price * 0.994 >= data[0]["tradePrice"]):
#sell(nowcode,mybal,mybal)
print(nowcode,data[0]["tradePrice"],"판매")
ret = upbit.sell_limit_order("KRW-"+nowcode, data[0]["tradePrice"], mybal)
print(ret)
try:
cancelcode =ret['uuid']
time.sleep(1)
ret = upbit.cancel_order(cancelcode)
try:
if(ret["error"]):
flag = False
bot.sendMessage(chat_id = '1780594186', text="["+get_my_KRW()+"]")
time.sleep(10)
except:
time.sleep(0.1)
except:
pass
if(mybal==0):
flag = False
else:
time.sleep(1)
time.sleep(0.2)<file_sep>/test2.bat
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py SC 60 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py TSHP 60 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py OBSR 60 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py MVL 60 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py QKC 60 1.5"
<file_sep>/test.py
import pandas as pd
from keras.layers.core import Dense, Dropout
from keras.layers.recurrent import GRU
from keras.models import Sequential, load_model
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import requests
import pandas as pd
import sys
import time
from bs4 import BeautifulSoup
import telegram
from urllib.parse import urlencode
import os
import jwt
import uuid
import hashlib
import datetime
import requests
import requests
import datetime
import time
import sys
import numpy
import numpy
from sklearn.preprocessing import OneHotEncoder
import pandas
import matplotlib.pyplot as plt
from pathlib import Path
from sklearn import preprocessing
from keras.models import load_model
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.layers.recurrent import LSTM
from keras.layers import LeakyReLU
from keras.losses import binary_crossentropy
from keras.optimizers import Adam
x_scale = MinMaxScaler()
y_scale = MinMaxScaler()
first = False
class Predict:
def __init__(self,length):
self.length_of_sequences = length
self.input_neurons = 9
self.output_neurons = 1
self.hidden_neurons = int(length/7*5)
self.batch_size = 10
self.epochs = 10
self.percentage = 0.7
self.Model = self.create_model()
# prepare data
def load_data(self, data, n_prev):
x, y = [], []
x2 = data[['OpeningPrice','highPrice','lowPrice','tradePrice','CandleAccTradeVolume','rsi','macd','exp','candleAccTradePrice']]
y1 = data[['up']]
x1 = x_scale.fit_transform(x2)
x2 = pandas.DataFrame(x1,columns=x2.columns, index=list(x2.index.values))
y_t = y_scale.fit_transform(y1)
y2 = pandas.DataFrame(y_t,columns=y1.columns, index=list(y1.index.values))
for i in range(len(data) - n_prev):
x.append(x2[['OpeningPrice','highPrice','lowPrice','tradePrice','CandleAccTradeVolume','rsi','macd','exp','candleAccTradePrice']].iloc[i:(i+n_prev)].values)
y.append(y2.iloc[i+n_prev].values)
print("---------------------------")
print(x_scale.inverse_transform(x2[['OpeningPrice','highPrice','lowPrice','tradePrice','CandleAccTradeVolume','rsi','macd','exp','candleAccTradePrice']].iloc[i:(i+n_prev)].values))
print(y_scale.inverse_transform(y2.iloc[i+n_prev].values.reshape(-1, 1)))
print("---------------------------")
X = numpy.array(x)
Y = numpy.array(y)
return X, Y
# make model
def create_model(self):
Model = Sequential()
Model.add(LSTM(50, activation='relu',input_shape=(self.length_of_sequences, self.input_neurons), return_sequences=True))
Model.add(LSTM(64, return_sequences=False))
Model.add(Dense(1))
Model.compile(loss='mean_squared_error', optimizer='adam')
return Model
# do learning
def train(self, x_train, y_train, epoch):
self.Model.fit(x_train, y_train, self.batch_size,epoch)
model1 = "" #
model2 = ""
model3 = ""
access_key = '<KEY>'
secret_key = '<KEY>'
server_url = 'https://api.upbit.com'
telegram_token = '<KEY>'
bot = telegram.Bot(token = telegram_token)
def buy(coin,volume,price):
query = {
'market': 'KRW-'+coin,
'side': 'bid',
'price': price,
'volume': '',
'ord_type': 'price',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
if(res.status_code==201):
return True
else:
return False
def sell(coin,volume,price):
query = {
'market': 'KRW-'+coin,
'side': 'ask',
'price': '',
'volume': volume,
'ord_type': 'market',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
if(res.status_code==201):
#return float(res.json()["price"])
return 1
else:
return 0
def get_my_value(coin):
query = {
'market': 'KRW-'+coin,
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.get(server_url + "/v1/orders/chance", params=query, headers=headers)
balance = float(res.json()["ask_account"]["balance"])
avg_buy_price = float(res.json()["ask_account"]["avg_buy_price"])
return balance,avg_buy_price
def rsi(ohlc: pd.DataFrame, period: int = 14):
ohlc["tradePrice"] = ohlc["tradePrice"]
delta = ohlc["tradePrice"].diff()
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
_gain = up.ewm(com=(period - 1), min_periods=period).mean()
_loss = down.abs().ewm(com=(period - 1), min_periods=period).mean()
RS = _gain / _loss
return pd.Series(100 - (100 / (1 + RS)), name="RSI")
def returndata(prices,length,model,first):
yahoo = prices[['OpeningPrice','highPrice','lowPrice','tradePrice','CandleAccTradeVolume','rsi','macd','exp','candleAccTradePrice','up']]
predict = yahoo[-(length+15):]
yahoo = yahoo[:-(length+15)]
#print(predict)
x_train, y_train = model.load_data(yahoo.iloc[0:int(len(yahoo)*1)], length)
x = []
y= []
tp = []
x1 = predict[['OpeningPrice','highPrice','lowPrice','tradePrice','CandleAccTradeVolume','rsi','macd','exp','candleAccTradePrice']]
y1= predict[['up']]
print(x1)
x_t = x_scale.fit_transform(x1)
x2 = pandas.DataFrame(x_t,columns=x1.columns, index=list(x1.index.values))
y_t = y_scale.fit_transform(y1)
y2 = pandas.DataFrame(y_t,columns=y1.columns, index=list(y1.index.values))
#print(x1)
for i in range(0,16):
x3 = x2.iloc[i:i+length].values
y3 = y2.iloc[i+length-1].values
tpv = x1.iloc[i+length-1:i+length].values[0][3]
#print(tpv)
x.append(x3)
y.append(y3)
tp.append(tpv)
#print(x_scale.inverse_transform(x3))
#print(y)
x = numpy.array(x)
return x_train,y_train,x,tp
def modelpredict(prices,length,model,first):
yahoo = prices[['OpeningPrice','highPrice','lowPrice','tradePrice','CandleAccTradeVolume','rsi','macd','exp','candleAccTradePrice']]
predict = yahoo[-(length+1):]
yahoo = yahoo[:-(length+1)]
x_train, y_train = model.load_data(yahoo.iloc[0:int(len(yahoo)*1)], length)
x = []
y= []
x1 = predict[['OpeningPrice','highPrice','lowPrice','tradePrice','CandleAccTradeVolume','rsi','macd','exp','candleAccTradePrice']]
y1= predict[['up']]
x_t = x_scale.fit_transform(x1)
x2 = pandas.DataFrame(x_t,columns=x1.columns, index=list(x1.index.values))
for i in range(0,1):
x3 = x2.iloc[i:i+length].values
y2 = y1.iloc[i+length-1:i+length].values[0][0]
x.append(x3)
y.append(y2)
x = numpy.array(x)
model.train(x_train, y_train,10)
x_predicted = model.predict(x)
return x_predicted[-1][1]
#print(numpy.argmax(x_predicted, axis=-1))
#print(y)
#print(coin)
def start(coin, time, rate,predictflag):
global first,model1,model2,model3
if(predictflag==False):
minutes_units = [time]
for minutes_unit in minutes_units:
req = requests.get(f'https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/{minutes_unit}?code=CRIX.UPBIT.KRW-'+coin+'&count=1000')
data = req.json()
df = pd.DataFrame(reversed(data))
df2 = pd.DataFrame(data)
df3 = df2.iloc[::-1]
df3=df3['tradePrice']
df=df.reindex(index=df.index[::-1]).reset_index()
df['close']=df["tradePrice"]
trade_price = float(df["tradePrice"][199])
result = []
test = -100000
up = 0
for i, candle in enumerate(data):
if(i>=100):
TradePrice = float(data[399-i]["tradePrice"])
TradePrice1 = float(data[398-i]["tradePrice"])
TradePrice2 = float(data[397-i]["tradePrice"])
TradePrice3 = float(data[396-i]["tradePrice"])
TradePrice4 = float(data[395-i]["tradePrice"])
TradePrice5 = float(data[394-i]["tradePrice"])
df4=df3.iloc[i-100:i+1].reset_index(drop = True)
nowrsi = rsi(df4[:i].reset_index(), 14).iloc[-1]
exp1 = df4.ewm(span=5, adjust=False).mean()
exp2 = df4.ewm(span=12, adjust=False).mean()
macd = exp1-exp2
exp3 = macd.ewm(span=7, adjust=False).mean()
#print(macd)
#print('MACD: ',macd[0])
#print('Signal: ',exp3[0])
test = TradePrice
result.append({
'OpeningPrice' : data[399-i]["openingPrice"],
'highPrice' : data[399-i]["highPrice"],
'lowPrice' : data[399-i]["lowPrice"],
'tradePrice' : data[399-i]["tradePrice"],
'CandleAccTradeVolume' : data[399-i]["candleAccTradeVolume"],
"candleAccTradePrice" : data[399-i]["candleAccTradePrice"],
"rsi" : nowrsi,
"macd" : macd[100],
"exp" : exp3[100],
"up" : data[398-i]["openingPrice"]
})
prices = pd.DataFrame(result)
rate = []
avg = []
tparray = []
sumrate = 0.0
buymoney = 0
stock = 0
x_train1,y_train1,x,tp = returndata(prices,5,model1,False)
x_predicted1 = model1.Model.predict(x)
x_train2,y_train2,x,tp = returndata(prices,10,model2,False)
x_predicted2 = model2.Model.predict(x)
x_train3,y_train3,x,tp = returndata(prices,20,model3,False)
x_predicted3 = model3.Model.predict(x)
tparray.append(tp)
for i in range(0,16):
rate1 = y_scale.inverse_transform(x_predicted1[i][-1].reshape(-1, 1))[0][0]
rate2 = y_scale.inverse_transform(x_predicted2[i][-1].reshape(-1, 1))[0][0]
rate3 = y_scale.inverse_transform(x_predicted3[i][-1].reshape(-1, 1))[0][0]
rate.append([rate1,rate2,rate3])
avg.append((rate1+rate2+rate3)/3)
print(tp[i],rate1,rate2,rate3,(rate1+rate2+rate3)/3)
if(i>1):
if(expect>=tp[i-1] and tp[i]>=tp[i-1]):
print("예측성공")
if(expect<=tp[i-1] and tp[i]<=tp[i-1]):
print("예측성공")
else:
print("예측실패")
expect = (rate1+rate2+rate3)/3
print('---------------------')
'''
if(avg>=0.66):
if(buy(coin,50000,50000)):
mybal,my_avg_price = get_my_value(coin)
bot.sendMessage(chat_id = '1780594186', text="["+coin+"] ["+str(time)+"] 코인 구매 완료 상승 신뢰도 "+str(float(round(x_predicted[-1][1],2)*100)))
else:
bot.sendMessage(chat_id = '1780594186', text="["+coin+"] 코인 구매 실패 확인 바람")
if(avg<0.5):
mybal,my_avg_price = get_my_value(coin)
if(mybal!=0.0):
sellprice = sell(coin,mybal,trade_price)
else:
sellprice = 0
if(sellprice!=0):
bot.sendMessage(chat_id = '1780594186', text="["+coin+"] ["+str(time)+"] 코인 판매 완료")
else:
if(mybal!=0.0):
bot.sendMessage(chat_id = '1780594186', text="["+coin+"] 코인 판매 실패 확인 바람")
model1.train(x_train1, y_train1,100)
model2.train(x_train2, y_train2,100)
model3.train(x_train3, y_train3,100)
'''
else:
minutes_units = [time]
for minutes_unit in minutes_units:
'''
Scraping minutes data
'''
req = requests.get(f'https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/{minutes_unit}?code=CRIX.UPBIT.KRW-'+coin+'&count=1000')
data = req.json()
df = pd.DataFrame(reversed(data))
df2 = pd.DataFrame(data)
df3 = df2.iloc[::-1]
df3=df3['tradePrice']
df=df.reindex(index=df.index[::-1]).reset_index()
df['close']=df["tradePrice"]
trade_price = float(df["tradePrice"][199])
result = []
test = -100000
up = 0
for i, candle in enumerate(data):
if(i>=100):
TradePrice = float(data[399-i]["tradePrice"])
TradePrice1 = float(data[398-i]["tradePrice"])
TradePrice2 = float(data[397-i]["tradePrice"])
TradePrice3 = float(data[396-i]["tradePrice"])
TradePrice4 = float(data[395-i]["tradePrice"])
TradePrice5 = float(data[394-i]["tradePrice"])
df4=df3.iloc[i-100:i+1].reset_index(drop = True)
nowrsi = rsi(df4[:i].reset_index(), 14).iloc[-1]
exp1 = df4.ewm(span=5, adjust=False).mean()
exp2 = df4.ewm(span=12, adjust=False).mean()
macd = exp1-exp2
exp3 = macd.ewm(span=7, adjust=False).mean()
#print(macd)
#print('MACD: ',macd[0])
#print('Signal: ',exp3[0])
test = TradePrice
result.append({
'OpeningPrice' : data[399-i]["openingPrice"],
'highPrice' : data[399-i]["highPrice"],
'lowPrice' : data[399-i]["lowPrice"],
'tradePrice' : data[399-i]["tradePrice"],
'CandleAccTradeVolume' : data[399-i]["candleAccTradeVolume"],
"candleAccTradePrice" : data[399-i]["candleAccTradePrice"],
"rsi" : nowrsi,
"macd" : macd[100],
"exp" : exp3[100],
"up" : data[398-i]["openingPrice"],
})
prices = pd.DataFrame(result)
print(prices)
rate = []
sumrate = 0.0
x_train1,y_train1,x1,tp = returndata(prices,5,model1,False)
x_train2,y_train2,x2,tp = returndata(prices,10,model2,False)
x_train3,y_train3,x3,tp = returndata(prices,20,model3,False)
model1.train(x_train1, y_train1,500)
model2.train(x_train2, y_train2,500)
model3.train(x_train3, y_train3,500)
x_predicted = model1.Model.predict(x1)
rate1 = y_scale.inverse_transform(x_predicted[-1].reshape(-1, 1))[0][0]
x_predicted = model2.Model.predict(x2)
rate2 = y_scale.inverse_transform(x_predicted[-1].reshape(-1, 1))[0][0]
x_predicted = model3.Model.predict(x3)
rate3 = y_scale.inverse_transform(x_predicted[-1].reshape(-1, 1))[0][0]
rate = []
sumrate = 0.0
rate.append(rate1)
rate.append(rate2)
rate.append(rate3)
sumrate = rate1 + rate2 + rate3
avg = sumrate/3
print(rate)
print(avg)
first = True
#model1.Model.save("save_1")
#model2.Model.save("save_2")
#model3.Model.save("save_3")
def setting():
global model1,model2,model3
my_file = Path("save_1") # Path는 string을 return하는것 아님.window에서만 사용하능함.
if my_file.is_file():
model1 = load_model("save_1")
model2 = load_model("save_2")
model3 = load_model("save_3")
print("load 성공")
else:
model1 = Predict(5)
model2 = Predict(10)
model3 = Predict(20)
if __name__ == '__main__':
setting()
start("XRP", sys.argv[2], sys.argv[3],True)
#start("ADA", sys.argv[2], sys.argv[3],True)
#start("MLK", sys.argv[2], sys.argv[3],True)
#start(sys.argv[1], sys.argv[2], sys.argv[3],True)
#start("ONT", sys.argv[2], sys.argv[3],True)
start("XRP", sys.argv[2], sys.argv[3],False)
'''
flag = True
while True:
now = time.localtime()
if(now.tm_min%int(sys.argv[2])==int(sys.argv[2])-1 and now.tm_sec>=int(sys.argv[4]) and flag == True):
try:
start(sys.argv[1], sys.argv[2],sys.argv[3],predict1,predict2,predict3)
except:
pass
flag = False
if(now.tm_min%int(sys.argv[2])!=int(sys.argv[2])-1):
flag = True
time.sleep(1)'''<file_sep>/crawl.py
import requests
import pandas as pd
from bs4 import BeautifulSoup
coin_list = ['LINK']
time_units = ['days', 'weeks']
minutes_units = [60, 240]
'''
'Time' : 시간
'OpeningPrice' : 시가
'HighPrice' : 고가
'LowPrice' : 저가
'TradePrice' : 체결가
'CandleAccTradeVolume' : 누적 거래량
'CandleAccTradePrice' : 누적 체결가
'''
for coin in coin_list:
for time_unit in time_units:
'''
Scraping days & weeks
'''
req = requests.get(f'https://crix-api-endpoint.upbit.com/v1/crix/candles/{time_unit}?code=CRIX.UPBIT.KRW-{coin}&count=100&')
data = req.json()
result = []
for i, candle in enumerate(data):
result.append({
'Time' : data[i]["candleDateTimeKst"],
'OpeningPrice' : data[i]["openingPrice"],
'HighPrice' : data[i]["highPrice"],
'LowPrice' : data[i]["lowPrice"],
'TradePrice' : data[i]["tradePrice"],
'CandleAccTradeVolume' : data[i]["candleAccTradeVolume"],
"candleAccTradePrice" : data[i]["candleAccTradePrice"]
})
coin_data = pd.DataFrame(result.reverse())
coin_data.to_csv(f'{coin}_KRW_{time_unit}.csv')
for minutes_unit in minutes_units:
'''
Scraping minutes data
'''
req = requests.get(f'https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/{minutes_unit}?code=CRIX.UPBIT.KRW-{coin}&count=1000')
data = req.json()
result = []
test = 1000000
for i, candle in enumerate(data):
TradePrice = float(data[i]["tradePrice"])
if(TradePrice<test*0.995):
up = 1
else:
up = 0
test = TradePrice
result.append({
'Time' : data[i]["candleDateTimeKst"],
'OpeningPrice' : data[i]["openingPrice"],
'HighPrice' : data[i]["highPrice"],
'LowPrice' : data[i]["lowPrice"],
'TradePrice' : data[i]["tradePrice"],
'CandleAccTradeVolume' : data[i]["candleAccTradeVolume"],
"candleAccTradePrice" : data[i]["candleAccTradePrice"],
"up" : up
})
coin_data = pd.DataFrame(reversed(result))
coin_data = coin_data.set_index('Time')
coin_data.to_csv(f'{coin}_KRW_{minutes_unit}min.csv')<file_sep>/stock_RNN.py
import pandas as pd
from keras.layers.core import Dense, Dropout
from keras.layers.recurrent import GRU
from keras.models import Sequential, load_model
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import requests
import pandas as pd
import sys
from bs4 import BeautifulSoup
def start(coin, time, rate):
print(coin,time)
minutes_units = [time]
for minutes_unit in minutes_units:
'''
Scraping minutes data
'''
req = requests.get(f'https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/{minutes_unit}?code=CRIX.UPBIT.KRW-'+coin+'&count=1000')
data = req.json()
result = []
test = 1000000
for i, candle in enumerate(data):
TradePrice = float(data[i]["tradePrice"])
if(TradePrice<test*(1-0.01*float(rate))):
up = 1
else:
up = 0
test = TradePrice
result.append({
'Time' : data[i]["candleDateTimeKst"],
'OpeningPrice' : data[i]["openingPrice"],
'HighPrice' : data[i]["highPrice"],
'LowPrice' : data[i]["lowPrice"],
'TradePrice' : data[i]["tradePrice"],
'CandleAccTradeVolume' : data[i]["candleAccTradeVolume"],
"candleAccTradePrice" : data[i]["candleAccTradePrice"],
"up" : up
})
coin_data = pd.DataFrame(reversed(result))
prices = coin_data.set_index('Time')
yahoo = prices[:-1]
yahoo = yahoo[['OpeningPrice', 'LowPrice', 'HighPrice', 'TradePrice','CandleAccTradeVolume','candleAccTradePrice','up']]
predict = yahoo[-10:]
yahoo = yahoo[:-10]
print(predict)
# preparing label data
#yahoo_shift = yahoo.shift(-1)
label = yahoo['up']
# adjusting the shape of both
yahoo.drop(yahoo.index[len(yahoo)-1], axis=0, inplace=True)
label.drop(label.index[len(label)-1], axis=0, inplace=True)
# conversion to numpy array
x, y = yahoo.values, label.values
# scaling values for model
x_scale = MinMaxScaler()
y_scale = MinMaxScaler()
X = x_scale.fit_transform(x)
test = x_scale.fit_transform(predict)
Y = y_scale.fit_transform(y.reshape(-1,1))
# splitting train and test
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3)
X_train = X_train.reshape((-1,1,7))
X_test = X_test.reshape((-1,1,7))
test = test.reshape((-1,1,7))
# creating model using Keras
# tf.reset_default_graph()
model_name = 'stock_price_GRU'
model = Sequential()
model.add(GRU(units=50,
return_sequences=True,
input_shape=(1, 7)))
model.add(Dropout(0.2))
model.add(GRU(units=50))
model.add(Dropout(0.2))
model.add(Dense(1, activation='hard_sigmoid'))
model.compile(loss='mse', optimizer='adam')
# model = load_model("{}.h5".format(model_name))
# print("MODEL-LOADED")
model.fit(X_train,y_train,batch_size=1024, epochs=2500, validation_split=0.1, verbose=1)
model.save("{}.h5".format(model_name))
print('MODEL-SAVED')
score = model.evaluate(X_test, y_test, batch_size=1024)
print('Score: ',score)
yhat = model.predict(X_test)
print(predict)
yhat = y_scale.inverse_transform(yhat)
test = model.predict(test)
ztest = y_scale.inverse_transform(test)
print(ztest)
y_test = y_scale.inverse_transform(y_test)
if __name__ == '__main__':
start(sys.argv[1], sys.argv[2],sys.argv[3])<file_sep>/auto.py
import requests
import pandas as pd
import time
import webbrowser
import numpy
import time
import sys
import telegram
import pandas as pd
import requests
import pandas as pd
import sys
import time
from bs4 import BeautifulSoup
import telegram
from urllib.parse import urlencode
import os
import jwt
import uuid
import hashlib
import datetime
import requests
import requests
import datetime
import time
import sys
import numpy
import readchar
import pandas
access_key = '<KEY>'
secret_key = '<KEY>'
server_url = 'https://api.upbit.com'
telegram_token = '1<PASSWORD>:AA<PASSWORD>'
bot = telegram.Bot(token = telegram_token)
flag = True
buymoney = 0
def buy(coin,volume,price):
query = {
'market': 'KRW-'+coin,
'side': 'bid',
'price': price,
'volume': '',
'ord_type': 'price',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
if(res.status_code==201):
return True
else:
return False
def sell(coin,volume,price):
query = {
'market': 'KRW-'+coin,
'side': 'ask',
'price': '',
'volume': volume,
'ord_type': 'market',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
if(res.status_code==201):
#return float(res.json()["price"])
return 1
else:
return 0
def get_my_value(coin):
query = {
'market': 'KRW-'+coin,
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.get(server_url + "/v1/orders/chance", params=query, headers=headers)
balance = float(res.json()["ask_account"]["balance"])
avg_buy_price = float(res.json()["ask_account"]["avg_buy_price"])
return balance,avg_buy_price
def rsi(ohlc: pd.DataFrame, period: int = 14):
ohlc["close"] = ohlc["close"]
delta = ohlc["close"].diff()
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
_gain = up.ewm(com=(period - 1), min_periods=period).mean()
_loss = down.abs().ewm(com=(period - 1), min_periods=period).mean()
RS = _gain / _loss
return pd.Series(100 - (100 / (1 + RS)), name="RSI")
def autotrading(MIN,COIN):
global buymoney
url = 'https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/'+str(MIN)+'?code=CRIX.UPBIT.KRW-'+COIN+'&count=400'
response = requests.request("GET", url)
data = response.json()
df = pd.DataFrame(data)
df=df.reindex(index=df.index[::-1]).reset_index()
df2=df.reindex(index=df.index[::-1]).reset_index()
df['close']=df["tradePrice"]
trade_price = float(df["tradePrice"][199])
money = 3000000
number = 0
rate = 10
price = 0
diff = 0
flag = 0
sellprice = 0
buycoin = 0
sonik = 3000000
buyflag = False
highPrice = 0
lastmsi = 100
rate = 0.4
repeat = 1
for i, candle in enumerate(data):
if(i>=101):
rsi_now = rsi(df[:i+1].reset_index(), 14).iloc[-1]
rsi_last1 = rsi(df[:i+1].reset_index(), 14).iloc[-2]
rsi_last2 = rsi(df[:i+1].reset_index(), 14).iloc[-3]
if(rsi_now>=36 and rsi_now>=rsi_last2 and rsi_last1<36):
if(repeat==1):
now_buy = 100000/data[399-i]["tradePrice"]
else:
now_buy = 100000/data[399-i]["tradePrice"] * (1 + 60*(pyungdan-data[399-i]["tradePrice"])/(pyungdan+data[399-i]["tradePrice"])/2)
number = number + now_buy
buycoin = buycoin + data[399-i]["tradePrice"] * now_buy
sonik = sonik - data[399-i]["tradePrice"] * now_buy
pyungdan = buycoin/number
print(i,"번째 구매 가격 : ",data[399-i]["tradePrice"])
print("구매 개수 : ", now_buy)
print("구매 won : ", data[399-i]["tradePrice"] * now_buy)
print("남은 돈 : ", sonik)
print("평단 : ",buycoin/number)
repeat = repeat + 1
if(rsi_now>=65 and rsi_now<=rsi_last2 and number!=0.0):
print(i,"번째 판매 가격 : ",data[399-i]["tradePrice"])
sonik = sonik + data[399-i]["tradePrice"] * number
print("남은 돈 : ", sonik)
number = 0
buycoin = 0
repeat = 1
#print("-------------------------")
'''
openingPrice = df.iloc[i]["openingPrice"]
tradePrice = df.iloc[i]["tradePrice"]
lowPrice = df.iloc[i]["lowPrice"]
highPrice = df.iloc[i]["highPrice"]
print("openingPrice : ",openingPrice)
print("tradePrice : ",tradePrice)
print("highPrice : ",highPrice)
print("lowPrice : ",lowPrice)
if(price==0):
if(openingPrice>tradePrice ):
diff = (highPrice-tradePrice)
price = highPrice - diff*3
flag = 1
print(flag,"차 매수 가격 설정완료 : ",price)
buyflag = False
else:
if(highPrice<=price):
price = highPrice-diff
if(lowPrice<=price):
number = number + rate* (1+(flag*0.5))
money = money - price * rate* (1+(flag*0.5))
buycoin = buycoin + price * rate* (1+(flag*0.5))
print(flag,"차 매수 완료 매수 개수 : ",number)
price = price - diff
flag = flag + 1
print(flag,"차 매수 가격 설정완료 : ",price)
buyflag = True
if(highPrice>=sellprice and sellprice!=0):
money = money + sellprice*number
number = 0
buyflag = False
sellprice = 0
price = 0
buycoin = 0
print("매도 완료")
if(openingPrice<tradePrice):
if(buyflag==True):
if(sellprice==0):
sellprice = lowPrice + (tradePrice-lowPrice)*2
print("매도 가격 설정완료 : ",sellprice)
else:
print("매수 포인트 초기화")
flag = 0
price = 0
calc = money + tradePrice*number
if(number!=0):
pyungdan = buycoin/number
else:
pyungdan = 0
print("money : ",money)
print("매도 설정 가격 : ",sellprice)
print("평단 : ",pyungdan)
print("평가 money : ",calc)
#c = readchar.readchar()
#print(df)
df=df.iloc[::-1]
df=df['tradePrice']
exp1 = df.ewm(span=3, adjust=False).mean()
exp2 = df.ewm(span=5, adjust=False).mean()
if(flag==True):
if(exp1[1]<exp2[1] and exp1[0]>=exp2[0] and exp1[0]-exp1[2]>0 and exp1[0]-exp1[1]>0 and exp2[0]-exp2[2]>0 and exp2[0]-exp2[1]>0):
#buy(COIN,10000,10000)
bot.sendMessage(chat_id = '1780594186', text="["+COIN+"] 구매 가격 : "+str(df[0]))
buymoney = int(df[0])
flag = False
else:
if(exp1[1]-exp1[2]>0 and exp1[0]-exp1[1]<0):
if(abs(exp1[1]-exp1[2])<=abs(exp1[0]-exp1[1])):
mybal,my_avg_price = get_my_value(COIN)
#if(mybal!=0.0):
#sell(COIN,mybal,mybal)
bot.sendMessage(chat_id = '1780594186', text="["+COIN+"] 판매 가격 : "+str(df[0])+", 수익 : "+str(df[0]-buymoney))
flag = True
elif(exp1[1]-exp1[2]<0 and exp1[0]-exp1[1]<0):
mybal,my_avg_price = get_my_value(COIN)
#if(mybal!=0.0):
#sell(COIN,mybal,mybal)
bot.sendMessage(chat_id = '1780594186', text="["+COIN+"] 판매 가격 : "+str(df[0])+", 수익 : "+str(df[0]-buymoney))
flag = True
time.sleep(5)
'''
if __name__ == '__main__':
autotrading(sys.argv[1], sys.argv[2])
'''
while True:
now = time.localtime()
if(now.tm_min%int(sys.argv[1])==int(sys.argv[1])-1 and now.tm_sec>=54):
autotrading(sys.argv[1], sys.argv[2])
time.sleep(1)'''<file_sep>/test3.bat
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py IOST 60 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py ELF 60 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py CHZ 60 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py XEM 60 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py HUNT 60 1.5"
<file_sep>/test2.py
import pandas as pd
from keras.layers.core import Dense, Dropout
from keras.layers.recurrent import GRU
from keras.models import Sequential, load_model
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import requests
import pandas as pd
import sys
import time
from bs4 import BeautifulSoup
import telegram
from urllib.parse import urlencode
import os
import jwt
import uuid
import hashlib
import datetime
import requests
import requests
import datetime
import time
import sys
x_scale = MinMaxScaler()
y_scale = MinMaxScaler()
model_name = 'stock_price_GRU'
model = Sequential()
model.add(GRU(units=50,
return_sequences=True,
input_shape=(1, 9)))
model.add(Dropout(0.15))
model.add(GRU(units=50))
model.add(Dropout(0.15))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='mse', optimizer='adam')
access_key = '<KEY>'
secret_key = '<KEY>'
server_url = 'https://api.upbit.com'
telegram_token = '1<PASSWORD>:<KEY>'
bot = telegram.Bot(token = telegram_token)
first = True
def buy(coin,volume,price):
query = {
'market': 'KRW-'+coin,
'side': 'bid',
'price': price,
'volume': '',
'ord_type': 'price',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
if(res.status_code==201):
return True
else:
return False
def sell(coin,volume,price):
query = {
'market': 'KRW-'+coin,
'side': 'ask',
'price': '',
'volume': volume,
'ord_type': 'market',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
if(res.status_code==201):
return float(res.json()["price"])
else:
return 0
def get_my_value(coin):
query = {
'market': 'KRW-'+coin,
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.get(server_url + "/v1/orders/chance", params=query, headers=headers)
balance = float(res.json()["ask_account"]["balance"])
avg_buy_price = float(res.json()["ask_account"]["avg_buy_price"])
return balance,avg_buy_price
def rsi(ohlc: pd.DataFrame, period: int = 14):
ohlc["close"] = ohlc["close"]
delta = ohlc["close"].diff()
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
_gain = up.ewm(com=(period - 1), min_periods=period).mean()
_loss = down.abs().ewm(com=(period - 1), min_periods=period).mean()
RS = _gain / _loss
return pd.Series(100 - (100 / (1 + RS)), name="RSI")
def start(coin, time, rate):
print(coin,time)
minutes_units = [time]
for minutes_unit in minutes_units:
'''
Scraping minutes data
'''
req = requests.get(f'https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/{minutes_unit}?code=CRIX.UPBIT.KRW-'+coin+'&count=1000')
data = req.json()
#print(data)
df = pd.DataFrame(reversed(data))
df2 = pd.DataFrame(data)
df=df.reindex(index=df.index[::-1]).reset_index()
df['close']=df["tradePrice"]
trade_price = float(df["tradePrice"][199])
result = []
test = -100000
up = 0
for i, candle in enumerate(data):
if(i>=100):
TradePrice = float(data[399-i]["tradePrice"])
TradePrice1 = float(data[398-i]["tradePrice"])
TradePrice2 = float(data[397-i]["tradePrice"])
TradePrice3 = float(data[396-i]["tradePrice"])
TradePrice4 = float(data[395-i]["tradePrice"])
TradePrice5 = float(data[394-i]["tradePrice"])
nowrsi = rsi(df[:i].reset_index(), 14).iloc[-1]
df3=df2.iloc[i-100:i]['tradePrice'].reset_index(drop = True).iloc[::-1]
exp1 = df3.ewm(span=12, adjust=False).mean()
exp2 = df3.ewm(span=26, adjust=False).mean()
macd = exp1-exp2
exp3 = macd.ewm(span=9, adjust=False).mean()
#print('MACD: ',macd[0])
#print('Signal: ',exp3[0])
if(TradePrice<(TradePrice1+TradePrice2+TradePrice3+TradePrice4+TradePrice5)/5):
up = 1
else:
up = 0
test = TradePrice
result.append({
'OpeningPrice' : data[399-i]["openingPrice"],
'HighPrice' : data[399-i]["highPrice"],
'LowPrice' : data[399-i]["lowPrice"],
'TradePrice' : data[399-i]["tradePrice"],
'CandleAccTradeVolume' : data[399-i]["candleAccTradeVolume"],
"candleAccTradePrice" : data[399-i]["candleAccTradePrice"],
"rsi" : nowrsi,
"macd" : macd[0],
"exp" : exp3[0],
"up" : up
})
prices = pd.DataFrame(reversed(result))
print(prices)
yahoo = prices[['OpeningPrice', 'LowPrice', 'HighPrice', 'TradePrice','CandleAccTradeVolume','rsi','macd','exp','candleAccTradePrice']]
predict = yahoo[:30]
yahoo = yahoo[:-30]
# print(yahoo)
#print(predict)
label = prices
label = label[['up']][:-30]
yahoo.drop(yahoo.index[len(yahoo)-1], axis=0, inplace=True)
label.drop(label.index[len(label)-1], axis=0, inplace=True)
x, y = yahoo.values, label.values
X = x_scale.fit_transform(x)
test = x_scale.fit_transform(predict)
Y = y
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3)
X_train = X_train.reshape((-1,1,9))
X_test = X_test.reshape((-1,1,9))
test = test.reshape((-1,1,9))
global first
if(first):
model.fit(X_train,y_train,batch_size=20, epochs=5000, validation_split=0.1, verbose=1)
else:
model.fit(X_train,y_train,batch_size=20, epochs=100, validation_split=0.1, verbose=1)
score = model.evaluate(X_test, y_test, batch_size=20)
yhat = model.predict(X_test)
result = model.predict(test)
print(predict)
print(np.round(result,1))
print(float(np.round(result,1)[0][0]))
print(coin,str(rate))
mybal,my_avg_price = get_my_value(coin)
if(first):
first = False
else:
if(float(result[0][0])>=0.8):
if(buy(coin,80000,80000)):
mybal,my_avg_price = get_my_value(coin)
bot.sendMessage(chat_id = '1780594186', text="["+coin+"] ["+str(time)+"] 코인 구매 완료 상승 신뢰도 "+str(float(np.round(result,2)[0][0])*100))
else:
bot.sendMessage(chat_id = '1780594186', text="["+coin+"] 코인 구매 실패 확인 바람")
else:
mybal,my_avg_price = get_my_value(coin)
if(mybal!=0.0):
sellprice = sell(coin,mybal,trade_price)
else:
sellprice = 0
if(sellprice!=0):
bot.sendMessage(chat_id = '1780594186', text="["+coin+"] ["+str(time)+"] 코인 판매 완료")
else:
if(mybal!=0.0):
bot.sendMessage(chat_id = '1780594186', text="["+coin+"] 코인 판매 실패 확인 바람")
if __name__ == '__main__':
flag = True
start(sys.argv[1], sys.argv[2],sys.argv[3])
<file_sep>/rsialarm.py
import requests
import pandas as pd
import time
import webbrowser
import numpy
import time
import sys
import telegram
import pandas as pd
import requests
import pandas as pd
import sys
import time
from bs4 import BeautifulSoup
import telegram
from urllib.parse import urlencode
import os
import jwt
import uuid
import hashlib
import datetime
import requests
import requests
import datetime
import time
import sys
import numpy
import readchar
import pandas
access_key = '<KEY>'
secret_key = '<KEY>'
server_url = 'https://api.upbit.com'
telegram_token = '<PASSWORD>'
bot = telegram.Bot(token = telegram_token)
symbols = ["XRP","DAWN","AERGO","DOGE","STRK","VET","HIVE","ETC","SRM","WAVES","MED","BTG","CHZ","NEO","QTUM","EOS","SC","CBK","PUNDIX","MARO","GAS","ZIL","MLK","SBD","PXL","AXS","ONT","OBSR","XEM","TRX","MVL","MOC","FLOW","DKA","ARK","MTL","TON","META","STX","SNT","MBL","XLM","TSHP","PLA","EMC2","STRAX","ADA","STMX","KMD","ORBS","PCI","CRE","IOST","SXP","DOT"] #,"MANA","STEEM","STPT","SSX","LINK","QTCON","DMT","RFR","CRO","BORA","LTC","MFT","LAMB","GRS","EDR","FCT2","AERGO","BCHA","AQT","BSV","UPP","TT"]#,"KNC","IQ","HUM","POWR","QKC","TFUEL","STORJ","HUNT","ICX","AHT","ARDR","JST","ZRX","WAXP","LSK","ONG","XTZ","KAVA","THETA","ANKR","HBAR","ENJ","OMG","REP","SAND","LBC","POLY","IGNIS","SOLVE","LOOM","CVC","GLM","ELF","ATOM","BAT","ADX","IOTA"]
buycoin = []
number = []
repeat = []
pyungdan = []
rsi_lasts = []
money = 0
moneyhap = 0
def buy(coin,price,volume):
query = {
'market': 'KRW-'+coin,
'side': 'bid',
'price': price,
'volume': volume,
'ord_type': 'limit',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
if(res.status_code==201):
return True
else:
return False
def sell(coin,price,volume):
query = {
'market': 'KRW-'+coin,
'side': 'ask',
'price': price,
'volume': volume,
'ord_type': 'limit',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
if(res.status_code==201):
#return float(res.json()["price"])
return 1
else:
return 0
def get_my_value(coin):
query = {
'market': 'KRW-'+coin,
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.get(server_url + "/v1/orders/chance", params=query, headers=headers)
balance = float(res.json()["ask_account"]["balance"])
avg_buy_price = float(res.json()["ask_account"]["avg_buy_price"])
return balance,avg_buy_price
for i in range(0,len(symbols)):
buycoin.append(0)
number.append(0)
repeat.append(1)
pyungdan.append(0)
rsi_lasts.append(0)
print("working")
while True:
for i in range(0,len(symbols)):
try:
time.sleep(0.5)
url = "https://api.upbit.com/v1/candles/minutes/5"
querystring = {"market":"KRW-"+symbols[i],"count":"500"}
response = requests.request("GET", url, params=querystring)
data = response.json()
df = pd.DataFrame(data)
df=df.reindex(index=df.index[::-1]).reset_index()
df['close']=df["trade_price"]
def rsi(ohlc: pd.DataFrame, period: int = 14):
ohlc["close"] = ohlc["close"]
delta = ohlc["close"].diff()
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
_gain = up.ewm(com=(period - 1), min_periods=period).mean()
_loss = down.abs().ewm(com=(period - 1), min_periods=period).mean()
RS = _gain / _loss
return pd.Series(100 - (100 / (1 + RS)), name="RSI")
rsi_now = rsi(df, 14).iloc[-1]
rsi_last = rsi(df, 14).iloc[-2]
rsi_last2 = rsi(df, 14).iloc[-3]
price = df["trade_price"].iloc[-1]
if(rsi_lasts[i]!=rsi_last):
if(rsi_now>=34 and rsi_now>=rsi_last2 and rsi_last<34):
'''
if(price<=100):
price = price-0.1
elif(price<=1000):
price = price-1
elif(price<=10000):
price = price-5
elif(price<=100000):
price = price-10
elif(price<=1000000):
price = price-50
'''
if(repeat[i]==1):
now_buy = 50000/price
else:
now_buy = 50000/price * (1 + 60*(pyungdan[i]-price)/(pyungdan[i]+price)/2)
number[i] = number[i] + now_buy
buycoin[i] = buycoin[i] + price * now_buy
pyungdan[i] = buycoin[i]/number[i]
bot.sendMessage(chat_id = '1780594186', text="["+symbols[i]+"] 구매("+str(repeat[i])+") 신호 "+str(price)+"원, 총 구매 :"+str(price* now_buy))
buy(symbols[i],price,now_buy)
repeat[i] = repeat[i] + 1
mybal,my_avg_price = get_my_value(symbols[i])
if(rsi_now>=75 and mybal!=0.0):
bot.sendMessage(chat_id = '1780594186', text="["+symbols[i]+"] 판매 "+str(my_avg_price)+"->"+str(price)+", 수익금 : "+str(mybal*(price-my_avg_price))+"원")
money = money + mybal*(price-my_avg_price)
bot.sendMessage(chat_id = '1780594186', text="누적 수익금 : "+str(money)+"원")
sellbuy(symbols[i],price,now_buy)
number[i] = 0
buycoin[i] = 0
repeat[i] = 1
if(rsi_last>=58 and rsi_now<=rsi_last2 and mybal!=0.0):
if(price<=100):
price = price-0.1
elif(price<=1000):
price = price-1
elif(price<=10000):
price = price-5
elif(price<=100000):
price = price-10
elif(price<=1000000):
price = price-50
bot.sendMessage(chat_id = '1780594186', text="["+symbols[i]+"] 판매 "+str(my_avg_price)+"->"+str(price)+", 수익금 : "+str(mybal*(price-my_avg_price))+"원")
money = money + mybal*(price-my_avg_price)
bot.sendMessage(chat_id = '1780594186', text="누적 수익금 : "+str(money)+"원")
sell(symbols[i],price,mybal)
number[i] = 0
buycoin[i] = 0
repeat[i] = 1
rsi_lasts[i] = rsi_last
except Exception as e:
print(e)
time.sleep(1)<file_sep>/buy.py
import requests
import pandas as pd
import time
import webbrowser
url = "https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/5?code=CRIX.UPBIT.KRW-KMD&count=100"
response = requests.request("GET", url)
data = response.json()
df = pd.DataFrame(data)
df=df.iloc[::-1]
df=df['tradePrice']
print(df)
exp1 = df.ewm(span=5, adjust=False).mean()
exp2 = df.ewm(span=12, adjust=False).mean()
macd = exp1-exp2
exp3 = macd.ewm(span=7, adjust=False).mean()
print(macd)
print('MACD: ',macd[0])
<file_sep>/test3.py
import requests
import pandas as pd
import time
import webbrowser
import numpy
import time
import sys
import telegram
import pandas as pd
import requests
import pandas as pd
import sys
import time
from bs4 import BeautifulSoup
import telegram
from urllib.parse import urlencode
import os
import jwt
import uuid
import hashlib
import datetime
import requests
import requests
import datetime
import time
import sys
import numpy
import pandas
access_key = '<KEY>'
secret_key = '<KEY>'
server_url = 'https://api.upbit.com'
telegram_token = '1<PASSWORD>:<KEY>7<KEY>'
bot = telegram.Bot(token = telegram_token)
def buy(coin,volume,price):
query = {
'market': 'KRW-'+coin,
'side': 'bid',
'price': price,
'volume': '',
'ord_type': 'price',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
if(res.status_code==201):
return True
else:
return False
def sell(coin,volume,price):
query = {
'market': 'KRW-'+coin,
'side': 'ask',
'price': '',
'volume': volume,
'ord_type': 'market',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
if(res.status_code==201):
#return float(res.json()["price"])
return 1
else:
print(res.json())
return 0
def get_my_value(coin):
query = {
'market': 'KRW-'+coin,
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.get(server_url + "/v1/orders/chance", params=query, headers=headers)
balance = float(res.json()["ask_account"]["balance"])
avg_buy_price = float(res.json()["ask_account"]["avg_buy_price"])
return balance,avg_buy_price
def start(COIN,MIN):
flag = True
money = 0
while True:
try:
time.sleep(2)
url = 'https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/'+str(MIN)+'?code=CRIX.UPBIT.KRW-'+COIN+'&count=400'
response = requests.request("GET", url)
data = response.json()
df = pd.DataFrame(data)
df=df.iloc[::-1]
df=df['tradePrice']
exp1 = df.ewm(span=12, adjust=False).mean()
exp2 = df.ewm(span=26, adjust=False).mean()
macd = exp1-exp2
exp3 = macd.ewm(span=9, adjust=False).mean()
exp4 = df.ewm(span=5, adjust=False).mean()
exp5 = df.ewm(span=7, adjust=False).mean()
exp6 = df.ewm(span=10, adjust=False).mean()
exp7 = df.ewm(span=3, adjust=False).mean()
test1=macd[0]-exp3[0]
test2 = macd[1]-exp3[1]
test3 =macd[2]-exp3[2]
lastdf = df[:-1]
bb_center=numpy.mean(df[len(df)-20:len(df)])
now = time.localtime()
if(test1>=test2>=test3 and df[1]>=bb_center and df[0]>=exp5[0] and exp7[0]>=bb_center and test1>test2 and test1>0 and exp7[0]>=exp4[0] and exp4[0]>=exp5[0]):
if(flag==True):
bot.sendMessage(chat_id = '1780594186', text="["+COIN+"] 구매 signal,"+str(df[0]))
money = float(df[0])
flag = False
time.sleep(3)
buy(COIN,50000,5 0000)
time.sleep(60)
if((test2+test3)/2>=test1):
if(flag==False):
sonik = df[0]-money
bot.sendMessage(chat_id = '1780594186', text="["+COIN+"] 판매 signal,"+str(df[0])+","+str(sonik))
flag = True
mybal,my_avg_price = get_my_value(COIN)
if(mybal!=0.0):
sellprice = sell(COIN,mybal,mybal)
time.sleep(60)
except Exception as e:
print(e)
if __name__ == '__main__':
start(sys.argv[1],sys.argv[2])
<file_sep>/전략3.py
import pandas as pd
import datetime
import requests
import pandas as pd
import time
import webbrowser
import telegram
import math
a = 1
code = ["AXS"]#,"DAWN","DOGE","STRK","ETC","SRM","WAVES","BTG","NEO","QTUM","EOS","SC","CBK","PUNDIX","GAS","MLK","SBD","AXS","ONT","OBSR","MVL","FLOW","ARK","MTL","TON","STX","MBL","TSHP","STRAX","ADA","STMX","PCI","CRE","IOST","SXP","DOT","MANA","STEEM","STPT","LINK","QTCON","DMT","RFR","LTC","MFT","LAMB","GRS","EDR","AERGO","BCHA","AQT","BSV","TT","KNC","IQ","QKC","STORJ","ICX","AHT","ZRX","LSK","ONG","XTZ","KAVA","THETA","ENJ","OMG","REP","ATOM","BAT","ADX","IOTA"]
buy_flag = []
pyungdan = []
sonik = []
telegram_token = '<PASSWORD>:AA<PASSWORD>'
bot = telegram.Bot(token = telegram_token)
url = "https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/60?code=CRIX.UPBIT.KRW-"+code[0]+"&count=400"
response = requests.request("GET", url)
data = response.json()
df = pd.DataFrame(data)
df = df.iloc[::-1].reset_index(drop=True)
high_prices = df['highPrice']
close_prices = df['tradePrice']
low_prices = df['lowPrice']
opening_prices = df['openingPrice']
dates = df.index
print(high_prices)
money = 1000000
for i in range(1,400):
if(high_prices[i]>=high_prices[i-1]-low_prices[i-1]+opening_prices[i]):
if(high_prices[i]>=(high_prices[i-1]-low_prices[i-1]+opening_prices[i])*1.02):
money = money * 1.02
print("2퍼센트 익절")
print(money)
else:
if((close_prices[i]-(high_prices[i-1]-low_prices[i-1]+opening_prices[i]))/(high_prices[i-1]-low_prices[i-1]+opening_prices[i])<=0):
print("close 손절",(close_prices[i]-(high_prices[i-1]-low_prices[i-1]+opening_prices[i]))/(high_prices[i-1]-low_prices[i-1]+opening_prices[i]))
else:
print("close 익절",(close_prices[i]-(high_prices[i-1]-low_prices[i-1]+opening_prices[i]))/(high_prices[i-1]-low_prices[i-1]+opening_prices[i]))
money = money * (1 + (close_prices[i]-(high_prices[i-1]-low_prices[i-1]+opening_prices[i]))/(high_prices[i-1]-low_prices[i-1]+opening_prices[i]))
print(money)
#print((close_prices[i]-(high_prices[i-1]-low_prices[i-1]+opening_prices[i]))/(high_prices[i-1]-low_prices[i-1]+opening_prices[i]))
<file_sep>/test.bat
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py MBL 30 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py TT 30 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py IQ 30 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py CRE 30 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py RFR 30 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py AHT 30 1.5"<file_sep>/data.py
import requests
import pandas as pd
import time
import webbrowser
import numpy
import time
import sys
import telegram
import pandas as pd
import requests
import pandas as pd
import sys
import time
from bs4 import BeautifulSoup
import telegram
from urllib.parse import urlencode
import os
import jwt
import uuid
import hashlib
import datetime
import requests
import requests
import datetime
import time
import sys
import numpy
import readchar
import pandas
access_key = '<KEY>'
secret_key = '<KEY>'
server_url = 'https://api.upbit.com'
def rsi(ohlc: pd.DataFrame, period: int = 14):
ohlc["tradePrice"] = ohlc["tradePrice"]
delta = ohlc["tradePrice"].diff()
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
_gain = up.ewm(com=(period - 1), min_periods=period).mean()
_loss = down.abs().ewm(com=(period - 1), min_periods=period).mean()
RS = _gain / _loss
return pd.Series(100 - (100 / (1 + RS)), name="RSI")
req = requests.get(f'https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/5?code=CRIX.UPBIT.KRW-KMD&count=1000')
data = req.json()
#print(data)
df = pd.DataFrame(reversed(data))
df2 = pd.DataFrame(data)
df3 = df2.iloc[::-1]
df3=df3['tradePrice']
df=df.reindex(index=df.index[::-1]).reset_index()
df['close']=df["tradePrice"]
trade_price = float(df["tradePrice"][199])
result = []
test = -100000
up = 0
for i, candle in enumerate(data):
if(i>=100):
print('---------------',i-100,i)
TradePrice = float(data[399-i]["tradePrice"])
TradePrice1 = float(data[398-i]["tradePrice"])
TradePrice2 = float(data[397-i]["tradePrice"])
TradePrice3 = float(data[396-i]["tradePrice"])
TradePrice4 = float(data[395-i]["tradePrice"])
TradePrice5 = float(data[394-i]["tradePrice"])
df4=df3.iloc[i-100:i+1].reset_index(drop = True)
print(df4)
nowrsi = rsi(df4[:i].reset_index(), 14).iloc[-1]
exp1 = df4.ewm(span=5, adjust=False).mean()
exp2 = df4.ewm(span=12, adjust=False).mean()
macd = exp1-exp2
exp3 = macd.ewm(span=7, adjust=False).mean()
#print(macd)
#print('MACD: ',macd[0])
#print('Signal: ',exp3[0])
if(TradePrice<(TradePrice1+TradePrice2+TradePrice3+TradePrice4+TradePrice5)/5):
up = 1
else:
up = 0
test = TradePrice
result.append({
'OpeningPrice' : data[399-i]["openingPrice"],
'HighPrice' : data[399-i]["highPrice"],
'LowPrice' : data[399-i]["lowPrice"],
'TradePrice' : data[399-i]["tradePrice"],
'CandleAccTradeVolume' : data[399-i]["candleAccTradeVolume"],
"candleAccTradePrice" : data[399-i]["candleAccTradePrice"],
"rsi" : nowrsi,
"macd" : macd[100],
"exp" : exp3[100],
"up" : up
})
prices = pd.DataFrame(reversed(result))
print(prices)<file_sep>/전략.py
import requests
import pandas as pd
import time
import webbrowser
code = ["XRP","DAWN","DOGE","STRK","ETC","SRM"]#,"WAVES","BTG","NEO","QTUM","EOS","SC","CBK","PUNDIX","GAS","MLK","SBD","AXS","ONT","OBSR","MVL","FLOW","ARK","MTL","TON","STX","MBL","TSHP","STRAX","ADA","STMX","PCI","CRE","IOST","SXP","DOT","MANA","STEEM","STPT","LINK","QTCON","DMT","RFR","LTC","MFT","LAMB","GRS","EDR","AERGO","BCHA","AQT","BSV","TT","KNC","IQ","QKC","STORJ","ICX","AHT","ZRX","LSK","ONG","XTZ","KAVA","THETA","ENJ","OMG","REP","ATOM","BAT","ADX","IOTA"]
hap = 0
cnt = 0
plus = 0
topplus = -1000000000
minus = 0
topminus = 100000000
topcoin = ""
topcoinmoney = 0
money = 2000000
print(len(code))
for j in range(0,len(code)):
print(code[j])
try:
url = "https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/60?code=CRIX.UPBIT.KRW-"+code[j]+"&count=400"
response = requests.request("GET", url)
data = response.json()
df = pd.DataFrame(data)
df=df.iloc[::-1]
#print(df)
buyflag = True
sonik = 0
realsonik = 0
for i in range(4,399):
#print(df.iloc[i-4]["tradePrice"],df.iloc[i-3]["tradePrice"],df.iloc[i-2]["tradePrice"],df.iloc[i-1]["tradePrice"])
if(buyflag):
if(df.iloc[i]["highPrice"]>df.iloc[i-1]["highPrice"] and df.iloc[i-1]["tradePrice"]<=df.iloc[i-2]["tradePrice"] and df.iloc[i]["highPrice"]>df.iloc[i-2]["highPrice"] ):
buyflag = False
price = df.iloc[i-1]["highPrice"]
if(price<=100):
price = price+0.2
elif(price<=1000):
price = price+2
elif(price<=10000):
price = price+10
elif(price<=100000):
price = price+20
elif(price<=1000000):
price = price+100
sonik = money / price
else:
if(df.iloc[i-1]["lowPrice"]>df.iloc[i]["tradePrice"] and buyflag == False):
price = df.iloc[i-1]["lowPrice"]
if(price<=100):
price = price-0.2
elif(price<=1000):
price = price-2
elif(price<=10000):
price = price-10
elif(price<=100000):
price = price-20
elif(price<=1000000):
price = price-100
print("구매가격 :",money/sonik,", 판매가격 :",price,", 이익 :",sonik * price - money)
if(sonik * price - money >= 0):
plus = plus + 1
if(topplus<sonik *price - money):
topplus = sonik *price - money
else:
minus = minus + 1
if(topminus>sonik *price - money):
topminus = sonik *price - money
money = money + sonik * price - money
print("현재 돈 :", money)
buyflag = True
cnt = cnt + 1
#print("sell")
#print("sonik",realsonik)
#print(df.iloc[i-4]["candleAccTradeVolume"]+df.iloc[i-3]["candleAccTradeVolume"]+df.iloc[i-2]["candleAccTradeVolume"],df.iloc[i-1]["candleAccTradeVolume"],df.iloc[i]["candleAccTradeVolume"])
if(topcoinmoney<money):
topcoinmoney = money
topcoin = code[j]
print(str(money))
hap = hap + money
except:
pass
print("총 이익 : ",hap)
print("구매 횟수 : ",cnt,"평균 구매 횟수 : ",cnt/len(code))
print("이득 횟수 : ",plus,"최고 이득 : ",topplus)
print("손해 횟수 : ",minus,"최고 손해 : ",topminus)
print("탑 코인 :",topcoin,"이익 :",topcoinmoney)
print(hap/400)<file_sep>/전략2.py
import requests
import pandas as pd
import time
import webbrowser
#code = ["BTT","MBL","AHT","TT","MFT","CRE","RFR","TSHP","IQ","MVL","OBSR","QKC","SC","STMX","EDR","IOST","QTCON","LAMB","STPT"]
code = ["BTC","ETH","BCH","LTC","BSV","ETC","BTG","NEO","STRK","LINK","REP","DOT","BCHA","WAVES","ATOM","FLOW","QTUM","SBD","GAS"]
cnt = 0
plus = 0
topplus = -1000000000
minus = 0
topminus = 100000000
topcoin = ""
topcoinmoney = 0
totalmoney = 1000000
sonik = 0
sonhae = 0
print(len(code))
for j in range(0,len(code)):
print(code[j])
try:
url = "https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/3?code=CRIX.UPBIT.KRW-"+code[j]+"&count=400"
response = requests.request("GET", url)
data = response.json()
df = pd.DataFrame(data)
df=df.iloc[::-1]
#print(df)
buyflag = True
realsonik = 0
money = 0
price = 10000000
for i in range(4,399):
#print(df.iloc[i-4]["tradePrice"],df.iloc[i-3]["tradePrice"],df.iloc[i-2]["tradePrice"],df.iloc[i-1]["tradePrice"],df.iloc[i]["tradePrice"])
if(df.iloc[i]["highPrice"] > df.iloc[i-1]["highPrice"] and df.iloc[i-2]["tradePrice"] > df.iloc[i-1]["tradePrice"] and df.iloc[i-3]["tradePrice"] > df.iloc[i-2]["tradePrice"]and buyflag):
price = df.iloc[i-1]["highPrice"]
buyflag=False
#totalmoney = totalmoney / price * df.iloc[i+1]["openingPrice"]
elif(price * 1.006 <= df.iloc[i]["highPrice"]and buyflag==False):
totalmoney = totalmoney * 1.006
buyflag= True
print("이익")
sonik = sonik + 1
elif(price * 0.994 >= df.iloc[i]["lowPrice"]and buyflag==False):
totalmoney = totalmoney * 0.994
buyflag= True
sonhae = sonhae + 1
print("손해")
except Exception as e:
print(e)
pass
print(totalmoney,sonik,sonhae)<file_sep>/README.md
# Stock Prediction using Time Series Analysis
Closing Price prediction of Yahoo stocks from 2010 - 2016 using Gated Recurrant Units
Model is already trained and saved in 'stock_price_GRU.h5' file
To obtain the trained model just comment out the lines 47-55 and 60-62, then uncomment the lines 57-58 to load 'stock_price_GRU.h5' file
Highly Recommend using GPU version of Tensorflow for running the model
#### DATA
INPUT_DATA
date open low high close
2010-01-04 16.940001 16.879999 17.200001 17.100000
2010-01-05 17.219999 17.000000 17.230000 17.230000
2010-01-06 17.170000 17.070000 17.299999 17.170000
2010-01-07 16.809999 16.570000 16.900000 16.700001
2010-01-08 16.680000 16.620001 16.760000 16.700001
LABEL_DATA
date close
2010-01-04 17.230000
2010-01-05 17.170000
2010-01-06 16.700001
2010-01-07 16.700001
2010-01-08 16.740000
#### MODEL
Layer (type) Output Shape Param #
_________________________________________________________________
gru_1 (GRU) (None, 1, 512) 794112
_________________________________________________________________
dropout_1 (Dropout) (None, 1, 512) 0
_________________________________________________________________
gru_2 (GRU) (None, 256) 590592
_________________________________________________________________
dropout_2 (Dropout) (None, 256) 0
_________________________________________________________________
dense_1 (Dense) (None, 1) 257
_________________________________________________________________
Total params: 1,384,961
Trainable params: 1,384,961
Non-trainable params: 0
_________________________________________________________________
#### TRAINING
Epoch 500/500
250/1061 [======>.......................] - ETA: 0s - loss: 7.2934e-04
750/1061 [====================>.........] - ETA: 0s - loss: 6.7267e-04
1061/1061 [==============================] - 0s 111us/step - loss: 6.4617e-04 - val_loss: 6.4601e-04
32/582 [>.............................] - ETA: 0s
352/582 [=================>............] - ETA: 0s
582/582 [==============================] - 0s 154us/step
Score: 0.000513115886573222
#### RESULTS
33% of Data used for Testing
Plot only shows the last points of test set and predicted values
![alt text](https://github.com/jha-prateek/Stock-Prediction-RNN/blob/master/predicted_test.JPG)
<file_sep>/test5.bat
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test2.py DAWN 30 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test2.py EMC2 30 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test2.py STX 30 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test2.py FLOW 30 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test2.py GRS 30 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test2.py BTG 30 1.5"
<file_sep>/test4.bat
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py AERGO 60 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py ARDR 60 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py AERGO 60 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py EMC2 60 1.5"
start cmd /k "cd C:\Users\devgu\Desktop\auto && python test.py POLY 60 1.5"<file_sep>/autotrade2.py
import requests
import pandas as pd
import time
import webbrowser
import numpy
import time
import sys
import telegram
import pandas as pd
import requests
import pandas as pd
import sys
import time
from bs4 import BeautifulSoup
import telegram
from urllib.parse import urlencode
import os
import jwt
import uuid
import hashlib
import datetime
import requests
import requests
import datetime
import time
import sys
import numpy
import readchar
import pandas
import pyupbit
access_key = '<KEY>'
secret_key = '<KEY>'
server_url = 'https://api.upbit.com'
upbit = pyupbit.Upbit(access_key, secret_key)
'''
ret2 = upbit.buy_limit_order("KRW-XRP", 20 , 50000/20)
ret = upbit.cancel_order(ret2['uuid'])
print(ret)
try:
if(ret["error"]):
print("yes")
except:
print("no")
ret = upbit.cancel_order(ret2['uuid'])
print(ret)
try:
if(ret["error"]):
print("yes")
except:
print("no")
'''
#code = ["XRP","DAWN","DOGE","STRK","ETC","SRM","WAVES","BTG","NEO","QTUM","EOS","SC","CBK","PUNDIX","GAS","MLK","SBD","AXS","ONT","OBSR","MVL","FLOW","ARK","MTL","TON","STX","MBL","TSHP","STRAX","ADA","STMX","PCI","CRE","IOST","SXP","DOT","MANA","STEEM","STPT","LINK","QTCON","DMT","RFR","LTC","MFT","LAMB","GRS","EDR","AERGO","BCHA","AQT","BSV","TT","KNC","IQ","QKC","STORJ","ICX","AHT","ZRX","LSK","ONG","XTZ","KAVA","THETA","ENJ","OMG","REP","ATOM","BAT","ADX","IOTA"]
#code = ["ETH","QTUM","BTC","XRP","EOS","BCH","BTT","ADA","LTC","KMD","EOS","SC","CBK","PUNDIX","GAS","MLK","SBD","AXS","ONT","OBSR","MVL","FLOW","ARK","MTL","TON","STX","MBL","TSHP","STRAX","ADA","STMX","PCI","CRE","IOST","SXP","DOT","MANA","STEEM","STPT","LINK","QTCON","DMT","RFR","LTC","MFT","LAMB","GRS","EDR","AERGO","BCHA","AQT","BSV","TT","KNC","IQ","QKC","STORJ","ICX","AHT","ZRX","LSK","ONG","XTZ","KAVA","THETA","ENJ","OMG","REP","ATOM","BAT","ADX","IOTA"]
#code = ["BTT","MBL","AHT","TT","MFT","CRE","RFR","TSHP","IQ","MVL","OBSR","QKC","SC","STMX","EDR","IOST","QTCON","LAMB","STPT"]
code = ["ADA","MLK","GRS","STX","ZRX","STORJ","IOTA","ARK","ENJ","ONT","ICX","PUNDIX","KNC","KMD","MTL","STRAX","SXP","AQT","KAVA","DAWN","CBK","XTZ","SBD","AXS","LSK","EOS","SRM","TON","OMG","THETA","GAS","QTUM","FLOW","ATOM","WAVES","REP","BCHA","LINK","STRK"]
cancelcode = []
buyflag = []
telegram_token = '<KEY>'
bot = telegram.Bot(token = telegram_token)
hap = 0
money = 20000000
cnt = 0
def get_my_value(coin):
query = {
'market': 'KRW-'+coin,
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.get(server_url + "/v1/orders/chance", params=query, headers=headers)
balance = float(res.json()["ask_account"]["balance"])
avg_buy_price = float(res.json()["ask_account"]["avg_buy_price"])
return balance,avg_buy_price
def get_my_KRW():
m = hashlib.sha512()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.get(server_url + "/v1/accounts", headers=headers)
#print(float(res.json()[0]["balance"]))
return float(res.json()[0]["balance"])
for j in range(0,len(code)):
buyflag.append(True)
cancelcode.append("")
while True:
try:
for j in range(0,len(code)):
print(code[j])
url = "https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/10?code=CRIX.UPBIT.KRW-"+code[j]+"&count=400"
response = requests.request("GET", url)
data = response.json()
df = pd.DataFrame(data)
#print(df.iloc[0]["tradePrice"])
sonik = 0
realsonik = 0
mybal,my_avg_price = get_my_value(code[j])
#print(code[j])
if(get_my_KRW()>20000):
if(buyflag[j]==True):
if(df.iloc[0]["highPrice"]>df.iloc[1]["highPrice"] and df.iloc[0]["lowPrice"]>df.iloc[1]["lowPrice"] and df.iloc[1]["tradePrice"]<=df.iloc[2]["tradePrice"] and df.iloc[0]["tradePrice"]<=df.iloc[1]["highPrice"]):
#print("buy")
buytmpflag = True
#print(df.iloc[0]["tradePrice"],get_my_KRW(),get_my_KRW()/df.iloc[0]["tradePrice"])
ret = upbit.buy_limit_order("KRW-"+code[j], df.iloc[0]["tradePrice"], (get_my_KRW()-10000)/df.iloc[0]["tradePrice"])
print(ret)
cancelcode[j] =ret['uuid']
#bot.sendMessa ge(chat_id = '1780594186', text="["+code[j]+"] 구매시도")
time.sleep(3)
if(mybal!=0.0):
if(my_avg_price*1.005<=df.iloc[0]["tradePrice"]):
ret = upbit.sell_limit_order("KRW-"+code[j], df.iloc[0]["tradePrice"], mybal)
print(ret)
cancelcode[j] =ret['uuid']
time.sleep(3)
#bot.sendMessage(chat_id = '1780594186', text="["+code[j]+"] 판매")
buytmpflag = False
tmp = df.iloc[0]["tradePrice"]
if(df.iloc[1]["highPrice"] > df.iloc[0]["highPrice"] and df.iloc[1]["lowPrice"] > df.iloc[0]["lowPrice"] and my_avg_price >= df.iloc[1]["lowPrice"]):
ret = upbit.sell_limit_order("KRW-"+code[j], df.iloc[0]["tradePrice"], mybal)
print(ret)
cancelcode[j] =ret['uuid']
time.sleep(3)
#bot.sendMessage(chat_id = '1780594186', text="["+code[j]+"] 판매")
buytmpflag = False
tmp = df.iloc[0]["tradePrice"]
if(cancelcode[j]!=""):
ret = upbit.cancel_order(cancelcode[j])
try:
if(ret["error"]):
if(buytmpflag == True):
#print(code[j] + "구매 완료")
buyflag[j]==False
cancelcode[j] = ""
else:
#print(code[j] + "판매 완료")
buyflag[j]==True
sonikmoney = (tmp - my_avg_price) * mybal
bot.sendMessage(chat_id = '1780594186', text="["+code[j]+"] 손익 : "+ str(sonikmoney))
cancelcode[j] = ""
except:
cancelcode[j] = ""
'''
if(buytmpflag == True):
print("구매 실패")
else:
print("판매 실패")
'''
pass
time.sleep(0.1)
except Exception as e:
print("에러")
print(e)
time.sleep(0.2)
<file_sep>/ilmok.py
import pandas as pd
import datetime
import requests
import pandas as pd
import time
import webbrowser
import telegram
a = 1
code = ["XRP","DAWN","DOGE","STRK","ETC","SRM","WAVES","BTG","NEO","QTUM","EOS","SC","CBK","PUNDIX","GAS","MLK","SBD","AXS","ONT","OBSR","MVL","FLOW","ARK","MTL","TON","STX","MBL","TSHP","STRAX","ADA","STMX","PCI","CRE","IOST","SXP","DOT","MANA","STEEM","STPT","LINK","QTCON","DMT","RFR","LTC","MFT","LAMB","GRS","EDR","AERGO","BCHA","AQT","BSV","TT","KNC","IQ","QKC","STORJ","ICX","AHT","ZRX","LSK","ONG","XTZ","KAVA","THETA","ENJ","OMG","REP","ATOM","BAT","ADX","IOTA"]
buy_flag = []
pyungdan = []
sonik = []
telegram_token = '<PASSWORD>:<PASSWORD>'
bot = telegram.Bot(token = telegram_token)
for i in range(0,len(code)):
buy_flag.append(True)
pyungdan.append(0)
sonik.append(0)
while True:
for i in range(0,len(code)):
try:
url = "https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/1?code=CRIX.UPBIT.KRW-"+code[i]+"&count=400"
response = requests.request("GET", url)
data = response.json()
df = pd.DataFrame(data)
df=df.iloc[::-1]
print(code[i],df['tradePrice'].iloc[-1])
high_prices = df['highPrice']
close_prices = df['tradePrice']
low_prices = df['lowPrice']
dates = df.index
nine_period_high = df['highPrice'].rolling(window=9).max()
nine_period_low = df['lowPrice'].rolling(window=9).min()
df['tenkan_sen'] = (nine_period_high + nine_period_low) /2
period26_high = high_prices.rolling(window=26).max()
period26_low = low_prices.rolling(window=26).min()
df['kijun_sen'] = (period26_high + period26_low) / 2
df['senkou_span_a'] = ((df['tenkan_sen'] + df['kijun_sen']) / 2).shift(26)
period52_high = high_prices.rolling(window=52).max()
period52_low = low_prices.rolling(window=52).min()
df['senkou_span_b'] = ((period52_high + period52_low) / 2).shift(26)
df['chikou_span'] = close_prices.shift(-26)
if(buy_flag[i]==True):
if(df['senkou_span_a'].iloc[-1]>=df['senkou_span_b'].iloc[-1] and df['senkou_span_a'].iloc[-3] > df['tradePrice'].iloc[-3] and df['senkou_span_a'].iloc[-2] <= df['tradePrice'].iloc[-2] and df['senkou_span_a'].iloc[-1] <= df['tradePrice'].iloc[-1]):
buy_flag[i] = False
pyungdan[i]=df['tradePrice'].iloc[-1]
print("buy")
else:
if(df['tradePrice'].iloc[-1]<df['lowPrice'].iloc[-2]):
print("sell")
buy_flag[i] = True
sonik[i] = sonik[i] + df['tradePrice'] - pyungdan[i]
bot.sendMessage(chat_id = '1780594186', text="["+code[i]+"] 판매 손익 "+str(df['tradePrice'].iloc[-1] - pyungdan[i]))
time.sleep(0.7)
except Exception as e:
print(e)
pass
<file_sep>/import requests.py
import requests
import pandas as pd
import time
import webbrowser
url = "https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/5?code=CRIX.UPBIT.KRW-KMD&count=400"
response = requests.request("GET", url)
data = response.json()
df = pd.DataFrame(data)
df=df.iloc[::-1]
print(df)
<file_sep>/ss.py
import pandas as pd
from keras.layers.core import Dense, Dropout
from keras.layers.recurrent import GRU
from keras.models import Sequential, load_model
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import requests
import pandas as pd
import sys
import time
from bs4 import BeautifulSoup
import telegram
from urllib.parse import urlencode
import os
import jwt
import uuid
import hashlib
import datetime
import requests
import requests
import datetime
import time
import sys
x_scale = MinMaxScaler()
y_scale = MinMaxScaler()
model_name = 'stock_price_GRU'
model = Sequential()
model.add(GRU(units=50,
return_sequences=True,
input_shape=(1, 6)))
model.add(Dropout(0.15))
model.add(GRU(units=50))
model.add(Dropout(0.15))
model.add(Dense(1, activation='tanh'))
model.compile(loss='mse', optimizer='adam')
access_key = '<KEY>'
secret_key = '<KEY>'
server_url = 'https://api.upbit.com'
telegram_token = '1<PASSWORD>:<KEY>'
bot = telegram.Bot(token = telegram_token)
first = True
def buy(coin,volume,price):
query = {
'market': 'KRW-'+coin,
'side': 'bid',
'price': price,
'volume': '',
'ord_type': 'price',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
if(res.status_code==201):
return True
else:
return False
def sell(coin,volume,price):
query = {
'market': 'KRW-'+coin,
'side': 'ask',
'price': '',
'volume': volume,
'ord_type': 'market',
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.post(server_url + "/v1/orders", params=query, headers=headers)
if(res.status_code==201):
return float(res.json()["price"])
else:
return 0
def get_my_value(coin):
query = {
'market': 'KRW-'+coin,
}
query_string = urlencode(query).encode()
m = hashlib.sha512()
m.update(query_string)
query_hash = m.hexdigest()
payload = {
'access_key': access_key,
'nonce': str(uuid.uuid4()),
'query_hash': query_hash,
'query_hash_alg': 'SHA512',
}
jwt_token = jwt.encode(payload, secret_key)
authorize_token = 'Bearer {}'.format(jwt_token)
headers = {"Authorization": authorize_token}
res = requests.get(server_url + "/v1/orders/chance", params=query, headers=headers)
balance = float(res.json()["ask_account"]["balance"])
avg_buy_price = float(res.json()["ask_account"]["avg_buy_price"])
return balance,avg_buy_price
def rsi(ohlc: pd.DataFrame, period: int = 14):
ohlc["close"] = ohlc["close"]
delta = ohlc["close"].diff()
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
_gain = up.ewm(com=(period - 1), min_periods=period).mean()
_loss = down.abs().ewm(com=(period - 1), min_periods=period).mean()
RS = _gain / _loss
return pd.Series(100 - (100 / (1 + RS)), name="RSI")
def start(coin, time, rate):
print(coin,time)
minutes_units = [time]
for minutes_unit in minutes_units:
'''
Scraping minutes data
'''
req = requests.get(f'https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/{minutes_unit}?code=CRIX.UPBIT.KRW-'+coin+'&count=1000')
data = req.json()
#print(data)
df = pd.DataFrame(reversed(data))
df2 = pd.DataFrame(data)
df=df.reindex(index=df.index[::-1]).reset_index()
df['close']=df["tradePrice"]
trade_price = float(df["tradePrice"][199])
result = []
test = -100000
up = 0
for i, candle in enumerate(data):
if(i>=100):
TradePrice = float(data[399-i]["tradePrice"])
nowrsi = rsi(df[:i].reset_index(), 14).iloc[-1]
df3=df2.iloc[i-100:i]['tradePrice'].reset_index(drop = True).iloc[::-1]
exp1 = df3.ewm(span=12, adjust=False).mean()
exp2 = df3.ewm(span=26, adjust=False).mean()
macd = exp1-exp2
exp3 = macd.ewm(span=9, adjust=False).mean()
#print('MACD: ',macd[0])
#print('Signal: ',exp3[0])
if(TradePrice*(1+0.01*float(rate))<test):
up = up+1
else:
if(TradePrice>=test):
up = 0
else:
pass
test = TradePrice
result.append({
'OpeningPrice' : data[399-i]["openingPrice"],
'HighPrice' : data[399-i]["highPrice"],
'LowPrice' : data[399-i]["lowPrice"],
'TradePrice' : data[399-i]["tradePrice"],
'CandleAccTradeVolume' : data[399-i]["candleAccTradeVolume"],
"candleAccTradePrice" : data[399-i]["candleAccTradePrice"],
"rsi" : nowrsi,
"macd" : macd[0],
"exp" : exp3[0],
"up" : up
})
prices = pd.DataFrame(result)<file_sep>/zz.py
import pandas as pd
import datetime
import requests
import pandas as pd
import time
import webbrowser
url = "https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/5?code=CRIX.UPBIT.KRW-GRS&count=400"
response = requests.request("GET", url)
data = response.json()
df = pd.DataFrame(data)
df=df.iloc[::-1]
high_prices = df['highPrice']
close_prices = df['tradePrice']
low_prices = df['lowPrice']
dates = df.index
nine_period_high = df['highPrice'].rolling(window=9).max()
nine_period_low = df['lowPrice'].rolling(window=9).min()
df['tenkan_sen'] = (nine_period_high + nine_period_low) /2
period26_high = high_prices.rolling(window=26).max()
period26_low = low_prices.rolling(window=26).min()
df['kijun_sen'] = (period26_high + period26_low) / 2
df['senkou_span_a'] = ((df['tenkan_sen'] + df['kijun_sen']) / 2).shift(26)
period52_high = high_prices.rolling(window=52).max()
period52_low = low_prices.rolling(window=52).min()
df['senkou_span_b'] = ((period52_high + period52_low) / 2).shift(26)
df['chikou_span'] = close_prices.shift(-26)
print('전환선: ',df['tenkan_sen'].iloc[-1])
print('기준선: ',df['kijun_sen'].iloc[-1])
print('후행스팬: ',df['chikou_span'].iloc[-27])
print('선행스팬1: ',df['senkou_span_a'].iloc[-1])
print('선행스팬2: ',df['senkou_span_b'].iloc[-1]) | c4655cdef4514239806c4d52a1e658143abddab0 | [
"Markdown",
"Batchfile",
"Python"
] | 24 | Markdown | rookie0806/testtesttest | 2b842b3f5a36d3278f3d0420e1db80cdcb03833a | 2acb8e20cc340a1d23c763d0d65fb590d903e9dc |
refs/heads/master | <repo_name>romeara/x-com-tac-com<file_sep>/README.md
# x-com-tac-com
Tactical game/strategy management program for X-COM: Enemy Within with the Long War Mod
| 620c1e99c8c11194c4ecd530d23bb36e78cefae1 | [
"Markdown"
] | 1 | Markdown | romeara/x-com-tac-com | fde8827df83ce16046290b9a14a6bcde1ef329ea | abb62d40265f98d3b358b854e6634011a38dbd98 |
refs/heads/master | <file_sep>LNURL implementation for Python
===============================
[![travis-badge]][travis]
[![codecov-badge]][codecov]
[![pypi-badge]][pypi]
[![pypi-versions]][pypi]
[![license-badge]](LICENSE)
A collection of helpers for building [LNURL][lnurl] support into wallets and services.
Basic usage
-----------
```python
>>> import lnurl
>>> lnurl.encode('https://service.io/?q=3fc3645b439ce8e7')
Lnurl('<KEY>', bech32=Bech32('<KEY>', hrp='lnurl', data=[13, 1, 26, 7, 8, 28, 3, 19, 7, 8, 23, 18, 30, 28, 27, 5, 14, 9, 27, 6, 18, 24, 27, 5, 5, 25, 20, 22, 30, 11, 25, 31, 14, 4, 30, 19, 6, 25, 19, 3, 6, 12, 27, 3, 8, 13, 11, 2, 6, 16, 25, 19, 18, 24, 27, 5, 7, 1, 18, 19, 14]), url=WebUrl('https://service.io/?q=3fc3645b439ce8e7', scheme='https', host='service.io', tld='io', host_type='domain', path='/', query='q=3fc3645b439ce8e7'))
>>> lnurl.decode('LNURL1DP68GURN8GHJ7UM9WFMXJCM99<KEY>NWXQ96S9')
WebUrl('https://service.io/?q=3fc3645b439ce8e7', scheme='https', host='service.io', tld='io', host_type='domain', path='/', query='q=3fc3645b439ce8e7')
```
The `Lnurl` object wraps a bech32 LNURL to provide some extra utilities.
```python
from lnurl import Lnurl
lnurl = Lnurl("LNURL<KEY>")
lnurl.bech32 # "LNURL1<KEY>"
lnurl.bech32.hrp # "lnurl"
lnurl.url # "https://service.io/?q=3fc3645b439ce8e7"
lnurl.url.host # "service.io"
lnurl.url.base # "https://service.io/"
lnurl.url.query # "q=3fc3645b439ce8e7"
lnurl.url.query_params # {"q": "3fc3645b439ce8e7"}
```
Parsing LNURL responses
-----------------------
You can use a `LnurlResponse` to wrap responses you get from a LNURL.
The different types of responses defined in the [LNURL spec][lnurl-spec] have a different model
with different properties (see `models.py`):
```python
import requests
from lnurl import Lnurl, LnurlResponse
lnurl = Lnurl('LN<KEY>')
r = requests.get(lnurl.url)
res = LnurlResponse.from_dict(r.json()) # LnurlPayResponse
res.ok # bool
res.max_sendable # int
res.max_sats # int
res.callback.base # str
res.callback.query_params # dict
res.metadata # str
res.metadata.list() # list
res.metadata.text # str
res.metadata.images # list
```
If you have already `requests` installed, you can also use the `.handle()` function directly.
It will return the appropriate response for a LNURL.
```python
>>> import lnurl
>>> lnurl.handle('lightning:LN<KEY>')
LnurlPayResponse(tag='payRequest', callback=WebUrl('https://lnurl.bigsun.xyz/lnurl-pay/callback/2169831', scheme='https', host='lnurl.bigsun.xyz', tld='xyz', host_type='domain', path='/lnurl-pay/callback/2169831'), min_sendable=10000, max_sendable=10000, metadata=LnurlPayMetadata('[["text/plain","NgHaEyaZNDnW iI DsFYdkI"],["image/png;base64","iVBOR...uQmCC"]]'))
```
Building your own LNURL responses
---------------------------------
For LNURL services, the `lnurl` package can be used to build **valid** responses.
```python
from lnurl import LnurlWithdrawResponse
res = LnurlWithdrawResponse(
callback="https://lnurl.bigsun.xyz/lnurl-withdraw/callback/9702808",
k1="38d304051c1b76dcd8c5ee17ee15ff0ebc02090c0afbc6c98100adfa3f920874",
min_withdrawable=551000,
max_withdrawable=551000,
default_description="sample withdraw",
)
res.json() # str
res.dict() # dict
```
All responses are [`pydantic`][pydantic] models, so the information you provide will be validated and you have
access to `.json()` and `.dict()` methods to export the data.
**Data is exported using :camel: camelCase keys by default, as per spec.**
You can also use camelCases when you parse the data, and it will be converted to snake_case to make your
Python code nicer.
If you want to export the data using :snake: snake_case (in your Python code, for example), you can change
the `by_alias` parameter: `res.dict(by_alias=False)` (it is `True` by default).
[travis]: https://travis-ci.com/python-ln/lnurl?branch=master
[travis-badge]: https://api.travis-ci.com/python-ln/lnurl.svg?branch=master
[codecov]: https://codecov.io/gh/python-ln/lnurl
[codecov-badge]: https://codecov.io/gh/python-ln/lnurl/branch/master/graph/badge.svg
[pypi]: https://pypi.org/project/lnurl/
[pypi-badge]: https://badge.fury.io/py/lnurl.svg
[pypi-versions]: https://img.shields.io/pypi/pyversions/lnurl.svg
[license-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[lnurl]: https://telegra.ph/lnurl-a-protocol-for-seamless-interaction-between-services-and-Lightning-wallets-08-19
[lnurl-spec]: https://github.com/btcontract/lnurl-rfc/blob/master/spec.md
[pydantic]: https://github.com/samuelcolvin/pydantic/
<file_sep>try:
import requests
except ImportError: # pragma: nocover
requests = None
from pydantic import ValidationError
from typing import Union
from .exceptions import LnurlResponseException, InvalidLnurl, InvalidUrl
from .helpers import _url_encode
from .models import LnurlResponse, LnurlResponseModel, LnurlAuthResponse
from .types import Lnurl, TorUrl, WebUrl
def decode(bech32_lnurl: str) -> Union[TorUrl, WebUrl]:
try:
return Lnurl(bech32_lnurl).url
except (ValidationError, ValueError):
raise InvalidLnurl
def encode(url: str) -> Lnurl:
try:
return Lnurl(_url_encode(url))
except (ValidationError, ValueError):
raise InvalidUrl
def get(url: str, *, response_class: LnurlResponseModel = None) -> LnurlResponseModel:
if requests is None: # pragma: nocover
raise ImportError("The `requests` library must be installed to use `lnurl.get()` and `lnurl.handle()`.")
try:
r = requests.get(url)
except Exception as e:
raise LnurlResponseException(str(e))
if response_class:
return response_class(**r.json())
return LnurlResponse.from_dict(r.json())
def handle(bech32_lnurl: str, *, response_class: LnurlResponseModel = None) -> LnurlResponseModel:
try:
lnurl = Lnurl(bech32_lnurl)
except (ValidationError, ValueError):
raise InvalidLnurl
if lnurl.is_login:
return LnurlAuthResponse(callback=lnurl.url, k1=lnurl.url.query_params["k1"])
return get(lnurl.url, response_class=response_class)
<file_sep>class LnurlException(Exception):
"""A LNURL error occurred."""
class LnurlResponseException(LnurlException):
"""An error ocurred processing LNURL response."""
class InvalidLnurl(LnurlException, ValueError):
"""The LNURL provided was somehow invalid."""
class InvalidUrl(LnurlException, ValueError):
"""The URL is not properly formed."""
class InvalidLnurlPayMetadata(LnurlResponseException, ValueError):
"""The response `metadata` is not properly formed."""
<file_sep>[tox]
envlist =
py36
py37
py38
[testenv]
deps =
pytest
pytest-cov
requests
commands =
pytest --cov=lnurl
passenv =
CI
TRAVIS
TRAVIS_*
<file_sep>import json
import pytest
from pydantic import ValidationError
from lnurl.models import (
LnurlErrorResponse,
LnurlSuccessResponse,
LnurlChannelResponse,
LnurlHostedChannelResponse,
LnurlPayResponse,
LnurlWithdrawResponse,
)
class TestLnurlErrorResponse:
def test_response(self):
res = LnurlErrorResponse(reason="blah blah blah")
assert res.ok is False
assert res.error_msg == "blah blah blah"
assert res.json() == '{"status": "ERROR", "reason": "blah blah blah"}'
assert res.dict() == {"status": "ERROR", "reason": "blah blah blah"}
def test_no_reason(self):
with pytest.raises(ValidationError):
LnurlErrorResponse()
class TestLnurlSuccessResponse:
def test_success_response(self):
res = LnurlSuccessResponse()
assert res.ok
assert res.json() == '{"status": "OK"}'
assert res.dict() == {"status": "OK"}
class TestLnurlChannelResponse:
@pytest.mark.parametrize(
"d", [{"uri": "node_key@ip_address:port_number", "callback": "https://service.io/channel", "k1": "c3RyaW5n"}]
)
def test_channel_response(self, d):
res = LnurlChannelResponse(**d)
assert res.ok
assert res.dict() == {**{"tag": "channelRequest"}, **d}
@pytest.mark.parametrize(
"d",
[
{"uri": "invalid", "callback": "https://service.io/channel", "k1": "c3RyaW5n"},
{"uri": "node_key@ip_address:port_number", "callback": "invalid", "k1": "c3RyaW5n"},
{"uri": "node_key@ip_address:port_number", "callback": "https://service.io/channel", "k1": None},
],
)
def test_invalid_data(self, d):
with pytest.raises(ValidationError):
LnurlChannelResponse(**d)
class TestLnurlHostedChannelResponse:
@pytest.mark.parametrize("d", [{"uri": "node_key@ip_address:port_number", "k1": "c3RyaW5n"}])
def test_channel_response(self, d):
res = LnurlHostedChannelResponse(**d)
assert res.ok
assert res.dict() == {**{"tag": "hostedChannelRequest", "alias": None}, **d}
@pytest.mark.parametrize(
"d", [{"uri": "invalid", "k1": "c3RyaW5n"}, {"uri": "node_key@ip_address:port_number", "k1": None}]
)
def test_invalid_data(self, d):
with pytest.raises(ValidationError):
LnurlHostedChannelResponse(**d)
metadata = '[["text/plain","lorem ipsum blah blah"]]'
class TestLnurlPayResponse:
@pytest.mark.parametrize(
"d",
[
{"callback": "https://service.io/pay", "min_sendable": 1000, "max_sendable": 2000, "metadata": metadata},
{"callback": "https://service.io/pay", "minSendable": 1000, "maxSendable": 2000, "metadata": metadata},
],
)
def test_success_response(self, d):
res = LnurlPayResponse(**d)
assert res.ok
assert (
res.json()
== res.json(by_alias=True)
== (
f'{{"tag": "payRequest", "callback": "https://service.io/pay", '
f'"minSendable": 1000, "maxSendable": 2000, "metadata": {json.dumps(metadata)}}}'
)
)
assert (
res.dict()
== res.dict(by_alias=True)
== {
"tag": "payRequest",
"callback": "https://service.io/pay",
"minSendable": 1000,
"maxSendable": 2000,
"metadata": metadata,
}
)
assert res.dict(by_alias=False) == {
"tag": "payRequest",
"callback": "https://service.io/pay",
"min_sendable": 1000,
"max_sendable": 2000,
"metadata": metadata,
}
@pytest.mark.parametrize(
"d",
[
{"callback": "invalid", "min_sendable": 1000, "max_sendable": 2000, "metadata": metadata},
{"callback": "https://service.io/pay"}, # missing fields
{"callback": "https://service.io/pay", "min_sendable": 0, "max_sendable": 0, "metadata": metadata}, # 0
{"callback": "https://service.io/pay", "minSendable": 100, "maxSendable": 10, "metadata": metadata}, # max
{"callback": "https://service.io/pay", "minSendable": -90, "maxSendable": -10, "metadata": metadata},
],
)
def test_invalid_data(self, d):
with pytest.raises(ValidationError):
LnurlPayResponse(**d)
class TestLnurlWithdrawResponse:
@pytest.mark.parametrize(
"d",
[
{
"callback": "https://service.io/withdraw",
"k1": "c3RyaW5n",
"min_withdrawable": 100,
"max_withdrawable": 200,
},
{
"callback": "https://service.io/withdraw",
"k1": "c3RyaW5n",
"minWithdrawable": 100,
"maxWithdrawable": 200,
},
],
)
def test_success_response(self, d):
res = LnurlWithdrawResponse(**d)
assert res.ok
assert (
res.json()
== res.json(by_alias=True)
== (
'{"tag": "withdrawRequest", "callback": "https://service.io/withdraw", "k1": "c3RyaW5n", '
'"minWithdrawable": 100, "maxWithdrawable": 200, "defaultDescription": ""}'
)
)
assert (
res.dict()
== res.dict(by_alias=True)
== {
"tag": "withdrawRequest",
"callback": "https://service.io/withdraw",
"k1": "c3RyaW5n",
"minWithdrawable": 100,
"maxWithdrawable": 200,
"defaultDescription": "",
}
)
assert res.dict(by_alias=False) == {
"tag": "withdrawRequest",
"callback": "https://service.io/withdraw",
"k1": "c3RyaW5n",
"min_withdrawable": 100,
"max_withdrawable": 200,
"default_description": "",
}
@pytest.mark.parametrize(
"d",
[
{"callback": "invalid", "k1": "c3RyaW5n", "min_withdrawable": 1000, "max_withdrawable": 2000},
{"callback": "https://service.io/withdraw", "k1": "c3RyaW5n"}, # missing fields
{"callback": "https://service.io/withdraw", "k1": "c3RyaW5n", "min_withdrawable": 0, "max_withdrawable": 0},
{
"callback": "https://service.io/withdraw",
"k1": "c3RyaW5n",
"minWithdrawable": 100,
"maxWithdrawable": 10,
},
{"callback": "https://service.io/withdraw", "k1": "c3RyaW5n", "minWithdrawable": -9, "maxWithdrawable": -1},
],
)
def test_invalid_data(self, d):
with pytest.raises(ValidationError):
LnurlWithdrawResponse(**d)
<file_sep>import math
from pydantic import BaseModel, Field, constr, validator
from typing import List, Optional, Union
try:
from typing import Literal
except ImportError: # pragma: nocover
from typing_extensions import Literal
from .exceptions import LnurlResponseException
from .types import LightningInvoice, LightningNodeUri, LnurlPayMetadata, MilliSatoshi, TorUrl, WebUrl
class LnurlPayRouteHop(BaseModel):
node_id: str = Field(..., alias="nodeId")
channel_update: str = Field(..., alias="channelUpdate")
class LnurlPaySuccessAction(BaseModel):
pass
class AesAction(LnurlPaySuccessAction):
tag: Literal["aes"] = "aes"
description: constr(max_length=144)
ciphertext: str # TODO
iv: constr(min_length=24, max_length=24)
class MessageAction(LnurlPaySuccessAction):
tag: Literal["message"] = "message"
message: constr(max_length=144)
class UrlAction(LnurlPaySuccessAction):
tag: Literal["url"] = "url"
description: constr(max_length=144)
url: Union[TorUrl, WebUrl]
class LnurlResponseModel(BaseModel):
class Config:
allow_population_by_field_name = True
def dict(self, **kwargs):
kwargs.setdefault("by_alias", True)
return super().dict(**kwargs)
def json(self, **kwargs):
kwargs.setdefault("by_alias", True)
return super().json(**kwargs)
@property
def ok(self) -> bool:
return not ("status" in self.__fields__ and self.status == "ERROR")
class LnurlErrorResponse(LnurlResponseModel):
status: Literal["ERROR"] = "ERROR"
reason: str
@property
def error_msg(self) -> str:
return self.reason
class LnurlSuccessResponse(LnurlResponseModel):
status: Literal["OK"] = "OK"
class LnurlAuthResponse(LnurlResponseModel):
tag: Literal["login"] = "login"
callback: Union[TorUrl, WebUrl]
k1: str
class LnurlChannelResponse(LnurlResponseModel):
tag: Literal["channelRequest"] = "channelRequest"
uri: LightningNodeUri
callback: Union[TorUrl, WebUrl]
k1: str
class LnurlHostedChannelResponse(LnurlResponseModel):
tag: Literal["hostedChannelRequest"] = "hostedChannelRequest"
uri: LightningNodeUri
k1: str
alias: Optional[str]
class LnurlPayResponse(LnurlResponseModel):
tag: Literal["payRequest"] = "payRequest"
callback: Union[TorUrl, WebUrl]
min_sendable: MilliSatoshi = Field(..., alias="minSendable")
max_sendable: MilliSatoshi = Field(..., alias="maxSendable")
metadata: LnurlPayMetadata
@validator("max_sendable")
def max_less_than_min(cls, value, values, **kwargs): # noqa
if "min_sendable" in values and value < values["min_sendable"]:
raise ValueError("`max_sendable` cannot be less than `min_sendable`.")
return value
@property
def min_sats(self) -> int:
return int(math.ceil(self.min_sendable / 1000))
@property
def max_sats(self) -> int:
return int(math.floor(self.max_sendable / 1000))
class LnurlPayActionResponse(LnurlResponseModel):
pr: LightningInvoice
success_action: Optional[Union[MessageAction, UrlAction, AesAction]] = Field(None, alias="successAction")
routes: List[List[LnurlPayRouteHop]] = []
class LnurlWithdrawResponse(LnurlResponseModel):
tag: Literal["withdrawRequest"] = "withdrawRequest"
callback: Union[TorUrl, WebUrl]
k1: str
min_withdrawable: MilliSatoshi = Field(..., alias="minWithdrawable")
max_withdrawable: MilliSatoshi = Field(..., alias="maxWithdrawable")
default_description: str = Field("", alias="defaultDescription")
@validator("max_withdrawable")
def max_less_than_min(cls, value, values, **kwargs): # noqa
if "min_withdrawable" in values and value < values["min_withdrawable"]:
raise ValueError("`max_withdrawable` cannot be less than `min_withdrawable`.")
return value
@property
def min_sats(self) -> int:
return int(math.ceil(self.min_withdrawable / 1000))
@property
def max_sats(self) -> int:
return int(math.floor(self.max_withdrawable / 1000))
class LnurlResponse:
@staticmethod
def from_dict(d: dict) -> LnurlResponseModel:
try:
if "tag" in d:
# some services return `status` here, but it is not in the spec
d.pop("status", None)
return {
"channelRequest": LnurlChannelResponse,
"hostedChannelRequest": LnurlHostedChannelResponse,
"payRequest": LnurlPayResponse,
"withdrawRequest": LnurlWithdrawResponse,
}[d["tag"]](**d)
if "successAction" in d:
d.pop("status", None)
return LnurlPayActionResponse(**d)
# some services return `status` in lowercase, but spec says upper
d["status"] = d["status"].upper()
if "status" in d and d["status"] == "ERROR":
return LnurlErrorResponse(**d)
return LnurlSuccessResponse(**d)
except Exception:
raise LnurlResponseException
<file_sep># flake8: noqa
from .core import (
decode,
encode,
get,
handle,
)
from .models import (
LnurlResponse,
LnurlErrorResponse,
LnurlSuccessResponse,
LnurlChannelResponse,
LnurlHostedChannelResponse,
LnurlPayResponse,
LnurlPayActionResponse,
LnurlWithdrawResponse,
)
from .types import Lnurl
<file_sep>import pytest
from pydantic import ValidationError, parse_obj_as
from typing import Union
from lnurl.helpers import _lnurl_clean
from lnurl.types import LightningInvoice, LightningNodeUri, Lnurl, LnurlPayMetadata, Url, TorUrl, WebUrl
class TestUrl:
def test_parameters(self):
url = parse_obj_as(Url, "https://service.io/?q=3fc3645b439ce8e7&test=ok")
assert url.host == "service.io"
assert url.base == "https://service.io/"
assert url.query_params == {"q": "3fc3645b439ce8e7", "test": "ok"}
@pytest.mark.parametrize(
"url",
[
"https://service.io/?q=3fc3645b439ce8e7&test=ok",
"https://[2001:db8:0:1]:80",
"https://protonirockerxow.onion/",
"http://protonirockerxow.onion/",
],
)
def test_valid(self, url):
url = parse_obj_as(Union[TorUrl, WebUrl], url)
assert isinstance(url, Url)
@pytest.mark.parametrize(
"url",
[
"http://service.io/?q=3fc3645b439ce8e7&test=ok",
"http://[2001:db8:0:1]:80",
f'https://service.io/?hash={"x" * 4096}',
"https://📙.la/⚡", # https://emojipedia.org/high-voltage-sign/
"https://xn--yt8h.la/%E2%9A%A1",
"https://1.1.1.1/\u0000",
],
)
def test_invalid_data(self, url):
with pytest.raises(ValidationError):
parse_obj_as(Union[TorUrl, WebUrl], url)
class TestLightningInvoice:
@pytest.mark.xfail(raises=NotImplementedError)
@pytest.mark.parametrize(
"bech32, hrp, prefix, amount, h",
[
(
"lntb20m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqhp58yjmdan79s6qqdhdzgynm4zwqd"
"5d7xmw5fk98klysy043l2ahrqsfpp3x9et2e20v6pu37c5d9vax37wxq72un98k6vcx9fz94w0qf237cm2rqv9pmn5lnexfvf55"
"79slr4zq3u8kmczecytdx0xg9rwzngp7e6guwqpqlhssu04sucpnz4axcv2dstmknqq6jsk2l",
"lntb20m",
"lntb",
20,
"h",
),
],
)
def test_valid(self, bech32, hrp, prefix, amount, h):
invoice = LightningInvoice(bech32)
assert invoice == parse_obj_as(LightningInvoice, bech32)
assert invoice.hrp == hrp
assert invoice.prefix == prefix
assert invoice.amount == amount
assert invoice.h == h
class TestLightningNode:
def test_valid(self):
node = parse_obj_as(LightningNodeUri, "node_key@ip_address:port_number")
assert node.key == "node_key"
assert node.ip == "ip_address"
assert node.port == "port_number"
@pytest.mark.parametrize("uri", ["https://service.io/node", "node_key@ip_address", "ip_address:port_number",])
def test_invalid_data(self, uri):
with pytest.raises(ValidationError):
parse_obj_as(LightningNodeUri, uri)
class TestLnurl:
@pytest.mark.parametrize(
"lightning, url",
[
(
"<KEY>"
"<KEY>",
"https://service.io/?q=3fc3645b439ce8e7f2553a69e5267081d96dcd340693afabe04be7b0ccd178df",
),
(
"lightning:<KEY>"
"<KEY>",
"https://service.io/?q=3fc3645b439ce8e7f2553a69e5267081d96dcd340693afabe04be7b0ccd178df",
),
],
)
def test_valid(self, lightning, url):
lnurl = Lnurl(lightning)
assert lnurl == lnurl.bech32 == _lnurl_clean(lightning) == parse_obj_as(Lnurl, lightning)
assert lnurl.bech32.hrp == "lnurl"
assert lnurl.url == url
assert lnurl.url.base == "https://service.io/"
assert lnurl.url.query_params == {"q": "3fc3645b439ce8e7f2553a69e5267081d96dcd340693afabe04be7b0ccd178df"}
assert lnurl.is_login is False
@pytest.mark.parametrize(
"bech32",
[
"abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw",
"split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w",
"BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4",
],
)
def test_decode_nolnurl(self, bech32):
with pytest.raises(ValidationError):
parse_obj_as(Lnurl, bech32)
class TestLnurlPayMetadata:
@pytest.mark.parametrize(
"metadata, image_type",
[
('[["text/plain", "main text"]]', None),
('[["text/plain", "main text"], ["image/jpeg;base64", "base64encodedimage"]]', "jpeg"),
('[["text/plain", "main text"], ["image/png;base64", "base64encodedimage"]]', "png"),
],
)
def test_valid(self, metadata, image_type):
m = parse_obj_as(LnurlPayMetadata, metadata)
assert m.text == "main text"
if m.images:
assert len(m.images) == 1
assert dict(m.images)[f"image/{image_type};base64"] == "base64encodedimage"
@pytest.mark.parametrize(
"metadata",
[
"[]",
'["text""plain"]',
'[["text", "plain"]]',
'[["text", "plain", "plane"]]',
'[["text/plain", "main text"], ["text/plain", "two is too much"]]',
'[["image/jpeg;base64", "base64encodedimage"]]',
],
)
def test_invalid_data(self, metadata):
with pytest.raises(ValidationError):
parse_obj_as(LnurlPayMetadata, metadata)
<file_sep>import pytest
from urllib.parse import urlencode
from lnurl.core import decode, encode, get, handle
from lnurl.exceptions import LnurlResponseException, InvalidLnurl, InvalidUrl
from lnurl.models import (
LnurlAuthResponse,
LnurlPayResponse,
LnurlPayActionResponse,
LnurlWithdrawResponse,
LnurlPaySuccessAction,
)
from lnurl.types import Lnurl, Url
class TestDecode:
@pytest.mark.parametrize(
"bech32, url",
[
(
"<KEY>"
"XUCRSVTY8YMXGCMYXV6RQD3EXDSKVCTZV5CRGCN9XA3RQCMRVSCNWWRYVCYAE0UU",
"https://service.io/?q=3fc3645b439ce8e7f2553a69e5267081d96dcd340693afabe04be7b0ccd178df",
)
],
)
def test_decode(self, bech32, url):
decoded_url = decode(bech32)
assert isinstance(decoded_url, Url)
assert decoded_url == str(decoded_url) == url
assert decoded_url.host == "service.io"
@pytest.mark.parametrize(
"bech32",
[
"<KEY>",
"split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w",
"BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4",
],
)
def test_decode_nolnurl(self, bech32):
with pytest.raises(InvalidLnurl):
decode(bech32)
class TestEncode:
@pytest.mark.parametrize(
"bech32, url",
[
(
"LN<KEY>ENJCM98PJNWE3JX56NXCFK89JN2V3K"
"XUCRSVTY8YMXGCMYXV6RQD3EXDSKVCTZV5CRGCN9XA3RQCMRVSCNWWRYVCYAE0UU",
"https://service.io/?q=3fc3645b439ce8e7f2553a69e5267081d96dcd340693afabe04be7b0ccd178df",
)
],
)
def test_encode(self, bech32, url):
lnurl = encode(url)
assert isinstance(lnurl, Lnurl)
assert lnurl.bech32 == bech32
assert lnurl.url.host == "service.io"
@pytest.mark.parametrize("url", ["http://service.io/"])
def test_encode_nohttps(self, url):
with pytest.raises(InvalidUrl):
encode(url)
class TestHandle:
"""Responses from the LNURL playground: https://lnurl.bigsun.xyz/"""
@pytest.mark.parametrize(
"bech32",
[("<KEY>")],
)
def test_handle_auth(self, bech32):
res = handle(bech32)
assert isinstance(res, LnurlAuthResponse)
assert res.tag == "login"
assert res.callback.host == "lnurl.bigsun.xyz"
assert hasattr(res, "k1")
@pytest.mark.parametrize(
"bech32",
[("<KEY>")],
)
def test_handle_withdraw(self, bech32):
res = handle(bech32)
assert isinstance(res, LnurlWithdrawResponse)
assert res.tag == "withdrawRequest"
assert res.callback.host == "lnurl.bigsun.xyz"
assert res.default_description == "sample withdraw"
assert res.max_withdrawable >= res.min_withdrawable
@pytest.mark.parametrize("bech32", ["BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4"])
def test_handle_nolnurl(self, bech32):
with pytest.raises(InvalidLnurl):
handle(bech32)
@pytest.mark.parametrize("url", ["https://lnurl.thisshouldfail.io/"])
def test_get_requests_error(self, url):
with pytest.raises(LnurlResponseException):
get(url)
class TestPayFlow:
"""Full LNURL-pay flow interacting with https://lnurl.bigsun.xyz/"""
@pytest.mark.xfail(raises=NotImplementedError)
@pytest.mark.parametrize(
"bech32", [("<KEY>")]
)
def test_pay_flow(self, bech32):
res = handle(bech32)
assert isinstance(res, LnurlPayResponse) is True
assert res.tag == "payRequest"
assert res.callback.host == "lnurl.bigsun.xyz"
assert len(res.metadata.list()) >= 1
assert res.metadata.text != ""
query = urlencode({**res.callback.query_params, **{"amount": res.max_sendable}})
url = "".join([res.callback.base, "?", query])
res2 = get(url, response_class=LnurlPayActionResponse)
res3 = get(url)
assert res2.__class__ == res3.__class__
assert res2.success_action is None or isinstance(res2.success_action, LnurlPaySuccessAction)
assert res2.pr.h == res.metadata.h
<file_sep>from bech32 import bech32_decode, bech32_encode, convertbits
from typing import List, Set, Tuple
from .exceptions import InvalidLnurl, InvalidUrl
def _bech32_decode(bech32: str, *, allowed_hrp: Set[str] = None) -> Tuple[str, List[int]]:
hrp, data = bech32_decode(bech32)
if None in (hrp, data) or (allowed_hrp and hrp not in allowed_hrp):
raise ValueError(f"Invalid Human Readable Prefix (HRP): {hrp}.")
return hrp, data
def _lnurl_clean(lnurl: str) -> str:
lnurl = lnurl.strip()
return lnurl.replace("lightning:", "") if lnurl.startswith("lightning:") else lnurl
def _lnurl_decode(lnurl: str) -> str:
"""
Decode a LNURL and return a url string without performing any validation on it.
Use `lnurl.decode()` for validation and to get `Url` object.
"""
hrp, data = _bech32_decode(_lnurl_clean(lnurl), allowed_hrp={"lnurl"})
try:
url = bytes(convertbits(data, 5, 8, False)).decode("utf-8")
except UnicodeDecodeError: # pragma: nocover
raise InvalidLnurl
return url
def _url_encode(url: str) -> str:
"""
Encode a URL without validating it first and return a bech32 LNURL string.
Use `lnurl.encode()` for validation and to get a `Lnurl` object.
"""
try:
lnurl = bech32_encode("lnurl", convertbits(url.encode("utf-8"), 8, 5, True))
except UnicodeEncodeError: # pragma: nocover
raise InvalidUrl
return lnurl.upper()
<file_sep>Changelog
=========
All notable changes to this project will be documented in this file.
## [Unreleased]
## [0.3.3] - 2020-02-18
### Added
- Support for `.onion` Tor URLs without SSL certificate (both http and https are valid for `TorUrl`).
### Fixed
- `__repr__` mixin.
## [0.3.2] - 2020-01-31
### Added
- Custom exception when `lnurl.get()` request fails.
### Fixed
- `LNURL_FORCE_SSL` and `LNURL_STRICT_RFC3986` environment variables are `True` when value is `"1"`.
## [0.3.1] - 2019-12-19
### Fixed
- Stupid import error for `Literal` in Python 3.8 :(
## [0.3.0] - 2019-12-19
### Added
- Changelog.
- New LNURL-pay metadata mime types for images.
- New `LnurlPayMetadata` properties: `.images` (_list_) and `.text` (_str_).
- `LnurlPayMetadata` now checks if the required "text/plain" entry exists.
- `LNURL_FORCE_SSL` and `LNURL_STRICT_RFC3986` environment variables.
### Changed
- For `LnurlPayMetadata` there is no `.list` property anymore: use `.list()` method instead.
- Hashed metadata should be accessed now with `LnurlPayResponse().metadata.h` instead of `LnurlPayResponse().h`
- `HttpsUrl` type is now called `Url`.
- `Url` is not valid when control characters are found or if it is not RFC3986 compliant.
### Fixed
- Fix `Url` type tests.
- Install `typing-extensions` only if Python version < 3.8.
## [0.2.0] - 2019-12-14
### Added
- Extra documentation in README.
- Full validation of LNURL responses using `pydantic` models.
- `.json()` and `.dict()` methods to export data from responses. Data is exported in camelCase
by default, but internally all properties are still pythonic (snake_case).
- `LnurlResponse.from_dict()` helper to parse a response and assign the right type.
- `handle()` function to get a typed response directly from a LNURL if you have `requests` installed.
- Typed returns for `encode()` and `decode()` functions.
- `black` for code formating.
### Changed
- Responses now require that you pass kwargs instead of a dictionary: use `LnurlResponseModel(**dict)`
instead of the previous `LnurlResponse(dict)`
- `HttpsUrl` uses default `pydantic` validations now.
## [0.1.1] - 2019-12-04
### Added
- Get URL checks back into `validate_url()` function (from 0.0.2).
### Changed
- We can now parse error responses in lowercase (even if this is not in the spec).
## [0.1.0] - 2019-11-24
### Added
- API documentation in README.
- `Lnurl` class and different `LnurlResponse` classes.
- New folder structure.
- Tests.
## [0.0.2] - 2019-11-21
### Removed
- Remove all duplicated code from `bech32` package. We import the package instead.
## [0.0.1] - 2019-11-14
### Added
- Initial commit, based on `bech32` package.
- `encode()` and `decode()` functions.
[unreleased]: https://github.com/python-ln/lnurl/compare/0.3.3...HEAD
[0.3.3]: https://github.com/python-ln/lnurl/compare/0.3.2...0.3.3
[0.3.2]: https://github.com/python-ln/lnurl/compare/0.3.1...0.3.2
[0.3.1]: https://github.com/python-ln/lnurl/compare/0.3.0...0.3.1
[0.3.0]: https://github.com/python-ln/lnurl/compare/0.2.0...0.3.0
[0.2.0]: https://github.com/python-ln/lnurl/compare/0.1.1...0.2.0
[0.1.1]: https://github.com/python-ln/lnurl/compare/0.1.0...0.1.1
[0.1.0]: https://github.com/python-ln/lnurl/compare/0.0.2...0.1.0
[0.0.2]: https://github.com/python-ln/lnurl/compare/0.0.1...0.0.2
[0.0.1]: https://github.com/python-ln/lnurl/releases/tag/0.0.1
<file_sep>language: python
python:
- "3.6"
- "3.7"
- "3.8"
install:
- pip install requests codecov tox-travis
script:
- tox
after_success:
- codecov
<file_sep>import json
import pytest
from lnurl import LnurlResponse
from lnurl.exceptions import LnurlResponseException
class TestLnurlResponse:
pay_res = json.loads(
r'{"tag":"payRequest","metadata":"[[\"text/plain\",\"lorem ipsum blah blah\"]]","k1":"<KEY>","callback":"https://lnurl.bigsun.xyz/lnurl-pay/callback/","maxSendable":300980,"minSendable":100980,"defaultDescription":"sample pay"}'
) # noqa
pay_res_invalid = json.loads(r'{"tag":"payRequest","metadata":"[\"text\"\"plain\"]"}')
withdraw_res = json.loads(
'{"tag":"withdrawRequest","k1":"<KEY>","callback":"https://lnurl.bigsun.xyz/lnurl-withdraw/callback/?param1=1¶m2=2","maxWithdrawable":478980,"minWithdrawable":478980,"defaultDescription":"sample withdraw"}'
) # noqa
def test_error(self):
res = LnurlResponse.from_dict({"status": "error", "reason": "error details..."})
assert not res.ok
assert res.error_msg == "error details..."
def test_success(self):
res = LnurlResponse.from_dict({"status": "OK"})
assert res.ok
def test_unknown(self):
with pytest.raises(LnurlResponseException):
LnurlResponse.from_dict({"status": "unknown"})
def test_pay(self):
res = LnurlResponse.from_dict(self.pay_res)
assert res.ok
assert res.max_sats == 300
assert res.min_sats == 101
assert res.metadata == '[["text/plain","lorem ipsum blah blah"]]'
assert res.metadata.list() == [("text/plain", "lorem ipsum blah blah")]
assert not res.metadata.images
assert res.metadata.text == "lorem ipsum blah blah"
assert res.metadata.h == "d824d0ea606c5a9665279c31cf185528a8df2875ea93f1f75e501e354b33e90a"
def test_pay_invalid_metadata(self):
with pytest.raises(LnurlResponseException):
LnurlResponse.from_dict(self.pay_res_invalid)
def test_withdraw(self):
res = LnurlResponse.from_dict(self.withdraw_res)
assert res.ok
assert res.max_withdrawable == 478980
assert res.max_sats == 478
assert res.min_sats == 479
<file_sep>import os
import re
from hashlib import sha256
from pydantic import Json, HttpUrl, PositiveInt, ValidationError, parse_obj_as
from pydantic.errors import UrlHostTldError
from pydantic.validators import str_validator
from urllib.parse import parse_qs
from typing import Dict, List, Optional, Tuple, Union
from .exceptions import InvalidLnurlPayMetadata
from .helpers import _bech32_decode, _lnurl_clean, _lnurl_decode
FORCE_SSL = os.environ.get("LNURL_FORCE_SSL", "1") == "1"
STRICT_RFC3986 = os.environ.get("LNURL_STRICT_RFC3986", "1") == "1"
def ctrl_characters_validator(value: str) -> str:
"""Checks for control characters (unicode blocks C0 and C1, plus DEL)."""
if re.compile(r"[\u0000-\u001f\u007f-\u009f]").search(value):
raise ValueError
return value
def strict_rfc3986_validator(value: str) -> str:
"""Checks for RFC3986 compliance."""
if re.compile(r"[^]a-zA-Z0-9._~:/?#[@!$&'()*+,;=-]").search(value):
raise ValueError
return value
class ReprMixin:
def __repr__(self) -> str: # pragma: nocover
attrs = [n for n in [n for n in self.__slots__ if not n.startswith("_")] if getattr(self, n) is not None]
extra = ", " + ", ".join(f"{n}={getattr(self, n).__repr__()}" for n in attrs) if attrs else ""
return f"{self.__class__.__name__}({super().__repr__()}{extra})"
class Bech32(ReprMixin, str):
"""Bech32 string."""
__slots__ = ("hrp", "data")
def __new__(cls, bech32: str, **kwargs) -> object:
return str.__new__(cls, bech32)
def __init__(self, bech32: str, *, hrp: Optional[str] = None, data: Optional[List[int]] = None):
str.__init__(bech32)
self.hrp, self.data = (hrp, data) if hrp and data else self.__get_data__(bech32)
@classmethod
def __get_data__(cls, bech32: str) -> Tuple[str, List[int]]:
return _bech32_decode(bech32)
@classmethod
def __get_validators__(cls):
yield str_validator
yield cls.validate
@classmethod
def validate(cls, value: str) -> "Bech32":
hrp, data = cls.__get_data__(value)
return cls(value, hrp=hrp, data=data)
class Url(HttpUrl):
"""URL with extra validations over pydantic's `HttpUrl`."""
max_length = 2047 # https://stackoverflow.com/questions/417142/
@classmethod
def __get_validators__(cls):
yield ctrl_characters_validator
if STRICT_RFC3986:
yield strict_rfc3986_validator
yield cls.validate
@property
def base(self) -> str:
return f"{self.scheme}://{self.host}{self.path}"
@property
def query_params(self) -> dict:
return {k: v[0] for k, v in parse_qs(self.query).items()}
class TorUrl(Url):
"""Tor anonymous onion service."""
allowed_schemes = {"https", "http"}
@classmethod
def validate_host(cls, parts: Dict[str, str]) -> Tuple[str, Optional[str], str, bool]:
host, tld, host_type, rebuild = super().validate_host(parts)
if tld != "onion":
raise UrlHostTldError()
return host, tld, host_type, rebuild
class WebUrl(Url):
"""Web URL, secure by default; users can override the FORCE_SSL setting."""
allowed_schemes = {"https"} if FORCE_SSL else {"https", "http"}
class LightningInvoice(Bech32):
"""Bech32 Lightning invoice."""
@property
def amount(self) -> int:
a = re.search(r"(lnbc|lntb|lnbcrt)(\w+)", self.hrp).groups()[1]
raise NotImplementedError
@property
def prefix(self) -> str:
return re.search(r"(lnbc|lntb|lnbcrt)(\w+)", self.hrp).groups()[0]
@property
def h(self):
raise NotImplementedError
class LightningNodeUri(ReprMixin, str):
"""Remote node address of form `node_key@ip_address:port_number`."""
__slots__ = ("key", "ip", "port")
def __new__(cls, uri: str, **kwargs) -> object:
return str.__new__(cls, uri)
def __init__(self, uri: str, *, key: Optional[str] = None, ip: Optional[str] = None, port: Optional[str] = None):
str.__init__(uri)
self.key = key
self.ip = ip
self.port = port
@classmethod
def __get_validators__(cls):
yield str_validator
yield cls.validate
@classmethod
def validate(cls, value: str) -> "LightningNodeUri":
try:
key, netloc = value.split("@")
ip, port = netloc.split(":")
except Exception:
raise ValueError
return cls(value, key=key, ip=ip, port=port)
class Lnurl(ReprMixin, str):
__slots__ = ("bech32", "url")
def __new__(cls, lightning: str, **kwargs) -> object:
return str.__new__(cls, _lnurl_clean(lightning))
def __init__(self, lightning: str, *, url: Optional[Union[TorUrl, WebUrl]] = None):
bech32 = _lnurl_clean(lightning)
str.__init__(bech32)
self.bech32 = Bech32(bech32)
self.url = url if url else self.__get_url__(bech32)
@classmethod
def __get_url__(cls, bech32: str) -> Union[TorUrl, WebUrl]:
return parse_obj_as(Union[TorUrl, WebUrl], _lnurl_decode(bech32))
@classmethod
def __get_validators__(cls):
yield str_validator
yield cls.validate
@classmethod
def validate(cls, value: str) -> "Lnurl":
return cls(value, url=cls.__get_url__(value))
@property
def is_login(self) -> bool:
return "tag" in self.url.query_params and self.url.query_params["tag"] == "login"
class LnurlPayMetadata(ReprMixin, str):
valid_metadata_mime_types = {"text/plain", "image/png;base64", "image/jpeg;base64"}
__slots__ = ("_list",)
def __new__(cls, json_str: str, **kwargs) -> object:
return str.__new__(cls, json_str)
def __init__(self, json_str: str, *, json_obj: Optional[List] = None):
str.__init__(json_str)
self._list = json_obj if json_obj else self.__validate_metadata__(json_str)
@classmethod
def __validate_metadata__(cls, json_str: str) -> List[Tuple[str, str]]:
try:
data = parse_obj_as(Json[List[Tuple[str, str]]], json_str)
except ValidationError:
raise InvalidLnurlPayMetadata
clean_data = [x for x in data if x[0] in cls.valid_metadata_mime_types]
mime_types = [x[0] for x in clean_data]
counts = {x: mime_types.count(x) for x in mime_types}
if not clean_data or "text/plain" not in mime_types or counts["text/plain"] > 1:
raise InvalidLnurlPayMetadata
return clean_data
@classmethod
def __get_validators__(cls):
yield str_validator
yield cls.validate
@classmethod
def validate(cls, value: str) -> "LnurlPayMetadata":
return cls(value, json_obj=cls.__validate_metadata__(value))
@property
def h(self) -> str:
return sha256(self.encode("utf-8")).hexdigest()
@property
def text(self) -> str:
for metadata in self._list:
if metadata[0] == "text/plain":
return metadata[1]
@property
def images(self) -> List[Tuple[str, str]]:
return [x for x in self._list if x[0].startswith("image/")]
def list(self) -> List[Tuple[str, str]]:
return self._list
class MilliSatoshi(PositiveInt):
"""A thousandth of a satoshi."""
| 77cced9b10a98b835f48f28ac992b2fb31abd7f4 | [
"Markdown",
"YAML",
"INI",
"Python"
] | 14 | Markdown | 21isenough/lnurl | aa721da53ecd52f7a89ca2454825cd4d11151813 | 9c96a1952c220a42c7019ba9876775539b559b53 |
refs/heads/main | <repo_name>SavignanoFrancesco/php-ajax-dischi<file_sep>/src/partials/_header.scss
header{
background: $background_color;
@include flex(row, space-between,center);
img{
width: 40px;
padding: 8px;
}
.genre-select{
// @include flex(row, flex-start, center);
select{
margin: 8px;
}
}
}
<file_sep>/php_version/index.php
<?php include '../database/dischi.php' ?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>php - ajax - dischi</title>
<link rel="stylesheet" href="../dist/app.css">
</head>
<body>
<header>
<img src="https://www.freepnglogos.com/uploads/spotify-logo-png/spotify-logo-vector-download-11.png" alt="">
</header>
<main>
<div class="container">
<div class="cards-container">
<?php
foreach ($dischi as $disco) {
?>
<div class="card">
<img src="<?php echo $disco['poster']; ?>" alt="">
<div class="bottom-card">
<h3><?php echo $disco['title']; ?></h3>
<em><?php echo $disco['author']; ?></em>
<p><?php echo $disco['genre']; ?></p>
<p><?php echo $disco['year']; ?></p>
</div>
</div>
<?php
}
?>
</div>
</div>
</main>
</body>
</html>
<file_sep>/src/partials/_common.scss
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container{
max-width: 1170px;
margin: 0 auto;
}
ul{
list-style-type: none;
}
a{
text-decoration: none;
}
h1, h2, h3, h4, h5, p, span, em{
color: $text_color;
}
| 72c981dfdd584c5ecf485e45c1a96afb3bbffc54 | [
"SCSS",
"PHP"
] | 3 | SCSS | SavignanoFrancesco/php-ajax-dischi | 807801e3f2c239e068e8745bc33c881eaeb16751 | fb70848ad0eba298d4dbaa01c38980bb1284459a |
refs/heads/master | <repo_name>serverless-stack/sst-start-demo<file_sep>/lib/index.js
import MySampleStack from "./MySampleStack";
export default function main(app) {
new MySampleStack(app, "sample");
}
<file_sep>/src/api.js
import AWS from "aws-sdk";
const sns = new AWS.SNS();
export async function handler(event) {
console.log(
`Logging from inside the API Lambda for route: ${event.routeKey}`
);
await sns
.publish({
MessageStructure: "string",
TopicArn: process.env.TOPIC_ARN,
Message: "Hello from the API Lambda",
})
.promise();
return {
statusCode: 200,
body: "Hello World",
headers: { "Content-Type": "text/plain" },
};
}
<file_sep>/lib/MySampleStack.js
import * as cdk from "@aws-cdk/core";
import * as sns from "@aws-cdk/aws-sns";
import * as apig from "@aws-cdk/aws-apigatewayv2";
import * as subscriptions from "@aws-cdk/aws-sns-subscriptions";
import * as apigIntegrations from "@aws-cdk/aws-apigatewayv2-integrations";
import * as sst from "@serverless-stack/resources";
export default class MySampleStack extends sst.Stack {
constructor(scope, id, props) {
super(scope, id, props);
// Create an SNS topic
const topic = new sns.Topic(this, "MyTopic", {
displayName: "Customer subscription topic",
});
// Create a Lambda function subscribed to the topic
const snsFunc = new sst.Function(this, "MySnsLambda", {
handler: "src/sns.handler",
});
topic.addSubscription(new subscriptions.LambdaSubscription(snsFunc));
// Create a Lambda function triggered by an HTTP API
const apiFunc = new sst.Function(this, "MyApiLambda", {
handler: "src/api.handler",
environment: {
TOPIC_ARN: topic.topicArn,
},
});
topic.grantPublish(apiFunc);
// Create the HTTP API
const api = new apig.HttpApi(this, "Api");
api.addRoutes({
integration: new apigIntegrations.LambdaProxyIntegration({
handler: apiFunc,
}),
methods: [apig.HttpMethod.GET],
path: "/",
});
// Show API endpoint in output
new cdk.CfnOutput(this, "ApiEndpoint", {
value: api.apiEndpoint,
});
}
}
<file_sep>/src/sns.js
export async function handler(event) {
console.log(
`Logging from inside the SNS Lambda with event message: "${event.Records[0].Sns.Message}"`
);
return { status: true };
}
<file_sep>/README.md
# `sst start`
A sample project to demo the new `sst start` command. This repo was bootstrapped with [Serverless Stack Toolkit (or SST)](https://github.com/serverless-stack/serverless-stack). SST is an extension of [AWS CDK](https://aws.amazon.com/cdk/) and is designed for developing Serverless apps on AWS.
---
The new `sst start` command starts up a local development environment that opens a WebSocket connection to your deployed app and proxies any Lambda requests to your local machine. This allows you to:
[![sst start](https://d1ne2nltv07ycv.cloudfront.net/SST/sst-start-demo/sst-start-demo-2.gif)](https://d1ne2nltv07ycv.cloudfront.net/SST/sst-start-demo/sst-start-demo-2.mp4)
- Work on your Lambda functions locally
- While, interacting with your entire deployed AWS infrastructure
- Supports all Lambda triggers, so there's no need to mock API Gateway, SQS, SNS, etc.
- Supports real Lambda environment variables
- And Lambda IAM permissions, so if a Lambda fails on AWS due to lack of IAM permissions, it would fail locally as well.
- And it's fast! There's nothing to deploy when you make a change!
Note that, everything lives in your AWS account and local machine. No 3rd party services like ngrok or Localtunnel are used.
A caveat is that, you can only have one `sst start` session open per stage. Meaning two people cannot actively develop on the same stage (or environment) of an app at the same time.
Currently, `sst start` only supports Node.js.
[**View the SST docs**](https://docs.serverless-stack.com).
## Demo
The demo app deploys a simple Serverless application with the following:
- An API Gateway endpoint
- An SNS topic
- A Lambda function (`api.js`) that responds to the API and sends a message to the SNS topic
- A Lambda function (`sns.js`) that subscribes to the SNS topic
This is a simple CDK app with one key modification to the Lambda functions. Instead of using `cdk.lambda.Function`, it uses `sst.Function`.
``` diff
- cdk.lambda.Function
+ sst.Function
```
So once you run `sst start` you'll get a deployed endpoint (say `https://dgib3y82wi.execute-api.us-east-1.amazonaws.com`). Any requests to this endpoint will run the the `api.js` on your local machine, then send a message to the SNS topic which in turn will run `sns.js` on your local.
The flow looks something like this:
![SST Start Demo Architecture](https://raw.githubusercontent.com/serverless-stack/sst-start-demo/master/sst-start-demo-architecture.png)
### Gettin Started
Start by cloning this repo.
``` bash
$ git clone https://github.com/serverless-stack/sst-start-demo.git
```
Install the dependencies.
``` bash
$ npm install
```
Run `sst start`.
``` bash
$ npx sst start
```
The first time this is run, it'll take a minute or two to deploy the `sst start` debug stack and the demo app. Once complete, you should see something like this:
```
Stack dev-sst-start-demo-sample
Status: deployed
Outputs:
ApiEndpoint: https://dgib3y82wi.execute-api.us-east-1.amazonaws.com
```
Head over to the URL (`https://dgib3y82wi.execute-api.us-east-1.amazonaws.com`) in your browser. You should see a `Hello World` message and a couple of log messages in your terminal. Including something like this:
```
Logging from inside the API Lambda for route: GET /
...
Logging from inside the SNS Lambda with event message: "Hello from the API Lambda"
```
These are `console.log` messages printed directly from the local versions of your Lambda function.
Now try editing, `src/api.js` or `src/sns.js` and refresh the above URL again.
## Wrapping up
Finally, you can either deploy this app.
``` bash
$ npx sst deploy
```
And to remove all the deployed resources (including the debug stack).
``` bash
$ npx sst remove
```
## Feedback
Feel free to send us any feedback or let us know if you have any questions — [<EMAIL>](mailto:<EMAIL>)
## Community
[Follow us on Twitter](https://twitter.com/ServerlessStack), [join us on Slack][slack], [post on our forums](https://discourse.serverless-stack.com), and [subscribe to our newsletter](https://emailoctopus.com/lists/1c11b9a8-1500-11e8-a3c9-06b79b628af2/forms/subscribe).
| edc9ad40b6f1774be2a0f455ad04323f2a6af5ec | [
"Markdown",
"JavaScript"
] | 5 | Markdown | serverless-stack/sst-start-demo | b99684a709640da5d125d3560424cccdfcb3fd3e | 6480f289b40911a311ab99b7d7d4c3c7de0f8f87 |
refs/heads/master | <file_sep># video-recording-examples
Examples of recording video with HTML5 and JavaScript
## Demo
http://chriskwan.github.io/video-recording-examples
## References
* [MediaStreamRecorder (Cross browser audio/video/screen recording library)](https://github.com/streamproc/MediaStreamRecorder)
* [Other methods to try out from Stack Overflow](http://stackoverflow.com/a/18509824)
<file_sep>// NOTE: this code will only work if running this code from a server
// (e.g. http-server) instead of a local file
// Ref: https://www.webrtc-experiment.com/msr/MultiStreamRecorder.html
(function() {
var multiStreamRecorder;
var videoElement = document.getElementById("msrVideo");
var setupButton = document.getElementById("setupBtn")
var startButton = document.getElementById("startBtn");
var stopButton = document.getElementById("stopBtn");
var playButton = document.getElementById("playBtn");
var pauseButton = document.getElementById("pauseBtn");
var videoRecordings = document.getElementById("videoRecordings");
var audioRecordings = document.getElementById("audioRecordings");
setupButton.onclick = setup;
startButton.onclick = startRecording;
stopButton.onclick = stopRecording;
playButton.onclick = playVideo;
pauseButton.onclick = pauseVideo;
var videoNumber = 0;
var audioNumber = 0;
var mediaConstraints = {
audio: true,
video: true
};
function setup() {
navigator.getUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
}
function onMediaSuccess(stream) {
multiStreamRecorder = new MultiStreamRecorder(stream);
multiStreamRecorder.video = videoElement;
multiStreamRecorder.audioChannels = 1;
multiStreamRecorder.ondataavailable = onMediaDataAvailable;
// Show the stream shows up in the video element
videoElement.src = URL.createObjectURL(stream);
}
function onMediaDataAvailable(blobs) {
console.log("ON DATA AVAILABLE");
videoNumber++;
makeLink(videoRecordings, blobs.video, videoNumber);
audioNumber++;
makeLink(audioRecordings, blobs.audio, audioNumber);
}
function makeLink(container, blob, number) {
var li = document.createElement('li');
// Ref: https://www.webrtc-experiment.com/msr/MultiStreamRecorder.html
var a = document.createElement('a');
a.target = "_blank";
var size = bytesToSize(blob.size);
a.innerHTML = "Recording #" + number + " (" + size + ")"; //cwkTODO add time
a.href = URL.createObjectURL(blob);
li.appendChild(a);
container.appendChild(li);
}
function onMediaError(e) {
console.error("media error", e);
}
function startRecording() {
if (!multiStreamRecorder) {
return;
}
console.log("START recording");
multiStreamRecorder.start(3 * 1000);
console.log("Recording STARTED");
}
function stopRecording() {
if (!multiStreamRecorder) {
return;
}
console.log("STOP recording");
multiStreamRecorder.stop();
console.log("Recording STOPPED");
}
function playVideo() {
//cwkTODO this doesn't quite work - it plays the stream
//need to change it to play the recorded video
videoElement.play();
}
function pauseVideo() {
videoElement.pause();
}
})(); | 95571907f8887c761e742591d70a1751fd9cfefb | [
"Markdown",
"JavaScript"
] | 2 | Markdown | chriskwan/video-recording-examples | 8d4bca389b8d8611ed27d836727adf2e9621cfcc | 2257f53e09eb0cd3022d5905305a10b662588fc6 |
refs/heads/master | <repo_name>YuriyLeeguy/zd04.loftschool<file_sep>/function.php
<?php
/* Задание № 1
Написать скрипт, который выведет всю информацию из этого файла в удобно
читаемом виде. Представьте, что результат вашего скрипта будет распечатан и выдан
курьеру для доставки, разберется ли курьер в этой информации?
*/
function task1()
{
$xml = simplexml_load_file('data.xml');
$result = $result1 = "";
$delimiterLine = '<BR>';
$deliveryNotes = "Примечание: " . $xml->DeliveryNotes->__toString() . $delimiterLine . $delimiterLine;
foreach ($xml->Address as $adr) {
$result .= "Тип доставки: " . $adr->attributes()->Type->__toString() . $delimiterLine
. "на Имя: " . $adr->Name->__toString() . $delimiterLine
. "доставить по Адресу:" . $delimiterLine
. "Улица: " . $adr->Street->__toString() . $delimiterLine
. "Город: " . $adr->City->__toString() . $delimiterLine
. "Штат: " . $adr->State->__toString() . $delimiterLine
. "Индекс: " . $adr->Zip->__toString() . $delimiterLine . $delimiterLine;
}
foreach ($xml->Items->Item as $val) {
$result1 .= "Артикул: " . $val->attributes()->PartNumber->__toString() . $delimiterLine;
$result1 .= "Наименование товара: " . $val->ProductName->__toString() . $delimiterLine;
$result1 .= "Количество: " . $val->Quantity->__toString() . $delimiterLine;
$result1 .= "Стоимость: " . $val->USPrice->__toString() . $delimiterLine;
$result1 .= "Дата отгрузки: " . $val->ShipDate->__toString() . $delimiterLine . $delimiterLine;
}
return $result . $delimiterLine . $deliveryNotes . $result1;
}
/*
Задача #2
1. Создайте массив, в котором имеется как минимум 1 уровень вложенности.
Преобразуйте его в JSON. Сохраните как output.json
2. Откройте файл output.json. Случайным образом, используя функцию rand(), решите
изменять данные или нет. Сохраните как output2.json
3. Откройте оба файла. Найдите разницу и выведите информацию об отличающихся
элементах
*/
function task2($potato, $onion, $garlic, $sourCream)
{
// Создали массив "Рецепт Борща"
if (($potato < 0 or $onion < 0) or ($garlic < 0 or $sourCream < 0)) {
echo 'Ведите положительные значения';
return null;
}
$recipe = ['Рецепт' => ['Борщ' => ['картошка' => $potato,
'Лук' => $onion,
'Чеснок' => $garlic,
'Сметана' => $sourCream]]];
$writeJason = json_encode($recipe, JSON_UNESCAPED_UNICODE); // Преобразовали в код Json
file_put_contents('output.json', $writeJason);// Создали файл output.json и поместили преобразованный код Json
if (!file_exists('output.json')) {
echo "<BR>Нет такого файла!<BR>";
}
$readJason = file_get_contents('output.json'); //Достали информацию из из файла 'output.json'
$array = $decoderOutput1 = json_decode($readJason, true); // Преобразовали код Json в PHP
if (1 == rand(1, 2)) {
echo "<BR> Файл успешно создан <BR>";
foreach ($array as $key => $val) {
foreach ($val as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
$array[$key][$key1][$key2] += rand(0, 10);
$writeJason = json_encode($array, JSON_UNESCAPED_UNICODE);
file_put_contents('output2.json', $writeJason);
}
}
}
$readJason2 = file_get_contents('output2.json');
$decoderOutput2 = json_decode($readJason2, true);
foreach ($decoderOutput2 as $key => $value) {
foreach ($value as $key1 => $value1) {
$newdecoderOutput2 = $decoderOutput2[$key][$key1];
}
}
foreach ($decoderOutput1 as $key => $value) {
foreach ($value as $key1 => $value1) {
$newDecoderOutput1 = $decoderOutput1[$key][$key1];
}
}
$result = array_diff_assoc($newdecoderOutput2, $newDecoderOutput1);
echo "<BR>Изменения были в следующих элементах: <BR>";
print_r($result);
} else {
echo "<BR>Файл не создан!<BR>";
echo "<BR>Не возмиожно сравнить два файла!<BR>";
return null;
}
}
/*Задача #3
1. Программно создайте массив, в котором перечислено не менее 50 случайных чисел
от 1 до 100
2. Сохраните данные в файл csv
3. Откройте файл csv и посчитайте сумму четных чисел
*/
function task3()
{
for ($i = 0; $i < 50; $i++) {
$array[$i] = rand(1, 100);
}
echo "Создали массив" . "<BR><BR>";
$fileCsv = fopen('fileCsv.csv', 'w');
fputcsv($fileCsv, $array, ';');
fclose($fileCsv);
echo "Информацию передали в fileCsv.csv" . "<BR><BR>";
$pathCsv = './fileCsv.csv';
$openfile = fopen($pathCsv, 'r');
if ($openfile) {
$res = fgetcsv($openfile, null, ";");
}
echo "Открыли файл fileCsv.csv для работы с данными." . "<BR><BR>";
$count = count($res);
$result = [];
for ($i = 1; $i < $count; $i++) {
if ($res[$i] % 2 == 0) {
$result[$i] = $res;
};
}
echo "Общая сумма четных чисел: " . count($result) . "<BR>";
}
/*Задача #4
1. С помощью PHP запросить данные по адресу:
https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&r
vprop=content&format=json
2. Вывести title и page_id*/
function task4()
{
$url = 'https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json';
$data = file_get_contents($url);
$decoderOutput1 = json_decode($data, true);
function search($array, $key)
{
$results = array();
if (is_array($array)) {
if (isset($array[$key])) {
$results[] = $array;
}
foreach ($array as $subArray) {
$results = array_merge($results, search($subArray, $key));
}
}
return $results;
}
$pageId = 'page_id';
$title = 'title';
$results1 = array_shift(search($decoderOutput1, $pageId));
$results2 = array_shift(search($decoderOutput1, $title));
if ($results1 == 0) {
echo "$pageId - Нет данных";
} else {
echo "$pageId - " . $results1[$pageId] . "<BR>";
}
if ($results2 == 0) {
echo "<BR> $title - Нет данных";
} else {
echo "<BR>$title - " . $results2[$title];
}
}
<file_sep>/index.php
<?php
$delimiterLine = "<BR>";
echo 'Задание № 1' . $delimiterLine;
include('function.php');
echo "<pre>";
print_r(task1());
echo $delimiterLine . 'Задание № 2' . $delimiterLine;
//echo "Выполняем задачи № 1 и 2" . $delimiterLine;
task2(2, 3, 100, 10);
echo $delimiterLine . 'Задание № 3' . $delimiterLine;
task3();
echo $delimiterLine . 'Задание № 4' . $delimiterLine;
task4();
| ee34805d392171ad40a3e281384adecf2d783841 | [
"PHP"
] | 2 | PHP | YuriyLeeguy/zd04.loftschool | 37fff39f3dc0cef0a86a239dc214879f1c081286 | 9914222ee4f0564f043d00b18d4330650520fa61 |
refs/heads/master | <repo_name>carlavillano/timescaling_cv<file_sep>/README.txt
WSOLA_CV - README
=================
Questo progetto contiene una app matlab in grado di processare file speech
col metodo WSOLA.
Il codice è basato sull’implementazione presente sul File Exchange della community MathWorks, all’URL
https://it.mathworks.com/matlabcentral/fileexchange/45451-waveform-similarity-and-overlap-add--wsola--for-speech-and-audio
Il codice è stato modificato:
- per correggere piccoli problemi dell’interfaccia grafica
- per dare la possibilità di scegliere una directory contenente il file
speech da processare senza accedere al repository MatWorks
- per consentire il salvataggio del file speech processato con un file name
contenente indicazioni sui parametri usati per il WSOLA processing
- per misurare il tempo di elaborazione (CPU time) necessario per processare il singolo file
speech
Per installare in MatLab la app basta cliccarci sopra. E’ necessaria semplicemente una versione di MatLab >= R2012b (la versione che ha introdotto le apps). E’ inoltre presente qui la licenza originaria e un file pdf che descrive il procedimento adoperato per il processing. Rimandando a tale documento per l’uso guidato dell’applicazione (peraltro dotata di interfaccia grafica estremamente intuitiva), si fa semplicemente presente che, lanciata l’app, si può procedere alla scelta della directory contenente i file speech e successivamente del file, o registrare alcuni secondi di parlato da microfono. A questo punto si potrà lanciare il processing, dopo una opportuna scelta dei parametri. Il file risultato viene salvato nella stessa directory del file originario, e quindi riprodotto.
<NAME>, 8/1/2017 | 8467f067ef40a43ce2a49d9fdf1630c4d66eaa9b | [
"Text"
] | 1 | Text | carlavillano/timescaling_cv | e60afcc840bcc740ca88780906367a46f51d10d4 | 18e418031ff31653a6ef42eb7f70713bdb58717e |
refs/heads/master | <file_sep># SysOpenNewWindow Changelog
see also [Releases on GitHub](https://github.com/mazzy-ax/SysOpenNewWindow/releases)
## 0.1.0 - 2020-09-05
* Initial release
<file_sep># SysOpenNewWindow
[project]:https://github.com/mazzy-ax/SysOpenNewWindow
[license]:https://github.com/mazzy-ax/SysOpenNewWindow/blob/master/LICENSE
[SysOpenNewWindow][project] – добавляет пункты в контекстное меню `Add-Ins \ Open new window` в [Microsoft Dynamics AX 2009](ax2009), [Microsoft Dynamics AX 2012](ax2012).
В `ax2009` добавлен пункт меню для объекта `AOT`:
* `View \ Query`: Open used Query
![aot with open new window menu in 2009](ax2009/Media/Aot.PNG)
В `ax2012` добавлены пункты меню для объектов `AOT`:
* `View \ Query`: Open used Query
* `Security \ Entry point`: Open used Menu item
* `Service`: Open used Class
* `Service group`: Open used Service
![aot with open new window menu in 2012](ax2012/Media/Aot.png)
## ChangeLog
* [CHANGELOG.md](CHANGELOG.md)
* <https://github.com/mazzy-ax/SysOpenNewWindow/releases>
## Помощь проекту
Буду признателен за ваши замечания, предложения и советы по проекту как в разделе [Issues](https://github.com/mazzy-ax/SysOpenNewWindow/issues), так и в виде письма на адрес <<EMAIL>>
<NAME> (mazzy)
| a46c3e8df9fc06e9b405a6d1f6cb34e09be71c42 | [
"Markdown"
] | 2 | Markdown | mazzy-ax/SysOpenNewWindow | e974480688f9fcdaeadcfdf901231e76e5994bdb | 01201942e35fce11a38a71a0f03d0f3ddb07aef7 |
refs/heads/master | <file_sep>import 'package:flutter/material.dart';
import 'package:spacespinner/services/auth.dart';
import 'package:spacespinner/shared/constants.dart';
import 'package:spacespinner/shared/loading.dart';
class Register extends StatefulWidget {
final Function toggleView;
Register({this.toggleView});
@override
_RegisterState createState() => _RegisterState();
}
class _RegisterState extends State<Register> {
final AuthService _auth = AuthService();
final _formKey = GlobalKey<FormState>();
bool loading = false;
String email = '';
String password = '';
String name = '';
String location = '';
String job = '';
static List<String> locations = [
'Kollam',
'Trivandrum',
'Bangalore',
'Coimbatore'
];
String error = '';
@override
Widget build(BuildContext context) {
return loading ? Loading() : Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.teal[00],
appBar: AppBar(
backgroundColor: Colors.teal[400],
elevation: 0.0,
title: Text('Sign up'),
actions: <Widget>[
FlatButton.icon(
onPressed: () {
widget.toggleView();
},
icon: Icon(Icons.person),
label: Text(
'Sign in',
style: TextStyle(color: Colors.white),
))
],
),
body: Container(
//padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
// padding: EdgeInsets.only(
//bottom: MediaQuery.of(context).viewInsets.bottom),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
SizedBox(height: 20.0),
TextFormField(
decoration: textInputDecoration.copyWith(hintText: 'Name'),
validator: (val)=> val.isEmpty ? 'Enter Name' : null,
onChanged: (val) {
setState(() {
name = val;
});
}),
SizedBox(height: 20.0),
DropdownButtonFormField(
decoration: textInputDecoration.copyWith(hintText: 'Select Location'),
items: locations.map((loc) {
return DropdownMenuItem(
value: loc,
child: Text('$loc'),
);
}).toList(),
onChanged: (val) => setState(() => location = val),
),
SizedBox(height: 20.0),
TextFormField(
decoration: textInputDecoration.copyWith(hintText: 'Job'),
validator: (val)=> val.isEmpty ? 'Enter Job' : null,
onChanged: (val) {
setState(() {
job = val;
});
}),
SizedBox(height: 20.0),
TextFormField(
decoration: textInputDecoration.copyWith(hintText: 'Email'),
validator: (val)=> val.isEmpty ? 'Enter Email' : null,
onChanged: (val) {
setState(() {
email = val;
});
}),
SizedBox(height: 20.0),
TextFormField(
decoration: textInputDecoration.copyWith(hintText: 'Password'),
obscureText: true,
validator: (val)=> val.length < 6 ? 'Enter a password 6+ chars long' : null,
onChanged: (val) {
setState(() {
password = val;
});
}),
SizedBox(height: 20.0),
RaisedButton(
color: Colors.red[400],
child: Text(
'Sign up',
style: TextStyle(color: Colors.white),
),
onPressed: () async {
if(_formKey.currentState.validate())
{
setState(() => loading = true);
dynamic result = await _auth.registerWithEmail(email, password, name,job,location);
if(result == null)
{
setState(() {
loading = false;
error = 'please check the form.';
});
}
}
},
),
SizedBox(height: 20.0),
Text(
error,
style: TextStyle(color:Colors.red, fontSize: 14.0),
),
],
),
)
)
);
}
}
<file_sep>class SS {
final String name;
final String job;
final String location;
SS( { this.name, this.job, this.location });
}<file_sep>import 'package:flutter/material.dart';
import 'package:spacespinner/screens/authenticate/forgotpassword.dart';
import 'package:spacespinner/screens/authenticate/register.dart';
import 'package:spacespinner/services/auth.dart';
import 'package:spacespinner/shared/constants.dart';
import 'package:spacespinner/shared/loading.dart';
class SignIn extends StatefulWidget {
final Function toggleView;
SignIn({this.toggleView});
@override
_SignInState createState() => _SignInState();
}
class _SignInState extends State<SignIn> {
final AuthService _auth = AuthService();
final _formKey = GlobalKey<FormState>();
bool loading = false;
String email = '';
String password = '';
String error = '';
@override
Widget build(BuildContext context) {
void _showForgotPanel()
{
showModalBottomSheet(context: context, builder: (context){
return Container(
padding: EdgeInsets.symmetric(vertical: 20.0,horizontal: 60.0),
child: ForgotForm(),
);
});
}
return loading ? Loading() : Scaffold(
backgroundColor: Colors.teal[00],
appBar: AppBar(
backgroundColor: Colors.teal[400],
elevation: 0.0,
title: Text('Sign In'),
actions: <Widget>[
FlatButton.icon(
onPressed: () {
widget.toggleView();
},
icon: Icon(Icons.person,color: Colors.white),
label: Text(
'Sign up',
style: TextStyle(color: Colors.white),
))
],
),
body: Container(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
SizedBox(height: 20.0),
TextFormField(
decoration: textInputDecoration.copyWith(hintText: 'Email'),
validator: (val) => val.isEmpty ? 'Enter Email' : null,
onChanged: (val) {
setState(() {
email = val;
});
}),
SizedBox(height: 20.0),
TextFormField(
decoration:
textInputDecoration.copyWith(hintText: 'Password'),
validator: (val) => val.length < 6
? 'Enter a password 6+ chars long'
: null,
obscureText: true,
onChanged: (val) {
setState(() {
password = val;
});
}),
SizedBox(height: 20.0),
RaisedButton(
color: Colors.red[400],
child: Text(
'Sign in',
style: TextStyle(color: Colors.white),
),
onPressed: () async {
if (_formKey.currentState.validate()) {
setState(() => loading = true);
dynamic result =
await _auth.signinWithEmail(email, password);
if (result == null) {
setState(() {
error = 'Invalid Credentials';
loading = false;
});
}
}
},
),
SizedBox(height: 20.0),
FlatButton.icon(
onPressed: () {
_showForgotPanel();
},
icon: Icon(Icons.error,color: Colors.red,size: 20.0,),
label: Text(
'Forgot Password ?',
style: TextStyle(color: Colors.pink),
)),
Text(
error,
style: TextStyle(color: Colors.red, fontSize: 14.0),
),
],
),
)),
);
}
}
<file_sep>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:spacespinner/models/ss.dart';
import 'package:spacespinner/screens/home/ss_title.dart';
import 'package:spacespinner/services/auth.dart';
class SSList extends StatefulWidget {
@override
_SSListState createState() => _SSListState();
}
class _SSListState extends State<SSList> {
final AuthService _auth = AuthService();
@override
Widget build(BuildContext context) {
final ss = Provider.of<List<SS>>(context) ?? [];
if (_auth.verifyUser() != null) {
return ListView.builder(
itemCount: ss.length,
itemBuilder: (context, index) {
return SStitle(ss: ss[index]);
},
);
}
}
}
<file_sep>import 'package:firebase_auth/firebase_auth.dart';
import 'package:spacespinner/models/user.dart';
import 'package:spacespinner/services/database.dart';
class AuthService{
final FirebaseAuth _auth = FirebaseAuth.instance;
// User obj based on FirebaseUser
User _userFromFirebaseUser(FirebaseUser user)
{
return user != null ? User(uid: user.uid) : null;
}
Stream<User> get user {
return _auth.onAuthStateChanged
//.map((FirebaseUser user) => _userFromFirebaseUser(user));
.map(_userFromFirebaseUser);
}
//sign in anonymously
Future signInAnon() async
{
try{
AuthResult result = await _auth.signInAnonymously();
FirebaseUser user = result.user;
return _userFromFirebaseUser(user);
}
catch (e)
{
print(e.toString());
return null;
}
}
Future registerWithEmail(String email, String password, String name, String job, String location) async {
try{
AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
await DatabaseService(uid:user.uid).updateUserData(name, job, location);
return _userFromFirebaseUser(user);
}
catch(e)
{
print(e.toString());
return null;
}
}
Future<String> getCurrentUID() async{
final FirebaseUser user = await _auth.currentUser();
final String uid = user.uid;
return uid;
if (user.isEmailVerified) return user.uid;
return null;
}
Future<String> verifyUser() async{
final FirebaseUser user = await _auth.currentUser();
if (user.isEmailVerified) {
return user.uid;
}
return null;
}
Future signinWithEmail(String email, String password) async {
try{
AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
await result.user.sendEmailVerification();
FirebaseUser user = result.user;
return _userFromFirebaseUser(user);
}
catch(e)
{
print(e.toString());
return null;
}
}
Future forgotEmailPassword(String email) async {
try{
print(email);
await _auth.sendPasswordResetEmail(email: email);
return true;
}
catch(e)
{
return false;
}
}
Future signOut() async {
try {
return await _auth.signOut();
}
catch(e)
{
print(e.toString());
return null;
}
}
}<file_sep>import 'package:flutter/material.dart';
import 'package:spacespinner/models/user.dart';
import 'package:spacespinner/services/database.dart';
import 'package:spacespinner/shared/constants.dart';
import 'package:provider/provider.dart';
import 'package:spacespinner/shared/loading.dart';
class SettingsForm extends StatefulWidget {
@override
_SettingsFormState createState() => _SettingsFormState();
}
class _SettingsFormState extends State<SettingsForm> {
final _formKey = GlobalKey<FormState>();
final List<String> locations = ['Kollam','Trivandrum','Bangalore','Coimbatore'];
String _currentName;
String _currentJob;
String _currentLocation;
bool loading = false;
@override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
return loading ? Loading() : StreamBuilder<UserData>(
stream: DatabaseService(uid: user.uid).userData,
builder:(context,snapshot){
if(snapshot.hasData) {
UserData userData = snapshot.data;
return Form(
key: _formKey,
child: Column(
children: <Widget>[
SizedBox(height: 10.0),
Text('Update your details.',style: TextStyle(color: Colors.teal,fontSize: 20.0),),
SizedBox(height: 20.0),
TextFormField(
initialValue: userData.name,
decoration: textInputDecoration.copyWith(hintText: 'Name'),
validator: (val) =>
val.isEmpty
? 'Please enter a name'
: null,
onChanged: (val) => setState(() => _currentName = val),
),
SizedBox(height: 20.0),
DropdownButtonFormField(
value: userData.location,
decoration: textInputDecoration,
items: locations.map((location) {
return DropdownMenuItem(
value: location ?? userData.location,
child: Text('$location '),
);
}).toList(),
onChanged: (val) => setState(() => _currentLocation = val),
),
SizedBox(height: 20.0),
TextFormField(
initialValue: userData.job,
decoration: textInputDecoration.copyWith(hintText: 'Job'),
validator: (val) => val.isEmpty ? 'Job' : null,
onChanged: (val) => setState(() => _currentJob = val),
),
SizedBox(height: 20.0),
RaisedButton(
color: Colors.pink[400],
child: Text(
'Update',
style: TextStyle(color: Colors.white),
),
onPressed: () async {
if(_formKey.currentState.validate())
{setState(() => loading = true);
await DatabaseService(uid: user.uid).updateUserData(
_currentName ?? userData.name,
_currentJob ?? userData.job,
_currentLocation ?? userData.location,
);
setState(() => loading = false);
}
},
)
],
),
);
} else {
return Loading();
}
});
}
}
<file_sep>import 'package:flutter/material.dart';
import 'package:spacespinner/models/user.dart';
import 'package:spacespinner/services/database.dart';
import 'package:spacespinner/shared/constants.dart';
import 'package:provider/provider.dart';
import 'package:spacespinner/shared/loading.dart';
class UserDataForm extends StatefulWidget {
@override
_UserDataFormState createState() => _UserDataFormState();
}
class _UserDataFormState extends State<UserDataForm> {
bool loading = false;
@override
Widget build(BuildContext context) {
return Container
(
child: Form (
child: Column(
children: <Widget>[
SizedBox(height: 50.0),
Text('User Details.',style: TextStyle(color: Colors.teal,fontSize: 20.0),),
SizedBox(height: 65.0),
Text('Name :',style: TextStyle(color: Colors.pink,fontSize: 18.0),),
SizedBox(height: 20.0),
Text('Location : ',style: TextStyle(color: Colors.pink,fontSize: 18.0),),
SizedBox(height: 20.0),
Text('Job : ',style: TextStyle(color: Colors.pink,fontSize: 18.0),),
SizedBox(height: 20.0),
],
)
)
);
}
}
<file_sep>package com.kizhakkillam.spacespinner
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
<file_sep>import 'package:flutter/material.dart';
import 'package:spacespinner/screens/wrapper.dart';
import 'package:provider/provider.dart';
import 'package:spacespinner/models/user.dart';
import 'package:flutter/services.dart';
import 'package:spacespinner/services/auth.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown])
.then((_) {
runApp(MyApp());
});
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return StreamProvider<User>.value(
value: AuthService().user,
child: MaterialApp(
home: Wrapper(),
),
);
}
}
<file_sep>import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:spacespinner/models/ss.dart';
import 'package:spacespinner/screens/home/userData.dart';
class SStitle extends StatelessWidget {
final SS ss;
SStitle({this.ss});
@override
Widget build(BuildContext context) {
void showData(String name,String location,String job)
{
showModalBottomSheet(context: context, builder: (context){
return Container(
child: UserDataForm(),
);
});
}
return Padding(
padding: EdgeInsets.only(top: 8.0),
child: Card(
child: ListTile(
leading: FlatButton.icon(
onPressed: () => showData(ss.name,ss.location,ss.job),
icon: Icon(Icons.account_circle,color: Colors.deepOrangeAccent,),
label: Text(
'',
style: TextStyle(color: Colors.white),
)),
title: Text(ss.name),
subtitle: Text(ss.job),
),
),
);
}
}
<file_sep>class User {
final String uid;
User ( {this.uid});
}
class UserData {
final String uid;
final String name;
final String location;
final String job;
UserData ( {this.uid, this.name, this.location, this.job});
}<file_sep>import 'package:flutter/material.dart';
import 'package:spacespinner/models/user.dart';
import 'package:spacespinner/shared/constants.dart';
import 'package:provider/provider.dart';
import 'package:spacespinner/shared/loading.dart';
import 'package:spacespinner/services/auth.dart';
class ForgotForm extends StatefulWidget {
@override
_ForgotFormState createState() => _ForgotFormState();
}
class _ForgotFormState extends State<ForgotForm> {
final AuthService _auth = AuthService();
final _formKey = GlobalKey<FormState>();
bool loading = false;
bool forgotConfirm = false;
String email ='';
String error='';
@override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
return loading ? Loading() : Container
(
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
SizedBox(height: 50.0),
Text(
'Forgot Password ?',
style: TextStyle(color: Colors.pink,fontSize: 18.0),
),
SizedBox(height: 20.0),
TextFormField(
decoration: textInputDecoration.copyWith(hintText: 'Email'),
validator: (val) => val.isEmpty ? 'Enter Email' : null,
onChanged: (val) {
setState(() {
email = val;
});
},
),
SizedBox(height: 20.0),
RaisedButton(
color: Colors.red[400],
child: Text(
'Send Link',
style: TextStyle(color: Colors.white,fontSize: 15.0),
),
onPressed: () async {
forgotConfirm = await _auth.forgotEmailPassword(email);
if (forgotConfirm)
{
setState(() {
error = 'Mail Sent Successfully.';
loading = false;
});
}
else
{
setState(() {
error = 'Please check your mail or try again later.';
loading = false;
});
}
},
),
SizedBox(height: 20.0),
Text(
error,
style: TextStyle(color: Colors.red, fontSize: 14.0),
),
],
),
));
}
}
<file_sep>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:provider/provider.dart';
import 'package:spacespinner/models/ss.dart';
import 'package:spacespinner/models/user.dart';
import 'package:spacespinner/screens/home/ss_list.dart';
class DatabaseService {
//collection reference
final String uid;
DatabaseService({this.uid});
final CollectionReference ssCollection = Firestore.instance.collection(('spacespinner'));
Future updateUserData(String name, String job, String location) async
{
return await ssCollection.document(uid).setData({
'name':name,
'job' :job,
'location':location,
});
}
List<SS> _SSListFromSnapshot (QuerySnapshot snapshot) {
return snapshot.documents.map((doc) {
return SS(
name: doc.data['name'] ?? 'NA',
job: doc.data['job'] ?? 'NA',
location: doc.data['location'] ?? 'NA',
);
}).toList();
}
//User Data from Snapshots.
UserData _userDataFromSnapshot(DocumentSnapshot snapshot)
{
return UserData(
uid: uid,
name:snapshot.data['name'],
job:snapshot.data['job'],
location:snapshot.data['location'],
);
}
// get collection
Stream<List<SS> > get ss {
return ssCollection.snapshots()
.map(_SSListFromSnapshot);
}
Stream<UserData> get userData {
return ssCollection.document((uid)).snapshots()
.map(_userDataFromSnapshot);
}
}<file_sep>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:spacespinner/screens/home/settings_form.dart';
import 'package:spacespinner/services/auth.dart';
import 'package:spacespinner/services/database.dart';
import 'package:provider/provider.dart';
import 'ss_list.dart';
import 'package:spacespinner/models/ss.dart';
class Home extends StatelessWidget {
final AuthService _auth = AuthService();
@override
Widget build(BuildContext context) {
void _showSettingPanel()
{
showModalBottomSheet(context: context, builder: (context){
return Container(
padding: EdgeInsets.symmetric(vertical: 20.0,horizontal: 60.0),
child: SettingsForm(),
);
});
}
return StreamProvider<List<SS> >.value(
value: DatabaseService().ss,
child: Scaffold(
backgroundColor: Colors.teal[00],
appBar: AppBar(
backgroundColor: Colors.teal[400],
elevation: 0.0,
actions: <Widget>[
FlatButton.icon(
icon: Icon(Icons.exit_to_app,color: Colors.white),
label: Text('Logout',
style: TextStyle(color: Colors.white),),
onPressed: () async {
await _auth.signOut();
},
),
FlatButton.icon(
onPressed: () => _showSettingPanel(),
icon: Icon(Icons.settings,color: Colors.white),
label:Text(''),
),
],
title: Text('Space Spinner'),
),
body: SSList(),
));
}
}
| 6de7d29913f9fed28ed1ba6818cadf49999cf27b | [
"Kotlin",
"Dart"
] | 14 | Kotlin | nam8u/spacespinner | cff7c33e5d33fdeddd10c917c1d75414fd76c89f | c0bca3220805505df03d174dd56e2f288bca2129 |
refs/heads/master | <repo_name>medaserenaite/CSharp<file_sep>/WeddingPlanner3/Controllers/AuthController.cs
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using WeddingPlanner3.Models;
using WeddingPlanner3.ViewModels;
using System.Linq;
using Microsoft.AspNetCore.Identity;
using System.Globalization;
namespace WeddingPlanner3.Controllers
{
public class AuthController : Controller
{
private DataContext _context;
public AuthController(DataContext context)
{
_context = context;
}
//----------------------------------------------------------- I N D E X ----------------------
[HttpGet]
[Route("")]
public IActionResult Index()
{
return View();
}
//------------------------------------------------------------- R E G I S T E R ----------------------
[HttpPost]
[Route("register")]
public IActionResult Registration(RegistrationViewModel reg)
{
if(!ModelState.IsValid)
{
return View("Index");
}
User UserInDB = _context.Users.FirstOrDefault(u => u.Email == reg.Email);
if(UserInDB != null)
{
ModelState.AddModelError("Email", "User already exists");
return View("Index");
}
PasswordHasher<RegistrationViewModel> hasher = new PasswordHasher<RegistrationViewModel>();
string hashedPW = hasher.HashPassword(reg, reg.Password);
User newUser = new User
{
FirstName = reg.FirstName,
LastName = reg.LastName,
Email = reg.Email,
Password = <PASSWORD>
};
_context.Users.Add(newUser);
_context.SaveChanges();
User loggedIn = _context.Users
.FirstOrDefault (u => u.Email == reg.Email);
HttpContext.Session.SetInt32 ("userId", loggedIn.UserID);
HttpContext.Session.SetString ("userName", loggedIn.FirstName);
return RedirectToAction("Home");
}
//---------------------------------------------------------------- L O G I N -----------------------
[HttpPost ("login")]
public IActionResult Login(LoginViewModel LoginUser)
{
if(!ModelState.IsValid)
{
return View("Index");
}
User userinDB = _context.Users.FirstOrDefault(u=>u.Email == LoginUser.Email);
if(userinDB is null)
{
ModelState.AddModelError("Email","Invalid Email");
return View("Index");
}
PasswordHasher<LoginViewModel> hasher = new PasswordHasher<LoginViewModel> ();
var result = hasher.VerifyHashedPassword (LoginUser, userinDB.Password, LoginUser.Password);
if (result == 0)
{
ModelState.AddModelError ("LoginEmail", "Invalid Login");
return View ("Index");
}
User loggedIn = _context.Users.FirstOrDefault (u => u.Email == LoginUser.Email);
HttpContext.Session.SetInt32 ("ID", loggedIn.UserID);
HttpContext.Session.SetString("UserName", loggedIn.FirstName);
HttpContext.Session.SetString("Login", "true");
return RedirectToAction("Home");
}//--------------------------------------------------------------- H O M E - G E T -------------------
[HttpGet]
[Route("Home")]
public IActionResult Home(int wedding_id)
{
//getting user id, which is set in session(done in login)
int? userId = HttpContext.Session.GetInt32 ("ID");
//if user is not logged in - he/she can't see the page
if (userId == null){
return RedirectToAction ("Index");
}
//getting all the wedding, including guests, who are attending? ? ? ?? ? ?
List<Wedding> allWeddings = _context.Weddings
.Include (w => w.Guests)
.ThenInclude (g => g.Attending)
.ToList ();
//getting user username stored in session
string userName = HttpContext.Session.GetString ("userName");
//passing user id to viewbag(in order to be able to display on html)
ViewBag.User = _context.Users.Where (u => u.UserID == userId).FirstOrDefault ();
//passing username in order to view on html
ViewBag.UserName = userName;
//passing weddings in order to display on page
ViewBag.Weddings = allWeddings;
return View("Home");
}
//---------------------------------------------------------- L O G O U T --------------------------
[HttpGet]
[Route("logout")]
public IActionResult Logout()
{
HttpContext.Session.Clear();
return RedirectToAction("Index");
}
//--------------------------------------------------------- N E W W E D D I N G -------------------------
[HttpGet]
[Route("NewWedding")]
public IActionResult NewWedding()
{
return View("NewWedding");
}
//--------------------------------------------------------- A D D W E D D I N G ---------------------------
[HttpPost]
[Route("add")]
public IActionResult AddWedding(AddWeddingViewModel wedding)
{
int? userID = HttpContext.Session.GetInt32("ID");
if(userID == null)
{
return RedirectToAction("Index");
}
if(!ModelState.IsValid)
{
return View("NewWedding");
}
Wedding NewWedding = new Wedding
{
WedderOne = wedding.WedderOne,
WedderTwo = wedding.WedderTwo,
Date = DateTime.Now,
UserID = (int) userID
};
_context.Weddings.Add(NewWedding);
_context.SaveChanges();
Console.WriteLine("####################################################################am i added#######################################################################");
return RedirectToAction("Home");
}
[HttpGet]
[Route("rsvp/{wedding_id}")]
public IActionResult RSVP(int wedding_id)
{
//getting user id from session
int? userId = HttpContext.Session.GetInt32 ("ID");
//we use logged in user id to describe user who's going to join the wedding
//this is going to be 'Attending' in the new guest table
User userToJoin = _context.Users
.FirstOrDefault (u => u.UserID == userId);
//we're creating rsvp here so wedding attaches to the guest with a wedding id
//are we joining the wedding with the creation of a new guest?
Wedding weddingToJoin = _context.Weddings
.Include (g => g.Guests)
.FirstOrDefault (w => w.WeddingID == wedding_id);
//creating new guest!!!!!!!
Guest newGuest = new Guest
{
UserID = (int) userId,
WeddingID = wedding_id,
Attending = userToJoin,
Wedding = weddingToJoin
};
_context.Guests.Add (newGuest);
_context.SaveChanges ();
return RedirectToAction("Home");
}
[HttpGet ("unrsvp/{wedding_id}")]
public IActionResult UnRsvp (int wedding_id)
{
int? userId = HttpContext.Session.GetInt32 ("ID");
Guest rsvp = _context.Guests
.FirstOrDefault (g => g.WeddingID == wedding_id && g.UserID == userId);
_context.Remove(rsvp);
_context.SaveChanges();
return RedirectToAction ("Home");
}
[HttpGet]
[Route("delete/{wedding_id}")]
public IActionResult Delete(int wedding_id)
{
int? userId = HttpContext.Session.GetInt32 ("ID");
if(userId == null)
{
return RedirectToAction("Index");
}
Wedding RetrievedWedding=_context.Weddings.FirstOrDefault(w=>w.WeddingID = wedding_id);
_context.Weddings.Remove(RetrievedWedding);
_context.SaveChanges();
return RedirectToAction("Home");
}
}
}
<file_sep>/ProductsAndCategories/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using ProductsAndCategories.Models;
using ProductsAndCategories.ViewModels;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace ProductsAndCategories.Controllers
{
public class HomeController : Controller
{
private DataContext _context;
public HomeController(DataContext context)
{
_context = context;
}
//----------------------------------- I N D E X -------------------------
[HttpGet]
[Route("")]
public IActionResult Index()
{
List<Product> allProducts = _context.Products.ToList();
ViewBag.Products = allProducts;
return View();
}
//----------------------------------- A D D N E W P R O D U C T -------------------------
[HttpPost]
[Route("NewProduct")]
public IActionResult NewProduct(ProductViewModel product)
{
Product NewProduct = new Product
{
ProductName = product.ProductName,
Description = product.Description,
Price = (int) product.Price
};
_context.Products.Add(NewProduct);
_context.SaveChanges();
return RedirectToAction("Index");
}
//----------------------------------- C A T E G O R Y P A G E -------------------------
[HttpGet]
[Route("categories")]
public IActionResult Categories()
{
List<Category> allCategories = _context.Categories.ToList();
ViewBag.Categories = allCategories;
return View();
}
//----------------------------------- A D D N E W C A T E G O R Y -------------------------
[HttpPost]
[Route("NewCategory")]
public IActionResult NewCategory(CategoryViewModel category)
{
Category NewCategory = new Category
{
CategoryName = category.CategoryName
};
_context.Categories.Add(NewCategory);
_context.SaveChanges();
return RedirectToAction("AddCategory");
}
//----------------------------------- G O T O P R O D U C T P A G E -------------------------
[HttpGet]
[Route("products/{product_id}")]
public IActionResult Product(int product_id)
{
Product RetrievedProduct=_context.Products.FirstOrDefault(p=> p.ProductID == product_id);
ViewBag.Product = RetrievedProduct;
List<Category> allCategories = _context.Categories.ToList();
ViewBag.Categories = allCategories;
return View("Product");
}
//----------------------------------- A D D A S S O C I A T I O N -------------------------
[HttpPost]
[Route("products/{product_id}")]
public IActionResult AddAssociation(int product_id, int category_id)
{
Category categoryToJoin = _context.Categories.FirstOrDefault(c=> c.CategoryID == category_id);
Product productToJoin = _context.Products.Include(a=>a.CategorizedProducts).FirstOrDefault(p=>p.ProductID == product_id);
// Product RetrievedProduct=_context.Products.FirstOrDefault(p=> p.ProductID == product_id);
// ViewBag.Product = RetrievedProduct;
// List<Category> allCategories = _context.Categories.ToList();
// ViewBag.Categories = allCategories;
// var productwithcatandass = _context.Products.Include(p=>p.CategorizedProducts).ThenInclude(c=>c.CategoryToJoin).ToList();
// var personWithSubsAndMags = dbContext.Persons
// .Include(person => person.Subscriptions)
// .ThenInclude(sub => sub.Magazine)
// .ToList();
Association newAssociation = new Association
{
ProductID = product_id,
CategoryID = category_id,
ProductToJoin = productToJoin,
CategoryToJoin = categoryToJoin
};
return RedirectToAction("Product");
}
//------------------------------------------- A D D C A T E G O R Y T O A P R O D U C T -------------------------------------
// [HttpPost]
// [Route("AddCategoryToPoduct")]
// public IActionResult AddCategoryToPoduct(Association association, int product_id, int category_id)
// {
// return RedirectToAction("Product");
}
}
<file_sep>/ProductsAndCategories/Views/Home/Product.cshtml
@model ProductsAndCategories.Models.Product
@{
ViewData["Title"] = "Home Page";
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<title>Product Page</title>
<style>
.name{
background-color: lightseagreen;
border: solid darkgreen 1px;
max-width: 400px;
margin:auto;
padding:10px;
margin-top:20px;
}
</style>
<body>
<h2 class="name">@ViewBag.Product.ProductName</h2>
<br>
<div id="container">
<div class="row">
<div class="col">
<h2>Categories</h2>
<br><br><br>
LOOP THROUGH ASSOCIATIONS IN THE PRODUCT?
</div>
<div class="col">
<h2>Add Category</h2>
<br><br><br>
<partial name="_CategoriesPartial" />
</div>
</div>
</div>
</body>
</html><file_sep>/DateTime/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using System.Globalization;
namespace DateTime.Controllers
{
public class HomeController : Controller//we get controller from ASp net core dot mvc
{
public IActionResult Index()
{
return View();
}
}
}
<file_sep>/ProductsAndCategories/Models/Association.cs
using System;
namespace ProductsAndCategories.Models
{
public class Association
{
public int AssociationID { get; set; }
public int ProductID { get; set; }
public Product ProductToJoin { get; set; }
public int CategoryID { get; set; }
public Category CategoryToJoin { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
}<file_sep>/DojoSurveyWithValidation/Views/User/Results.cshtml
@model DojoSurveyWithValidation.Models.SurveyForm
@{
ViewData["Title"] = "Success Page";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv='X-UA-compatible' content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>"
crossorigin="anonymous">
<title>Dojo Survey w/ validations</title>
</head>
<body>
<div id="container">
<h3>Results</h3>
@Model.Name
@Model.Location
@Model.Language
@Model.Comment
</div>
</body>
</html><file_sep>/CRUDelicious2/Views/Home/Show.cshtml
@model CRUDelicious2.Models.Dish
@{
ViewData["Title"] = "Show Page";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv='X-UA-compatible' content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>"
crossorigin="anonymous">
<title>CRUDelicious</title>
</head>
<style>
.col-sm{
background-color: green;
border: solid 1px darkgray;
border-radius: 15px;
padding:15px;
color: wheat;
margin: 10px;
height: 300px;
}
.break{
border-bottom: solid 1px darkgray;
}
</style>
<body>
<div id="container">
<h1>@ViewBag.retrieveddish.Name</h1>
<h5 class="break">@ViewBag.retrieveddish.Chef</h5>
<p>@ViewBag.retrieveddish.Description</p>
<p>@ViewBag.retrieveddish.Calories</p>
<p>@ViewBag.retrieveddish.Tastiness</p>
<a href="/Edit/@ViewBag.retrieveddish.DishID">Edit</a>
<a href="/Delete/@ViewBag.retrieveddish.DishID">Delete</a>
</div>
</body>
</html><file_sep>/ProductsAndCategories/Models/Product.cs
using System;
using System.Collections.Generic;
namespace ProductsAndCategories.Models
{
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string Description { get; set; }
public int Price { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public List<Association> CategorizedProducts { get; set; }
}
}<file_sep>/Dojodachi/Models/Dachi.cs
//1. using system
//2. namespace. inside public class Dachi. inside pcD, set get; set;
//3. method dachi: start with the start values for the variables
using System;
namespace Dojodachi
{
public class Dachi
{
public int Fullness { get; set; }
public int Happiness { get; set; }
public int Energy { get; set; }
public int Meals { get; set; }
public string Message { get; set; }
public Dachi()
{
Fullness = 20;
Happiness = 20;
Energy = 50;
Meals = 3;
}
public void Feed()
{
Meals = Meals - 1;
Random rand = new Random();
if(rand.Next(1,4) !=1)
{
Fullness = Fullness + rand.Next(5,10);
}
}
public void Play()
{
Energy = Energy - 5;
Random rand = new Random();
if(rand.Next(1,4) !=1 )
{
Happiness = Happiness + rand.Next(5,10);
}
}
public void Work()
{
Energy = Energy - 5;
Random rand = new Random();
Meals = Meals + rand.Next(1,3);
}
public void Sleep()
{
Energy = Energy + 15;
Fullness = Fullness - 5;
Happiness = Happiness - 5;
}
// public void Total()
// {
// if(Energy+Fullness+Happiness>=100)
// {
// Message="You Win!";
// //also need to display Restart button w/ this happening
// }
// if(Fullness==0 || Happiness==0)
// {
// Message="You Lose!";
// //also needs a restart button to display
// }
// }
}
}
<file_sep>/CRUDelicious2/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using CRUDelicious2.Models;
using System.Linq;
namespace CRUDelicious2.Controllers
{
public class HomeController : Controller
{
private CRUDcontext dbContext;
public HomeController(CRUDcontext context)
{
dbContext = context;
}
// GET: /Home/--------------------------------------------------------------------------
[HttpGet]
[Route("")]
public IActionResult Index()
{
List<Dish> AllDishes = dbContext.dishes.ToList();
ViewBag.dishes = AllDishes;
return View();
}
//-----------NEW---------------------------------------------------------------
[HttpGet]
[Route("New")]
public IActionResult New()
{
return View("New");
}
//-----------CREATE------------------------------------------------------------------
[HttpPost]
[Route("Create")]
public IActionResult Create(Dish dish)
{
Dish newDish = new Dish
{
Name = dish.Name,
Chef = dish.Chef,
Tastiness =dish.Tastiness,
Calories = dish.Calories,
Description = dish.Description,
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now
};
dbContext.Add(newDish);
dbContext.SaveChanges();
Console.WriteLine("######################################################AADDDEEEDDD##########################");
return RedirectToAction("Index");
}
//--------SHOW------------------------------------------------------------------
[HttpGet]
[Route("Show")]
public IActionResult Show()
{
return RedirectToAction("Show");
}
//--------{DISH ID}------------------------------------------------------------------
[HttpGet]
[Route("{dish_id}")]
public IActionResult Show(int dish_id)
{
Dish RetrievedDish = dbContext.dishes.SingleOrDefault(dish=> dish.DishID == dish_id);//dish a
ViewBag.retrieveddish = RetrievedDish;
return View("Show");
}
//------------EDIT--------------------------------------------
[HttpGet]
[Route("Edit/{dish_id}")]
public IActionResult Edit(int dish_id)
{
Dish RetrievedDish = dbContext.dishes.SingleOrDefault(dish=> dish.DishID == dish_id);
ViewBag.retrieveddish = RetrievedDish;
return View("Edit");
}
//-----------UPDATE---------------------------------------
[HttpPost]
[Route("Update/{dish_id}")]
public IActionResult Update(Dish editDish, int dish_id)
{
Dish RetrievedDish = dbContext.dishes.SingleOrDefault(a=> a.DishID == dish_id);
RetrievedDish.Name = editDish.Name;
RetrievedDish.Chef = editDish.Chef;
RetrievedDish.Tastiness = editDish.Tastiness;
RetrievedDish.Calories = editDish.Calories;
RetrievedDish.Description = editDish.Description;
RetrievedDish.UpdatedAt = DateTime.Now;
dbContext.SaveChanges();
return RedirectToAction("Index");
}
//------------DELETE-------------------------------------
[HttpGet]
[Route("Delete/{dish_id}")]
public IActionResult Delete(int dish_id)
{
Dish RetrievedDish = dbContext.dishes.SingleOrDefault(dish=> dish.DishID == dish_id);
dbContext.dishes.Remove(RetrievedDish);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/WeddingPlanner3/Controllers/WeddingController.cs
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using WeddingPlanner3.Models;
namespace WeddingPlanner3.Controllers
{
public class WeddingController : Controller
{
}
}
// [HttpGet]
// [Route("weddings")]
// public IActionResult Index()
// {
// List<Wedding> allWeddings = _context.Weddings.Include(w => w.Planner).Include(u => u.Guest).ToList();
// foreach ( var wedding in allWeddings)
// {
// System.Console.WriteLine($"{wedding.WedderOne} is getting married to {wedding.WedderOne} wedding planned by )
// foreach(var guest in wedding.Guest)
// {
// }
// }
// string userName=HttpContext.Session.GetString("userName");
// ViewBag.UserName = userName;
// return View();
// // }
<file_sep>/ProductsAndCategories/ViewModels/CategoryViewModel.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ProductsAndCategories.ViewModels {
public class CategoryViewModel {
[Key]
public int CategoryID { get; set; }
[Required(ErrorMessage = "Required Field")]
[MinLength(2, ErrorMessage = "Category Name must be at least 2 characters long")]
public string CategoryName { get; set; }
}
}<file_sep>/WeddingPlanner3/Views/Auth/NewWedding.cshtml
@model WeddingPlanner3.ViewModels.AddWeddingViewModel
@{
ViewData["Title"] = "New Wedding";
}
<h1>Please create a wedding</h1>
<form asp-action="AddWedding" asp-controller="Auth" method="POST">
<span asp-validation-for="WedderOne"></span>
<label asp-for="WedderOne">Wedder One</label><br>
<input asp-for="WedderOne" type="text"><br>
<span asp-validation-for="WedderTwo"></span>
<label asp-for="WedderTwo">WedderTwo</label><br>
<input asp-for="WedderTwo" type="text"><br>
<span asp-validation-for="Date"></span>
<label asp-for="Date">Date</label><br>
<input asp-for="Date" type="datetime-local"><br>
<input type="submit" value="submit">
</form>
<a href="Home">Home Page</a><file_sep>/DateTime/Views/Home/index.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv='X-UA-compatible' content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>"
crossorigin="anonymous">
<title>DateTime</title>
</head>
<body>
<div id="container">
@{ DateTime CurrentTime = DateTime.Now; }
<div>
<h3>The Current Date and Time</h3>
</div>
<div>
<p>Date: @CurrentTime.ToString("MMM d, yyy") </p>
<p>Time: @CurrentTime.ToString("h:mm tt") </p>
</div>
</div>
</body>
</html><file_sep>/LoginAndRegistration2/Controllers/UserController.cs
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using LoginAndRegistration2.Models;
using System.Linq;
using Microsoft.AspNetCore.Identity;
using LoginAndRegistration2.ViewModels;
namespace LoginAndRegistration2.Controllers
{
public class UserController : Controller
{
private DataContext dbContext;
// here we can "inject" our context service into the constructor
public UserController(DataContext context)
{
dbContext = context;
}
//---------------------------------------------------------------------------------------INDEX--------------------------------
[HttpGet]
[Route("")]
public IActionResult Index()
{
// List<User> AllUsers = dbContext.users.ToList();
// ViewBag.users = AllUsers;
return View();
}
//-----------------------------------------------------------------------------------------CREATE METHOD------------------------------
[HttpPost]
[Route("Create")]
public IActionResult Create(User user)
{
if(!ModelState.IsValid)
{
if(dbContext.users.Any(u => u.Email == user.Email))
{
ModelState.AddModelError("Email", "Email already in use!");
}
return View("Index");
}
else{
PasswordHasher<User> Hasher = new PasswordHasher<User>();//----
user.Password = Hasher.HashPassword(user, user.Password);//-----
User newUser = new User
{
FirstName = user.FirstName,
LastName = user.LastName,
Email = user.Email,
Password = user.Password,
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now
};
dbContext.Add(newUser);
dbContext.SaveChanges();
Console.WriteLine("###############################################success???#############################################################################################################");
return RedirectToAction("GoToLogin");
}
}
//---------------------------------------------------------------------------------------LOGIN--------------------------------
[HttpPost]
[Route("Login")]
public IActionResult Login(ViewModels.LoginViewModel LoginUser) {
if(ModelState.IsValid){
var userinDB = dbContext.users.FirstOrDefault(u=>u.Email == LoginUser.Email);
if(userinDB == null)
{
ModelState.AddModelError("Email","Invalid Email");
return View();
}
var hasher = new PasswordHasher<ViewModels.LoginViewModel>();
var result = hasher.VerifyHashedPassword(LoginUser, userinDB.Password, LoginUser.Password);
if (result == 0){
ModelState.AddModelError("Password", "Invalid Password");
return View();
}else{
var UserName = userinDB.FirstName;
HttpContext.Session.SetString("UserName", UserName);
HttpContext.Session.SetString("Login", "true");
return RedirectToAction("Success");
}
}
return View ("Index");
}
//----------------------------------------------------------------------------------------GOTOLOGINPAGE-------------------------------
[HttpGet]
[Route("GoToLogin")]
public IActionResult GoToLogin()
{
return View("Login");
}
//-----------------------------------------------------------------------------------------------------------------------
[HttpGet]
[Route("Success")]
public IActionResult Success()
{
if(HttpContext.Session.GetString("Login") != "true" )
{
return RedirectToAction("Success");
}
else
{
ViewBag.FirstName =HttpContext.Session.GetString("FirstName"); ;
return View ("Success");
}
}
[HttpGet]
[Route("Logout")]
public IActionResult Logout()
{
return RedirectToAction("Index");
}
}
}
<file_sep>/ProductsAndCategories/Views/Shared/_CategoriesPartial.cshtml
@model ProductsAndCategories.Models.Category
@{
ViewData["Title"] = "Home Page";
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<title>Category add form Page</title>
<body>
<form action="NewCategory" method="POST">
<label name="CategoryName">Category Name</label><br>
<select>
@foreach (var Category in ViewBag.Category)
{
<option name="CategoryName">
@Category.CategoryName
</option>
}
</select>
<input type="submit" value="submit">
</form>
</body>
</html><file_sep>/ViewModelFun/Views/Home/Index.cshtml
@using ViewModelFun.Models
@model User
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv='X-UA-compatible' content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>"
crossorigin="anonymous">
<title></title>
</head>
<style>
body{
background-color: gainsboro;
}
#container{
margin: 40px;
border: solid 1px black;
background-color:skyblue;
max-width: 500px;
padding: 20px;
}
</style>
<body>
<div id="container">
<h3>Here's a message</h3>
<p>
Powder caramels tiramisu chocolate cake sugar plum dragée jelly beans. Dragée cake brownie topping fruitcake. Oat cake lollipop cotton candy chocolate bar jelly-o pudding topping.
</p>
</div>
</body>
</html><file_sep>/PortfolioOne/Views/Home/Index.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv='X-UA-compatible' content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>"
crossorigin="anonymous">
<title></title>
</head>
<style>
body{
background-color: grey;
}
</style>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item active">
<a class="nav-link" href="/projects">Projects <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item active">
<a class="nav-link" href="/contact">Contact <span class="sr-only">(current)</span></a>
</li>
</ul>
</div>
</nav>
<h3>About Me</h3>
<div id="container">
<div class="container">
<div class="row">
<div class="col">
<img src="/images/Tuli.jpg" alt="Tuli">
</div>
<div class="col">
<p>Doggo ipsum much ruin diet tungg very hand that feed shibe porgo, pupper h*ck. Dat tungg tho blop porgo woofer you are doing me a frighten, doggo corgo. Waggy wags heckin angery woofer corgo waggy wags, blep. heckin angery woofer shibe. Porgo vvv aqua doggo pupperino fat boi aqua doggo corgo, borkdrive noodle horse pats most angery pupper I have ever seen very hand that feed shibe. Snoot heckin good boys mlem floofs boof long water shoob he made many woofs long woofer h*ck, long woofer big ol pupper ruff clouds much ruin diet aqua doggo. Pupperino very good spot you are doin me a concern, such treat. Corgo adorable doggo shoob puggorino fluffer doge yapper big ol, most angery pupper I have ever seen you are doing me a frighten dat tungg tho big ol pupper adorable doggo. Borking doggo long water shoob length boy fluffer boofers pupperino, bork floofs maximum borkdrive.</p>
</div>
</div>
</div>
</body>
</html><file_sep>/LoginAndRegistration2/Data/DataContext.cs
using Microsoft.EntityFrameworkCore;
namespace LoginAndRegistration2.Models
{
public class DataContext : DbContext
{
// base() calls the parent class' constructor passing the "options" parameter along
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
public static object Users { get; internal set; }
// This DbSet contains "Person" objects and is called "Users"
public DbSet<User> users { get; set; }
}
}<file_sep>/Dojodachi/Controllers/HomeController.cs
//1. using statements; namespace.Controllers; HomeController : Controller;
//2. Feed method
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
// using DbConnection;
namespace Dojodachi.Controllers
{
public class HomeController : Controller
{
[HttpGet]
[Route("")]
public IActionResult Index()
{
if(HttpContext.Session.GetObjectFromJson<Dachi>("DachiData") == null)
{
HttpContext.Session.SetObjectAsJson("DachiData", new Dachi());
}
ViewBag.DachiData = HttpContext.Session.GetObjectFromJson<Dachi>("DachiData");
if(ViewBag.DachiData.Fullness < 1 || ViewBag.DachiData.Happiness < 1 ){
ViewBag.DachiData.Message = "Your Dachi just died...";
}
if(ViewBag.DachiData.Fullness > 100 && ViewBag.DachiData.Happiness > 100 && ViewBag.DachiData.energy > 100){
ViewBag.DachiData.Message = "Your Dachi just succeeded in life...";
}
return View();
}
[HttpGet]
[Route("feed")]
public IActionResult FeedDojodachi()
{
Dachi CurrDachiData = HttpContext.Session.GetObjectFromJson<Dachi>("DachiData");//tikriausiai reiks mintinai atsimint
if(CurrDachiData.Meals > 0)
{
CurrDachiData.Feed();
CurrDachiData.Message = "Your Dachi is eating!";
}
else
{
CurrDachiData.Message = "There are no meals! Go work to earn more!";
}
HttpContext.Session.SetObjectAsJson("DachiData",CurrDachiData);//antra dalis atsiminimui
return RedirectToAction("Index");
}
[HttpGet]
[Route("play")]
public IActionResult PlayDojodachi()
{
Dachi CurrDachiData = HttpContext.Session.GetObjectFromJson<Dachi>("DachiData");
if(CurrDachiData.Energy<5)
{
CurrDachiData.Message = ("You don't have enough energy to play. Get some sleep!");
}
else
{
CurrDachiData.Play();
CurrDachiData.Message = "Your Dachi is playing!";
}
HttpContext.Session.SetObjectAsJson("DachiData",CurrDachiData);
return RedirectToAction("Index");
}
[HttpGet]
[Route("work")]
public IActionResult WorkDojodachi()
{
Dachi CurrDachiData = HttpContext.Session.GetObjectFromJson<Dachi>("DachiData");
if(CurrDachiData.Energy<5)
{
CurrDachiData.Message = ("You don't have enough energy to work. Get some sleep!");
}
else
{
CurrDachiData.Work();
CurrDachiData.Message = "Your Dachi is working!";
}
HttpContext.Session.SetObjectAsJson("DachiData",CurrDachiData);
return RedirectToAction("Index");
}
[HttpGet]
[Route("sleep")]
public IActionResult SleepDojodachi()
{
Dachi CurrDachiData = HttpContext.Session.GetObjectFromJson<Dachi>("DachiData");
if(CurrDachiData.Fullness<5 || CurrDachiData.Happiness<5)
{
CurrDachiData.Message = ("Your fullness and happiness need to be at least 5 each in order to sleep");
}
else
{
CurrDachiData.Sleep();
CurrDachiData.Message = "Your Dachi is Sleeping!";
}
HttpContext.Session.SetObjectAsJson("DachiData",CurrDachiData);
return RedirectToAction("Index");
}
[HttpGet]
[Route("reset")]
public IActionResult Reset()
{
HttpContext.Session.Clear();
return RedirectToAction("Index");
}
}
}
// Somewhere in your namespace, outside other classescopy
public static class SessionExtensions
{
// We can call ".SetObjectAsJson" just like our other session set methods, by passing a key and a value
public static void SetObjectAsJson(this ISession session, string key, object value)
{
// This helper function simply serializes theobject to JSON and stores it as a string in session
session.SetString(key, JsonConvert.SerializeObject(value));
}
// generic type T is a stand-in indicating that we need to specify the type on retrieval
public static T GetObjectFromJson<T>(this ISession session, string key)
{
string value = session.GetString(key);
// Upon retrieval the object is deserialized based on the type we specified
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
}<file_sep>/ProductsAndCategories/ViewModels/ProductViewModel.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ProductsAndCategories.ViewModels {
public class ProductViewModel {
[Key]
public int ProductID { get; set; }
[Required(ErrorMessage = "Required Field")]
[MinLength(2, ErrorMessage = "Product Name must be at least 2 characters long")]
public string ProductName { get; set; }
[Required(ErrorMessage = "Required Field")]
[MinLength(2, ErrorMessage = "Description must be at least 2 characters long")]
public string Description { get; set; }
[Required(ErrorMessage = "Required Field")]
public int Price { get; set; }
}
}<file_sep>/WeddingPlanner3/Views/Auth/Home.cshtml
@model WeddingPlanner3.Models.Wedding
@{
ViewData["Title"] = "Home Page";
}
<partial name="_HomePartial" />
<table class="table">
<thead>
<tr>
<th scope="col">Wedding</th>
<th scope="col">Guest Count</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
@foreach (var Wedding in ViewBag.Weddings)
{
<tr>
<th scope="col"> @Wedding.WedderOne</th>
<th scope="col">@Wedding.WedderTwo</th>
<th scope="col">@Wedding.Date</th>
<th scope="col">planned by: @Wedding.Planner.FirstName</th>
<th>
@{
var attending = false;
foreach(var guest in @Wedding.Guests)
{
if(guest.UserID == @ViewBag.User.UserID)
{
attending = true;
}
}
@if(@ViewBag.User.UserID == @Wedding.UserID)
{
<a href="rsvp/@Wedding.WeddingID">Delete</a>
}
else if(attending)
{
<a href="unrsvp/@Wedding.WeddingID">Un-RVSP</a>
} else {
<a href="rsvp/@Wedding.WeddingID">RVSP</a>
}
}
</th>
</tr>
}
</tbody>
</table>
<a href="NewWedding">Add a new wedding</a>
<file_sep>/ProductsAndCategories/Models/Category.cs
using System;
using System.Collections.Generic;
namespace ProductsAndCategories.Models
{
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public List<Association> ProductedCategories{ get; set; }
}
}<file_sep>/WeddingPlanner3/ViewModels/AddWeddingViewModel.cs
using System.ComponentModel.DataAnnotations;
namespace WeddingPlanner3.ViewModels {
public class AddWeddingViewModel {
[Required(ErrorMessage = "Required Field")]
public string WedderOne { get; set; }
[Required(ErrorMessage = "Required Field")]
public string WedderTwo { get; set; }
[Required(ErrorMessage = "Required Field")]
[DataType(DataType.Date)]
public string Date { get; set; }
}
}<file_sep>/ViewModelFun/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
namespace RazorFun.Controllers
{
public class HomeController : Controller
{
public IActionResult Users()
{
string[] names = new string[]
{
"Sally",
"Billy",
"Joe",
"Moose"
};
return View("users");
}
public IActionResult Index()
{
return View();
}
}
}<file_sep>/RandomPasscode/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
namespace RandomPasscode.Controllers
{
public class HomeController : Controller
{
private static Random Rand = new Random();//Generating a random passcode
[HttpGet]
[Route("")]
public IActionResult Index()
{
//int? count = HttpContext.Session.GetInt32("count");
//if(count is null)
// {
// count +=1;
// Viewbag.Password = Generate() -----> the method with creating random passcode
// Viewbag.Count = count;
// }
// else
// {
// count ++;
// Viewbag.Password = Generate() -----> the method with creating random passcode
// Viewbag.Count = count;
// }
//HttpContext.Session.SetInt32("count", (int)count);
int? RunCount = HttpContext.Session.GetInt32("RunCount");//Stores the string in session
RunCount = (RunCount == null) ? 0 : RunCount;
RunCount++;//Total count of generating passwords/refreshing
string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string random14 = "";
for (int i=0;i<14;i++)
{
random14 = random14 + (chars[Rand.Next(0, chars.Length)]);// also could be done
}
ViewBag.PassCode = random14;//passing passcode and count to views through viewbag
ViewBag.RunCount = RunCount;
HttpContext.Session.SetInt32("RunCount", (int)RunCount);//The first string passed is the key and the second is the value we want to retrieve later
return View();
}
}
}
//we could also create a new method, where we create a random number (without a route and httpget/post.... returning a random passcode)
//We can also create the same No-Route method for clearing sessions in order to clear it<file_sep>/PortfolioOne/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
//using portfolio.Models;
namespace portfolio.Controllers
{
public class HomeController : Controller
{
public ViewResult Index()
{
return View();
}
//-----------------------------------------
[HttpGet("projects")]
public ViewResult Projects()
{
return View("projects");
}
//-----------------------------------------
[HttpGet("contact")]
public ViewResult Contact()
{
return View("contact");
}
}
}<file_sep>/Dojodachi/readme.txt
Your Dojodachi should start with 20 happiness, 20 fullness, 50 energy, and 3 meals.
After every button press, display a message showing how the Dojodachi reacted
Feeding your Dojodachi costs 1 meal and gains a random amount of fullness between 5 and 10 (you cannot feed your Dojodachi if you do not have meals)
Playing with your Dojodachi costs 5 energy and gains a random amount of happiness between 5 and 10
Every time you play with or feed your dojodachi there should be a 25% chance that it won't like it. Energy or meals will still decrease, but happiness and fullness won't change.
Working costs 5 energy and earns between 1 and 3 meals
Sleeping earns 15 energy and decreases fullness and happiness each by 5
If energy, fullness, and happiness are all raised to over 100, you win! a restart button should be displayed.
If fullness or happiness ever drop to 0, you lose, and a restart button should be displayed.<file_sep>/DojoSurveyWithValidation/Controllers/UserController.cs
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using DojoSurveyWithValidation.Models;//ADD THIS TO CONNECT TO MODELS
using Microsoft.AspNetCore.Http;
namespace DojoSurveyWithValidation.Controllers
{
public class UserController : Controller
{
//---------------------------------------------Index----------------------------
[HttpGet]
[Route("")]
public IActionResult Index()
{
return View();
}
//---------------------------------------------Results Page----------------------------
// [HttpGet]
// [Route("Results")]
// public RedirectToActionResult Results()
// {
// return RedirectToAction("Results");
// }
//---------------------------------------------Submit action---------------------------
[HttpPost]
[Route("submit")]
public IActionResult Submit(SurveyForm surveyForm)
{
if(!ModelState.IsValid)
{
return View("Index", surveyForm);
}
return RedirectToAction("Results", surveyForm);
}
}
}
<file_sep>/ProductsAndCategories/Views/Home/Categories.cshtml
@model ProductsAndCategories.Models.Category
@{
ViewData["Title"] = "Home Page";
}
<!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://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<title>Products And Categories</title>
<body>
<div id="container">
<div class="row">
<div class="col">
<h2><a href="/">Products</a></h2>
<br><br><br>
<form asp-action="NewCategory" asp-controller="Home" method="POST">
<span asp-validation-for="CategoryName"></span>
<label asp-for="CategoryName">Category Name</label><br>
<input asp-for="CategoryName"><br>
<input type="submit" value="submit">
</form>
</div>
<div class="col">
<h2><a href="categories">Categories</a></h2>
<br><br><br>
@foreach (var Category in ViewBag.Categories)
{
<p>@Category.CategoryName</p>
}
</div>
</div>
</div>
</body>
</html><file_sep>/RazorFun/Views/Home/index.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv='X-UA-compatible' content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>"
crossorigin="anonymous">
<title></title>
</head>
<style>
h3, .list{
padding: 20px;
margin: 20px;
}
.list{
background-color: lightgrey;
border: solid 2px darkslategrey;
border-radius: 15px;
max-width: 300px;
}
</style>
<body>
<div id="container">
<h3>Here are some delicious foods!</h3>
<div class="list">
@{
var StringList = new List<string>{
"Apple Pie",
"Burritos",
"Clams Casino",
"Donuts"
};
foreach(var word in StringList)
{
<p>@word</p>
if(word.StartsWith("C"))
{
<p style="color:red">@word</p>
}
}
}
</div>
</div>
</body>
</html><file_sep>/DojoSurveyWithValidation/Models/SurveyForm.cs
using System.ComponentModel.DataAnnotations;
namespace DojoSurveyWithValidation.Models
{
public class SurveyForm
{
[Required(ErrorMessage="Name cannot be empty")]
[MinLength(2, ErrorMessage="Name must be at least 2 characters")]
public string Name { get; set; }
[Required(ErrorMessage="Location cannot be empty")]
public string Location { get; set; }
[Required(ErrorMessage="Language cannot be empty")]
public string Language { get; set; }
[MaxLength(20)]
public string Comment { get; set; }
}
}<file_sep>/WeddingPlanner3/Views/Shared/_HomePartial.cshtml
@model WeddingPlanner3.Models.User
@{
ViewData["Title"] = "Home Page";
}
<a href="/logout">Logout</a>
<h1>@ViewBag.UserName's Wedding list page</h1><file_sep>/WeddingPlanner3/Models/Guest.cs
using WeddingPlanner3.Models;
namespace WeddingPlanner3.Models
{
public class Guest
{
public int GuestID { get; set; }
public int UserID { get; set; }
public User Attending { get; set; }
public int WeddingID { get; set; }
public Wedding Wedding { get; set; }
}
} | de3e7fa25ab1e8c022ea5db1d47fcb79cfd44d79 | [
"HTML+Razor",
"C#",
"Text"
] | 34 | HTML+Razor | medaserenaite/CSharp | b087325e7724e38407c70d2f399382dfa6364a7d | 9899a201c0370e6d6c572b0ee7c6c130f5cd2e9c |
refs/heads/master | <repo_name>Ollijensen/HTML-Basic<file_sep>/pages/hello-world.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello world</title>
</head>
<body>
<header><!--semantisk HTML: sidehovedet-->
<h1>Hello world!</h1>
</header>
<!--Navigation-->
<nav>
<a href="../index.html">Home</a>
<a href="#">Hello World</a>
<a href="tables.html">The animal table</a>
<a href="contact.html">Contact</a>
<a href="https://www.cphbusiness.dk/" target="_blank">My School</a>
</nav>
<section>
<h2>Section 1</h2>
<article>
<h3>Article 1</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nec ligula porttitor, egestas libero sed, mollis sapien. Mauris aliquam urna purus, vitae luctus ante commodo in. Vestibulum sed felis vulputate dui imperdiet bibendum nec nec enim. Vestibulum sit amet eros id mauris vehicula varius sit amet in lectus. Duis placerat ullamcorper arcu, id auctor est porta ac. Sed est velit, egestas eu diam ut, varius tristique elit. Suspendisse viverra orci sapien, ac gravida magna posuere eget. Integer id ipsum aliquet, pellentesque lectus quis, ullamcorper odio. Donec luctus libero ex, at rhoncus enim aliquam eget. Donec eros nulla, porttitor non auctor non, porttitor ullamcorper risus. Aenean gravida quam metus, et malesuada purus feugiat non. Cras ut mauris vitae odio suscipit scelerisque in sed tortor. Nam nec hendrerit magna. In fringilla hendrerit libero, sed convallis sem placerat eget.</p>
<p>Vivamus quis venenatis lacus, posuere mollis nisi. Vestibulum aliquet iaculis mattis. Quisque volutpat blandit nisl ut vulputate. Mauris vulputate sapien in tellus ultricies, et mattis diam dapibus. Cras a ligula elit. Mauris tincidunt eros ut porttitor mollis. Fusce ultrices consectetur euismod. Cras augue tellus, pellentesque vel est id, fermentum auctor turpis.</p>
</article>
<article>
<h3>Article 2</h3>
Donec congue elit efficitur, facilisis sapien vitae, ornare sapien. Ut diam ipsum, congue imperdiet placerat vitae, volutpat eget augue. Integer id erat ut nunc egestas blandit in molestie enim. Sed et magna a elit tempor tempus sed eget tellus. Nullam fermentum urna cursus, commodo velit sit amet, egestas enim. In sollicitudin, nisi et commodo porttitor, lorem ligula fringilla erat, quis semper est nunc non ligula. Phasellus et aliquam lacus. Nunc lacinia fringilla ipsum.
<p>Vivamus non lectus metus. Aliquam bibendum maximus ipsum, non sagittis elit volutpat eu. Proin eget ex laoreet, dignissim nibh sed, pellentesque tortor. Duis ac mollis dolor. Etiam aliquam, purus in aliquet eleifend, magna ligula vestibulum lectus, id luctus ligula metus porttitor odio. Cras vitae libero tortor. Nullam blandit sodales ex, non ornare neque efficitur sit amet. Maecenas consectetur id erat ac auctor. Fusce mi magna, elementum feugiat magna et, viverra sollicitudin nisi. Phasellus venenatis venenatis est.</p>
<p> Donec magna felis, ullamcorper eget elit id, laoreet gravida nisl. Praesent tristique, nunc hendrerit scelerisque malesuada, risus tortor fermentum odio, vitae vestibulum augue lectus vitae felis. Nam sit amet elit mauris. Duis feugiat sem auctor nisi ultricies congue a sed metus. Sed non ultricies lorem. Cras convallis non tortor ut suscipit. Fusce vel est dictum, pharetra massa eu, dignissim eros. Aliquam erat volutpat. Vivamus sem ex, efficitur sit amet risus sed, ornare accumsan odio. Integer cursus elit libero, ac mollis libero consectetur sed. Fusce a lorem quis quam euismod sollicitudin. Pellentesque semper erat eget dui mollis, a tincidunt erat fermentum.</p>
</article>
</section>
</body>
</html> | 896c24bbaf1904fda5fdde1b4b5cfd23a7f3e577 | [
"HTML"
] | 1 | HTML | Ollijensen/HTML-Basic | 3a41726a6d9ca7d0661dad2ae966c2b58b65e502 | 0dcd1b990cf14f59f8c9e2e547861df442a277b2 |
refs/heads/master | <file_sep>package LatUKL;
public class Lat3 {
public static void main(String[] args) {
int a = 10;
int b = 5;
int c = 80;
int d;
for (int i = 0; i < 3; i++) {
d = a;
a += b;
for (int k = 0; k < 5; k++) {
System.out.print(" " + d);
}
System.out.println("");
}
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package otakatik;
import javax.swing.JOptionPane;
/**
*
* @author W10
*/
public class otakatikv2 {
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Masukkan Jenis Kelamin : ");
String input2 = JOptionPane.showInputDialog("Masukkan Nilai : ");
int input3 = Integer.parseInt(input2);
if((input = "L" || input = "P") && input3 >=85){
JOptionPane.showMessageDialog(cmpnt, args, input2, input3, icon);
}}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package otakatik;
/**
*
* @author W10
*/
public class bc {
public static void main(String[] args) {
ab tampil = new ab();
tampil.setNama("Rafi");
System.out.println("Nama : " + tampil.getNama());
System.out.println("Alamat : " + tampil.alamat);
System.out.println("Hobi : " + tampil.hobi);
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package otakatik;
/**
*
* @author W10
*/
public class NewClass1 {
public static void main(String[] args) {
int a, b; // inisialisasi variabel a dan b dengan tipe data integer
for (a = 0; a < 5; a++) { // sebagai perulangan luar
System.out.println(" ");// untuk membentuk baris sesuai pola perulangan
for (b = 0; b < a; b++) { // sebagai perulangan dalam dari 1 hingga 4
System.out.print("*"); // untuk menampilkan bintang dengan membentuk pola segitiga
}
}
System.out.println("\n");
for (a = 1; a <= 5; a++) { // sebagai perulangan luar
System.out.println(""); // untuk membentuk baris sesuai pola perulangan
for (b = a; b <= 5; b++) { // sebagai perulangan dalam mulai dari 5 hingga 1
System.out.print("*"); // untuk menampilkan bintang dengan membentuk pola segitiga
}
}
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author abi_sofyana
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class abicell {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//input scanner
Scanner input=new Scanner(System.in);
BufferedReader input2=new BufferedReader (new InputStreamReader (System.in));
//inisialisasi variabel
int i =0;
String [] hp = new String [100];
String [] perdana = new String [100];
int [] harga = new int[100];
int [] harga2 = new int[100];
String keputusan = "Y";
int jumlah =0;
int hargatotal=0;
//buat tampilan awal
System.out.println("*******************************************");
System.out.println("Abi Cell");
System.out.println("Welcome & Happy Shopping");
System.out.println("*******************************************");
System.out.println("Ready segala merk HP dan perdana segala operator");
System.out.println("Pilihan merk HP :");
System.out.println("1. Samsung = Rp. 2.500.000,-");
System.out.println("2. <NAME> = Rp. 2.000.000,-");
System.out.println("3. OPPO = Rp. 2.300.000,-");
System.out.println("Pilihan Perdana :");
System.out.println("1. Perdana Telkomsel = Rp. 25.000,-");
System.out.println("2. Perdana Indosat = Rp. 23.000,-");
System.out.println("3. Perdana XL = Rp. 23.500,-");
System.out.println("");
System.out.println("*******************************************");
System.out.println("");
//pengkondisian
while (keputusan.equals("Y")||keputusan.equals("y"))
{
System.out.print("Silahkan pilih merk hp yang anda inginkan : ");
int pil = input.nextInt();
switch (pil) {
case 1:
hp [i] = "Samsung";
harga [i] = 2500000;
break;
case 2:
hp [i] = "<NAME>";
harga [i] = 2000000;
break;
case 3:
hp [i] = "OPPO";
harga [i] = 2300000;
break;
case 4:
default:
System.out.println("HP yang anda inginkan sedang out of stock.");
break;
}
for (int k=pil;k<4;k++){
System.out.println("Merk HP yang anda pilih adalah : "+hp[i]);
System.out.print("Jumlah pesanan : ");
int jmlhp = input.nextInt();
harga[i]=harga[i]*jmlhp;
System.out.println("Harga HP sebesar : Rp. "+harga[i]+ " ;");
break;
}
System.out.println("");
System.out.print("Silahkan pilih perdana yang anda inginkan : ");
int pil2=input.nextInt();
switch (pil2){
case 1:
perdana [i] = "Perdana Telkomsel";
harga2 [i] = 25000;
break;
case 2:
perdana [i] = "Perdana Indosat";
harga2 [i] = 23000;
break;
case 3:
perdana [i] = "Perdana XL";
harga2 [i] = 23500;
break;
case 4:
default:
System.out.println("Perdana yang anda inginkan sedang out of stock.");
break;
}
for (int j=pil2;j<4;j++){
System.out.println("Perdana yang anda pilih adalah : "+perdana[i]);
System.out.print("Jumlah pesanan : ");
int jmlperdana = input.nextInt();
harga2[i]=harga2[i]*jmlperdana;
System.out.println("Harga Perdana sebesar : Rp. "+harga2[i]+ " ;");
break;
}
System.out.println("");
int totalhp = 0;
int totalperdana = 0;
int total=harga[i]+harga2[i];
System.out.println("Total belanja anda sebesar : Rp. "+total+ " ;");
System.out.println("Apakah anda ingin order lagi ? Y/N : ");
try{
keputusan = input2.readLine();
}catch(IOException e){
System.out.println("Failed to Read Keyboard");
}
i++;
System.out.println("List Pesanan anda adalah : ");
for (int a = 0; a<i;a++){
System.out.println(hp[a]);
}
for (int b = 0; b<i;b++){
System.out.println(perdana[b]);
}
System.out.println("");
for (int c = 0; c5000000){
System.out.println("Diskon : Rp."+diskon);
}
int totalbayar=hargatotal-diskon;
System.out.println("Total pembayaran sebesar : Rp."+totalbayar);
}
}
}
| 07b10b3b873317fa9c790f317542f3513e28e0d6 | [
"Java"
] | 5 | Java | RafiAthallahN/LatUKL | 29e2f5804d1bd2900569e501b74bd102e28ed384 | 37848ab2c1333fe3213720d7fa6b7339a8da6950 |
refs/heads/master | <repo_name>jennbowers/11.3-Thymeleaf-Fragments<file_sep>/src/main/java/com/jennbowers/thymeleaffun/repositories/PlaylistRepository.java
package com.jennbowers.thymeleaffun.repositories;
import com.jennbowers.thymeleaffun.models.Playlist;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PlaylistRepository extends CrudRepository<Playlist, Long> {
}
| 42b8e6fb175b222545ad25e9cd406ca9f74b31f9 | [
"Java"
] | 1 | Java | jennbowers/11.3-Thymeleaf-Fragments | b1db69729564b8b821e6f6f0262c85c710219903 | dacf919f0a929d5735343a35495c7e54180cee9f |
refs/heads/master | <file_sep><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<style media="screen">
.error{
color: red;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-5">
<h2>Employee form</h2>
<!-- @if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif -->
<form method="post" action="{{ URL::to('store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" value="{{ old('name') }}">
<span class="error">{{ $errors->first('name') }}</span>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" value="{{ old('email') }}">
<span class="error">{{ $errors->first('email') }}</span>
</div>
<div class="form-group">
<label for="contact">Contact:</label>
<input type="tel" class="form-control" id="contact" name="contact" pattern="01[1|5|6|7|8|9][0-9]{8}" value="{{ old('contact') }}">
<span class="error">{{ $errors->first('contact') }}</span>
</div>
<div class="form-group">
<label for="dob">Birth Date:</label>
<input type="date" class="form-control" id="dob" name="dob" value="{{ old('dob') }}">
<span class="error">{{ $errors->first('dob') }}</span>
</div>
<div class="form-group">
<label for="address">Address:</label>
<input type="text" class="form-control" id="address" name="address" value="{{ old('address') }}">
<span class="error">{{ $errors->first('address') }}</span>
</div>
<div class="form-group">
<label for="salary">Salary:</label>
<input type="number" class="form-control" id="salary" name="salary" value="{{ old('salary') }}">
<span class="error">{{ $errors->first('salary') }}</span>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="<PASSWORD>" class="form-control" id="pwd" name="password" value="{{ old('password') }}">
<span class="error">{{ $errors->first('password') }}</span>
</div>
<div class="form-group">
<label for="pwd">Confirm Password:</label>
<input type="<PASSWORD>" class="form-control" id="pwd" name="confirm_password" value="{{ old('confirm_password') }}">
<span class="error">{{ $errors->first('confirm_password') }}</span>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</body>
</html>
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ValidationController extends Controller
{
public function add()
{
return view('add');
}
public function store(Request $req)
{
$validatedData = $req -> validate([
'name' => 'required|regex:/(^[A-Za-z ]+$)+/',
'email' => 'required|email|unique:employees,email',
'address' => 'required',
'contact' => 'required|unique:employees,contact',
'salary' => 'required|integer|between:5000,8000',
'dob' => 'required|before:2014-12-12',
'password' => '<PASSWORD>:8|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$/',
'confirm_password' => '<PASSWORD>:password|same:<PASSWORD>'
]);
}
}
| 3b8011928a6e4a5a34d62f4849825d4721d90882 | [
"Blade",
"PHP"
] | 2 | Blade | enuenan/validation | 7e55edfde131fe757fbe8c774fa413b6ba58d99a | 96d6f07f4a1ee7cb74d87e716110f914d2b0c4a6 |
refs/heads/master | <repo_name>ryoyakawai/candle-bluetooth_async_await<file_sep>/README.md
Candle Bluetooth Codelab (async/await)
======================================
This is copy of https://googlecodelabs.github.io/candle-bluetooth/.
Modified Promise style to async/await style.
See https://codelabs.developers.google.com/codelabs/candle-bluetooth/ for codelab instructions.
Final working version of the codelab can be found at https://googlecodelabs.github.io/candle-bluetooth/.
<file_sep>/playbulbCandle.js
(function() {
'use strict';
let encoder = new TextEncoder('utf-8');
let decoder = new TextDecoder('utf-8');
const CANDLE_SERVICE_UUID = 0xFF02;
const CANDLE_DEVICE_NAME_UUID = 0xFFFF;
const CANDLE_COLOR_UUID = 0xFFFC;
const CANDLE_EFFECT_UUID = 0xFFFB;
class PlaybulbCandle {
constructor() {
this.device = null;
this._isEffectSet = false;
}
async connect() {
let options = {filters:[{services:[ CANDLE_SERVICE_UUID ]}],
optionalServices: ['battery_service']};
const device = await navigator.bluetooth.requestDevice(options);
this.device = device;
return device.gatt.connect();
}
async getDeviceName() {
const service = await this.device.gatt.getPrimaryService(CANDLE_SERVICE_UUID);
const characteristic = await service.getCharacteristic(CANDLE_DEVICE_NAME_UUID);
const data = await characteristic.readValue();
let decoder = new TextDecoder('utf-8');
return decoder.decode(data);
}
async setDeviceName(name) {
const service = await this.device.gatt.getPrimaryService(CANDLE_SERVICE_UUID);
const characteristic = await service.getCharacteristic(CANDLE_DEVICE_NAME_UUID);
let encoder = new TextEncoder('utf-8');
characteristic.writeValue(encoder.encode(name));
}
async getBatteryLevel() {
const service = await this.device.gatt.getPrimaryService('battery_service');
const characteristic = await service.getCharacteristic('battery_level');
const data = await characteristic.readValue();
return data.getUint8(0);
}
async setColor(r, g, b) {
await stopEffect.bind(this)();
if (!this._isEffectSet) {
await update.bind(this)();
}
return [r, g, b];
async function stopEffect() {
// Turn off Color Effect first.
const data = new Uint8Array([0x00, r, g, b, 0x05, 0x00, 0x01, 0x00]);
const service = await this.device.gatt.getPrimaryService(CANDLE_SERVICE_UUID);
const characteristic = await service.getCharacteristic(CANDLE_EFFECT_UUID);
await characteristic.writeValue(data);
}
async function update() {
const data = new Uint8Array([0x00, r, g, b]);
const service = await this.device.gatt.getPrimaryService(CANDLE_SERVICE_UUID);
const characteristic = await service.getCharacteristic(CANDLE_COLOR_UUID);
await characteristic.writeValue(data);
}
}
async setCandleEffectColor(r, g, b) {
let data = new Uint8Array([0x00, r, g, b, 0x04, 0x00, 0x01, 0x00]);
const service = await this.device.gatt.getPrimaryService(CANDLE_SERVICE_UUID);
const characteristic = await service.getCharacteristic(CANDLE_EFFECT_UUID);
await characteristic.writeValue(data);
this._isEffectSet = true;
return [r,g,b];
}
async setFlashingColor(r, g, b) {
let data = new Uint8Array([0x00, r, g, b, 0x00, 0x00, 0x1F, 0x00]);
const service = await this.device.gatt.getPrimaryService(CANDLE_SERVICE_UUID);
const characteristic = await service.getCharacteristic(CANDLE_EFFECT_UUID);
await characteristic.writeValue(data);
this._isEffectSet = true;
return [r,g,b];
}
async setPulseColor(r, g, b) {
// We have to correct user color to make it look nice for real...
const newRed = Math.min(Math.round(r / 64) * 64, 255);
const newGreen = Math.min(Math.round(g / 64) * 64, 255);
const newBlue = Math.min(Math.round(b / 64) * 64, 255);
const data = new Uint8Array([0x00, newRed, newGreen, newBlue, 0x01, 0x00, 0x09, 0x00]);
const service = await this.device.gatt.getPrimaryService(CANDLE_SERVICE_UUID);
const characteristic = await service.getCharacteristic(CANDLE_EFFECT_UUID);
await characteristic.writeValue(data);
this._isEffectSet = true;
return [r,g,b];
}
async setRainbow() {
const data = new Uint8Array([0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00]);
const service = await this.device.gatt.getPrimaryService(CANDLE_SERVICE_UUID);
const characteristic = await service.getCharacteristic(CANDLE_EFFECT_UUID);
await characteristic.writeValue(data);
this._isEffectSet = true;
return;
}
async setRainbowFade() {
const data = new Uint8Array([0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x26, 0x00]);
const service = await this.device.gatt.getPrimaryService(CANDLE_SERVICE_UUID);
const characteristic = await service.getCharacteristic(CANDLE_EFFECT_UUID);
await characteristic.writeValue(data);
this._isEffectSet = true;
return;
}
}
window.playbulbCandle = new PlaybulbCandle();
})();
| 6a156c59c6cbda2d47d4977de71f8e23953a3751 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | ryoyakawai/candle-bluetooth_async_await | 9fc3e6754a29e9a618b8973801ccbb0f823f30e8 | 6ea1bd7834fcb4922e63dd2cbd0e19f435848f89 |
refs/heads/master | <file_sep>ツイート保存アプリ プロトタイプ2
====
### 概要
引数で指定したURLのツイートをアイコンや添付画像と一緒にローカルにアーカイブします。(複数ツイート対応)
### 使い方
以下の環境変数を設定します。
- TWITTER_ACCESS_TOKEN_KEY
- TWITTER_ACCESS_TOKEN_SECRET
- TWITTER_CONSUMER_KEY
- TWITTER_CONSUMER_SECRET
コマンドライン引数
$ dist/index.js add tweet_url
指定したツイートをデータベースに追加します
$ dist/index.js remove tweet_url
指定したツイートをデータベースから削除します
$ dist/index.js output
データベースに保存されているすべてのツイートをHTMLに出力します
<file_sep>import * as DataStore from "nedb";
export default class TweetRepository {
private db;
public constructor() {
this.db = new DataStore({ filename: "db/tweet.db" });
}
public async load(): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.db.loadDatabase((error) => {
if (error !== null) {
reject(error);
}
resolve();
});
});
}
public async insert(insertDoc: any): Promise<any> {
return new Promise<any>((resolve, reject) => {
this.db.insert(insertDoc, (error, newDoc) => {
if (error !== null) {
reject(error);
}
resolve(newDoc);
});
});
}
public async remove(condition): Promise<number> {
return new Promise<number>((resolve, reject) => {
this.db.remove(condition, (error, numRemoved) => {
if (error !== null) {
reject(error);
}
resolve(numRemoved);
});
});
}
public async find(condition): Promise<any[]> {
return new Promise<any[]>((resolve, reject) => {
this.db.find(condition, (error, newDocs) => {
if (error !== null) {
reject(error);
}
resolve(newDocs);
});
});
}
}
<file_sep>import * as fs from "fs";
import * as DateFns from "date-fns";
export function createDirName(): string {
const tweetDate: string = DateFns.format(new Date(), "YYYY-MM-DD");
const baseDirName = `./output-${tweetDate}`;
let dirName: string;
for (let i = 0; ; i++) {
if (i === 0) {
dirName = baseDirName;
}
else {
dirName = `${baseDirName}_${i}`;
}
if (fs.existsSync(dirName) === false) {
break;
}
}
return dirName;
}
| 0475e10bf553ccf1b0d418da34c7539155195eb2 | [
"Markdown",
"TypeScript"
] | 3 | Markdown | hajipy/TweetArchiverPrototype2 | 6f80dc8b6c7f72f656e4ebb7d47483505def2673 | 8db528490b1a6a545b7d870bcfcc84df33a513e4 |
refs/heads/master | <file_sep>/*
* TwoPointNet.cpp
*
* Created on: 16.08.2015
* Author: Julia
*/
#include "TwoPointNet.hpp"
#include <cmath>
using namespace std;
TwoPointNet::TwoPointNet(Pin first, Pin second) {
this->first = first;
this->second = second;
netArea = calcMR();
}
TwoPointNet::~TwoPointNet() {}
int TwoPointNet::calcMR(){
int deltaX = abs(first.get_xKoo() - second.get_xKoo());
int deltaY = abs(first.get_yKoo() - second.get_yKoo());
return deltaX * deltaY;
}
bool TwoPointNet::operator<(TwoPointNet const& rhs) {
return (netArea < rhs.netArea);
}
void TwoPointNet::calc_isLocal(vector<int> origin, vector<int> tiledim){
int xKoo_1 = (first.get_xKoo() - origin[0]) / tiledim[0]; //converting Koo to Bin-Koo
int yKoo_1 = (first.get_yKoo() - origin[1]) / tiledim[1];
int xKoo_2 = (second.get_xKoo() - origin[0]) / tiledim[0];
int yKoo_2 = (second.get_yKoo() - origin[1]) / tiledim[1];
if(xKoo_1 == xKoo_2 && yKoo_1 == yKoo_2 ){ //comparing Bin-Koo
isLocal = true;
} else {
isLocal = false;
}
}
<file_sep>/*
* Parser.hpp
*
* Created on: 13.08.2015
* Author: Julia
*/
#ifndef PARSER_HPP_
#define PARSER_HPP_
#include "Edge.hpp"
#include <string>
#include <vector>
#include "Net.hpp"
using namespace std;
class Parser {
private:
string fileName;
int gX,gY,nL,nmbrNet,nmbrBlockages;
vector<int> vertCap,horiCap,minW,minS,viaS,grid,origin, tiledim;
list<Net> nets;
vector<Edge> blockages;
public:
Parser(string fileName);
virtual ~Parser();
void parseConfig();
list<Net> getNetsOrderedByMR();
int getGridX() const{return gX;};
int getGridY() const{return gY;};
int getGridL() const{return nL;};
int getNmbrNet() const{return nmbrNet;};
int getNmbrBlockages() const{return nmbrBlockages;};
vector<int> getVertCap() const{return vertCap;};
vector<int> getHoriCap() const{return horiCap;};
vector<int> getMinW() const{return minW;};
vector<int> getMinS() const{return minS;};
vector<int> getViaS() const{return viaS;};
vector<int> getGrid() const{return grid;};
vector<int> getOrigin() const{return origin;};
vector<int> getTiledim() const{return tiledim;};
list<Net> getNets() const{return nets;};
vector<Edge> getBlockages() const{return blockages;};
};
#endif /* PARSER_HPP_ */
<file_sep>OBJS1 = src/Edge.o src/Graph.o src/main.o src/Net.o src/Parser.o src/Pin.o src/TwoPointNet.o
CC1 = g++
CFLAGS1 = -std=c++11 -O3 -Wall -c
OBJS2 = src/flute/dist.o src/flute/dl.o src/flute/err.o src/flute/heap.o src/flute/mst2.o src/flute/neighbors.o \
src/flute/bookshelf_IO.o src/flute/memAlloc.o src/flute/flute.o src/flute/flute_mst.o
CC2 = gcc
CFLAGS2 = -O3 -Wall -c
Router : $(OBJS2) $(OBJS1)
$(CC1) $(LFLAGS1) -o Router $(OBJS2) $(OBJS1)
src/flute/%.o: src/flute/%.c
$(CC2) $(CFLAGS2) -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
src/%.o: src/%.cpp
$(CC1) $(CFLAGS1) -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
clean:
\rm src/*.o src/*.d src/flute/*.o src/flute/*.d Router
tar: clean
tar cfv Router.tar src POST9.dat POWV9.dat config1 config2 config3 <file_sep>/*
* TwoPointNet.hpp
*
* Created on: 16.08.2015
* Author: Julia
*/
#ifndef TWOPOINTNET_HPP_
#define TWOPOINTNET_HPP_
#include "Pin.hpp"
#include <vector>
class TwoPointNet {
private:
Pin first;
Pin second;
int netArea;
bool isLocal;
public:
TwoPointNet(Pin first,Pin second);
virtual ~TwoPointNet();
int calcMR();
bool operator<(TwoPointNet const& rhs);
void calc_isLocal(std::vector<int> origin, std::vector<int> tiledim);
bool get_isLocal() const{return isLocal;};
Pin get_first() const{return first;};
Pin get_second() const{return second;};
};
#endif /* TWOPOINTNET_HPP_ */
<file_sep>/*
* Edge.hpp
*
* Created on: 13.08.2015
* Author: Julia
*/
#ifndef EDGE_HPP_
#define EDGE_HPP_
class Edge {
private:
int id,source,target,capacity,cost,overflow,numtracks;
bool isVia;
public:
Edge(int source, int target, int capacity);
Edge(int id, int source, int target, int capacity, bool isVia);
virtual ~Edge();
int getSource() const{return source;};
int getTarget() const{return target;};
int getCapacity() const{return capacity;};
int getCost() const{return cost;};
int getId() const {return id;}
int getOverflow() const {return overflow;};
int getNumtracks() const {return numtracks;};
void updateCost();
};
#endif /* EDGE_HPP_ */
<file_sep>/*
* Net.cpp
*
* Created on: 13.08.2015
* Author: Julia
*/
#include <iostream>
#include "Net.hpp"
#include <algorithm>
#include "flute.h"
#include <boost/foreach.hpp>
using namespace std;
Net::Net(std::string netName) : netName(netName){}
Net::~Net() {
}
//Adding one new pin
void Net::addPin(Pin pin){
pins.push_back(pin);
}
void Net::addSteinerPin(Pin st_pin){
if((find(steinerPins.begin(), steinerPins.end(), st_pin)) == steinerPins.end()){
steinerPins.push_back(st_pin);
}
}
//Calculates the total number of pins from one net
int Net::calc_numpins(){
return pins.size();
}
//using instead of flute
void Net::makeRandomTwoPointNet(std::vector<int> tiledim, std::vector<int> origin){
for(int i=0;i<(int)pins.size()-1;i++){
TwoPointNet n_two_PinNet(pins[i],pins[i+1]);
n_two_PinNet.calc_isLocal(origin, tiledim); //calculating: global or local net
if (n_two_PinNet.get_isLocal()){
if(n_two_PinNet.get_first() == n_two_PinNet.get_second()){
globalTwoPointNets.push_back(n_two_PinNet);
} else {
localTwoPointNets.push_back(n_two_PinNet);
}
} else{
globalTwoPointNets.push_back(n_two_PinNet);
}
}
}
//splitting up in TwoPointNets and separating global and local nets
void Net::runflute(const vector<int>& tiledim, const vector<int>& origin){
int d = 0;
DTYPE x[pins.size()], y[pins.size()];
int i= 0;
vector<Pin> tmp_pins;
vector<int> n_idx;
BOOST_FOREACH(Pin curr_pin, pins){
x[i] = (DTYPE)curr_pin.get_xKoo();
y[i] = (DTYPE)curr_pin.get_yKoo();
d= calc_numpins();
i++;
}
Tree t;
t = flute(d,x,y,ACCURACY);
//plottree(t);
//printtree(t);
for (i=0; i<t.deg; i++){ //getting normal pins
Pin position(t.branch[i].x,t.branch[i].y,pins[0].get_layer());
tmp_pins.push_back(position);
n_idx.push_back(t.branch[i].n);
}
for (i=t.deg; i<2*t.deg-2; i++){ //getting steiner pins
vector<int> std_vector_init;
Pin n_steiner_Pin(t.branch[i].x,t.branch[i].y);
tmp_pins.push_back(n_steiner_Pin);
addSteinerPin(n_steiner_Pin);
n_idx.push_back(t.branch[i].n);
}
free(t.branch); // CleanUP Heap from flute()
t.branch=NULL; // CleanUP Heap from flute()
for (int i=0;i<(int)tmp_pins.size();i++){ //calculating TwoPointNet
//printf("(%d,%d) <-> (%d,%d) \n",tmp_pins[i].get_xKoo(),
// tmp_pins[i].get_yKoo(),tmp_pins[n_idx[i]].get_xKoo(),tmp_pins[n_idx[i]].get_yKoo());
TwoPointNet n_two_PinNet(tmp_pins[i],tmp_pins[n_idx[i]]);
n_two_PinNet.calc_isLocal(origin, tiledim); //calculating: global or local net
if (n_two_PinNet.get_isLocal()){
if(n_two_PinNet.get_first() == n_two_PinNet.get_second()){
if(!(n_two_PinNet.get_first().get_isSteiner() == n_two_PinNet.get_second().get_isSteiner())){
updateSteinerLayer(tmp_pins[i], tmp_pins[n_idx[i]]);
}
} else {
localTwoPointNets.push_back(n_two_PinNet);
}
} else{
globalTwoPointNets.push_back(n_two_PinNet);
}
}
}
void Net::calcNetArea() {
int x_koo_min = MAX_VALUE;
int x_koo_max = 0;
int y_koo_min = MAX_VALUE;
int y_koo_max = 0;
BOOST_FOREACH(Pin curr_pin, pins){
if (curr_pin.get_xKoo() < x_koo_min){
x_koo_min = curr_pin.get_xKoo();
}
if (curr_pin.get_xKoo() > x_koo_max){
x_koo_max = curr_pin.get_xKoo();
}
if (curr_pin.get_yKoo() < y_koo_min){
y_koo_min = curr_pin.get_yKoo();
}
if (curr_pin.get_yKoo() > y_koo_max){
y_koo_max = curr_pin.get_yKoo();
}
}
netArea = calcRectangular(x_koo_min, x_koo_max, y_koo_min, y_koo_max);
}
int Net::calcRectangular(int x_min, int x_max, int y_min, int y_max){
return (x_max - x_min)*(y_max - y_min);
}
//for nets ordering in descending order(area of minimal rect)
bool Net::operator<(Net const& rhs) {
return (netArea > rhs.netArea);
}
list<TwoPointNet> Net::getGlobalOrderedTwoPointNets(){
globalTwoPointNets.sort();
return getGlobalTwoPointNets();
}
list<TwoPointNet> Net::getLocalOrderedTwoPointNets(){
localTwoPointNets.sort();
return getLocalTwoPointNets();
}
void Net::updateSteinerLayer(Pin p_first, Pin p_second){
if(p_first.get_isSteiner()){
vector<Pin>::iterator it;
it = find(steinerPins.begin(), steinerPins.end(), p_first);
it->set_steinerlayer(p_second.get_layer());
} else if(p_second.get_isSteiner()){
vector<Pin>::iterator it;
it = find(steinerPins.begin(), steinerPins.end(), p_second);
it->set_steinerlayer(p_first.get_layer());
} else{
cout << "No Pin/Steiner Net" << endl;
}
}
void Net::updateSteinerLayer(Pin st_pin, int st_lay){
vector<Pin>::iterator it;
it = find(steinerPins.begin(), steinerPins.end(), st_pin);
it->set_steinerlayer(st_lay);
}
<file_sep>/*
* Graph.cpp
*
* Created on: 14.06.2015
* Author: Julia
*/
#include "Graph.hpp"
#include <iostream>
#include <algorithm>
#include <boost/property_map/property_map.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/property_map/transform_value_property_map.hpp>
#include <list>
#include <boost/foreach.hpp>
#define MAX_VAL 429496000 //2^32 -1 = 4294967295
Graph::Graph(std::vector<int> gridxyl, std::vector<int> horicapacity, std::vector<int> vertcapacity, std::vector<int> tiledim) :
gridxyl(gridxyl),horicapacity(horicapacity),vertcapacity(vertcapacity),tiledim(tiledim){
num_nodes = gridxyl[0] * gridxyl[1];
build_edges();
size_t max_node;
boost::partial_sort_copy(
edges | boost::adaptors::transformed([](Edge const* e) -> size_t { return std::max(e->getSource(), e->getTarget()); }),
boost::make_iterator_range(&max_node, &max_node + 1),
std::greater<size_t>());
auto e = edges | boost::adaptors::transformed([](Edge const *ve) { return std::make_pair(ve->getSource(), ve->getTarget()); });
kGraph = graph_t(e.begin(), e.end(), edges.begin(), max_node + 1);
}
std::pair<std::vector<int>, int> Graph::run_dijkstra(std::vector<int> startVerts, std::vector<int> endVerts){
int curr_cost = MAX_VAL;
std::vector<int> path;
BOOST_FOREACH(int startVert, startVerts){
std::pair<std::vector<int>, int> result = run_dijkstra(startVert, endVerts);
int dijk_cost = result.second;
if ((curr_cost > dijk_cost) || ((curr_cost == dijk_cost) && (path.size() > result.first.size()))){
curr_cost = dijk_cost;
path = result.first;
}
}
return std::make_pair(path,curr_cost);
}
std::pair<std::vector<int>, int> Graph::run_dijkstra(int startVert, std::vector<int> endVerts) {
auto kWeightMap = boost::make_transform_value_property_map([](Edge* ve) { return ve->getCost(); },boost::get(boost::edge_bundle, kGraph));
vertex_descriptor kS = vertex(startVert, kGraph);
kP = std::vector<vertex_descriptor>(num_vertices(kGraph));
kD = std::vector<int>(num_vertices(kGraph));
std::set<vertex_descriptor> targs;
std::vector<int> path;
int costs=0;
BOOST_FOREACH(int vert, endVerts){
targs.insert(vertex(vert, kGraph));
}
try {
dijkstra_shortest_paths(kGraph, kS,
predecessor_map(boost::make_iterator_property_map(kP.begin(),
get(boost::vertex_index, kGraph))).distance_map(boost::make_iterator_property_map(kD.begin(), get(boost::vertex_index, kGraph))).visitor(target_visit(targs,boost::on_examine_vertex()))
.weight_map(kWeightMap));
}catch(vertex_descriptor best_targ){
vertex_descriptor current=best_targ;
costs = kD[best_targ];
//std::cout << "BestTarget= " << best_targ << "\n";
//std::cout << "Way: " << best_targ;
while(current!=kS) {
path.push_back(current);
current=kP[current];
//std::cout << "<-" << current;
}
//std::cout << std::endl;
path.push_back(kS);
}
return std::make_pair(path,costs);
}
std::pair<std::vector<int>, int> Graph::run_astar(std::vector<int> startVerts, std::vector<int> endVerts){
int curr_cost = MAX_VAL;
std::vector<int> path;
BOOST_FOREACH(int startVert, startVerts){
std::pair<std::vector<int>, int> result = run_astar(startVert, endVerts);
int dijk_cost = result.second;
if ((curr_cost > dijk_cost) || ((curr_cost == dijk_cost) && (path.size() > result.first.size()))){
curr_cost = dijk_cost;
path = result.first;
}
}
return std::make_pair(path,curr_cost);
}
std::pair<std::vector<int>, int> Graph::run_astar(int startVert, std::vector<int> endVerts){
auto kWeightMap = boost::make_transform_value_property_map([](Edge* ve) { return ve->getCost(); },boost::get(boost::edge_bundle, kGraph));
vertex_descriptor kS = vertex(startVert, kGraph);
kP = std::vector<vertex_descriptor>(num_vertices(kGraph));
kD = std::vector<int>(num_vertices(kGraph));
std::set<vertex_descriptor> targs;
std::vector<int> path;
int costs=0;
BOOST_FOREACH(int vert, endVerts){
targs.insert(vertex(vert, kGraph));
}
try {
// call astar named parameter interface
astar_search
(kGraph,kS,boost::distance_heuristic<graph_t, int>(targs,gridxyl),
predecessor_map(boost::make_iterator_property_map(kP.begin(),get(boost::vertex_index, kGraph))).
distance_map(boost::make_iterator_property_map(kD.begin(), get(boost::vertex_index, kGraph))).
visitor(boost::astar_goal_visitor<vertex_descriptor>(targs)).weight_map(kWeightMap));
}catch(vertex_descriptor best_targ){
vertex_descriptor current=best_targ;
costs = kD[best_targ];
//std::cout << "BestTarget= " << best_targ << "\n";
//std::cout << "Way: " << best_targ;
while(current!=kS) {
path.push_back(current);
current=kP[current];
//std::cout << "<-" << current;
}
//std::cout << std::endl;
path.push_back(kS);
}
return std::make_pair(path,costs);
}
void Graph::linking_steiner(Pin st_pin, std::vector<int> grid, std::vector<int> origin){
if(st_pin.get_steinerlayer().size() != 0){
std::vector<int> path;
int low = *std::next(st_pin.get_steinerlayer().begin(), 0);
int high = *std::next(st_pin.get_steinerlayer().end(), 0);
for(int i = low; i <= high; i++){
st_pin.set_layer(i);
int cell_nmbr = st_pin.calc_cellnumber(grid,origin,tiledim);
path.push_back(cell_nmbr);
}
update_Cost(path);
}
}
void Graph::update_Cost(std::vector<int> path){
for(int i=0;i<(int)path.size()-1;i++){
int id;
id = calc_edgeid(path[i],path[i+1]);
edges[id]->updateCost();
}
}
void Graph::print_path() {
std::cout << "distances and parents:" << std::endl;
boost::graph_traits<graph_t>::vertex_iterator vi, vend;
for (boost::tie(vi, vend) = vertices(kGraph); vi != vend; ++vi) {
std::cout << "distance(" << *vi << ") = " << kD[*vi] << ", ";
std::cout << "parent(" << *vi << ") = " << kP[*vi] << "\n";
}
}
void Graph::build_edges(){
std::vector<int> name;
int id = 0;
for(int lay=0; lay <gridxyl[2]; lay++){
for(int i=0; i< num_nodes; i++){
int curr_nod = i + lay*num_nodes;
name.push_back(curr_nod); //creating all nodes
if (horicapacity[lay] != 0 && ((i+1)%gridxyl[0] != 0)){ // creating all horizontal edges
edges.push_back(new Edge(id,curr_nod, curr_nod+1,horicapacity[lay],false));
if(id != calc_edgeid(curr_nod, curr_nod+1)){
std::cout<< "ID falsch berechnet!" << id << "vs" << calc_edgeid(curr_nod, curr_nod+1) <<std::endl;
}
id++;
}
}
}
for(int lay=0; lay <gridxyl[2]; lay++){ //creating all vertical edges
if (vertcapacity[lay] != 0){
for(int i=0; i< num_nodes; i++){
if(i>=gridxyl[0]){
int curr_nod = i + lay*num_nodes;
edges.push_back(new Edge(id, curr_nod-gridxyl[0], curr_nod, vertcapacity[lay],false));
if(id != calc_edgeid(curr_nod-gridxyl[0], curr_nod)){
std::cout<< "ID falsch berechnet!" << id << "vs" << calc_edgeid(curr_nod-gridxyl[0], curr_nod) <<std::endl;
}
id++;
}
}
}
}
//creating all via edges
for(int i=0; i<(gridxyl[2]-1)*num_nodes; i++){
edges.push_back(new Edge(id, i, i+num_nodes, tiledim[0]*tiledim[1], false));
if(id != calc_edgeid(i, i+num_nodes)){
std::cout<< "ID falsch berechnet!" << id << "vs" << calc_edgeid(i, i+num_nodes) <<std::endl;
}
id++;
}
}
int Graph::calc_edgeid(int first, int second){
int id = -1;
int num_hori = (gridxyl[0]-1) * gridxyl[1] * gridxyl[2]; //number of all horizontal edges
int num_vert = gridxyl[0] * (gridxyl[1]-1) * gridxyl[2]; //number of all vertical edges
if(second < first){//estimating first = min value, second = max value
int var = second;
second = first;
first = var;
}
int lay = first/num_nodes;;
int calib = 0;
if(second == first + 1){ //horizontal edge
for(int l=0; l<lay; l++){
if(horicapacity[l] == 0){
calib = calib + (gridxyl[0]-1) * gridxyl[1];
}
}
id = first - (first / gridxyl[0]) - calib;
} else if (second == first + gridxyl[0]){ //vertical edge
for(int l=0; l<gridxyl[2]; l++){
if(vertcapacity[l] == 0 && l<=lay){
calib = calib + gridxyl[0] * (gridxyl[1]-1);
}
if(horicapacity[l] == 0){
calib = calib + (gridxyl[0]-1) * gridxyl[1];
}
}
id = num_hori + first - lay*gridxyl[0] - calib;
} else if (second == first + num_nodes){ //via edge
for(int l=0; l<gridxyl[2]; l++){
if(vertcapacity[l] == 0){
calib = calib + gridxyl[0] * (gridxyl[1]-1);
}
if(horicapacity[l] == 0){
calib = calib + (gridxyl[0]-1) * gridxyl[1];
}
}
id = num_hori + num_vert + first - calib;
} else{
std::cout << "No valid edge!" << '\n';
}
return id;
}
void Graph::update_capacity(std::vector<Edge> blockages){
BOOST_FOREACH(Edge edge, blockages){
edges[calc_edgeid(edge.getSource(),edge.getTarget())]->updateCost();
}
}
void Graph::calc_wirelengthTotalMaxOverflow(){
std::list<Edge>::iterator edge_it;
BOOST_FOREACH(Edge* edge, edges){
if(max_overflow < edge->getOverflow()){
max_overflow = edge->getOverflow();
}
total_overflow = total_overflow + edge->getOverflow();
wirelength = wirelength + edge->getNumtracks();
}
}
<file_sep>/*
* Net.hpp
*
* Created on: 13.08.2015
* Author: Julia
*/
#ifndef NET_HPP_
#define NET_HPP_
#include <vector>
#include <string>
#include <list>
#include "Pin.hpp"
#include "TwoPointNet.hpp"
#include <boost/foreach.hpp>
//ACHTUNG! TO DO: Bessere Möglichkeit um max Wert zu berechnen!
// Sonst eventll negative Werte -> neg NetArea -> falsche Sortierung
#define MAX_VALUE 429496000 //2^32 -1 = 4294967295
class Net {
private:
std::string netName;
std::vector<Pin> pins;
std::list<TwoPointNet> localTwoPointNets;
std::list<TwoPointNet> globalTwoPointNets;
std::vector<Pin> steinerPins;
int netArea;
public:
Net(std::string NetName);
virtual ~Net();
void addPin(Pin newPin);
int calc_numpins();
void makeRandomTwoPointNet(std::vector<int> tiledim, std::vector<int> origin);
void runflute(const std::vector<int>& tiledim, const std::vector<int>& origin);
std::list<TwoPointNet> getLocalOrderedTwoPointNets();
std::list<TwoPointNet> getGlobalOrderedTwoPointNets();
void calcNetArea();
int calcRectangular(int x_min, int x_max, int y_min, int y_max);
bool operator<(Net const& rhs);
void addSteinerPin(Pin pin);
void updateSteinerLayer(Pin p_first, Pin p_second);
void updateSteinerLayer(Pin st_pin, int st_lay);
std::vector<Pin> getPins() const{return pins;};
std::list<TwoPointNet> getLocalTwoPointNets() const{return localTwoPointNets;};
std::list<TwoPointNet> getGlobalTwoPointNets() {return globalTwoPointNets;};
std::vector<Pin> getSteinerPins() const{return steinerPins;};
};
#endif /* NET_HPP_ */
<file_sep>/*
* Pin.cpp
*
* Created on: 06.07.2015
* Author: Julia
*/
#include "Pin.hpp"
#include <algorithm>
#include <cstdlib>
using namespace std;
// Steiner-Pin Constructor
Pin::Pin(int x, int y) : xKoo(x),yKoo(y){
this->layer = 0;
isSteiner=true;
}
// Normal-Pin Constructor
Pin::Pin(int x, int y, int l) : xKoo(x),yKoo(y),layer(l){
isSteiner=false;
}
int Pin::calc_cellnumber(vector<int> grid, vector<int> origin, vector<int> tiledim){
int xKoo_ = (xKoo - origin[0]) / tiledim[0];
int yKoo_ = (yKoo - origin[1]) / tiledim[1];
return xKoo_ + yKoo_*grid[0] + (layer-1)*grid[0]*grid[1];
}
//Preparation for dijkstra
vector<int> Pin::calc_vec_cellnumber(vector<int> grid, vector<int> origin, vector<int> tiledim){
vector<int> val;
int lim = 0;
if (isSteiner){
lim = grid[2];
layer = 1;
} else {
lim = 1;
}
for(int i = 0; i<lim; i++){
val.push_back(calc_cellnumber(grid, origin, tiledim));
if(isSteiner){
layer++;
}
}
return val;
}
void Pin::set_steinerlayer(int st_lay){
this->steinerlayer.insert(st_lay);
}
void Pin::set_layer(int layer){
this->layer = layer;
}
bool Pin::operator==(const Pin &inp) const{
if(inp.xKoo == this->xKoo && inp.yKoo == this->yKoo){
return true;
} else{
return false;
}
}
bool Pin::operator!=(const Pin &inp) const{
return !(operator==(inp));
}
bool Pin::operator<(const Pin &inp) const{
if(xKoo<inp.xKoo){
if(yKoo<inp.yKoo)
return true;
else
return false;
}else
return false;
}
<file_sep>/*
* Edge.cpp
*
* Created on: 13.08.2015
* Author: Julia
*/
#include "Edge.hpp"
#include <math.h>
#define OF_MAX 10
Edge::Edge(int source, int target, int capacity) : source(source),target(target),capacity(capacity){
this->cost = 1;
this->overflow = 0;
this->numtracks = 0;
this->id = -1; //false initializing to show this value has not been set yet
this->isVia = -1;
}
Edge::Edge(int id, int source, int target, int capacity, bool isVia) : id(id),source(source),target(target),capacity(capacity),isVia(isVia){
this->cost = 1;
this->overflow = 0;
this->numtracks = 0;
}
Edge::~Edge() {}
void Edge::updateCost(){
numtracks++;
if (numtracks <= (0.5*capacity)){
//NO COSTS -> avoiding detours in the beginning
} else if (numtracks > 0.5*capacity && numtracks < capacity){
cost++;
} else if (numtracks >= capacity){
overflow++;
cost = cost*OF_MAX;
}
}
<file_sep>//============================================================================
// Name : main.cpp
// Author : Julia
// Version :
// Copyright : Your copyright notice
// Description : Global Router
//============================================================================
#include "Parser.hpp"
#include "Graph.hpp"
#include "TwoPointNet.hpp"
#include <boost/foreach.hpp>
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
std::vector<std::string> argList;
string algorithm,fileName;
string verbose;
for(int i=0;i<argc;i++)
argList.push_back(argv[i]);
if(argc==3){
fileName=argList[1];
algorithm=argList[2];
verbose="";
}else if(argc==4){
fileName=argList[1];
algorithm=argList[2];
verbose=argList[3];
}else{
algorithm = "dijkstra"; // dijkstra/astar
verbose = ""; // v1
fileName= "config4"; // config1 config2 config 3...
}
cout << "<<<<<<<<<< Using Algorithm: " << algorithm << ">>>>>>>>>>" << endl;
clock_t start;
start = clock();
Parser parse(fileName);
parse.parseConfig();
cout << "ParseZeit: " << (clock() - start) / (double) CLOCKS_PER_SEC << '\n';
Graph graph(parse.getGrid(), parse.getHoriCap(), parse.getVertCap(), parse.getTiledim());
cout << "BuildZeit: " << (clock() - start) / (double) CLOCKS_PER_SEC << '\n';
graph.update_capacity(parse.getBlockages());
cout << "UpdateCapacityZeit: " << (clock() - start) / (double) CLOCKS_PER_SEC << '\n';
list<Net> nets = parse.getNetsOrderedByMR();
pair<std::vector<int>, int> result;
int gesamtKosten=0;
BOOST_FOREACH(Net net, nets){
list<TwoPointNet> g_nets = net.getGlobalOrderedTwoPointNets();
BOOST_FOREACH(TwoPointNet tpnet, g_nets){
vector<int> start = tpnet.get_first().calc_vec_cellnumber(parse.getGrid(),parse.getOrigin(),parse.getTiledim());
vector<int> finish = tpnet.get_second().calc_vec_cellnumber(parse.getGrid(),parse.getOrigin(),parse.getTiledim());
if(verbose=="v1"){
std::stringstream string_start,string_finish;
std::copy(start.begin(), start.end(), std::ostream_iterator<int>(string_start, " "));
std::copy(finish.begin(), finish.end(), std::ostream_iterator<int>(string_finish, " "));
cout << "NEW TWOPINNET: start ->" << string_start.str().c_str() << " finish ->" << string_finish.str().c_str() << endl;
}
if(algorithm=="dijkstra"){
result = graph.run_dijkstra(start,finish);
} else if(algorithm=="astar") {
result = graph.run_astar(start,finish);
}
if(verbose=="v1"){
std::stringstream result_path;
std::copy(result.first.begin(), result.first.end(), std::ostream_iterator<int>(result_path, " "));
cout << "Shortest Way: " << result_path.str().c_str() << endl;
}
gesamtKosten=gesamtKosten+result.second;
graph.update_Cost(result.first);
if(tpnet.get_first().get_isSteiner()){
net.updateSteinerLayer(tpnet.get_first(),result.first.back()/(parse.getGridX()*parse.getGridY())+1);
}
if(tpnet.get_second().get_isSteiner()){
net.updateSteinerLayer(tpnet.get_second(),result.first.front()/(parse.getGridX()*parse.getGridY())+1);
}
}
//connecting all steinerpins
BOOST_FOREACH(Pin pin, net.getSteinerPins()){
graph.linking_steiner(pin, parse.getGrid(), parse.getOrigin());
}
}
cout << "AlgoZeit: " << (clock() - start) / (double) CLOCKS_PER_SEC << '\n';
cout << "GesamtKosten: " << gesamtKosten << endl;
graph.calc_wirelengthTotalMaxOverflow();
cout << "Totaler Overflow: " << graph.getTotalOverflow() << endl;
cout << "Wirelength: " << graph.getWirelength() << endl;
return 0;
}
<file_sep>/*
* Parser.cpp
*
* Created on: 13.08.2015
* Author: Julia
*/
#include "Parser.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include "flute.h"
#define VERBOSE 0
Parser::Parser(string fileName) : fileName(fileName), nmbrBlockages(-1) {
// nothing to-do
}
Parser::~Parser() {}
void Parser::parseConfig(){
int block=0;
ifstream file;
file.open(fileName.c_str());
if(!file) {
cout << "File not found" << endl;
exit(EXIT_FAILURE);
}
string line;
int lineNmbr=0;
bool isReadLUT = false;
while(getline(file, line)) {
lineNmbr++;
if(!line.length()){
block++;
if (block == 1 && !isReadLUT){
readLUT();
isReadLUT = true;
}
if(VERBOSE>-1)
cout << "--Next Block--: Line: " << lineNmbr << endl;
continue; //skip empty lines
}
string first,second;
std::stringstream parse(line);
if (block==0) {
while (parse >> first){
if(first=="grid"){
parse >> gX >> gY >> nL;
grid=vector<int>{gX,gY,nL};
if(VERBOSE>0)
cout << gX << "," << gY << "," << nL << endl;
}else if(first=="vertical" || first=="horizontal" || first=="minimum" || first=="via"){
parse >> second;
int nmbr;
while(parse >> nmbr){
if(first=="vertical" && second=="capacity")
vertCap.push_back(nmbr);
if(first=="horizontal" && second=="capacity")
horiCap.push_back(nmbr);
if(first=="minimum" && second=="width")
minW.push_back(nmbr);
if(first=="minimum" && second=="spacing")
minS.push_back(nmbr);
if(first=="via" && second=="spacing")
viaS.push_back(nmbr);
if(VERBOSE>0)
cout << nmbr << ",";
}
if(VERBOSE>0)
cout << endl;
}else{
int sizeX, sizeY,origX,origY;
origX=stoi(first);
parse >> origY >> sizeX >> sizeY;
origin.push_back(origX);origin.push_back(origY);
tiledim.push_back(sizeX);tiledim.push_back(sizeY);
if(VERBOSE>0)
cout << origX << "," << origY << "," << sizeX << "," << sizeY << endl;
}
}
}else if(block==1){
while (parse >> first){
parse >> second;
if(first=="num" && second=="net"){
parse >> nmbrNet;
if(VERBOSE>0)
cout << nmbrNet << endl;
}else if(first[0]=='n'){
int nmbrPins,iLayer;
parse >> nmbrPins >> iLayer;
if(VERBOSE>1)
cout << "NewNet: " << second << "," << nmbrPins << "," << iLayer << endl;
Net newNet(second);
int x,y,l;
for(int iPin=0;iPin<nmbrPins;iPin++){
getline(file, line);
lineNmbr++;
std::stringstream parsePinKords(line);
parsePinKords >> x >> y >> l;
Pin newPin(x,y,l);
newNet.addPin(newPin);
if(VERBOSE>2)
cout << newPin.get_xKoo() << "," << newPin.get_yKoo() << "," << newPin.get_layer() << endl;
}
newNet.runflute(getTiledim(), getOrigin());
//newNet.makeRandomTwoPointNet(getTiledim(), getOrigin());
nets.push_back(newNet);
}
}
}else if(block==3){
// BlockadeHeader
parse >> nmbrBlockages;
block++;
}else if(block==4){
// BlockageBody
int node1_x, node1_y, node1_l, node2_x, node2_y, node2_l,capacity;
parse >> node1_x >> node1_y >> node1_l >> node2_x >> node2_y >> node2_l >> capacity;
Edge newEdge(node1_x+node1_y*gX+node1_l*gX*nL,node2_x+node2_y*gX+node2_l*gX*nL,capacity); // GraphNodesValue
blockages.push_back(newEdge);
if(VERBOSE>2)
cout << node1_x << "," << node1_y << "," << node1_l << "," << node2_x << "," << node2_y << "," << node2_l << "," << capacity << endl;
}
}
if (VERBOSE>-1)
cout << nmbrNet << "-> Nets Defined and Parsed <-"<< nets.size() << endl;
if (VERBOSE>-1)
cout << nmbrBlockages << "-> Blockages Defined and Parsed <-" << blockages.size() << endl;
file.close();
}
list<Net> Parser::getNetsOrderedByMR(){
nets.sort();
return getNets();
}
<file_sep>/*
* Pin.hpp
*
* Created on: 06.07.2015
* Author: Julia
*/
#ifndef PIN_HPP_
#define PIN_HPP_
#include <vector>
#include <set>
class Pin{
private:
int xKoo,yKoo,layer;
bool isSteiner;
std::set<int> steinerlayer;
public:
Pin() = default;
Pin(int x, int y);
Pin(int x, int y, int l);
int calc_cellnumber(std::vector<int> grid, std::vector<int> origin, std::vector<int> tiledim);
std::vector<int> calc_vec_cellnumber(std::vector<int> grid, std::vector<int> origin, std::vector<int> tiledim);
int get_xKoo() const {return xKoo;};
int get_yKoo() const {return yKoo;};
int get_layer() const {return layer;};
bool get_isSteiner() const{return isSteiner;};
std::set<int> get_steinerlayer() {return steinerlayer;};
void set_steinerlayer(int st_lay);
void set_layer(int layer);
bool operator==(const Pin &inp) const;
bool operator!=(const Pin &inp) const;
bool operator<(const Pin &inp) const;
};
#endif /* PIN_HPP_ */
<file_sep>/*
* Graph.hpp
*
* Created on: 15.06.2015
* Author: Julia
*/
#ifndef GRAPH_HPP_
#define GRAPH_HPP_
#include "Edge.hpp"
#include "Pin.hpp"
#include <vector>
#include <utility>
#include <iostream>
#include <boost/config.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/astar_search.hpp>
namespace boost{
// ASTAR
// euclidean distance heuristic
template <class Graph, class CostType>
class distance_heuristic : public astar_heuristic<Graph, CostType>
{
public:
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
distance_heuristic(const std::set<Vertex>& targets, std::vector<int> grid)
: targets(targets), grid(grid) {}
CostType operator()(Vertex u)
{
CostType dl = 0;
CostType dx = abs( u - *(targets.begin()) ) % grid[0];
CostType dy = ( abs( u - *(targets.begin()) ) % (grid[0]*grid[1]) )/ grid[0];
if(targets.size() == 1){
dl = abs(u - *(targets.begin())) / (grid[0]*grid[1]);
}
return (dx + dy + dl)*(dx + dy + dl);
}
private:
std::set<Vertex> targets;
std::vector<int> grid;
};
// A star visitor that terminates when reaching goal
template <class Vertex>
class astar_goal_visitor : public boost::default_astar_visitor
{
public:
astar_goal_visitor(const std::set<Vertex>& targets) : targets(targets) { }
template <class Graph>
void examine_vertex(Vertex v, Graph& g)
{
if(targets.find(v) != targets.end())
{
throw(v);
}
}
private:
std::set<Vertex> targets;
};
// START visitor
template <class Vertex, class Tag>
struct target_visitor : public default_dijkstra_visitor
{
target_visitor(const std::set<Vertex>& targets) : targets(targets) { }
template <class Graph>
void examine_vertex(Vertex v, Graph& g)
{
if(targets.find(v) != targets.end())
{
throw(v);
}
}
private:
std::set<Vertex> targets;
};
template <class Vertex, class Tag>
target_visitor<Vertex, Tag>
target_visit(const std::set<Vertex>& targets, Tag)
{
return target_visitor<Vertex, Tag>(targets);
}
// ENDE visitor
}
typedef boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS, boost::no_property, Edge*> graph_t;
typedef boost::graph_traits<graph_t>::vertex_descriptor vertex_descriptor;
typedef boost::graph_traits<graph_t>::edge_descriptor edge_descriptor;
class Graph {
public:
Graph(std::vector<int> gridxyl, std::vector<int> horicapacity, std::vector<int> vertcapacity, std::vector<int> tiledim);
~Graph() {
while(!edges.empty()) delete edges.back(), edges.pop_back();
}
std::pair<std::vector<int>, int> run_dijkstra(int startVert, std::vector<int> endVerts);
std::pair<std::vector<int>, int> run_dijkstra(std::vector<int> startVerts, std::vector<int> endVerts);
void linking_steiner(Pin st_pin, std::vector<int> grid, std::vector<int> origin);
void calc_wirelengthTotalMaxOverflow();
std::pair<std::vector<int>, int> run_astar(int startVert, std::vector<int> endVerts);
std::pair<std::vector<int>, int> run_astar(std::vector<int> startVerts, std::vector<int> endVerts);
void print_path();
void build_edges();
int calc_edgeid(int first, int second);
void update_capacity(std::vector<Edge> blockages);
void update_Cost(std::vector<int> path);
int getTotalOverflow() const{return total_overflow;};
int getMaxOverflow() const{return max_overflow;};
int getWirelength() const{return wirelength;};
private:
graph_t kGraph;
std::vector<int> kD;
std::vector<vertex_descriptor> kP;
std::vector<Edge*> edges;
std::vector<int> gridxyl;
std::vector<int> horicapacity;
std::vector<int> vertcapacity;
std::vector<int> tiledim;
int num_nodes; //number of all nodes in ONE layer
int wirelength = 0;
int total_overflow = 0;
int max_overflow = 0;
};
#endif /* GRAPH_HPP_ */
| 1fdb4242e15d49c77a03ef6902507dccaba847bd | [
"Makefile",
"C++"
] | 14 | Makefile | JuliaKristin/RCE | 4db1869f7a36237884d411c4bc6d1b9d183e21eb | b0c0456741f32da3f401ebfcdca7f4ec366fcb4d |
refs/heads/master | <file_sep>var myRouter = Backbone.Router.extend({
personalInfoView: null,
addressInfoView: null,
displayDetailsView: null,
initialize: function() {
this.personalInfo = new PersonalInfoModel();
},
routes: {
"": "showPersonalInfoPage",
"home": "showPersonalInfoPage",
"addressInfo": "showAddressInfoPage",
"displayDetails": "showDetailsPage",
"*actions": "handleInvalidRoutes"
},
showPersonalInfoPage: function() {
if (this.personalInfoView == null) {
this.personalInfoView = new View1({
model: this.personalInfo
});
}
this.personalInfoView.render();
},
showAddressInfoPage: function() {
if (this.addressInfoView == null) {
this.addressInfoView = new View2({
model: this.personalInfo
});
}
this.addressInfoView.render();
},
showDetailsPage: function() {
if (this.displayDetailsView == null) {
this.displayDetailsView = new View3({
model: this.personalInfo
});
}
this.displayDetailsView.render();
},
handleInvalidRoutes: function() {
alert("Page not available, so redirecting to home page");
this.navigate('home', {trigger: true});
}
});<file_sep>var View1 = Backbone.View.extend({
el: "#rAppContainer",
initialize: function() {
this.render();
},
events: {
"input input": "updateModel"
},
render: function() {
var template = _.template($('#personalInfoTemplate').html());
this.$el.html(template());
return this;
},
updateModel: function(e) {
var $elem = $(e.currentTarget);
if ($elem.val() && $elem.val().trim() !== "") {
value = $elem.val();
}
var modelAttribute = $elem.attr("name");
this.model.set(modelAttribute, value);
}
});
var View2 = Backbone.View.extend({
el: "#rAppContainer",
initialize: function() {
this.render();
},
events: {
"input input": "updateModel"
},
render: function() {
var template = _.template($('#addressTemplate').html());
this.$el.html(template());
return this;
},
updateModel: function(e) {
var $elem = $(e.currentTarget);
if ($elem.val() && $elem.val().trim() !== "") {
value = $elem.val();
}
var modelAttribute = $elem.attr("name");
this.model.set(modelAttribute, value);
}
});
var View3 = Backbone.View.extend({
el: "#rAppContainer",
initialize: function() {
this.render();
},
render: function() {
var template = _.template($('#infoDisplayTemplate').html());
this.$el.html(template(this.model.attributes));
return this;
}
});
| 01fcb6210174f771121ac1f1311ca0054b713c47 | [
"JavaScript"
] | 2 | JavaScript | Sindhura04/BackboneTest | dbfe43b99522d4023e538b6ab9b80d7986cfca28 | 7606c121a8027b19175d98bb3b53e39752298c76 |
refs/heads/master | <file_sep># Fail2Ban
## Installation
```bash
apt-get install fail2ban
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
```
## Configuration
### /etc/fail2ban/jail.local
```
[ssh]
enabled = true
# Replace port with your SSH port
port = 2211
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 900
[ssh-ddos]
enabled = true
# Replace port with your SSH port
port = 2211
filter = sshd-ddos
logpath = /var/log/auth.log
maxretry = 6
```<file_sep># Summary
* [Introduction](README.md)
* [Tools](tools.md)
* [OpenSSH](openssh.md)
* [IPtables](iptables.md)
* [Fail2Ban](fail2ban.md)
* [BTSync](btsync.md)
* [ACL support](acl.md)
* [Everyday User](everyday_user.md)
* [Savestream](savestream.md)
* [Dotdeb Repository](dotdeb.md)
* [NGiNX](nginx.md)
* [jinnai.de](nginx/jinnai.md)
<file_sep># Savestream
## Requirements
[Everyday user](everyday_user.md)
[ACL Support](acl.md)
[BitTorrent Sync](btsync.md)
## Installation
Install required software for the script to work properly.
```bash
apt-get install rtmpdump
apt-get install virtualenv
```
Create a folder where the streams will be saved and set permissions.
```bash
su - btsync
mkdir stream
# Make sure user btsync can always delete objects in folder
setfacl -dm u:btsync:rwx stream/
# Allow user michael to read and write to folder
# --x is required to traverse into directory
setfacl -m u:michael:rwx stream/
```
Create virtualenv with livestreamer
```bash
cd /home/michael/
# Create virtual environment
virtualenv livestreamer
# Enter virtual environment
source livestreamer/bin/activate
# Install livestreamer
pip install livestreamer
# Leave virtual environment
deactivate
```
Install savestream.sh
```bash
# Upload savestream.sh via SCP and move it to /home/michael/savestream.sh
chown michael:michael ~michael/savestream.sh
chmod u+x savestream.sh
# Edit savestream.sh to match environment
# STREAMDIR=/srv/btsync/stream/
# LIVESTREAMER=/home/michael/livestreamer/bin/livestreamer
```
## Configuration
### /srv/btsync/btsync.conf
Add the following configuration to the BitTorrent Sync configuration file.
```json
"shared_folders" :
[
{
"secret" : "[redacted]", // required field - use --generate-secret in command line to create new secret
"dir" : "/srv/btsync/stream", // * required field
"use_relay_server" : true, // use relay server when direct connection fails
"use_tracker" : true,
"search_lan" : false,
"use_sync_trash" : false, // enable SyncArchive to store files deleted on remote devices
"overwrite_changes" : false, // restore modified files to original version, ONLY for Read-Only folders
"known_hosts" : // specify hosts to attempt connection without additional search
[
]
}/* , */
]
```
### crontab
Edit crontab of user michael with ```crontab -e```
```
* 14-20 * * 1 /bin/bash /home/michael/savestream.sh twitch bobross > /dev/null
* * * * * /bin/bash /home/michael/savestream.sh twitch helblinde > /dev/null
* 18-23 * * * /bin/bash /home/michael/savestream.sh rtmp nanaone > /dev/null
* * * * * /bin/bash /home/michael/savestream.sh twitch nanaonelive > /dev/null
```<file_sep># OpenSSH
## Installation
```bash
apt-get install openssh-server
```
## Configuration
### /etc/ssh/sshd_config
See also: [SSH Config](https://stribika.github.io/2015/01/04/secure-secure-shell.html)
```
# Package generated configuration file
# See the sshd_config(5) manpage for details
# What ports, IPs and protocols we listen for
Port 2211
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes
KexAlgorithms <EMAIL>25519-sha256<EMAIL>,diffie-hellman-group-exchange-sha256
Ciphers <EMAIL>20-<EMAIL>30<EMAIL>,<EMAIL>,<EMAIL>,aes256-ctr,aes192-ctr,aes128-ctr
MACs <EMAIL>-sha2-512-et<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL>,hmac-sha2-512,hmac-sha2-256,hmac-ripemd160,<EMAIL>
# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 1024
# Logging
SyslogFacility AUTH
LogLevel INFO
# Authentication:
LoginGraceTime 120
PermitRootLogin without-password
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile %h/.ssh/authorized_keys
# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes
# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no
# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no
# Change to no to disable tunnelled clear text passwords
PasswordAuthentication no
# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no
#MaxStartups 10:30:60
#Banner /etc/issue.net
# Allow client to pass locale environment variables
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication. Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes
# Allow only root to login
AllowUsers root
```
### /root/.ssh/authorized_keys
```
ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQBXEdrVrPzaUfhqXwAHL9bPsjikhGYiJyUNn1DE++nzm+K0t+Nm0BHldVDmqFD88XE00It+L/b+iJSkgIxGniDf0SHsZCANHzO3JewVoskmIIUI9IW4YXRjA6MtNnszGONZrHaGF1Vpv/bpVMO94pUu20VZ+Z6duZl9tMQ7kmfVyg+mK2DaDw7QooUrcHHtagucOPcdXJuP40PT3zC62MA1gvshOJO68gMBh97ewT6JZGa4jTilAwq170fb6nVVQl710ksSJbCL4NkY5srDhm6J5A7ruhiVyptM5QD+H0zxJ5Xhn8VE4Ymz08A7wKuDNWYUAdQpZkEhWyiFgZrSG9Gn michael@home
ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAgEArpmL0CceZHpNqJrjUM98Oji9cgZ5oEJcHYcM4Ryu6P7wJVLqLWlm/c3y3quVEKAN3/rLeTfIBKCAWWzhgWmB9EucvIzxQ1r2kaJaNn41YUt8QNqn8fUl3cXKHI6G13bsWTJErEGuCXKjiXmldIWL69AUP4D9n6gatbziyC6Z//YHIUVVXrTedFKlXu+zyGYRK8d6cq/cVEee7CX6NEVBK4uA/Z3t3qjE1lrrqDYPlmsT2S3rTdt8Bz23/8EyoIOW78ZFmnFN7Ccl5dyOMHPL6nDnxpgf8sT3e0OV5FT8+K4k7ylnjWnIY+Kif8gKRlClbcp0oVrlmpvctwddUs3ic6ZGI0s4YY04V/SbSofli1JcppgDvvyxJoF894HY<KEY>= michael@andorid
```<file_sep># ACL support
```bash
# Check, if filesystem has acl support enabled
# If not, add acl to /etc/fstab mount options
#
# Sample output:
# tune2fs 1.42.12 (29-Aug-2014)
# Filesystem volume name: <none>
# Last mounted on: /
# Filesystem UUID: 936eb0be-512f-42e9-8f63-eb99b199e688
# […]
# Default mount options: user_xattr acl #<-- !
# Filesystem state: clean
# […]
tune2fs -l /dev/sda1
# Check, if ACL tools are installed
# If not, install with apt-get install acl
#
# Sample output:
# ii acl 2.2.52-2 amd64 Access control list utilities
dpkg --list | grep acl
```<file_sep># Jinnai.de
## Installation
```
# apps.jinnai.de
mkdir -p /srv/www/de.jinnai.apps/html
# apps.jinnai.de/az
mkdir -p /srv/www/de.jinnai.apps/html/az
# Move Appfiles to /srv/www/de.jinnai.apps/html/az
chown -R www-data:www-data /srv/www/de.jinnai.apps
ln -s /etc/nginx/sites-available/jinnai.de /etc/nginx/sites-enabled/jinnai.de
service nginx restart
```
## Configuration
### /etc/nginx/sites-available/jinnai.de
```
#
## apps.jinnai.de
#
server {
listen 80;
server_name apps.jinnai.de;
root /srv/www/de.jinnai.apps/html;
index index.html;
}
```<file_sep># BTSync
## Installation
```bash
adduser --system --home /srv/btsync --shell /bin/bash --group btsync
su - btsync
wget https://download-cdn.getsync.com/stable/linux-x64/BitTorrent-Sync_x64.tar.gz
tar -xvf BitTorrent-Sync_x64.tar.gz
rm LICENSE.TXT README BitTorrent-Sync_x64.tar.gz
# --> Provide btsync.conf
mkdir /srv/btsync/.sync
# --> Provide Init-Script
chmod +x /etc/init.d/btsync
update-rc.d btsync defaults
```
## Configuration
### /srv/btsync/btsync.conf
```json
{
"device_name": "VM-LNX-vServer",
"listening_port" : 8887, // 0 - randomize port
/* storage_path dir contains auxilliary app files */
"storage_path" : "/srv/btsync/.sync",
/* set location of pid file */
"pid_file" : "/srv/btsync/btsync.pid",
/* use UPnP for port mapping */
"use_upnp" : true,
/* limits in kB/s. 0 - no limit */
"download_limit" : 0,
"upload_limit" : 0,
/* Advanced options
See also: http://help.getsync.com/hc/en-us/articles/207371636-Power-user-preferences */
"send_statistics" : false,
"disk_low_priority" : true,
"net.allow_lan_connections" : false
}
```
### /etc/init.d/btsync
```bash
#!/bin/sh
### BEGIN INIT INFO
# Provides: btsync
# Required-Start: $local_fs $network
# Required-Stop: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: BitTorrent Sync
# Description: BitTorrent Sync daemon
### END INIT INFO
# Required files
ROOT=/srv/btsync
EXEC=${ROOT}/btsync
CONF=${ROOT}/btsync.conf
PID=${ROOT}/btsync.pid
# User / Group to be used for the process
USER=btsync
GROUP=btsync
start() {
echo "Starting BitTorrent Sync..."
start-stop-daemon --exec ${EXEC} --pidfile ${PID} \
--start --chuid btsync:btsync \
-- --config ${CONF}
}
stop() {
echo "Stopping BitTorrent Sync..."
start-stop-daemon --exec ${EXEC} --pidfile ${PID} \
--stop --remove-pidfile
}
status() {
start-stop-daemon --exec ${EXEC} --pidfile ${PID} \
--status
if [ $? -eq 0 ]; then
echo "BitTorrent Sync is running with PID $(cat ${PID})"
else
echo "BitTorrent Sync is not running!"
fi
}
case "$1" in
start|stop|status)
$1
;;
*)
echo "Usage: $0 {start|stop|status}"
exit 1
;;
esac
```<file_sep># IPtables
## Installation
```bash
apt-get install iptables
apt-get install iptables-persistent
```
![rules.v4](img/iptables_install-1.png)
![rules.v6](img/iptables_install-2.png)
## Configuration
### /etc/iptables/rules.v4
```
# Generated by iptables-save v1.4.21 on Sat Mar 5 16:09:10 2016
*filter
:INPUT DROP [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [482:253368]
# SSH public key auth
-A INPUT -m conntrack --ctstate ESTABLISHED -j ACCEPT
# SSH
-A INPUT -p tcp -m tcp --dport 2211 -j ACCEPT
# HTTP
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
# Reject all other
-A INPUT -j REJECT --reject-with icmp-port-unreachable
COMMIT
# Completed on Sat Mar 5 16:09:10 2016
```<file_sep>
# vServer Documentation
Hosted server configuration with a focus on security and manageability.
Based on Debian 8.3 (Jessie)
<file_sep># Dotdeb Repository
## Installation
Add the following to _/etc/apt/sources.list_
```
deb http://packages.dotdeb.org jessie all
deb-src http://packages.dotdeb.org jessie all
```
Install GPG-Key
```bash
wget https://www.dotdeb.org/dotdeb.gpg
sudo apt-key add dotdeb.gpg
apt-get update
```
<file_sep># Tools
## Vim
### Installation
```bash
apt-get install vim
```
### ~/.vimrc
```
syntax on
set number
set tabstop=4 expandtab
set shiftwidth=4
colorscheme pablo
set encoding=utf-8
```
<file_sep># Everyday User
Create a unprivileged user for everyday work.
```bash
adduser michael
``` | 57e5cda70356fc1dc75d67ae574c19c68deb9e0b | [
"Markdown"
] | 12 | Markdown | mr-bigbang/vserver-doc | 6f069ef4f325d10db76dd145a18d432fe6084065 | 9d0f6997536792ab4108de7992f48304a1633678 |
refs/heads/master | <file_sep><%@ Page Title="" Language="C#" MasterPageFile="~/shopping.Master" AutoEventWireup="true" CodeBehind="home.aspx.cs" Inherits="FINALPROJECT_shoppingCart_.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<style type="text/css">
.auto-style1 {
font-size: large;
text-decoration: underline;
color: #3333FF;
}
.auto-style2 {
text-align: right;
}
.auto-style3 {
width: 100%;
height: 65px;
}
.auto-style4 {
height: 29px;
text-align: left;
}
.auto-style5 {
width: 100%;
}
.auto-style6 {
text-align: center;
}
.auto-style7 {
text-align: center;
height: 31px;
}
.auto-style8 {
text-align: left;
height: 284px;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="auto-style2">
<strong><span class="auto-style1">
<table class="auto-style5" style="font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; font-size: medium; color: #0033CC">
<tr>
<td class="auto-style4">
<asp:Label ID="welcome2" runat="server"></asp:Label>
<asp:LinkButton ID="LinkButton5" runat="server" OnClick="LinkButton5_Click">Login</asp:LinkButton>
<asp:LinkButton ID="LinkButton6" runat="server" OnClick="LinkButton6_Click">Sign Out</asp:LinkButton>
You have
<asp:Label ID="Label8" runat="server" Text="0"></asp:Label>
products in Cart
<asp:LinkButton ID="LinkButton7" runat="server" OnClick="LinkButton7_Click">View Cart</asp:LinkButton>
</td>
</tr>
</table>
<em> <br />
</em>
<table class="auto-style3">
<tr>
<td class="auto-style4" style="background-color: #33CCFF; font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; color: #000099;">Product Categories :
<asp:LinkButton ID="LinkButton1" runat="server" ForeColor="#000099" OnClick="LinkButton1_Click">Laptops</asp:LinkButton>
| <strong><span class="auto-style1" style="color: #000099">
<asp:LinkButton ID="LinkButton2" runat="server" ForeColor="#000099" OnClick="LinkButton2_Click">Gaming Consoles</asp:LinkButton>
| <span class="auto-style1">
<asp:LinkButton ID="LinkButton3" runat="server" ForeColor="#000099" OnClick="LinkButton3_Click">Mobiles</asp:LinkButton>
|
<asp:LinkButton ID="LinkButton4" runat="server" ForeColor="#000099" OnClick="LinkButton4_Click">View All Products</asp:LinkButton>
</span></span></strong></span></strong></td>
</tr>
</table>
<br />
<br />
<asp:DataList ID="DataList1" runat="server" DataKeyField="item_Id" DataSourceID="SqlDataSource1" Height="497px" OnItemCommand="DataList1_ItemCommand" OnSelectedIndexChanged="DataList1_SelectedIndexChanged" RepeatColumns="4" RepeatDirection="Horizontal" Width="1170px">
<ItemTemplate>
<table border="1" class="auto-style5" style="font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; font-size: small; background-color: #99CCFF; color: #000099;">
<tr>
<td class="auto-style6">Product ID :
<asp:Label ID="Label9" runat="server" Text='<%# Eval("item_Id") %>'></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style6">
<asp:Label ID="Label7" runat="server" Font-Bold="True" Font-Size="Medium" ForeColor="#000099" Text=" "></asp:Label>
<asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Size="Large" Text='<%# Eval("item_name") %>'></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style6">
<asp:Image ID="Image2" runat="server" Height="215px" ImageUrl='<%# Eval("image") %>' Width="284px" />
</td>
</tr>
<tr>
<td class="auto-style6"> <asp:Label ID="Label5" runat="server" Font-Bold="True" Font-Size="Medium" ForeColor="#000099" Text="Price :"></asp:Label>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("price") %>'></asp:Label>
$</td>
</tr>
<tr>
<td class="auto-style8">
<br />
<asp:Label ID="Label6" runat="server" Font-Bold="True" Font-Size="Medium" ForeColor="#000099" Text="Description :"></asp:Label>
<asp:Label ID="Label4" runat="server" Font-Bold="False" Font-Size="Small" Font-Underline="False" ForeColor="#003300" Text='<%# Eval("description") %>'></asp:Label>
</td>
</tr>
<tr>
<td class="auto-style7">
<asp:ImageButton ID="ImageButton1" runat="server" CommandArgument='<%# Eval("item_id")%>' Height="50px" ImageUrl="~/Images/add.png" OnClick="ImageButton1_Click" Width="100px" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RegistrationConnectionString %>" SelectCommand="SELECT * FROM [item]"></asp:SqlDataSource>
<br />
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:RegistrationConnectionString %>" OnSelecting="SqlDataSource2_Selecting" SelectCommand="SELECT * FROM [item] WHERE ([category_Id] = @category_Id)">
<SelectParameters>
<asp:QueryStringParameter Name="category_Id" QueryStringField="category" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<br />
</div>
</span></strong>
</asp:Content>
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FINALPROJECT_shoppingCart_
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["New"] != null)
{
welcome2.Text = "Welcome, " + Session["New"].ToString();
LinkButton5.Visible = false;
}
else
{
Response.Redirect("Login.aspx");
}
if (Request.QueryString["category"] != null)
{
DataList1.DataSourceID = null;
DataList1.DataSource = SqlDataSource2;
DataList1.DataBind();
}
DataTable dt = new DataTable();
dt = (DataTable)Session["cart"];
if (dt != null)
{
Label8.Text = dt.Rows.Count.ToString();
}
else
{
Label8.Text = "0";
}
}
protected void btnLogout_Click(object sender, EventArgs e)
{
Session["New"] = null;
Response.Redirect("Login.aspx");
}
protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void LinkButton4_Click(object sender, EventArgs e)
{
DataList1.DataSourceID = null;
DataList1.DataSource = SqlDataSource1;
DataList1.DataBind();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Response.Redirect("home.aspx?category=2");
}
protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Response.Redirect("home.aspx?category=3");
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
Response.Redirect("home.aspx?category=1");
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
}
protected void LinkButton6_Click(object sender, EventArgs e)
{
Session.Abandon();
Response.Redirect("Login.aspx");
}
protected void LinkButton5_Click(object sender, EventArgs e)
{
Response.Redirect("Login.aspx");
}
protected void LinkButton7_Click(object sender, EventArgs e)
{
Response.Redirect("AddToCart.aspx");
}
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
Response.Redirect("AddtoCart.aspx?id=" + e.CommandArgument.ToString() + "&quantity=1");
}
}
}<file_sep><%@ Page Title="" Language="C#" MasterPageFile="~/shopping.Master" AutoEventWireup="true" CodeBehind="CheckOut.aspx.cs" Inherits="FINALPROJECT_shoppingCart_.CheckOut" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Label ID="lblCartEmpty" runat="server" Font-Bold="True" ForeColor="Red" Text="Please add items to cart." Visible="False"></asp:Label>
<br />
<asp:Label ID="lblbeforeTax" runat="server" Text="Total Price"></asp:Label>
:
<asp:TextBox ID="txtBeforeTax" runat="server" ReadOnly="True"></asp:TextBox>
<br />
<asp:Label ID="lblTax" runat="server" Text="Tax"></asp:Label>
:
<asp:TextBox ID="txtTax" runat="server" ReadOnly="True"></asp:TextBox>
<br />
<asp:Label ID="lblAfterTax" runat="server" Text="Net Price"></asp:Label>
:
<asp:TextBox ID="txtAfterTax" runat="server" ReadOnly="True"></asp:TextBox>
<br />
<br />
<asp:Label ID="lblPay" runat="server" Text="Payment Information"></asp:Label>
<br />
<br />
<asp:Label ID="lblcardHolderName" runat="server" Text="Card Holder Name: "></asp:Label>
<asp:TextBox ID="txtCardHolderName" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="rqdvalCardName" runat="server" ControlToValidate="txtCardHolderName" Display="Dynamic" ErrorMessage="Please enter Card Holder Name." Font-Bold="True" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="cmpValName" runat="server" ControlToValidate="txtCardHolderName" Display="Dynamic" ErrorMessage="Please enter valid name." Font-Bold="True" ForeColor="Red" Operator="DataTypeCheck" SetFocusOnError="True" Enabled="False"></asp:CompareValidator>
<br />
<asp:Label ID="lblCardNumber" runat="server" Text="Card Number: "></asp:Label>
<asp:TextBox ID="txtCardNumber" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="rqdvalCardNumber" runat="server" ControlToValidate="txtCardNumber" Display="Dynamic" ErrorMessage="Please enter Card Number." Font-Bold="True" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="cmpValCardNumber" runat="server" ControlToValidate="txtCardNumber" Enabled="False" ErrorMessage="Please enter a valid card number." Font-Bold="True" ForeColor="Red" Operator="DataTypeCheck" Type="Integer"></asp:CompareValidator>
<br />
<asp:Label ID="lblCCV" runat="server" Text="Security Code: "></asp:Label>
<asp:TextBox ID="txtSecCode" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="rqdValSecCode" runat="server" ControlToValidate="txtSecCode" Display="Dynamic" ErrorMessage="Please enter Security Code." Font-Bold="True" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="cmpValSecCode" runat="server" ControlToValidate="txtSecCode" Enabled="False" ErrorMessage="Please enter a valid security code." Font-Bold="True" ForeColor="Red" Operator="DataTypeCheck" Type="Integer"></asp:CompareValidator>
<br />
<asp:Label ID="lblExpiryDate" runat="server" Text="Expiry Date: "></asp:Label>
<asp:TextBox ID="txtExpiryDate" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="rqdValExpiryDAte" runat="server" ControlToValidate="txtExpiryDate" Display="Dynamic" ErrorMessage="Please enter Expiry Date." Font-Bold="True" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="btnOrder" runat="server" OnClick="btnOrder_Click" Text="Confirm Order" />
<asp:Label ID="lblOrderSuccess" runat="server" Font-Bold="True" Text="Order placed sucessfully!!" Visible="False"></asp:Label>
<br />
</asp:Content>
<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FINALPROJECT_shoppingCart_
{
public partial class AddToCart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["New"] == null)
{
Response.Redirect("Login.aspx");
}
else
{
Label2.Text = "Hello " + Session["New"].ToString();
LinkButton1.Visible = true;
}
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("item_id");
dt.Columns.Add("item_name");
dt.Columns.Add("quantity");
dt.Columns.Add("price");
dt.Columns.Add("totalprice");
dt.Columns.Add("image");
if (Request.QueryString["id"] != null)
{
if (Session["cart"] == null)
{
dr = dt.NewRow();
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
String myquery = "select * from item where item_id=" + Request.QueryString["id"];
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = scon;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
dr["item_id"] = ds.Tables[0].Rows[0]["item_id"].ToString();
dr["item_name"] = ds.Tables[0].Rows[0]["item_name"].ToString();
dr["image"] = ds.Tables[0].Rows[0]["image"].ToString();
dr["quantity"] = 1;
dr["price"] = ds.Tables[0].Rows[0]["price"].ToString();
int price = Convert.ToInt16(ds.Tables[0].Rows[0]["price"].ToString());
int quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
int totalprice = price * quantity;
dr["totalprice"] = totalprice;
savecartdetail(Convert.ToInt32(ds.Tables[0].Rows[0]["item_id"].ToString()), Convert.ToInt32(Session["id"].ToString()));
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["cart"] = dt;
GridView1.FooterRow.Cells[4].Text = "Total Amount";
GridView1.FooterRow.Cells[5].Text = grandtotal().ToString();
Response.Redirect("AddToCart.aspx");
}
else
{
dt = (DataTable)Session["cart"];
int sr;
sr = dt.Rows.Count;
dr = dt.NewRow();
String mycon = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection scon = new SqlConnection(mycon);
String myquery = "select * from item where item_id=" + Request.QueryString["id"];
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = scon;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
dr["item_id"] = ds.Tables[0].Rows[0]["item_id"].ToString();
dr["item_name"] = ds.Tables[0].Rows[0]["item_name"].ToString();
dr["image"] = ds.Tables[0].Rows[0]["image"].ToString();
dr["quantity"] = Request.QueryString["quantity"];
dr["price"] = ds.Tables[0].Rows[0]["price"].ToString();
int price = Convert.ToInt16(ds.Tables[0].Rows[0]["price"].ToString());
int quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
int totalprice = price * quantity;
dr["totalprice"] = totalprice;
savecartdetail(Convert.ToInt32(ds.Tables[0].Rows[0]["item_id"].ToString()), Convert.ToInt32(Session["id"].ToString()));
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["cart"] = dt;
GridView1.FooterRow.Cells[4].Text = "Total Amount";
GridView1.FooterRow.Cells[5].Text = grandtotal().ToString();
Response.Redirect("AddToCart.aspx");
}
}
else
{
dt = (DataTable)Session["cart"];
GridView1.DataSource = dt;
GridView1.DataBind();
if (GridView1.Rows.Count > 0)
{
GridView1.FooterRow.Cells[4].Text = "Total Amount";
GridView1.FooterRow.Cells[5].Text = grandtotal().ToString();
}
}
Label2.Text = GridView1.Rows.Count.ToString();
}
}
private void savecartdetail(int itemid, int userid)
{
String query = "insert into cart values (" +itemid +"," +userid +")";
String mycon = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
public int grandtotal()
{
DataTable dt = new DataTable();
dt = (DataTable)Session["cart"];
int nrow = dt.Rows.Count;
int i = 0;
int gtotal = 0;
while (i < nrow)
{
gtotal = gtotal + Convert.ToInt32(dt.Rows[i]["totalprice"].ToString());
i = i + 1;
}
Session["Total"] = gtotal;
return gtotal;
}
private void clearsavedcart()
{
String mycon = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
String updatedata = "delete from cart where user_id=" + Session["id"] ;
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = updatedata;
cmd.Connection = con;
cmd.ExecuteNonQuery();
Response.Redirect("Home.aspx");
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Session["cart"] = null;
clearsavedcart();
}
protected void lnkCheckOut_Click(object sender, EventArgs e)
{
String mycon = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
String insertOrder = "Insert into orders(user_id, item_ID) select user_id, item_id from cart;";
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = insertOrder;
cmd.Connection = con;
cmd.ExecuteNonQuery();
if (Session["cart"] == null)
lblCartEmpty.Visible = true;
else
Response.Redirect("CheckOut.aspx");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FINALPROJECT_shoppingCart_
{
public partial class CheckOut : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Total"] == null)
{
Response.Redirect("AddToCart.aspx");
//txtTax.Text = "0.00";
//txtBeforeTax.Text = "0.00";
//txtAfterTax.Text = "0.00";
}
else
{
txtBeforeTax.Text = Session["Total"].ToString();
double price = double.Parse(txtBeforeTax.Text);
double taxRate = 0.13;
double tax = price * taxRate;
double netPrice = price * 1.13;
txtTax.Text = tax.ToString();
txtAfterTax.Text = netPrice.ToString();
}
}
protected void btnOrder_Click(object sender, EventArgs e)
{
if (txtCardHolderName.Text != "" || txtCardNumber.Text != "" || txtExpiryDate.Text != "" || txtSecCode.Text != "")
lblOrderSuccess.Visible = true;
}
private void clearsavedcart()
{
String mycon = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
String updatedata = "delete from cart where user_id=" + Session["id"];
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = updatedata;
cmd.Connection = con;
cmd.ExecuteNonQuery();
Response.Redirect("Home.aspx");
}
//protected void txtCardNumber_TextChanged(object sender, EventArgs e)
//{
// cmpValCardNumber.Enabled = true;
//}
//protected void txtSecCode_TextChanged(object sender, EventArgs e)
//{
// cmpValSecCode.Enabled = true;
//}
//protected void txtExpiryDate_TextChanged(object sender, EventArgs e)
//{
// //cmpValExpDate.Enabled = true;
//}
//protected void txtCardHolderName_TextChanged(object sender, EventArgs e)
//{
// cmpValName.Enabled = true;
//}
}
}<file_sep><%@ Page Title="" Language="C#" MasterPageFile="~/shopping.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="FINALPROJECT_shoppingCart_.About" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<style type="text/css">
.auto-style1 {
width: 100%;
border: 5px solid #0000FF;
background-color: #00FFFF;
}
.auto-style2 {
text-align: center;
}
.auto-style3 {
text-align: center;
width: 535px;
}
.auto-style4 {
width: 535px;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<p>
<asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="Large" ForeColor="#000099" Text="About Us"></asp:Label>
</p>
<p>
This Website was created with the help of ASP.NET technology.
</p>
<p>
It includes the use ADO.NET to retrieve database values.</p>
<p>
It uses query strings.</p>
<p>
<asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Size="Medium" ForeColor="#000099" Text="Group Project:"></asp:Label>
</p>
<table cellpadding="4" cellspacing="4" class="auto-style1">
<tr>
<td class="auto-style3" style="font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; font-size: medium; color: #000080">NAMES </td>
<td class="auto-style2" style="font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; font-size: medium; color: #000080">ID</td>
</tr>
<tr>
<td class="auto-style4" style="font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; font-size: medium; color: #000080"><NAME>INGH</td>
<td class="auto-style2" style="font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; font-size: medium; color: #000080">991489996</td>
</tr>
<tr>
<td class="auto-style4" style="font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; font-size: medium; color: #000080"><NAME></td>
<td class="auto-style2" style="font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; font-size: medium; color: #000080">991498957</td>
</tr>
<tr>
<td class="auto-style4" style="font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; font-size: medium; color: #000080">KARANBIR SINGH</td>
<td class="auto-style2" style="font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; font-size: medium; color: #000080">991501554</td>
</tr>
</table>
<p>
</p>
</asp:Content>
<file_sep><%@ Page Title="" Language="C#" MasterPageFile="~/shopping.Master" AutoEventWireup="true" CodeBehind="AddToCart.aspx.cs" Inherits="FINALPROJECT_shoppingCart_.AddToCart" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<style type="text/css">
.auto-style1 {
width: 100%;
height: 1px;
}
.auto-style2 {
height: 42px;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<table class="auto-style1">
<tr>
<td class="auto-style2" style="font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; font-size: medium; color: #000099">
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:LinkButton ID="LinkButton1" runat="server" Font-Bold="True" Font-Size="Medium" ForeColor="#000099">Sign out</asp:LinkButton>
You have
<asp:Label ID="Label2" runat="server"></asp:Label>
product(s) in Cart
<asp:HyperLink ID="HyperLink1" runat="server" Font-Bold="True" ForeColor="#000099" NavigateUrl="~/home.aspx">Continue to Shopping</asp:HyperLink>
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="5px" CellPadding="4" Font-Bold="True" Height="226px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" ShowFooter="True" Width="551px">
<Columns>
<asp:BoundField DataField="item_id" HeaderText="Product ID ">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:ImageField DataImageUrlField="image" HeaderText="Product Image">
<ControlStyle Height="100px" Width="100px" />
<ItemStyle Height="50px" HorizontalAlign="Center" Width="50px" />
</asp:ImageField>
<asp:BoundField DataField="item_name" HeaderText="Product name">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="price" HeaderText="Price">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Quantity" HeaderText="Quantity">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="totalprice" HeaderText="Total Price">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
<br />
<asp:LinkButton ID="LinkButton2" runat="server" Font-Bold="True" ForeColor="#000099" OnClick="LinkButton2_Click">Clear Cart</asp:LinkButton>
<asp:Label ID="lblCartEmpty" runat="server" Font-Bold="True" ForeColor="Red" Text="Your cart is empty." Visible="False"></asp:Label>
<asp:LinkButton ID="lnkCheckOut" runat="server" Font-Bold="True" Font-Size="Medium" ForeColor="#000999" OnClick="lnkCheckOut_Click">CheckOut</asp:LinkButton>
</asp:Content>
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace FINALPROJECT_shoppingCart_
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
lblpassword.Visible = false;
lblusername.Visible = false;
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
connection.Open();
string checkuser = "select count(*) from users where username='" + txtusername.Text + "'";
SqlCommand command = new SqlCommand(checkuser, connection);
int temp = Convert.ToInt32(command.ExecuteScalar().ToString());
connection.Close();
if (temp == 1)
{
lblusername.Visible = false;
connection.Open();
string checkpass = "select password from users where username ='" + txtusername.Text + "'";
SqlCommand passcommand = new SqlCommand(checkpass, connection);
string password = passcommand.ExecuteScalar().ToString().Replace(" ","");
if(password == txtpassword.Text)
{
lblpassword.Visible = false;
Session["New"] = txtusername.Text;
string getid = "select user_id from users where username ='" + txtusername.Text + "'";
SqlCommand idcommand = new SqlCommand(getid, connection);
int id = Convert.ToInt32(idcommand.ExecuteScalar().ToString());
Session["id"] = id;
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("item_id");
dt.Columns.Add("item_name");
dt.Columns.Add("quantity");
dt.Columns.Add("price");
dt.Columns.Add("totalprice");
dt.Columns.Add("image");
dr = dt.NewRow();
string getcart = "select * from item i inner join cart c on (i.item_id = c.item_id) where c.user_id = " + id;
int price =0;
int totalprice = 0;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = getcart;
cmd.Connection = connection;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dr["item_id"] = ds.Tables[0].Rows[i]["item_id"].ToString();
dr["item_name"] = ds.Tables[0].Rows[i]["item_name"].ToString();
dr["image"] = ds.Tables[0].Rows[i]["image"].ToString();
dr["quantity"] = 1;
dr["price"] = ds.Tables[0].Rows[i]["price"].ToString();
price = Convert.ToInt16(ds.Tables[0].Rows[i]["price"].ToString());
totalprice = price * 1;
dr["totalprice"] = totalprice;
dt.Rows.Add(dr);
dr = dt.NewRow();
}
Session["cart"] = dt;
lblpassword.Visible = false;
Response.Write("Password is correct");
Response.Redirect("Home.aspx");
}
else
{
lblpassword.Visible = true;
}
}
else
{
lblusername.Visible = true;
}
connection.Close();
}
}
} | 796239ad3d2d889a68fa7ee6a21c072a5fa88551 | [
"C#",
"ASP.NET"
] | 8 | C# | harleen4309/ShoppingCart | 1af5006185280f457c5e291faab77568a3cdc04c | b179ee80446c6738a6fbe54ef0c0d75868c1b23c |
refs/heads/master | <file_sep>import cv2
import numpy as np
cap = cv2.VideoCapture(0)
bckg_sub = cv2.createBackgroundSubtractorMOG2()
while True:
ret, frame = cap.read()
mask = bckg_sub.apply(frame)
res = cv2.bitwise_and(frame, frame, mask=mask)
cv2.imshow("original",frame)
cv2.imshow("motion",mask)
cv2.imshow("mo", res)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
| 81e404d9ad87ba97f80286ce675713058fa07fcb | [
"Python"
] | 1 | Python | chanstefvi/motion_detection | d63a4ab87969bd5887626a9f10af65c676072b87 | c25aae139a53b5547c752529de2ce93d8abf4ce5 |
refs/heads/master | <file_sep>object galvan {
var sueldo = 15000
var balance = 0
method sueldo() {
return sueldo
}
method totalDinero(){
return balance.max(0)
}
method totalDeuda(){
return balance.min(0).abs()
}
method sueldo(nuevoValor) {
sueldo = nuevoValor
}
method gastar(cuanto){
balance -= cuanto
}
method cobrarSueldo() {
balance += self.sueldo()
}
}
object baigorria {
var cantidadEmpanadasVendidas = 0
const montoPorEmpanada = 15
var totalCobrado = 0
method venderEmpanadas(cant) {
cantidadEmpanadasVendidas += cant
}
method sueldo() = cantidadEmpanadasVendidas * montoPorEmpanada
method cobrarSueldo() {
totalCobrado += self.sueldo()
cantidadEmpanadasVendidas = 0
}
method totalCobrado() = totalCobrado
}
object gimenez {
var dinero = 300000
method dinero() {
return dinero
}
method pagarA(empleado) {
dinero -= empleado.sueldo()
empleado.cobrarSueldo()
}
}
| 9f88b63f8495d316b9d5a161e2d2d37ff6346c8c | [
"Wollok"
] | 1 | Wollok | algo1unsam/2021s2-empanadas-gimenez-UnaLuz | b8da4736acf76fe287d438edbcbc2e7925ccf586 | b07f8080690b5463f5a38f4cd93e78b8d2f1899a |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codigo;
import generated.Perros;
import java.io.File;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
/**
*
* @author Marta
*/
public class JaxClass {
JAXBContext contexto; //Crea un contexto con una una nueva instancia de JaxB para la clase principal obtenida del esquema XML.
Perros misPerros; //Creamos un objeto tipo Perros
public int abrirJAXB(File fichero){
try{
//Se crea la instancia JAXB.
contexto=JAXBContext.newInstance(Perros.class);
//Se usa para obtener del documento XML los datos que son almacenados en la estructura de objetos Java.
Unmarshaller u=contexto.createUnmarshaller();
//Deserializa el fichero. Se lee el fichero y lo interpreta en las clases Java.
misPerros=(Perros)u.unmarshal(fichero);
return 0;
}catch(Exception ex){
ex.printStackTrace();
return -1;
}
}
//Método para recorrer la lista que nos genera JaxB. Vamos a guardar los datos en un array que usaremos en la aplicación
//para guardar los datos en sus correspondientes textareas para modificarlos posteriormente.
public String[] recorrerJaxB(String entrada){
String datos[]=new String[10]; //Declaramos un array donde vamos a guardar los datos que obtendremos al recorrer el archivo
String auxiliar=""; //String que vamos a utilizar para hacer comprobaciones.
try{
//Se crea una lista con objetos de tipo Perro.
List<Perros.Perro> losPerros=misPerros.getPerro();
//Recorremos la lista para sacar los valores.
for(int i=0; i<losPerros.size(); i++){
//Vamos a guardar el valor del chip en una variable string auxiliar, que usaremos para hacer una comprobación
//Si coincide con elvalor introducido por el usuario como parámetro de entrada, entonces guardamos los
//datos relacionados con ese chip en un array.
auxiliar=losPerros.get(i).getChip();
if(auxiliar.equals(entrada)){
datos[0]=losPerros.get(i).getChip();
datos[1]=losPerros.get(i).getAfijo();
datos[2]=losPerros.get(i).getNacimiento();
datos[3]=losPerros.get(i).getNombre();
datos[4]=losPerros.get(i).getRaza();
datos[5]=losPerros.get(i).getSexo();
datos[6]=losPerros.get(i).getPropietario();
datos[7]=losPerros.get(i).getDeporte();
datos[8]=losPerros.get(i).getGrado();
datos[9]=losPerros.get(i).getClub();
}
}
}catch(Exception e){
e.printStackTrace();
}
return datos;
}
//Método que edita los datos en JaxB. Le pasamos los valores como parámetros de entrada.
public int editarJaxB(String chip, String afijo, String nacimiento, String nombre, String raza,
String sexo, String propietario, String deporte, String grado, String club){
String auxiliar=""; //Vamos a utilizar el String auxiliar para hacer comprobaciones.
try{
List<Perros.Perro> losPerros=misPerros.getPerro();
for(int i=0;i<losPerros.size();i++){
auxiliar=losPerros.get(i).getChip(); //Asignamos el valor del objeto chip al String auxiliar.
//En caso que sea igual al del parámetro que le hemos pasado como entrada, ejecuta
//Modifica todos los datos para facilitar la tarea.
if(auxiliar.equals(chip)){
losPerros.get(i).setAfijo(afijo);
losPerros.get(i).setNacimiento(nacimiento);
losPerros.get(i).setNombre(nombre);
losPerros.get(i).setRaza(raza);
losPerros.get(i).setSexo(sexo);
losPerros.get(i).setPropietario(propietario);
losPerros.get(i).setDeporte(deporte);
losPerros.get(i).setGrado(grado);
losPerros.get(i).setClub(club);
}
}
return 0;
}catch(Exception e){
e.printStackTrace();
return -1;
}
}
//Método para guardar.
public void guardarJaxB(File archivo){
try{
//Creamos un objeto marshaller
Marshaller m=contexto.createMarshaller();
//Le damos formato para que no nos lo guarde en una linea
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//llamamos al marshaller y serializamos el objeto misPerros en el archivo que le pasamos como parámetro
m.marshal(misPerros, archivo);
}catch(Exception e){
e.printStackTrace();
}
}
}
| 61044de15c5e7da3c96764dd5df309724cdad3c7 | [
"Java"
] | 1 | Java | KalyanLazair/PracticaFinal | f0614e4b9c1f4698175ca4ae698eae00076db341 | 8c41a44bc5e5d8a0ed5ac7be01dd4312982d0662 |
refs/heads/master | <file_sep>package com.company;
import com.company.Modelos.Alumno;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Main {
public static void main(String[] args) {
SimpleDateFormat objSDF=new SimpleDateFormat("dd-mm-yyyy");
Date fechanacimiento=null;
try {
fechanacimiento=objSDF.parse("28-02-1985");
} catch (ParseException e) {
e.printStackTrace();
}
Alumno alumno=new Alumno("juan","Rodrigues",fechanacimiento,"36157889h");
System.out.println(alumno.toString());
LocalDate fHoy= LocalDate.now();
LocalDate cumple= LocalDate.of(1985, Month.FEBRUARY, 28);
long edad= ChronoUnit.YEARS.between(cumple, fHoy);
System.out.println("Tu edad es: "+edad);
// Mostramos el resultado de llamar a la función calcular pasando
// como parametro la fecha de nacimiento YYYY-MM-DD
}
}
| 2f267e2c46f28af54682070aaf9b5e8bc29fca3b | [
"Java"
] | 1 | Java | kmeseye/repasojava | 463a2db5705dff71baf60666b395170c492f1cc3 | f171db279fb63af3f9ffb170b077839a967212e8 |
refs/heads/master | <file_sep># Navigation goals
ROS package for mobile robot navigation based on move_base.
<img src="https://github.com/RuslanAgishev/navigation_goals/blob/master/figures/husky_example.png"/>
## Installation
```bash
sudo apt-get install ros-<distro>-navigation
```
Install husky simulation, [reference](http://wiki.ros.org/husky_navigation/Tutorials):
```bash
sudo apt-get install ros-<distro>-husky-*
echo "export HUSKY_GAZEBO_DESCRIPTION=$(rospack find husky_gazebo)/urdf/description.gazebo.xacro" >> ~/.bashrc
source ~/.bashrc
```
Husky simulation is tested on Gazebo 7 + ROS kinetic.
In case you want to use a turtlebot3 simulation, [reference](https://hotblackrobotics.github.io/en/blog/2018/01/29/seq-goals-py/):
```bash
sudo apt-get install ros-<distro>-turtlebot3-*
echo "export TURTLEBOT3_MODEL=burger" >> ~/.bashrc
source ~/.bashrc
```
Turtlebot simulation is tested both on Gazebo 7 + ROS kinetic and Gazebo 9 + ROS melodic set-ups.
## Waypoints following example
Bringup simulated environment and spawn a husky robot in it.
```bash
roslaunch navigation_goals husky_main.launch
```
Or in order to spwan a turtlebot in a simulated environment:
```bash
roslaunch navigation_goals turtlebot3_main.launch
```
Command a robot to visit a sequence of waypoints.
```bash
roslaunch navigation_goals send_wp_sequence.launch
```
<file_sep># Building singularity image from the def file
sudo singularity build --nv husky.sif recepie.def
<file_sep>#!/usr/bin/env python
from stamped_msgs.msg import Float64
from sensor_msgs.msg import Imu
import rospy
from tf.transformations import euler_from_quaternion
import numpy as np
class Imu2Azimuth(object):
def __init__(self, imu_topic='/imu/data'):
self.mag_pub = rospy.Publisher(name='mag_azimuth', data_class=Float64, queue_size=1)
self.imu_topic = rospy.get_param('~imu_in', imu_topic)
self.imu_sub = rospy.Subscriber(imu_topic, data_class=Imu, queue_size=1, callback=self.imu_cb)
rospy.loginfo('Subscribed to %s', self.imu_topic)
def imu_cb(self, imu_msg):
mag_azimuth_msg = Float64()
q = [imu_msg.orientation.x, imu_msg.orientation.y, imu_msg.orientation.z, imu_msg.orientation.w]
roll, pitch, yaw = euler_from_quaternion(q)
rospy.logdebug('Roll [deg]: %f, Pitch [deg]: %f, Yaw [deg]: %f',
np.rad2deg(roll), np.rad2deg(pitch), np.rad2deg(yaw))
mag_azimuth_msg.header = imu_msg.header
mag_azimuth_msg.data = np.rad2deg(yaw)
rospy.loginfo('Azimuth: %f', np.rad2deg(yaw))
self.mag_pub.publish(mag_azimuth_msg)
if __name__ == "__main__":
rospy.init_node('imu_to_mag_azimuth', anonymous=True, log_level=rospy.INFO)
converter = Imu2Azimuth()
rospy.spin()
| 1695ff006edcb468dfd6dd1a8f2590c1ca1e7b58 | [
"Markdown",
"Shell",
"Python"
] | 3 | Markdown | RuslanAgishev/navigation_goals | a6a553b2dde780f820df65209078814d03c8c42c | 1dea7a48e9fae0db7c0e43fa0f7ebca75965b8b3 |
refs/heads/master | <repo_name>alyssanycum/object_advanced<file_sep>/main.js
const pope = {
name: "Francis",
age: 83,
hasTallHat: true,
baseballCards: [],
bless: function (blessee) {
console.log(`I bless you, ${blessee}`);
},
celebrateBirthday: function () {
console.log('Yay!');
this.age++;
},
addCard: function (card) {
console.log(`Adding ${card} to collection.`)
this.baseballCards.push(card);
},
displayCards: function () {
console.log("Look at my cards, y'all!")
for (let i = 0; i < this.baseballCards.length; i++) {
console.log(this.baseballCards[i]);
}
}
};
const tellMeAboutThePope = function() {
console.log(`The Pope is named ${pope.name}. He is ${pope.age} years old.`);
}
tellMeAboutThePope();
pope.bless("Bryan");
pope.celebrateBirthday();
tellMeAboutThePope();
console.log(pope);
pope.displayCards();
pope.addCard("<NAME>");
pope.addCard("<NAME>.");
pope.displayCards();
pope.addCard("<NAME>");
pope.addCard("<NAME>");
pope.displayCards();
| 52947352e603fe990102887f75eb04a48a00c069 | [
"JavaScript"
] | 1 | JavaScript | alyssanycum/object_advanced | 5bfdba08d01ea2edfffadce8ceffe8a83638c31a | b98fa55f68127ae3cfa4f91c0d5f2ebee1c5488a |
refs/heads/master | <repo_name>Zukhruf/Pemrograman<file_sep>/src/Robot.java
public class Robot {
//atribut
private int kecepatan = 0;
private int arah = 1;
//metode
public void tambahKecepatan(int k){
kecepatan +=k;
}
public void setArah(int a){
if (a!=arah){
kecepatan = 0; arah = a;
}
}
public void setArahRobotLain(Robot r, int a){
r.setArah(a);
}
public void menari(){
System.out.println("Hahaha asyik kawan aku robot lagi menari");
}
public void tampilRobot(){
System.out.println("Robot berjalan arah "+arah+" Kecepatan "+kecepatan);
}
}
<file_sep>/src/HandphoneTest.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.
*/
/**
*
* @author <NAME>
*/
public class HandphoneTest {
public static void main(String[] args) {
Handphone samsung = new Handphone();
samsung.tambahNomor();
samsung.telepon();
samsung.deringan(3);
samsung.profil();
}
}
| 0ddb62a4bdb02549ea0772c66f66f99f21753801 | [
"Java"
] | 2 | Java | Zukhruf/Pemrograman | 90ac510541bcc80fc9978d2776107c8e626cdb87 | afd9684b25fc7bc25418dcf7f74346b7363a7e34 |
refs/heads/main | <repo_name>small-rose/distributed-transaction<file_sep>/boot-seata-at/README.md
## distributed-tx-seata
### Seata AT 模式分布式事务Demo工程
- seata AT 模式Demo
- 理论就不重复介绍了,随便一搜就有。
### 分布式事务环境介绍
- SpringBoot 2.2.2.RELEASE
- SpringCloud Hoxton.SR8
- Spring-Cloud-alibaba 2.2.3.RELEASE
- seata-server 1.3.0
- 服务注册与服务发现 使用 Eureka
- 服务调用openfeign + ribbon+ hystrix
- 数据库 MySQL 5.7.31
- 测试仅学习和演示分布式事务,表设计和工程尽可能简化
### 服务说明
- server-eureka-9900 作为注册中心来使用
- server-order-9901 模拟订单服务 server-order
- server-store-9902 模拟库存服务 server-store
- server-account-9903 模拟扣款服务 server-account
相关端口号均和服务名上的一致。
#### 调用流程
server-order ---> server-store ---> server-account
### 工程使用
#### 1、下载工程代码
```bash
git clone <EMAIL>:small-rose/distributed-tx-seata.git
```
导入IDEA即可,maven 编译即可。
#### 2、准备环境
- jdk 1.8 (必须)
- mysql 5.7 (建议)
- seata 版本:seata-server 1.3.0 (建议)
#### 3、数据库环境
因为是模拟,可以创建四个数据库,也可以在一个数据库里然后使用四个数据源的方式。
我使用的创建4个数据库:
- seata
- server-order
- server-store
- server-account
#### 4、启动注册中心
server-eureka-9900
访问地址:http://localhost:9900/
#### 5、启动Seata-server
windows 版本
```bash
seata.bat -m db
```
linux 版本
```bash
seata.sh -m db
```
刷新注册中心地址:http://localhost:9900/ 验证seata-server 注册情况。
#### 6、启动其他工程
依次启动三个工程:(没有特别顺序要求)
- server-order-9900 (访问入口工程)
- server-store-9900
- server-account-9900
刷新注册中心地址:http://localhost:9900/ 验证相关服务注册情况。
#### 7、测试验证
访问入口:http://localhost:9901/v1/order/add/1001/1
#### 8、更多详细说明
欢迎stars 和 fork , 也欢迎邮件交流 <a href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=ssHf097en8Ddwdfyw8Oc0d3f"> 给我Emall </a>
使用此demo过程有问题可以参考我的博客文章:[《SpringCloud 分布式事务 Seata 方案实例》](https://notes.zhangxiaocai.cn/posts/ea07db80.html)
如果涉及seata版本问题,文章也有整理说明。
如果有异常可以参考文章 [《spring-cloud 常见异常》](https://notes.zhangxiaocai.cn/posts/1618e871.html) (适合新手)。
### Seata-Server 配置
服务端 file.conf 的配置
```
transport {
# tcp udt unix-domain-socket
type = "TCP"
#NIO NATIVE
server = "NIO"
#enable heartbeat
heartbeat = true
# the client batch send request enable
enableClientBatchSendRequest = false
#thread factory for netty
threadFactory {
bossThreadPrefix = "NettyBoss"
workerThreadPrefix = "NettyServerNIOWorker"
serverExecutorThreadPrefix = "NettyServerBizHandler"
shareBossWorker = false
clientSelectorThreadPrefix = "NettyClientSelector"
clientSelectorThreadSize = 1
clientWorkerThreadPrefix = "NettyClientWorkerThread"
# netty boss thread size,will not be used for UDT
bossThreadSize = 1
#auto default pin or 8
workerThreadSize = "default"
}
shutdown {
# when destroy server, wait seconds
wait = 3
}
serialization = "seata"
compressor = "none"
}
# service configuration, only used in client side
service {
#transaction service group mapping
vgroupMapping.my_test_tx_group = "default"
default.grouplist = "127.0.0.1:8091"
#degrade, current not support
enableDegrade = false
#disable seata
disableGlobalTransaction = false
}
#client transaction configuration, only used in client side
client {
rm {
asyncCommitBufferLimit = 10000
lock {
retryInterval = 10
retryTimes = 30
retryPolicyBranchRollbackOnConflict = true
}
reportRetryCount = 5
tableMetaCheckEnable = false
reportSuccessEnable = false
sqlParserType = druid
}
tm {
commitRetryCount = 5
rollbackRetryCount = 5
}
undo {
dataValidation = true
logSerialization = "jackson"
logTable = "undo_log"
}
log {
exceptionRate = 100
}
}
## transaction log store, only used in seata-server
store {
## store mode: file、db、redis
mode = "db"
## file store property
file {
## store location dir
dir = "sessionStore"
# branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
maxBranchSessionSize = 16384
# globe session size , if exceeded throws exceptions
maxGlobalSessionSize = 512
# file buffer size , if exceeded allocate new buffer
fileWriteBufferCacheSize = 16384
# when recover batch read size
sessionReloadReadSize = 100
# async, sync
flushDiskMode = async
}
## database store property
db {
## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
datasource = "druid"
## mysql/oracle/postgresql/h2/oceanbase etc.
dbType = "mysql"
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://127.0.0.1:3306/seata"
user = "root"
password = "<PASSWORD>"
minConn = 5
maxConn = 30
globalTable = "global_table"
branchTable = "branch_table"
lockTable = "lock_table"
queryLimit = 100
maxWait = 5000
}
## redis store property
redis {
host = "127.0.0.1"
port = "6379"
password = ""
database = "0"
minConn = 1
maxConn = 10
queryLimit = 100
}
}
## server configuration, only used in server side
server {
recovery {
#schedule committing retry period in milliseconds
committingRetryPeriod = 1000
#schedule asyn committing retry period in milliseconds
asynCommittingRetryPeriod = 1000
#schedule rollbacking retry period in milliseconds
rollbackingRetryPeriod = 1000
#schedule timeout retry period in milliseconds
timeoutRetryPeriod = 1000
}
undo {
logSaveDays = 7
#schedule delete expired undo_log in milliseconds
logDeletePeriod = 86400000
}
#unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent
maxCommitRetryTimeout = "-1"
maxRollbackRetryTimeout = "-1"
rollbackRetryTimeoutUnlockEnable = false
}
## metrics configuration, only used in server side
metrics {
enabled = false
registryType = "compact"
# multi exporters use comma divided
exporterList = "prometheus"
exporterPrometheusPort = 9898
}
```
服务端 registry.conf 的配置
```$xslt
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "eureka"
nacos {
application = "seata-server"
serverAddr = "127.0.0.1:8848"
group = "SEATA_GROUP"
namespace = ""
cluster = "default"
username = ""
password = ""
}
eureka {
serviceUrl = "http://localhost:9900/eureka"
application = "seata_server"
weight = "1"
}
redis {
serverAddr = "localhost:6379"
db = 0
password = ""
cluster = "default"
timeout = 0
}
zk {
cluster = "default"
serverAddr = "127.0.0.1:2181"
sessionTimeout = 6000
connectTimeout = 2000
username = ""
password = ""
}
consul {
cluster = "default"
serverAddr = "127.0.0.1:8500"
}
etcd3 {
cluster = "default"
serverAddr = "http://localhost:2379"
}
sofa {
serverAddr = "127.0.0.1:9603"
application = "default"
region = "DEFAULT_ZONE"
datacenter = "DefaultDataCenter"
cluster = "default"
group = "SEATA_GROUP"
addressWaitTime = "3000"
}
file {
name = "file.conf"
}
}
config {
# file、nacos 、apollo、zk、consul、etcd3
type = "file"
nacos {
serverAddr = "127.0.0.1:8848"
namespace = ""
group = "SEATA_GROUP"
username = ""
password = ""
}
consul {
serverAddr = "127.0.0.1:8500"
}
apollo {
appId = "seata-server"
apolloMeta = "http://192.168.1.204:8801"
namespace = "application"
}
zk {
serverAddr = "127.0.0.1:2181"
sessionTimeout = 6000
connectTimeout = 2000
username = ""
password = ""
}
etcd3 {
serverAddr = "http://localhost:2379"
}
file {
name = "file.conf"
}
}
```
<file_sep>/boot-seata-at/server-order-9901/src/main/java/com/xiaocai/distran/serverorder/config/GlobalConfig.java
package com.xiaocai.distran.serverorder.config;
import feign.Logger;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @description: TODO 功能角色说明:
* TODO 描述:
* @author: 张小菜
* @date: 2020/11/9 22:39
* @version: v1.0
*/
@Configuration
@MapperScan(basePackages = {"com.xiaocai.distran.serverorder.mapper"})
public class GlobalConfig {
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
<file_sep>/boot-seata-at/server-order-9901/src/main/java/com/xiaocai/distran/serverorder/config/SeataRestTemplateAutoConfiguration.java
package com.xiaocai.distran.serverorder.config;
import org.springframework.context.annotation.Configuration;
/**
* @description: TODO 功能角色说明:
* TODO 描述:
* @author: 张小菜
* @date: 2020/11/12 14:48
* @version: v1.0
*/
@Configuration
public class SeataRestTemplateAutoConfiguration {
/*@Autowired( required = false)
private Collection<RestTemplate> restTemplates;
@Autowired
private SeataRestTemplateInterceptor seataRestTemplateInterceptor;
public SeataRestTemplateAutoConfiguration() {
}
@Bean
public SeataRestTemplateInterceptor seataRestTemplateInterceptor() {
return new SeataRestTemplateInterceptor();
}
@PostConstruct
public void init() {
if (this.restTemplates != null) {
Iterator var1 = this.restTemplates.iterator();
while (var1.hasNext()) {
RestTemplate restTemplate = (RestTemplate) var1.next();
List<ClientHttpRequestInterceptor> interceptors = new ArrayList(restTemplate.getInterceptors());
interceptors.add(this.seataRestTemplateInterceptor);
restTemplate.setInterceptors(interceptors);
}
}
}*/
}
<file_sep>/boot-seata-at/server-order-9901/src/main/java/com/xiaocai/distran/serverorder/service/OrderService.java
package com.xiaocai.distran.serverorder.service;
import com.xiaocai.distran.serverorder.bean.OrderBean;
public interface OrderService {
boolean addOrder(OrderBean orderBean);
}
<file_sep>/boot-seata-at/server-order-9901/src/main/java/com/xiaocai/distran/serverorder/config/SeataAutoConfig.java
package com.xiaocai.distran.serverorder.config;
import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
* @description: TODO 功能角色说明:
* TODO 描述:
* @author: 张小菜
* @date: 2020/11/12 17:21
* @version: v1.0
*/
@Configuration
public class SeataAutoConfig {
@Value("${spring.application.name}")
private String appId ;
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource druidDataSource() {
return new DruidDataSource();
}
/**
* 需要将 DataSourceProxy 设置为主数据源,否则事务无法回滚
*
* @param druidDataSource The DruidDataSource
* @return The default datasource
*/
@Primary
@Bean("dataSource")
public DataSourceProxy dataSource(DruidDataSource druidDataSource) {
return new DataSourceProxy(druidDataSource);
}
/*
@Bean
public GlobalTransactionScanner globalTransactionScanner() {
String applicationName = this.applicationContext.getEnvironment().getProperty("spring.application.name");
String txServiceGroup = this.seataProperties.getTxServiceGroup();
if (StringUtils.isEmpty(txServiceGroup)) {
txServiceGroup = applicationName + "-fescar-service-group";
this.seataProperties.setTxServiceGroup(txServiceGroup);
}
return new GlobalTransactionScanner(applicationName, txServiceGroup);
}
*/
/* @Bean
public GlobalTransactionScanner globalTransactionScanner() {
return new GlobalTransactionScanner(appId,"my_test_tx_group");
}*/
}
<file_sep>/boot-hmily-tcc/hmily-order/src/main/java/com/xiaocai/distran/hmilyorder/openfeign/fallback/StockFallBack.java
package com.xiaocai.distran.hmilyorder.openfeign.fallback;
import com.xiaocai.distran.hmilyorder.openfeign.StockClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @description: TODO 功能角色说明:
* TODO 描述:
* @author: 张小菜
* @date: 2020/11/14 0:55
* @version: v1.0
*/
@Component
@Slf4j
public class StockFallBack implements StockClient {
@Override
public boolean decreaseStock(Integer prodId, Integer count) {
log.info("-----Store Fall Back-----");
return false;
}
}
<file_sep>/boot-seata-at/sql/server_store.sql
/*
Navicat MySQL Data Transfer
Source Server : LocalHost
Source Server Version : 50731
Source Host : localhost:3306
Source Database : server_store
Target Server Type : MYSQL
Target Server Version : 50731
File Encoding : 65001
Date: 2020-11-13 00:57:52
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for undo_log
-- ----------------------------
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`branch_id` bigint(20) NOT NULL,
`xid` varchar(100) NOT NULL,
`context` varchar(128) NOT NULL,
`rollback_info` longblob NOT NULL,
`log_status` int(11) NOT NULL,
`log_created` datetime NOT NULL,
`log_modified` datetime NOT NULL,
`ext` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of undo_log
-- ----------------------------
-- ----------------------------
-- Table structure for wms_store
-- ----------------------------
DROP TABLE IF EXISTS `wms_store`;
CREATE TABLE `wms_store` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`prod_id` int(11) DEFAULT NULL,
`prod_name` varchar(15) DEFAULT NULL,
`prod_price` double DEFAULT NULL,
`storage` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of wms_store
-- ----------------------------
INSERT INTO `wms_store` VALUES ('1', '1001', '小米手机', '1500', '1000');
INSERT INTO `wms_store` VALUES ('2', '1002', 'ThinkPad笔记本', '9000', '2000');
<file_sep>/boot-seata-at/server-order-9901/src/main/java/com/xiaocai/distran/serverorder/openfeign/fallback/StoreFallBack.java
package com.xiaocai.distran.serverorder.openfeign.fallback;
import com.xiaocai.distran.serverorder.openfeign.StoreClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @description: TODO 功能角色说明:
* TODO 描述:
* @author: 张小菜
* @date: 2020/11/9 22:58
* @version: v1.0
*/
@Component
@Slf4j
public class StoreFallBack implements StoreClient {
@Override
public boolean decreaseStore(Integer prodId, Integer number, Integer userId) {
log.info("---call store fall back---");
return false;
}
}
<file_sep>/boot-seata-at/server-order-9901/src/main/java/com/xiaocai/distran/serverorder/controller/OrderController.java
package com.xiaocai.distran.serverorder.controller;
import com.xiaocai.distran.serverorder.bean.OrderBean;
import com.xiaocai.distran.serverorder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* @description: TODO 功能角色说明:
* TODO 描述:
* @author: 张小菜
* @date: 2020/11/9 22:00
* @version: v1.0
*/
@RestController
public class OrderController {
@Autowired
private OrderService orderService;
private int num = 1 ;// 可以让测试的时候订单不一样
/**
* 事务测试入口
* @param prodId
* @return
*/
@GetMapping(value = "/v1/order/add/{prodId}/{number}")
public String addOrder(@PathVariable("prodId") int prodId, @PathVariable("number") Integer number){
OrderBean orderBean = new OrderBean();
String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
orderBean.setOrderId(format);
orderBean.setUserId(202001);
orderBean.setNumber(number);
orderBean.setProdId(prodId);
boolean bool = orderService.addOrder(orderBean);
num++;
return bool ? "下单成功" : "下单失败";
}
}
<file_sep>/boot-seata-at/server-account-9903/src/main/java/com/xiaocai/distran/serveraccount/service/AccountService.java
package com.xiaocai.distran.serveraccount.service;
public interface AccountService {
public boolean decreaseAccount(int userId, double money);
}
<file_sep>/boot-hmily-tcc/sql/hmily_store.sql
/*
Navicat MySQL Data Transfer
Source Server : LocalHost
Source Server Version : 50731
Source Host : localhost:3306
Source Database : hmily_store
Target Server Type : MYSQL
Target Server Version : 50731
File Encoding : 65001
Date: 2020-11-15 15:26:29
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for wms_store
-- ----------------------------
DROP TABLE IF EXISTS `wms_store`;
CREATE TABLE `wms_store` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`prod_id` int(11) DEFAULT NULL,
`prod_name` varchar(15) DEFAULT NULL,
`prod_price` double DEFAULT NULL,
`total_stock` int(11) unsigned zerofill NOT NULL DEFAULT '00000000000',
`lock_stock` int(10) unsigned zerofill NOT NULL DEFAULT '0000000000',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
<file_sep>/boot-seata-at/server-order-9901/src/main/java/com/xiaocai/distran/serverorder/bean/OrderBean.java
package com.xiaocai.distran.serverorder.bean;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
/**
* @description: TODO 功能角色说明:
* TODO 描述:
* @author: 张小菜
* @date: 2020/11/9 22:41
* @version: v1.0
*/
@Data
@NoArgsConstructor
@ToString
public class OrderBean implements Serializable {
private Integer id ;
private String orderId ; // 订单ID
private Integer userId; // 用户ID
private Integer prodId ;//商品ID // 假设每次只买一种商品
private Integer number ; // 订单里的商品数量
}
<file_sep>/boot-hmily-tcc/hmily-order/src/main/java/com/xiaocai/distran/hmilyorder/service/impl/PayServiceImpl.java
package com.xiaocai.distran.hmilyorder.service.impl;
import com.xiaocai.distran.hmilyorder.bean.OrderBean;
import com.xiaocai.distran.hmilyorder.constants.OrderStatusEnum;
import com.xiaocai.distran.hmilyorder.mapper.OrderMapper;
import com.xiaocai.distran.hmilyorder.openfeign.AccountClient;
import com.xiaocai.distran.hmilyorder.openfeign.StockClient;
import com.xiaocai.distran.hmilyorder.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.HmilyTCC;
import org.dromara.hmily.core.holder.HmilyTransactionHolder;
import org.dromara.hmily.repository.spi.entity.HmilyTransaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @description: TODO 功能角色说明:
* TODO 描述:
* @author: 张小菜
* @date: 2020/11/15 10:51
* @version: v1.0
*/
@Service
@Slf4j
public class PayServiceImpl implements PayService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private StockClient stockClient;
@Autowired
private AccountClient accountClient;
/**
* 扣减账户金额,扣减库存
* @param order
*/
@Override
@HmilyTCC(confirmMethod = "orderConfirm", cancelMethod = "orderCancel")
public void payAccount(OrderBean order){
HmilyTransactionHolder instance = HmilyTransactionHolder.getInstance();
HmilyTransaction currentTransaction = instance.getCurrentTransaction();
Long transId = currentTransaction.getTransId();
long start = System.currentTimeMillis();
//String tranxsId = String.valueOf(HmilyTransactionHolder.getInstance().getCurrentTransaction().getTransId());
log.info("try order tranxsId : {}", transId);
orderMapper.updateStatus(order.getOrderId(), OrderStatusEnum.PAYING.getCode());
// 扣减账户金额
Boolean boolacct = accountClient.decreaseAccount(order.getUserId(), order.getTotalAmount());
// 扣减库存
Boolean boolstore = stockClient.decreaseStock(order.getProdId(), order.getNumbers());
System.out.println("hmily-cloud分布式事务耗时:" + (System.currentTimeMillis() - start));
if(!boolacct || !boolstore){ // 有一个失败事务就需要回滚
throw new RuntimeException("decrease account or decrease stock failed,订单需要回滚");
}
}
public void orderConfirm(OrderBean order) {
log.info("----- confirm add order ----");
Long transId = HmilyTransactionHolder.getInstance().getCurrentTransaction().getTransId();
log.info("----- confirm add order transId : " + transId );
orderMapper.updateStatus(order.getOrderId(), OrderStatusEnum.PAY_SECCESS.getCode());
log.info("----- 确认订单支付成功- -------- ");
}
public void orderCancel(OrderBean order) {
log.info("----- cancel add order ----");
Long transId = HmilyTransactionHolder.getInstance().getCurrentTransaction().getTransId();
log.info("----- cancel add order transId : " + transId );
orderMapper.updateStatus(order.getOrderId(), OrderStatusEnum.PAY_FAIL.getCode());
log.info("----- 确认订单支付失败- -------- ");
}
}
<file_sep>/boot-hmily-tcc/hmily-stock/src/main/java/com/xiaocai/distran/hmilystock/mapper/StockMapper.java
package com.xiaocai.distran.hmilystock.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Component;
@Mapper
@Component
public interface StockMapper {
/**
* 预备扣减库存操作
* @param prodId
* @param count
* @return
*/
@Update("update wms_store set total_stock = total_stock - #{count}, lock_stock = lock_stock + #{count} where prod_id= #{prodId}")
public Integer tryDecreaseStock(@Param("prodId") Integer prodId, @Param("count") Integer count);
/**
* 确认扣减库存
* @param prodId
* @param count
* @return
*/
@Update("update wms_store set lock_stock = lock_stock - #{count} " +
"where prod_id = #{productId} and total_stock > 0 ")
int confirmDecreaseStock(@Param("prodId") Integer prodId, @Param("count") Integer count);
/**
* 取消扣减库存
* @param prodId
* @param count
* @return
*/
@Update("update wms_store set total_stock = total_stock + #{count} ," +
" lock_stock = lock_stock - #{count} " +
" where prod_id = #{prodId} and lock_stock > 0 ")
int cancelDecreaseStock(@Param("prodId") Integer prodId, @Param("count") Integer count);
}
<file_sep>/boot-hmily-tcc/hmily-stock/src/main/java/com/xiaocai/distran/hmilystock/service/StockService.java
package com.xiaocai.distran.hmilystock.service;
public interface StockService {
boolean decreaseStock(Integer prodId, Integer count);
}
<file_sep>/boot-seata-at/server-account-9903/src/main/java/com/xiaocai/distran/serveraccount/controller/AccountController.java
package com.xiaocai.distran.serveraccount.controller;
import com.xiaocai.distran.serveraccount.service.AccountService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @description: TODO 功能角色说明:
* TODO 描述:
* @author: 张小菜
* @date: 2020/11/12 18:52
* @version: v1.0
*/
@RestController
@Slf4j
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping(value = "/v1/account/decrease" ,method = RequestMethod.POST)
public boolean decreaseAccount(@RequestParam("userId") int userId, @RequestParam("money") double money){
log.info("---decreaseAccount XID : "+ RootContext.getXID());
log.info(" receive param userId = "+userId);
log.info(" receive param money = "+money);
boolean bool = accountService.decreaseAccount(userId,money);
return bool;
}
}
<file_sep>/boot-hmily-tcc/hmily-order/src/main/java/com/xiaocai/distran/hmilyorder/constants/OrderStatusEnum.java
package com.xiaocai.distran.hmilyorder.constants;
public enum OrderStatusEnum {
NOT_PAY(1, "未支付"),
PAYING(2, "支付中"),
PAY_SECCESS(3, "支付成功"),
PAY_FAIL(4,"支付失败");
private final int code ;
private final String desc ;
OrderStatusEnum(int code, String desc){
this.code = code;
this.desc = desc ;
}
public int getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
<file_sep>/README.md
## 分布式事务Demo
## 1、 boot-seata-at
基于spring boot + seata + eureka + openfeign + mybatis 做的seata AT 模式分布式事务Demo
详细使用文档在 boot-seata-at 文件夹下的[README文档](https://github.com/small-rose/distributed-transaction/tree/main/boot-seata-at)
### 1.1 相关事宜
欢迎stars 和 fork , 也欢迎邮件交流 <a href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=ssHf097en8Ddwdfyw8Oc0d3f"> 给我Emall </a>
使用此demo过程有问题可以参考我的博客文章:[《SpringCloud 分布式事务 Seata 方案实例》](https://notes.zhangxiaocai.cn/posts/ea07db80.html)
如果涉及seata版本问题,文章也有整理说明。
如果有异常可以参考文章 [《spring-cloud 常见异常》](https://notes.zhangxiaocai.cn/posts/1618e871.html) (适合新手)。
### 2、 boot-hmily-tcc
基于spring boot + hmily + nacos + openfeign + mybatis 做的Hmily TCC 模型分布式事务Demo
详细使用文档在 boot-hmily-tcc 文件夹下的[README文档](https://github.com/small-rose/distributed-transaction/tree/main/boot-hmily-tcc)
<file_sep>/boot-hmily-tcc/sql/hmily_account.sql
/*
Navicat MySQL Data Transfer
Source Server : LocalHost
Source Server Version : 50731
Source Host : localhost:3306
Source Database : hmily_account
Target Server Type : MYSQL
Target Server Version : 50731
File Encoding : 65001
Date: 2020-11-15 15:25:26
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for ams_account
-- ----------------------------
DROP TABLE IF EXISTS `ams_account`;
CREATE TABLE `ams_account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`user_name` varchar(255) DEFAULT NULL,
`account` varchar(255) DEFAULT NULL,
`balance` decimal(15,2) DEFAULT NULL,
`freeze_amount` decimal(15,2) DEFAULT '0.00',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of ams_account
-- ----------------------------
INSERT INTO `ams_account` VALUES ('1', '202001', 'xiaocai', '2020011020201112', '10000.00', '0.00', '2020-11-15 12:19:30');
<file_sep>/boot-seata-at/server-store-9902/src/main/java/com/xiaocai/distran/serverstore/controller/StoreController.java
package com.xiaocai.distran.serverstore.controller;
import com.xiaocai.distran.serverstore.service.StoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @description: TODO 功能角色说明:
* TODO 描述:
* @author: 张小菜
* @date: 2020/11/9 23:43
* @version: v1.0
*/
@RestController
@Slf4j
public class StoreController {
@Autowired
private StoreService storeService;
@RequestMapping(value = "/v1/store/decrease" ,method = RequestMethod.POST)
public boolean updateStore(@RequestParam("prodId") Integer prodId, @RequestParam("number") Integer number, @RequestParam("userId") Integer userId){
log.info(" receive param prodId = "+prodId);
log.info(" receive param number = "+number);
log.info(" receive param userId = "+userId);
boolean bool = storeService.decreaseStore(prodId,number,userId);
return bool ;
}
}
<file_sep>/boot-hmily-tcc/sql/hmily_order.sql
/*
Navicat MySQL Data Transfer
Source Server : LocalHost
Source Server Version : 50731
Source Host : localhost:3306
Source Database : hmily_order
Target Server Type : MYSQL
Target Server Version : 50731
File Encoding : 65001
Date: 2020-11-15 15:25:49
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for oms_order
-- ----------------------------
DROP TABLE IF EXISTS `oms_order`;
CREATE TABLE `oms_order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` varchar(20) DEFAULT NULL,
`user_id` int(20) DEFAULT NULL,
`prod_id` int(11) DEFAULT NULL,
`status` int(11) DEFAULT NULL,
`numbers` int(11) DEFAULT NULL,
`total_amount` double DEFAULT NULL,
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=70 DEFAULT CHARSET=utf8mb4;
<file_sep>/boot-seata-at/server-store-9902/src/main/java/com/xiaocai/distran/serverstore/config/DataSourceConfig.java
package com.xiaocai.distran.serverstore.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @description: TODO 功能角色说明:
* TODO 描述:
* @author: 张小菜
* @date: 2020/11/12 17:21
* @version: v1.0
*/
@Configuration
public class DataSourceConfig {
@Value("${spring.application.name}")
private String appId ;
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource druidDataSource() {
return new DruidDataSource();
}
}
<file_sep>/boot-hmily-tcc/hmily-account/src/main/resources/application.yml
server:
port: 9913
spring:
application:
name: hmily-account
#--------------- datasource -----------
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/hmily_account?allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimeZone=GMT+8&nullCatalogMeansCurrent=true
username: root
password: <PASSWORD>
#------------- nacos discovery -----------
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
#--------------------- logging --------------
logging:
level:
root: info
com:
xiaocai:
distran: info
org:
dromara:
hmily: info
io:
netty: info
mybatis:
# spring boot集成mybatis的方式打印sql
configuration:
mapUnderscoreToCamelCase: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#Ribbon的负载均衡策略
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
MaxAutoRetriesNextServer : 0
MaxAutoRetries: 0
ReadTimeout: 3000
feign:
hystrix:
enabled : false
# 在feign中开启hystrix功能,默认情况下feign不开启hystrix功能
<file_sep>/boot-seata-at/server-store-9902/src/main/resources/wms_store.sql
/*
Navicat MySQL Data Transfer
Source Server : LocalHost
Source Server Version : 50731
Source Host : localhost:3306
Source Database : server_store
Target Server Type : MYSQL
Target Server Version : 50731
File Encoding : 65001
Date: 2020-11-09 21:59:35
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for wms_store
-- ----------------------------
DROP TABLE IF EXISTS `wms_store`;
CREATE TABLE `wms_store` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`prod_id` int(11) DEFAULT NULL,
`prod_name` varchar(15) DEFAULT NULL,
`store` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of wms_store
-- ----------------------------
INSERT INTO `wms_store` VALUES ('1', '1001', '小米手机', '1000');
INSERT INTO `wms_store` VALUES ('2', '1002', 'ThinkPad笔记本', '2000');
<file_sep>/boot-hmily-tcc/README.md
Exception now , DO NOT USE!
### Hmily TCC Error not found service provider for : org.dromara.hmily.core.service.HmilyTransactionHandlerFactory
TRACE LOG LIKE THIS:
```code
2020-11-15 15:18:44.844 INFO 13656 --- [nio-9912-exec-1] c.x.d.h.controller.StockController : receive param prodId = 1001
2020-11-15 15:18:44.844 INFO 13656 --- [nio-9912-exec-1] c.x.d.h.controller.StockController : receive param count = 1
2020-11-15 15:18:44.870 ERROR 13656 --- [nio-9912-exec-1] org.dromara.hmily.spi.ExtensionLoader : not found service provider for : org.dromara.hmily.core.service.HmilyTransactionHandlerFactory
2020-11-15 15:18:44.893 INFO 13656 --- [nio-9912-exec-1] c.x.d.h.service.impl.StockServiceImpl : ----- decrease Store try ...
2020-11-15 15:18:44.894 INFO 13656 --- [nio-9912-exec-1] c.x.d.h.service.impl.StockServiceImpl : ----开始执行 try 扣减库存操作-----
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4743d72a] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.jdbc.JDBC4Connection@40aa9fa] will not be managed by Spring
==> Preparing: update wms_store set total_stock = total_stock - ?, lock_stock = lock_stock + ? where prod_id= ?
==> Parameters: 1(Integer), 1(Integer), 1001(Integer)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4743d72a]
2020-11-15 15:18:44.928 INFO 13656 --- [nio-9912-exec-1] c.x.d.h.service.impl.StockServiceImpl : ----执行 try 扣减库存操作成功-----
2020-11-15 15:18:45.032 INFO 13656 --- [nio-9912-exec-2] c.x.d.h.controller.StockController : receive param prodId = 1001
2020-11-15 15:18:45.032 INFO 13656 --- [nio-9912-exec-2] c.x.d.h.controller.StockController : receive param count = 1
2020-11-15 15:18:45.057 ERROR 13656 --- [nio-9912-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.dromara.hmily.common.exception.HmilyRuntimeException: hmilyParticipant execute confirm exception:HmilyParticipant(participantId=5598468807666819072, participantRefId=null, transId=5598468483128352768, transType=TCC, status=1, appName=null, role=3, retry=0, targetClass=com.xiaocai.distran.hmilystock.service.impl.StockServiceImpl, targetMethod=decreaseStock, confirmMethod=confirmDecreaseStock, cancelMethod=cancelDecreaseStock, version=1, createTime=Sun Nov 15 15:18:44 CST 2020, updateTime=Sun Nov 15 15:18:44 CST 2020, confirmHmilyInvocation=HmilyInvocation(targetClass=interface com.xiaocai.distran.hmilystock.service.StockService, methodName=decreaseStock, parameterTypes=[class java.lang.Integer, class java.lang.Integer], args=[1001, 1]), cancelHmilyInvocation=HmilyInvocation(targetClass=interface com.xiaocai.distran.hmilystock.service.StockService, methodName=decreaseStock, parameterTypes=[class java.lang.Integer, class java.lang.Integer], args=[1001, 1]))] with root cause
org.dromara.hmily.common.exception.HmilyRuntimeException: hmilyParticipant execute confirm exception:HmilyParticipant(participantId=5598468807666819072, participantRefId=null, transId=5598468483128352768, transType=TCC, status=1, appName=null, role=3, retry=0, targetClass=com.xiaocai.distran.hmilystock.service.impl.StockServiceImpl, targetMethod=decreaseStock, confirmMethod=confirmDecreaseStock, cancelMethod=cancelDecreaseStock, version=1, createTime=Sun Nov 15 15:18:44 CST 2020, updateTime=Sun Nov 15 15:18:44 CST 2020, confirmHmilyInvocation=HmilyInvocation(targetClass=interface com.xiaocai.distran.hmilystock.service.StockService, methodName=decreaseStock, parameterTypes=[class java.lang.Integer, class java.lang.Integer], args=[1001, 1]), cancelHmilyInvocation=HmilyInvocation(targetClass=interface com.xiaocai.distran.hmilystock.service.StockService, methodName=decreaseStock, parameterTypes=[class java.lang.Integer, class java.lang.Integer], args=[1001, 1]))
at org.dromara.hmily.tcc.executor.HmilyTccTransactionExecutor.participantConfirm(HmilyTccTransactionExecutor.java:180) ~[hmily-tcc-2.1.1.jar:na]
at org.dromara.hmily.tcc.handler.ParticipantHmilyTccTransactionHandler.handler(ParticipantHmilyTccTransactionHandler.java:74) ~[hmily-tcc-2.1.1.jar:na]
at org.dromara.hmily.core.service.HmilyTransactionAspectInvoker.invoke(HmilyTransactionAspectInvoker.java:70) ~[hmily-core-2.1.1.jar:na]
at org.dromara.hmily.core.interceptor.HmilyGlobalInterceptor.interceptor(HmilyGlobalInterceptor.java:44) ~[hmily-core-2.1.1.jar:na]
at org.dromara.hmily.core.aspect.AbstractHmilyTransactionAspect.interceptTccMethod(AbstractHmilyTransactionAspect.java:54) ~[hmily-core-2.1.1.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:633) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at com.xiaocai.distran.hmilystock.service.impl.StockServiceImpl$$EnhancerBySpringCGLIB$$ac49238f.decreaseStock(<generated>) ~[classes/:na]
at com.xiaocai.distran.hmilystock.controller.StockController.decreaseStock(StockController.java:32) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.29.jar:9.0.29]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108) ~[spring-boot-actuator-2.2.2.RELEASE.jar:2.2.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) [tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367) [tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) [tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591) [tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.29.jar:9.0.29]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_191]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_191]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.29.jar:9.0.29]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_191]
2020-11-15 15:19:44.564 INFO 13656 --- [self-recovery-1] .s.HmilyTransactionSelfRecoveryScheduled : hmily tcc transaction begin self recovery: HmilyParticipant(participantId=5598468807666819072, participantRefId=null, transId=5598468483128352768, transType=TCC, status=1, appName=hmily-stock, role=3, retry=1, targetClass=com.xiaocai.distran.hmilystock.service.impl.StockServiceImpl, targetMethod=decreaseStock, confirmMethod=confirmDecreaseStock, cancelMethod=cancelDecreaseStock, version=2, createTime=Sun Nov 15 15:19:44 CST 2020, updateTime=Sun Nov 15 15:19:44 CST 2020, confirmHmilyInvocation=HmilyInvocation(targetClass=interface com.xiaocai.distran.hmilystock.service.StockService, methodName=decreaseStock, parameterTypes=[class java.lang.Integer, class java.lang.Integer], args=[1001, 1]), cancelHmilyInvocation=HmilyInvocation(targetClass=interface com.xiaocai.distran.hmilystock.service.StockService, methodName=decreaseStock, parameterTypes=[class java.lang.Integer, class java.lang.Integer], args=[1001, 1]))
2020-11-15 15:19:44.567 ERROR 13656 --- [self-recovery-1] .d.h.c.s.HmilyTransactionRecoveryService : hmily Recovery executor confirm exception param:HmilyParticipant(participantId=5598468807666819072, participantRefId=null, transId=5598468483128352768, transType=TCC, status=1, appName=hmily-stock, role=3, retry=1, targetClass=com.xiaocai.distran.hmilystock.service.impl.StockServiceImpl, targetMethod=decreaseStock, confirmMethod=confirmDecreaseStock, cancelMethod=cancelDecreaseStock, version=2, createTime=Sun Nov 15 15:19:44 CST 2020, updateTime=Sun Nov 15 15:19:44 CST 2020, confirmHmilyInvocation=HmilyInvocation(targetClass=interface com.xiaocai.distran.hmilystock.service.StockService, methodName=decreaseStock, parameterTypes=[class java.lang.Integer, class java.lang.Integer], args=[1001, 1]), cancelHmilyInvocation=HmilyInvocation(targetClass=interface com.xiaocai.distran.hmilystock.service.StockService, methodName=decreaseStock, parameterTypes=[class java.lang.Integer, class java.lang.Integer], args=[1001, 1]))
java.lang.NullPointerException: null
at org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(MethodUtils.java:219) ~[commons-lang3-3.9.jar:3.9]
at org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(MethodUtils.java:256) ~[commons-lang3-3.9.jar:3.9]
at org.dromara.hmily.core.reflect.HmilyReflector.executeLocal(HmilyReflector.java:84) ~[hmily-core-2.1.1.jar:na]
at org.dromara.hmily.core.reflect.HmilyReflector.executor(HmilyReflector.java:59) ~[hmily-core-2.1.1.jar:na]
at org.dromara.hmily.core.schedule.HmilyTransactionRecoveryService.confirm(HmilyTransactionRecoveryService.java:62) ~[hmily-core-2.1.1.jar:na]
at org.dromara.hmily.core.schedule.HmilyTransactionSelfRecoveryScheduled.tccRecovery(HmilyTransactionSelfRecoveryScheduled.java:138) [hmily-core-2.1.1.jar:na]
at org.dromara.hmily.core.schedule.HmilyTransactionSelfRecoveryScheduled.lambda$selfTccRecovery$2(HmilyTransactionSelfRecoveryScheduled.java:124) [hmily-core-2.1.1.jar:na]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_191]
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) ~[na:1.8.0_191]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_191]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) ~[na:1.8.0_191]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_191]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_191]
at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_191]
Process finished with exit code -1
```
## boot-hmily-tcc
### Hmily TCC 模式分布式事务Demo工程
- Hmily TCC 模式Demo (非官方Demo)
- 理论就不重复介绍了,随便一搜就有。
### 分布式事务环境介绍
- JDK 1.8
- Apache-maven-3.6.0
- SpringBoot 2.2.2.RELEASE
- SpringCloud Hoxton.SR8
- Spring-Cloud-alibaba 2.2.3.RELEASE
- Nacos-Server 1.4.0
- 服务调用openfeign + ribbon+ hystrix
- 数据库 MySQL 5.7.31
- 测试仅学习和演示分布式事务,表设计和工程尽可能简化
### 服务说明
- Nacos-Server 作为注册中心来使用
- hmily-order 模拟订单服务 hmily-order 端口号 9911
- hmily-stock 模拟库存服务 hmily-store 端口号 9912
- hmily-account 模拟扣款服务 hmily-account 端口号 9913
相关端口号写在了服务名上。
#### 调用流程
hmily-order ---> hmily-store and hmily-account
测试入口:
http://localhost:9911/v1/order/add/1001/1/120
<file_sep>/boot-hmily-tcc/hmily-stock/src/main/java/com/xiaocai/distran/hmilystock/bean/StockBean.java
package com.xiaocai.distran.hmilystock.bean;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* @description: TODO 功能角色说明:
* TODO 描述:
* @author: 张小菜
* @date: 2020/11/12 19:14
* @version: v1.0
*/
@Data
@NoArgsConstructor
@ToString
public class StockBean {
private Integer id ;
private Integer prodId ;
private String prodName ;
private double prodPrice ;
private Integer totalStock ;
private Integer lockStock ;
}
<file_sep>/boot-seata-at/server-store-9902/src/main/java/com/xiaocai/distran/serverstore/service/StoreService.java
package com.xiaocai.distran.serverstore.service;
public interface StoreService {
public boolean decreaseStore(Integer prodId, Integer number, Integer userId);
}
<file_sep>/boot-seata-at/server-store-9902/src/main/resources/application.yml
server:
port: 9902
servlet:
application-display-name: server-store
#====================================datasource =============================================
spring:
application:
name: server-store
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
platform: mysql
url: jdbc:mysql://127.0.0.1:3306/server_store?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
username: root
password: <PASSWORD>
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# filters: stat,wall,log4j
logShowSql: true
#====================================cloud =============================================
cloud:
alibaba:
seata:
enabled: true
tx-service-group: my_test_tx_group
enable-auto-data-source-proxy: true
service:
disable-global-transaction: false
vgroupMapping.my_test_tx_group: seata_server
grouplist:
default: 127.0.0.1:8091
# consul:
# host: localhost
# port: 8500
# discovery:
# service-name: ${spring.application.name}
#==================================== logging =============================================
logging:
level:
root: info
com:
xiaocai:
distran:
serverorder: info
mapper: info
io:
seata: info
org:
springframework:
cloud:
alibaba:
seata:
web: info
mybatis:
# spring boot集成mybatis的方式打印sql
configuration:
mapUnderscoreToCamelCase: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#==================================== eureka =============================================
eureka:
client: #客户端注册进eureka服务列表内
service-url:
defaultZone: http://localhost:9900/eureka
fetch-registry: true
instance:
instance-id: server-store # 可以自定义服务名称展示
prefer-ip-address: true # 访问路径可以显示IP
<file_sep>/boot-hmily-tcc/sql/hmily.sql
/*
Navicat MySQL Data Transfer
Source Server : LocalHost
Source Server Version : 50731
Source Host : localhost:3306
Source Database : hmily
Target Server Type : MYSQL
Target Server Version : 50731
File Encoding : 65001
Date: 2020-11-15 15:24:50
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for hmily_lock
-- ----------------------------
DROP TABLE IF EXISTS `hmily_lock`;
CREATE TABLE `hmily_lock` (
`lock_id` bigint(20) NOT NULL COMMENT '主键id',
`trans_id` bigint(20) NOT NULL COMMENT '全局事务id',
`participant_id` bigint(20) NOT NULL COMMENT 'hmily参与者id',
`resource_id` varchar(256) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '资源id',
`target_table_name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '锁定目标表名',
`target_table_pk` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '锁定表主键',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`lock_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='hmily全局lock表';
-- ----------------------------
-- Records of hmily_lock
-- ----------------------------
-- ----------------------------
-- Table structure for hmily_participant_undo
-- ----------------------------
DROP TABLE IF EXISTS `hmily_participant_undo`;
CREATE TABLE `hmily_participant_undo` (
`undo_id` bigint(20) NOT NULL COMMENT '主键id',
`participant_id` bigint(20) NOT NULL COMMENT '参与者id',
`trans_id` bigint(20) NOT NULL COMMENT '全局事务id',
`resource_id` varchar(256) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '资源id,tac模式下为jdbc url',
`undo_invocation` longblob NOT NULL COMMENT '回滚调用点',
`status` tinyint(4) NOT NULL COMMENT '状态',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`undo_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='hmily事务参与者undo记录,用在AC模式';
-- ----------------------------
-- Records of hmily_participant_undo
-- ----------------------------
-- ----------------------------
-- Table structure for hmily_transaction_global
-- ----------------------------
DROP TABLE IF EXISTS `hmily_transaction_global`;
CREATE TABLE `hmily_transaction_global` (
`trans_id` bigint(20) NOT NULL COMMENT '全局事务id',
`app_name` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '应用名称',
`status` tinyint(4) NOT NULL COMMENT '事务状态',
`trans_type` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '事务模式',
`retry` int(11) NOT NULL DEFAULT '0' COMMENT '重试次数',
`version` int(11) NOT NULL COMMENT '版本号',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`trans_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='hmily事务表(发起者)';
-- ----------------------------
-- Records of hmily_transaction_global
-- ----------------------------
-- ----------------------------
-- Table structure for hmily_transaction_participant
-- ----------------------------
DROP TABLE IF EXISTS `hmily_transaction_participant`;
CREATE TABLE `hmily_transaction_participant` (
`participant_id` bigint(20) NOT NULL COMMENT '参与者事务id',
`participant_ref_id` bigint(20) DEFAULT NULL COMMENT '参与者关联id且套调用时候会存在',
`trans_id` bigint(20) NOT NULL COMMENT '全局事务id',
`trans_type` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '事务类型',
`status` tinyint(4) NOT NULL COMMENT '分支事务状态',
`app_name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '应用名称',
`role` tinyint(4) NOT NULL COMMENT '事务角色',
`retry` int(11) NOT NULL DEFAULT '0' COMMENT '重试次数',
`target_class` varchar(512) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '接口名称',
`target_method` varchar(128) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '接口方法名称',
`confirm_method` varchar(128) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'confirm方法名称',
`cancel_method` varchar(128) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'cancel方法名称',
`confirm_invocation` longblob COMMENT 'confirm调用点',
`cancel_invocation` longblob COMMENT 'cancel调用点',
`version` int(11) NOT NULL DEFAULT '0',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`participant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='hmily事务参与者';
-- ----------------------------
-- Records of hmily_transaction_participant
-- ----------------------------
<file_sep>/boot-seata-at/server-order-9901/src/main/java/com/xiaocai/distran/serverorder/interceptor/SeataRestTemplateInterceptor.java
package com.xiaocai.distran.serverorder.interceptor;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;
import java.io.IOException;
/**
* @description: TODO 功能角色说明:
* TODO 描述:
* @author: 张小菜
* @date: 2020/11/12 14:16
* @version: v1.0
*/
@Slf4j
public class SeataRestTemplateInterceptor implements ClientHttpRequestInterceptor {
public SeataRestTemplateInterceptor() {
log.info(" SeataRestTemplateInterceptor 初始化构造...");
}
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
HttpRequestWrapper requestWrapper = new HttpRequestWrapper(httpRequest);
String xid = RootContext.getXID();
log.info("---intercept xid : "+xid);
if (StringUtils.isNotEmpty(xid)) {
requestWrapper.getHeaders().add(RootContext.KEY_XID, xid);
}
return clientHttpRequestExecution.execute(requestWrapper, bytes);
}
}
<file_sep>/boot-seata-at/sql/server_account.sql
/*
Navicat MySQL Data Transfer
Source Server : LocalHost
Source Server Version : 50731
Source Host : localhost:3306
Source Database : server_account
Target Server Type : MYSQL
Target Server Version : 50731
File Encoding : 65001
Date: 2020-11-13 00:57:05
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for ams_account
-- ----------------------------
DROP TABLE IF EXISTS `ams_account`;
CREATE TABLE `ams_account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`user_name` varchar(255) DEFAULT NULL,
`account` varchar(255) DEFAULT NULL,
`amount` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of ams_account
-- ----------------------------
INSERT INTO `ams_account` VALUES ('1', '202001', 'xiaocai', '2020011020201112', '10000');
-- ----------------------------
-- Table structure for undo_log
-- ----------------------------
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`branch_id` bigint(20) NOT NULL,
`xid` varchar(100) NOT NULL,
`context` varchar(128) NOT NULL,
`rollback_info` longblob NOT NULL,
`log_status` int(11) NOT NULL,
`log_created` datetime NOT NULL,
`log_modified` datetime NOT NULL,
`ext` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of undo_log
-- ----------------------------
<file_sep>/boot-seata-at/sql/server_order.sql
/*
Navicat MySQL Data Transfer
Source Server : LocalHost
Source Server Version : 50731
Source Host : localhost:3306
Source Database : server_order
Target Server Type : MYSQL
Target Server Version : 50731
File Encoding : 65001
Date: 2020-11-13 00:57:28
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for oms_order
-- ----------------------------
DROP TABLE IF EXISTS `oms_order`;
CREATE TABLE `oms_order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` varchar(20) DEFAULT NULL,
`user_id` int(20) DEFAULT NULL,
`prod_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Table structure for undo_log
-- ----------------------------
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`branch_id` bigint(20) NOT NULL,
`xid` varchar(100) NOT NULL,
`context` varchar(128) NOT NULL,
`rollback_info` longblob NOT NULL,
`log_status` int(11) NOT NULL,
`log_created` datetime NOT NULL,
`log_modified` datetime NOT NULL,
`ext` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB AUTO_INCREMENT=75 DEFAULT CHARSET=utf8;
<file_sep>/boot-hmily-tcc/hmily-stock/src/main/java/com/xiaocai/distran/hmilystock/HmilyStockApplication.java
package com.xiaocai.distran.hmilystock;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication(exclude = MongoAutoConfiguration.class)
@EnableDiscoveryClient
@EnableTransactionManagement
public class HmilyStockApplication {
public static void main(String[] args) {
SpringApplication.run(HmilyStockApplication.class, args);
}
}
| b25641c41c7f80e61ba973eaaa33483d9bb8e144 | [
"Java",
"Markdown",
"SQL",
"YAML"
] | 33 | Java | small-rose/distributed-transaction | c706554e5d4c2b228d42e271018d406b04cfffc9 | f1cf4867cf489167e497306545445c2e299418d0 |
refs/heads/master | <file_sep>'use strict';
const UsuarioDelAPI = require('../../models/UsuarioDelAPI');
const i18n = require('../../lib/i18nSetup')();
const jwt = require('jsonwebtoken');
class LoginController {
// GET /api/authenticate
index(req, res, next) {
res.locals.user = ''; // para que la vista tenga el nombre de usuario
res.locals.error = '';
res.render('APILogin');
}
// POST /api/authenticate
async post(req, res, next) {
// async jwtCreation(req, res, next) {
const userName = req.body.user; // Esto se hace en Ajax
console.log('SERVIDOR en loginController.js ---> El usuario es:', userName);
// const user = await UsuarioDelAPI.findOne({ user: userName });
// Creamos el JWT token
//jwt.sign({ _id: user._id }, process.env.JWT_SECRET, {
jwt.sign(
{ _id: userName._id }, // user._id },
'miclave', // Clave del servidor
{
expiresIn: '2d'
},
(err, token_id) => {
if (err) {
return next(err);
}
//window.localStorage.setItem('myJWT', token_id);
console.log('token_id PASADO al navegador:', token_id);
// respondemos con un JWT
//req.session.jwtToken = token_id;
res.setHeader('x-access-token', token_id);
res.json({ ok: true, token_id: token_id });
// res.send(token_id);
}
);
}
logout(req, res, next) {
delete req.session.authUser;
req.session.regenerate(function(err) {
if (err) {
return next(err);
}
res.redirect('/');
});
}
} // End of the class
module.exports = new LoginController();
<file_sep>'use strict';
/* let register = function(Handlebars) {
let helpers = {
i18nHelper: function() { return 'AABB';}
}
};
for (let prop in register.helpers) {
Handlebars.registerHelper(prop, helpers[prop]);
}
module.exports.register = register;
module.exports.helpers = register(null);
*/
exports.yell = function(msg) {
return msg.toUpperCase();
}<file_sep>'use strict';
const mongoose = require('mongoose');
// var hash = require('hash.js')
const usuarioSchema = mongoose.Schema({
user: String,
});
/*usuarioSchema.statics.hashPassword = function(plain) {
return hash.sha256().update(plain).digest('hex');
} */
var UsuarioDelAPI = mongoose.model('UsuarioDelAPI', usuarioSchema);
module.exports = UsuarioDelAPI;
<file_sep> <!--
Visor de Markdown
http://strapdownjs.com/
-->
<xmp theme="united" style="display:none;">
{{readme}}
</xmp>
<script src="http://strapdownjs.com/v/0.2/strapdown.js"></script>
<file_sep>const i18n = require('./i18nSetup')();
module.exports = {
//Setup our default layout
defaultLayout: 'index',
//More handlebars configuration
// ..
//Register handlebars helpers
helpers: {
//Register your helpers
// ..
//Helper for multiple languages
i18n: function(str){
//return i18n.__.apply(this, arguments);
return i18n.__(str); // Both lines do the same thing
},
getLocales: function() {
return getLocales();
}
}
}
// module.exports = hbsconf;
<file_sep>'use strict';
const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser'); // We can get info from POST and/or URL parameters
const session = require('express-session');
const sessionAuth = require('./lib/sessionAuth');
const jwtAuth = require('./lib/jwtAuth');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);
// Conexión a la base de datos
const db = require('./lib/connectMongoose'); // ??
require('dotenv').config(); // inicializamos variables de entrono desde el fichero .env
// Cargamos las definiciones de todos nuestros modelos
require('./models/Anuncio');
require('./models/Usuario');
require('./models/UsuarioDelAPI');
// view engine setup
// Source: https://webapplog.com/jade-handlebars-express/
let helpers = require('./public/hs/helpers');
const app = express();
//let dirName = __dirname; //.includes('api') ? path.dirname(module.parent.__dirname) : __dirname;
// Load handlebars engine and load our configuration
// from the file hbsconf.js under a libs folder at the same level of the application
const handlebars = require('express-handlebars').create(require('./lib/hbsconf.js'));
//Set our application to use our configured handlebars module as the view engine
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
// app.use(logger('dev'));
if (process.env.LOG_FORMAT !== 'nolog') {
app.use(logger(process.env.LOG_FORMAT || 'dev'));
}
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
const i18n = require('./lib/i18nSetup')();
app.use(i18n.init);
// Global Template variables
app.locals.title = 'NodePop';
// Login
const loginController = require('./routes/loginController');
const APILoginController = require('./routes/apiv1/loginController');
app.get('/api/authenticate', APILoginController.index);
app.post('/api/authenticate', APILoginController.post);
app.get('/api/logout', APILoginController.logout);
//app.post('/api/authenticate', loginController.APIPost); //jwtCreation);
//app.use('/api/anuncios', jwtAuth(), require('./routes/apiv1/anuncios'));
// catch API 404 and forward to error handler
// app.use('/api', function (req, res, next) {
app.use('/api', function(req, res, next) {
const err = new Error(__('not_found'));
err.status = 404;
next(err);
});
// middleware de control de sesiones
app.use(
session({
name: 'nodepop',
secret: '<KEY>',
resave: false,
saveUninitialized: false,
cookie: { maxAge: 2 * 24 * 3600 * 1000 }, // dos dias de inactividad
store: new MongoStore({
// url: cadena de conexión
mongooseConnection: mongoose.connection,
autoReconnect: true,
clear_interval: 3600
})
})
);
// usamos las rutas de un controlador
app.get('/login', loginController.index); // Si comenta esta línea, el navegador da error: "TOO_MANY_REDIRECTS" !!
app.post('/login', loginController.post);
app.get('/logout', loginController.logout);
app.use('/', sessionAuth(), require('./routes/index')); // Ponía sessionAuth, sin paréntesis, y no cargaba ninguna página !!
app.use('/anuncios', require('./routes/index'));
// app.use('/hola', require('./routes/hola').router);
// Web
// app.use('/', require('./routes/anuncios'));
// app.use('/anuncios', require('./routes/anuncios'));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
const err = new Error(__('not_found'));
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
if (err.array) {
// validation error
err.status = 422;
const errInfo = err.array({ onlyFirstError: true })[0];
err.message = isAPI(req)
? { message: __('not_valid'), errors: err.mapped() }
: `${__('not_valid')} - ${errInfo.param} ${errInfo.msg}`;
}
// establezco el status a la respuesta
err.status = err.status || 500;
res.status(err.status);
// si es un 500 lo pinto en el log
if (err.status && err.status >= 500) console.error(err);
// si es una petición al API respondo JSON...
if (isAPI(req)) {
res.json({ success: false, error: 'Petición al API. ' + err.message });
return;
}
// ...y si no respondo con HTML...
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.render('error');
});
function isAPI(req) {
return req.originalUrl.indexOf('/api') === 0;
}
module.exports = app;
<file_sep>
{{> header}}
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>{{i18n "Ads List"}}</h1>
<p class="lead">{{i18n "Listing"}}: {{total}} {{i18n "Of"}} {{total}} </p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-hover">
<thead><tr>
<th>{{i18n "Name"}}</th>
<th>{{i18n "For Sale"}}</th>
<th style="text-align: right">{{i18n "Price"}}</th>
<th>{{i18n "Photo"}}</th>
<th>{{i18n "Tags"}}</th>
<th>#</th>
</tr></thead>
<tbody>
{{#each anuncios}}
<tr>
<td>{{i18n this.nombre}}</td>
<td>{{this.venta}}</td>
<td style="text-align: right">{{this.precio}} / 100 €</td>
<td><img src="{{this.foto}}"></td>
<td>{{#each this.tags}}
{{i18n this}}
{{/each}}
</td>
<td>{{this.anuncio._id}}</td>
</tr>
{{/each}}
</tbody>
</table>
<p>{{i18n "Examples"}}:</p>
<ul>
<li><a href="?">{{i18n "All the ads"}}</a></li>
<li><a href="?start=2&limit=2">{{i18n "paginated"}}</a></li>
<li><a href="?sort=precio">{{i18n "Sorted by increasing price"}}</a></li>
<li><a href="?sort=-precio">{{i18n "Sorted by decreasing price"}}</a></li>
<li><a href="?tag=mobile">{{i18n "With the mobile tag"}}</a></li>
</ul>
</div>
</div>
<a href="/">{{i18n "Go back home"}}</a>
</div>
<file_sep>
<div class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header"><a href="/" class="navbar-brand">Nodeapi</a></div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Lista de anuncios</h1>
<p class="lead">Listando: anuncios.length de total /p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-hover">
<thead><tr>
<th>Nombre</th>
<th>Venta</th>
<th style="text-align: right">Precio</th>
<th>Foto</th>
<th>Tags</th>
<th>#</th>
</tr></thead>
<tbody>
{{#each anuncios}}
<tr>
<td>{{this.nombre}}</td>
<td>anuncio.venta ? 'Si' : 'No' </td>
<td style="text-align: right"><{{this.precio}} / 100 €</td>
<td><img src="{{this.foto}}"></td>
<td>{{this.tags}}</td>
<td>{{this.anuncio._id}}</td>
</tr>
{{/each}}
</tbody>
</table>
<p>Ejemplos:</p>
<ul>
<li><a href="?">Todos (max. 1000)</a></li>
<li><a href="?start=2&limit=2">Paginado</a></li>
<li><a href="?sort=precio">Ordenado por precio ascendente</a></li>
<li><a href="?sort=-precio">Ordenado por precio descendente</a></li>
<li><a href="?tag=mobile">Con tag mobile</a></li>
</ul>
</div>
</div>
<a href="/">Volver a la home</a>
</div>
<file_sep>{{> header}}
<section class="main">
<div class="container h-100">
<div class="row h-100">
<p>{{i18n 'Please login to access application'}}</p>
</div>
<div class="row h-100">
<form method="POST">
<div class="form-group">
<label for="email">{{i18n 'Email address'}}</label>
<input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email"
name="email"
value={{email}} >
<small id="emailHelp" class="form-text text-muted"></small>
</div>
<div class="form-group">
<label for="password">{{i18n 'Password'}}</label>
<input type="<PASSWORD>" class="form-control" id="password" placeholder="{{i18n '<PASSWORD>'}}"
name="password">
</div>
<button type="submit" id="login" class="btn btn-primary">{{i18n 'Submit'}}</button>
<div class="error">{{error}}</div>
</form>
</div>
</section>
<file_sep><div class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header"><a href="/" class="navbar-brand">{{title}}</a></div>
<span class="navbar-logout">
<a href="/logout" class="language-item">{{i18n 'Logout'}}</a>
</span>
<span class="navbar-language-selector">
{{#each getLocales}}
<a href="/lang/{{this}}" class="language-item">{{this}}</a>
{{/each}}
</span>
</div>
</div>
<file_sep>'use strict';
const connectionPromise = require('./connectAMQP');
const q = 'q3';
// Publicador
// IIFE Inmediatelly Invoked Function Expression
(async () => {
// nos aseguramos de que está conectado
const conn = await connectionPromise;
// conectarnos a un canal
const ch2 = await conn.createChannel();
// conecto a una cola
await ch2.assertQueue(q, {
// auto_delete: true,
durable: false // NO sobrevive a reinicios
});
// maximo teórico del tamaño de un mensaje:
// 9,223,372,036,854,775,807 B
//setInterval(() => {
//const mensaje = {
// const directorio = 'home/jose/1-KeepCoding/Proyecto-articulos/src/img/';
const rutaFoto = '/home/jose/1-KeepCoding/Proyecto-articulos/src/img/libro1.jpg';
//};
// mandar mensaje
// const res = ch.sendToQueue(q, new Buffer(JSON.stringify(mensaje)), {
const res = ch2.sendToQueue(q, new Buffer(rutaFoto), {
// persistent: true // para sobrevivir a reinicios
});
console.log(`enviado: ${rutaFoto} ${res}`);
})().catch((err) => console.error(err));
<file_sep>'use strict';
function crearJWTToken() {
$.ajax({
method: 'post',
url: '/api/authenticate',
data: {
// Valores que se pasan al cuerpo de la petición del servidor (res.body)
user: $('#user').val()
},
success: function(data) {
// "data" designa al objeto JSON enviado por el servidor
console.log('Hola, soy el cliente');
console.log('Token recibido:', data.token_id);
localStorage.setItem('token2', data.token_id);
},
error: function(err) {
console.log('Error:', err);
}
});
}
function getRequestToTheAPI() {
let token = localStorage.getItem('token');
$.ajax({
method: 'get',
url: '/api/anuncios',
data: {
// Valores que se pasan al cuerpo de la petición del servidor (req.body)
},
headers: { 'x-access-token': token },
// Valores que se pasan a la cabecera de la petición del servidor (req.headers)
success: function(data) {
// "data" designa al objeto JSON mandado por el servidor
console.log('DATOS recibidos:', data._id);
},
error: function(err) {
console.log('Error:', err);
}
});
}
$(document).ready(function() {
// Esta línea es imprescindible !!!
// document.getElementById('prueba').addEventListener('click', function() {
$('#API-login').on('click', function() {
crearJWTToken();
});
let token = localStorage.getItem('token');
// JR Duda: qué evento está asociado a esta función ajax
/*$.ajax({
method: 'get',
url: '/api/anuncios',
data: {
// Valores que se pasan al cuerpo de la petición del servidor (req.body)
},
headers: { 'x-access-token': localStorage.getItem('token') }, // token },
// Valores que se pasan a la cabecera de la petición del servidor (req.headers)
success: function(data) {
// "data" designa al objeto JSON mandado por el servidor
console.log('DATOS recibidos:', data._id);
},
error: function(err) {
console.log('Error:', err);
}
}); */
/*$(document).on('readystatechange', function() {
console.log('Dirección cambiada !!');
});*/
});
<file_sep>#for f in *.ejs; do echo "$f"; done
#for f in *.ejs; do new=$(echo $f | sed -e 's/\.ejs$/\.hbrs/'); echo ${new}; done
convert() {
## Command to rename all the template files to "handlebars"
for f in $(ls $PWD | grep $1); do
new=$(echo $f | sed -e "s/$1/$2/");
## new=$(echo $f | sed -e 's/$1/EXT/');
## Esto no funciona, pq con comillas simples no hay interpolación de variables !!
mv -v $f $new;
done;
}
convert '..handlebars' '.handlebars'
<file_sep>'use strict';
const router = require('express').Router();
const fs = require('fs');
const Anuncio = require('mongoose').model('Anuncio');
const i18n = require('../lib/i18nSetup')();
//i18n('en');
/* GET anuncios page. */
router.get('/', async function(req, res, next) {
try {
const start = parseInt(req.query.start) || 0;
const limit = parseInt(req.query.limit) || 1000; // nuestro api devuelve max 1000 registros
const sort = req.query.sort || '_id';
const includeTotal = true;
const filters = {};
if (req.query.tag) {
}
if (req.query.venta) {
filters.venta = req.query.venta;
}
const { total, rows } = await Anuncio.list(filters, start, limit, sort, includeTotal);
res.render('anuncios', { total, anuncios: rows }); // Original
} catch (err) {
return res.next(err);
}
});
router.get('/lang/:locale', (req, res, next) => {
//console.log('LA VISTA TIENE ESTO:', res.locals);
const locale = req.params.locale;
console.log('LCambio a ', locale);
const referer = req.query.redir || req.get('referer');
res.cookie('nodepop-lang', locale, { maxAge: 900000, httpOnly: true });
res.redirect(referer);
});
module.exports = router;
<file_sep>'use strict';
const jwt = require('jsonwebtoken');
module.exports = function(token) {
// devuelve un middleware que si no hay usuario responde con error
return function(req, res, next) {
// let existingToken = '<KEY>';
// req.header('x-access-token');
let existingToken = req.session.jwtToken;
// res.setHeader('Acces-Control-Allow-Headers', 'x-access-token, mytoken');
let token = existingToken || req.body.token || req.query.token || req.get('x-access-token');
res.setHeader('x-access-token', token);
console.log('Token q usaremos:', token);
if (!token) {
const err = new Error('no token provided');
next(err);
return;
}
// tengo token
// jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
jwt.verify(token, 'mi<PASSWORD>', (err, decoded) => {
if (err) {
return next(err);
}
// guardo el id del usuario en request para que
// los siguientes middlewares puedan usarlo
// res.json(decoded);
console.log('Token correcto-1111111', req.session.jwtToken);
req.userId = decoded._id;
console.log('Token correcto', decoded._id);
// el usuario está autenticado
next();
// if everything is good, save to request for use in other routes
// req.decoded = decoded;
});
};
};
<file_sep>'use strict';
const connectionPromise = require('./connectAMQP');
const Jimp = require('jimp');
const q = 'q3';
// Consumidor
// IIFE Inmediatelly Invoked Function Expression
(async () => {
// nos aseguramos de que está conectado
const conn = await connectionPromise;
// conectarnos a un canal
const ch2 = await conn.createChannel();
// conecto a una cola
await ch2.assertQueue(q, { durable: false });
// le decimos a rabbitMQ cuántos mensaje puede darme en paralelo
ch2.prefetch(1);
await ch2.consume(q, function(msg) {
let photo = msg.content.toString();
console.log('Consumidor:', photo);
// procesamos el mensaje
Jimp.read(photo)
.then(function(photo) {
photo
.resize(100, 100) // resize
.quality(60) // set JPEG quality
.write('thumbnail.jpg'); // save
// confirmamos a rabbit que está procesado
ch2.ack(msg); // ch2.nack(msh)
})
.catch(function(err) {
console.error(err);
});
});
})();
<file_sep>{{> header}}
<section class="main">
<div class="container h-100">
<div class="row h-100">
<p>{{i18n 'Please login to access the API'}}</p>
</div>
<div class="row h-100">
<form method="POST">
<div class="form-group">
<label for="email">{{i18n 'User'}}</label>
<input type="text" class="form-control" id="user" aria-describedby="emailHelp" placeholder={{i18n 'Enter user'}}
name="user"
value={{user}} >
<small id="emailHelp" class="form-text text-muted"></small>
</div>
<button type="submit" id="API-login" class="btn btn-primary">{{i18n 'Submit'}}</button>
<div class="error">{{error}}</div>
</form>
</div>
</section>
<file_sep>'use strict';
//const mongoose = require('mongoose');
const readLine = require('readline');
//const async = require('async');
//require('./lib/i18nSetup');
const conn = require('./lib/connectMongoose');
const Usuario = require('./models/Usuario'); // Cargamos las definiciones de todos nuestros modelos
conn.once('open', async function() {
// uso try/catch para cazar los errores de async/await
try {
await initUsuarios();
// otros inits ...
conn.close();
} catch(err) {
console.log('Hubo un error:', err);
process.exit(1);
}
});
async function initUsuarios() {
const deleted = await Usuario.deleteMany();
console.log(`Eliminados ${deleted.result.n} usuarios.`);
const inserted = await Usuario.insertMany([
{ name: 'admin',
email: '<EMAIL>',
password: <PASSWORD>('<PASSWORD>') }
]);
console.log(`Insertados ${inserted.length} usuarios.`);
}
/*conn.once('open', async function () {
const rl = readLine.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Are you sure you want to empty conn? (no) ', function (answer) {
rl.close();
if (answer.toLowerCase() === 'yes') {
runInstallScript();
} else {
console.log('conn install aborted!');
return process.exit(0);
}
});
});
function runInstallScript() {
async.series([
initAnuncios
], (err) => {
if (err) {
console.error( __('generic', { err }) );
return process.exit(1);
}
return process.exit(0);
}
);
}
function initAnuncios(cb) {
const Anuncio = mongoose.model('Anuncio');
Anuncio.remove({}, ()=> {
console.log('Anuncios borrados.');
// Cargar anuncios.json
const fichero = './anuncios.json';
console.log('Cargando ' + fichero + '...');
Anuncio.cargaJson(fichero, (err, numLoaded)=> {
if (err) return cb(err);
console.log(`Se han cargado ${numLoaded} anuncios.`);
return cb(null, numLoaded);
});
}); */
| 03732dcb978d23c9eaceabf2c453505576393bb8 | [
"Handlebars",
"Shell",
"JavaScript"
] | 18 | Handlebars | josealonso/KC-Modulo-de-Node-js-avanzado | 5a661baa04472ca3660ae67bc753467bd1b1c5a4 | 865ae8bdf8670fafe65638335d30166e994ee192 |
refs/heads/master | <repo_name>decassidy/jssandbox<file_sep>/.atom/config.cson
"*":
"atom-ide-ui":
"atom-ide-diagnostics-ui":
autoVisibility: true
"autocomplete-python":
pythonPaths: "C:\\Users\\derri\\AppData\\Local\\Programs\\Python\\Python36-32\\python.exe"
showDescriptions: false
useKite: false
useSnippets: "all"
"autocomplete-python-jedi":
useSnippets: "all"
"build-python":
customInterpreter: "C:\\Users\\derri\\AppData\\Local\\Programs\\Python\\Python36-32\\python.exe"
core:
disabledPackages: [
"linter"
]
telemetryConsent: "no"
uriHandlerRegistration: "always"
"exception-reporting":
userId: "40243124-4957-4471-b8aa-e24cd795c773"
"ide-python":
pylsPlugins:
pydocstyle:
enabled: true
python: "C:\\Users\\derri\\AppData\\Local\\Programs\\Python\\Python36-32\\python.exe"
"linter-ui-default":
panelHeight: 266
"python-debugger":
pythonExecutable: "C:\\Users\\derri\\AppData\\Local\\Programs\\Python\\Python36-32\\python.exe"
"python-indent":
hangingIndentTabs: 2
"python-tools":
pythonPath: "C:\\Users\\derri\\AppData\\Local\\Programs\\Python\\Python36-32\\python.exe"
typewriter:
enabledForAllScopes: true
showGutter: true
showScrollbar: true
".console.python.text":
editor:
showIndentGuide: true
softWrapAtPreferredLineLength: true
".python.regexp.source":
editor:
showIndentGuide: true
".python.source":
editor:
showIndentGuide: true
".python.text.traceback":
editor:
showIndentGuide: true
<file_sep>/.gitconfig
[user]
name = <NAME>
email = <EMAIL>
| 8cfcb8f738b78d5f7953447c20fe39b106a50aaa | [
"CSON",
"Git Config"
] | 2 | CSON | decassidy/jssandbox | ccd5545a07222904310f491b949100dd1c3c43f7 | b508614bfbb3341488107d545287e005047d8c81 |
refs/heads/master | <file_sep><a href="<?php echo site_url($menu['category_info']->slug);?>"><?php echo $menu['category_info']->name; ?></a>
<?php if(isset($menu['sub_category_info'])){
?>
>> <a href="<?php echo site_url($menu['sub_category_info']->slug);?>"><?php echo $menu['sub_category_info']->name; ?></a>
<?php } ?>
<?php if(!empty($category->description)): ?>
<!--<div class="row">
<div class="span12"><?php echo $category->description; ?></div>
</div>-->
<?php endif; ?>
<?php if((!isset($subcategories) || count($subcategories)==0) && (count($products) == 0)):?>
<div class="alert alert-info">
<a class="close" data-dismiss="alert">×</a>
<?php echo lang('no_products');?>
</div>
<?php endif;?>
<div class="span9 content_body">
<div class="row">
<?php if(count($products) > 0):?>
<?php foreach($products as $product):?>
<?php
$photo = theme_img('no_picture.png', lang('no_image_available'));
$product->images = array_values($product->images);
if(!empty($product->images[0]))
{
$primary = $product->images[0];
foreach($product->images as $photo)
{
if(isset($photo->primary))
{
$primary = $photo;
}
}
//$photo = '<img width= height="104" src="'.base_url('uploads/images/thumbnails/'.$primary->filename).'" alt="'.$product->seo_title.'"/>';
}
$photo = '<img width="" height="104" src="'.base_url('uploads/images/thumbnails/'.$product->images[0]).'" alt="'.$product->seo_title.'"/>';
?>
<div class="span2" style="height:305px;margin-bottom: 10px">
<div class="shop_box">
<div class="title">RECENTLY LISTED</div>
<?php //echo theme_img('siteimg/jacket.png', true );?>
<a class="thumbnail" href="<?php echo site_url(implode('/', $base_url).'/'.$product->slug); ?>">
<?php echo $photo; ?>
</a>
<?php if($product->excerpt != ''): ?>
<div class="sub-title">
<?php echo $this->common_model->word_crop($product->name,'28','..');?></div>
<?php endif; ?>
<div class="info">
<span class="condition">Condition: Excellent</span>
<span class="discount">64% off of Retail</span>
</div>
<div class="price">
<?php if($product->saleprice > 0):?>
<?php echo format_currency($product->price); ?>
<?php echo format_currency($product->saleprice); ?>
<?php else: ?>
<?php echo format_currency($product->price); ?>
<?php endif; ?>
</div>
<?php if((bool)$product->track_stock && $product->quantity < 1) { ?>
<div class="stock_msg"><?php echo lang('out_of_stock');?></div>
<?php } else{ ?>
<div class="stock_msg"><b>Quantity</b> <?php echo $product->quantity;?></div>
<?php } ?>
</div>
</div>
<!-- span2 -->
<?php endforeach?>
<?php endif;?>
</div>
</div>
<file_sep><?php include('header.php');?>
<?php $GLOBALS['option_value_count'] = 0;
?>
<?php $timestamp = time();?>
<style>
.errorfield{color:#F00}
</style>
<div class="container mar-top">
<div class="row header_widgets">
<div class="span19">
<div class="head_widget">
<span class="edit pull-left"> </span>
<h3>LIST YOUR PARTS OR GEAR</h3>
<p>Take some photo % write a few words. It's free to list.</p>
</div>
<!-- head_widget -->
</div>
<div class="span19">
<div class="head_widget">
<span class="ship pull-left"> </span>
<h3>SHIP YOUR PARTS OR GEAR</h3>
<p>Update the tracking number in My Account.</p>
</div>
<!-- head_widget -->
</div>
<div class="span19">
<div class="head_widget">
<span class="dollar pull-left"> </span>
<h3>GET PAID</h3>
<p>We will mail you a check.</p>
</div>
<!-- head_widget -->
</div>
</div>
<!-- /.row -->
<div class="row">
<div class="span9 content_body fl">
<div class="tab-pane" id="product_photos">
<div class="row">
</div>
<div class="row">
<div class="span8">
<div id="gc_photos">
</div>
</div>
</div>
</div>
<div class="form_wrapper">
<div class="title bdr-top-right"><span class="picture"> </span> UPLOAD PICTURES</div>
<div class="box center pagination-centered">
<span class="camera"> </span>
<div id="brandImage">
<?php
foreach($images as $key=>$img){
?>
<img id='img_<?php echo $key; ?>' class='image_cls' src='<?php echo site_url('uploads/images/small/'.$img);?>' width='50' hieght='50' onClick="del_img('<?php echo $img; ?>','<?php echo $key; ?>',false)">
<?php
}
?>
</div>
<div class="bold light-gray">Add a photo or two!</div>
<p class="short">Or three, or more! Prospective Buyers love photos that highlight the features of your parts or gear.</p>
<form class="ajaxform" method="post" enctype="multipart/form-data" action='<?php echo site_url('UploadImage/upload_Image');?>'>
<input type="hidden" name="do" value="upload"/>
Upload your image <input type="file" name="Filedata" id="photo" onChange="abc()" />
<input type="hidden" name="timestamp" value="<?php echo $timestamp;?>" />
<input type="hidden" name="token" value="<?php echo md5('unique_salt' . $timestamp);?>" />
<input type="hidden" name="customer_id" value="<?php echo $customer['id'];?>" />
</form>
</div>
<!-- /.box.center -->
<?php echo form_open('/secure/add_item/'.$id, array('id'=>'listitem') ); ?>
<div id="img_cant"> <?php
foreach($images as $key=>$img){
?>
<input type="hidden" value="<?php echo $img; ?>" name="images[]" id="hid_<?php echo $key; ?>">
<?php } ?>
</div>
<div class="title"><span class="title-edit"> </span> Give us a Title for what you are selling</div>
<div class="box">
<?php
$data = array('placeholder'=>lang('name'), 'name'=>'name', 'id'=>'name', 'value'=>set_value('name', $name), 'class'=>'text-box');
echo form_input($data);
?>
<div id="nameError" class="errorfield"></div>
<span class="help-block pagination-right">50 characters remaining</span>
</div>
<!-- /.box.center -->
<div class="title"><span class="title-edit"> </span> Tell a Story ABOUT YOUR PARTS OR GEAR</div>
<div class="box">
<label for="">You know your item best. The more information you can provide, the faster it will sell.</label>
<?php
$data = array('name'=>'description', 'class'=>'text-box','id'=>'description', 'value'=>set_value('description', $description));
echo form_textarea($data);
?>
<div id="descriptionError" class="errorfield"></div>
<span class="help-block pagination-right">1000 characters remaining</span>
</div>
<!-- /.box.center -->
<div class="title"><span class="grid"> </span> Choose a Category that best fits.</div>
<div class="box">
<div class="styled-select">
<select name="category" id="category_id" class="text-box">
<option value=''>Select category</option>
<?php
foreach($category_list as $catval):
?>
<option value="<?php echo $catval->id; ?>" <?php if(isset($cat_id) && $cat_id==$catval->id){ ?> selected="selected"<?php }?>><?php echo( $catval->name); ?></option>
<?php
endforeach;
?>
</select>
</div>
<div id="categoryError" class="errorfield"></div>
<div id='sub_category_container' <?php if(!isset($sub_category_data)){ ?> style="display:none" <?php } ?>>
<div id='sub_category_list' class="styled-select">
<?php echo (isset($sub_category_data)? $sub_category_data:'');?>
</div>
</div>
<div class="line"> </div>
<div class="styled-select">
<select name="company_id" id="company_id" class="text-box">
<option value=''>Select Brand</option>
<?php
foreach($company_list as $company_val):
?>
<option value="<?php echo $company_val->company_id; ?>"
<?php if($company_id==$company_val->company_id){ ?>selected="selected" <?php } ?>><?php echo( $company_val->company_name); ?></option>
<?php
endforeach;
?>
<option value="other">Other</option>
</select>
</div>
<div id="companyError" class="errorfield"></div>
<div id='othercatCantner' style="display:none"></div>
<div id='modelContener' <?php if(!isset($model_data)){ ?> style="display:none" <?php } ?>>
<?php echo (isset($model_data)? $model_data:'');?>
</div>
<div class="line"> </div>
<div class="styled-select">
<?php
$options = array( '0' => 'Select Condetion',
'1' => 'Old',
'2' => 'Good',
'3' => 'Exilent'
);
echo form_dropdown('condition', $options, set_value('condition',$condition), 'class="text-box"');
?>
</div>
<div class="styled-select">
<?php
$options = array( '1' => lang('shippable')
,'0' => lang('not_shippable')
);
echo form_dropdown('shippable', $options, set_value('shippable',$shippable), 'class="text-box"');
?></div>
<div class="styled-select">
<?php
$options = array( '0' => 'Select Quantity'
,'1' => '1'
,'2' => '2'
,'3' => '3'
,'4' => '4'
,'5' => '5'
,'10' => '10'
,'20' => '20'
,'40' => '40'
,'50' => '50'
,'100' => '100'
);
echo form_dropdown('quantity', $options, set_value('quantity',$quantity), 'class="text-box"');
?>
</div>
</div>
<!-- /.box.center -->
<div class="title"><span class="money"> </span> SET YOUR PRICE</div>
<div class="box clearfix">
<?php
$data = array('name'=>'price', 'value'=>set_value('price', $price), 'class'=>'text-box', 'placeholder'=>"Retail Price");
echo form_input($data);?>
<?php
$data = array('name'=>'saleprice', 'value'=>set_value('saleprice', $saleprice), 'class'=>'text-box','placeholder'=>"Enter Price");
echo form_input($data);?>
<button name="submit" value="submit" type="submit" class="pull-right btnn red"><?php echo lang('form_save');?></button>
</div>
<!-- /.box -->
</div>
</form>
<!-- form_wrapper -->
</div>
<!-- .span9 -->
<div class="span3 sidebar fr">
<div class="widget_box pagination-centered mtop">
<h3 class="redc">PHOTO TIP</h3>
<p>Listings with multiple images are 5x more likely to sell</p>
<p>Would you buy anything used if you didn’t see a picture of it?</p>
</div>
<!-- widget_box -->
<div class="widget_box pagination-centered mtop">
<h3 class="redc">LISTING YOUR PARTS OR GEAR IS FREE</h3>
<p>If your item does not sell, we don’t charge you. We handle all the payments processing and customer service. All you need to do is list and ship your gear then we send you a check.</p>
</div>
<!-- widget_box -->
<div class="widget_box pagination-centered mtop">
<h3 class="redc">TALK ABOUT YOUR PARTS OR GEAR</h3>
<p>Take some photos & write a few words. It's free to list.</p>
</div>
<!-- widget_box -->
</div>
<!-- span3 -->
</div>
<!-- row -->
<?php include('feature.php'); ?>
<!-- .row -->
</div>
<?php include('footer.php'); ?>
<script>
$(document).ready(function() {
// apply class in uploadify
//$('#file_upload-button').attr('class','btnn red');
$('#category_id').change(function()
{
$.post("<?php echo site_url('secure/ajaxrequest');?>", { id: $('#category_id').val(), type:'getsubcat'},
function(data) { if(data) {
$('#sub_category_list').html(data);
$('#sub_category_container').show();
} else {
$('#sub_category_list').html('');
$('#sub_category_container').hide();
}
});
});
$('#company_id').change( function(){
var catval = $('#company_id').val();
if('other'==catval){
$("#modelContener").html('');
$('#othercatCantner').html('<input type="text" name="newcompany" id="newcompany" class="text-box" placeholder="Other Brand"><input type="text" name="newmodelname" id="newmodelname" class="text-box" placeholder="Other Model">').show();
}
else{
$('#othercatCantner').html('').hide();
// show model
$.post("<?php echo site_url('secure/ajaxrequest');?>", { id: catval, type:'getmodelcat'},
function(data) {
$('#modelContener').html(data).show();
});
//
}
});
// submit form validation js
$('#listitem').submit(function(){
var haserror = false;
if($('#name').val().trim()==''){
haserror = true;
$('#nameError').html('Enter item title');
$('#name').focus();
} else {$('#nameError').html('');}
/*if($('#description').val().trim()==''){
haserror = true;
$('#descriptionError').html('Enter item desc');
} else {$('#nameError').html('');}
*/
if($('#category_id').val()==''){
haserror = true;
$('#categoryError').html('Select category for item');
$('#category_id').focus();
} else $('#categoryError').html('');
if($('#company_id').val()==''){
haserror = true;
$('#companyError').html('Select company for item');
} else $('#companyError').html('');
if(haserror==true){
return false;
} else return true;
});
});
function addNewModel(modelValue)
{
if(modelValue == 'other') {
$('#modelContener').append('<input type="text" name="newmodelname" id="newmodelname" class="text-box" placeholder="Other Model">');
}
}
<?php if(count($images)==0){?>
var i = 0;
<?php } else{ ?>
var i = <?php echo count($images)+1; ?>;
<?php } ?>
function abc(){
$("#view").html('');
$("#view").html('<img src="./theme/img/loading.gif" />');
$(".ajaxform").ajaxForm(function(response){
// alert('The File ' + file.name + " has been uploaded with response "+response+" --data status: "+data);
$('#brandImage').append("<img id='img_"+i+"' class='image_cls' src='<?php echo site_url('uploads/images/small/');?>/"+response+"' width='50' hieght='50' onClick=del_img('"+response+"','"+i+"','"+true+"')>");
$('#img_cant').append("<input type='hidden' id='hid_"+i+"' name='images[]' value='"+response+"'>");
i++;
}).submit();
}
function del_img(img_name,sr,isremove){
var con = window.confirm('Are you sure want to remove this image from list?');
if(con==true){
$('#img_'+sr).remove();
$('#hid_'+sr).remove();
if(isremove==true){
$.post("<?php echo site_url('UploadImage/remove_image');?>", { img_name: img_name},
function(data) {
});
}
}
}
</script>
<file_sep> <footer class="footer">
<div style="text-align:center;"><a href="#" target="_blank"><img alt="arun"></a></div>
</footer>
</div>
</body>
</html><file_sep><?php if(validation_errors()):?>
<div class="alert allert-error">
<a class="close" data-dismiss="alert">×</a>
<?php echo validation_errors();?>
</div>
<?php endif;?>
<script type="text/javascript">
$(document).ready(function(){
$('.delete_address').click(function(){
if($('.delete_address').length > 1)
{
if(confirm('<?php echo lang('delete_address_confirmation');?>'))
{
$.post("<?php echo site_url('secure/delete_address');?>", { id: $(this).attr('rel') },
function(data){
$('#address_'+data).remove();
$('#address_list .my_account_address').removeClass('address_bg');
$('#address_list .my_account_address:even').addClass('address_bg');
});
}
}
else
{
alert('<?php echo lang('error_must_have_address');?>');
}
});
$('.edit_address').click(function(){
$.post('<?php echo site_url('secure/address_form'); ?>/'+$(this).attr('rel'),
function(data){
$('#address-form-container').html(data).modal('show');
}
);
// $.fn.colorbox({ href: '<?php echo site_url('secure/address_form'); ?>/'+$(this).attr('rel')});
});
if ($.browser.webkit) {
$('input:password').attr('autocomplete', 'off');
}
});
function set_default(address_id, type)
{
$.post('<?php echo site_url('secure/set_default_address') ?>/',{id:address_id, type:type});
}
</script>
<?php
$company = array('id'=>'company', 'class'=>'span6', 'name'=>'company', 'value'=> set_value('company', $customer['company']));
$first = array('id'=>'firstname', 'class'=>'span4', 'name'=>'firstname', 'value'=> set_value('firstname', $customer['firstname']));
$last = array('id'=>'lastname', 'class'=>'span4', 'name'=>'lastname', 'value'=> set_value('lastname', $customer['lastname']));
$email = array('id'=>'email', 'class'=>'span4', 'name'=>'email', 'value'=> set_value('email', $customer['email']));
$phone = array('id'=>'phone', 'class'=>'span4', 'name'=>'phone', 'value'=> set_value('phone', $customer['phone']));
//$password = array('id'=>'password', 'class'=>'span2', 'name'=>'password', 'value'=>'');
//$confirm = array('id'=>'confirm', 'class'=>'span2', 'name'=>'confirm', 'value'=>'');
?>
<?php echo $this->common_model->getMessage(); ?>
<div class="span9">
<div class="my-account-box">
<?php echo form_open('myaccount/index'); ?>
<fieldset>
<div class="page-header margin-topn"><h2><?php echo lang('account_information');?></h2></div>
<div class="row mar-bot">
<div class="span6 sidebar">
<label for="company"><?php echo lang('account_company');?></label>
<?php echo form_input($company);?>
</div>
</div>
<div class="row mar-bot">
<div class="span4 sidebar">
<label for="account_firstname"><?php echo lang('account_firstname');?></label>
<?php echo form_input($first);?>
</div>
<div class="span4">
<label for="account_lastname"><?php echo lang('account_lastname');?></label>
<?php echo form_input($last);?>
</div>
</div>
<div class="row mar-bot">
<div class="span4 sidebar">
<label for="account_email"><?php echo lang('account_email');?></label>
<?php echo form_input($email);?>
</div>
<div class="span4">
<label for="account_phone"><?php echo lang('account_phone');?></label>
<?php echo form_input($phone);?>
</div>
</div>
<div class="row mar-bot">
<div class="span7 sidebar">
<label class="checkbox">
<input type="checkbox" name="email_subscribe" value="1" <?php if((bool)$customer['email_subscribe']) { ?> checked="checked" <?php } ?>/> <?php echo lang('account_newsletter_subscribe');?>
</label>
</div>
</div>
<input type="submit" value="<?php echo lang('form_submit');?>" class="btn btn-primary" />
</fieldset>
</form>
</div>
</div>
<div id="address-form-container" class="hide">
</div></div><file_sep><?php if(validation_errors()):?>
<div class="alert allert-error">
<a class="close" data-dismiss="alert">×</a>
<?php echo validation_errors();?>
</div>
<?php endif;?>
<?php
$password = array('id'=>'password', 'class'=>'span3', 'name'=>'password', 'value'=>'');
$confirm = array('id'=>'confirm', 'class'=>'span3', 'name'=>'confirm', 'value'=>'');
?>
<?php echo $this->common_model->getMessage();?>
<div class="row">
<div class="span9">
<div class="my-account-box">
<?php echo form_open('myaccount/change_password'); ?>
<fieldset>
<div class="page-header margin-topn"><h2><?php echo "Change your Password";?></h2></div>
<div class="row mar-bot">
<div class="span3 sidebar">
<label for="account_password"><?php echo lang('current_password');?></label>
<?php echo form_password(array('name'=>'current_password', 'id' => '<PASSWORD>', 'class' => 'span3'));?>
</div>
<div class="span3 ">
<label for="account_password"><?php echo lang('account_password');?></label>
<?php echo form_password($password);?>
</div>
<div class="span3 ">
<label for="account_confirm"><?php echo lang('account_confirm');?></label>
<?php echo form_password($confirm);?>
</div>
</div>
<input name="update" type="submit" value="update" class="btn btn-primary" />
</fieldset>
</form>
</div>
</div>
</div>
</div><file_sep><div class="container mar-top">
<div class="span3 sidebar">
<div class="widget_box">
<div class="widget_title">My Account</div>
<div class="widget_body">
<?php $uri = $_SERVER['REQUEST_URI'];
$seg = $this->uri->segment(2);
?>
<ul class="styled">
<li><a <?php if (strpos($uri,'/myaccount/') !== false && $seg == '') echo 'class="act"';?> href="<?php echo base_url().'myaccount/'; ?>">Edit Accounnt Information</a></li>
<li><a <?php if (strpos($uri,'/myaccount/inbox') !== false) echo 'class="act"';?> href="<?php echo base_url().'myaccount/inbox'; ?>">Inbox</a></li>
<li><a <?php if (strpos($uri,'/myaccount/order') !== false) echo 'class="act"';?> href="<?php echo base_url().'myaccount/order/'; ?>">Order History</a></li>
<li><a <?php if (strpos($uri,'/myaccount/list_item') !== false) echo 'class="act"';?> href="<?php echo base_url().'myaccount/list_item'; ?>">My listed Itemes</a></li>
<li><a <?php if (strpos($uri,'/myaccount/address') !== false) echo 'class="act"';?> href="<?php echo base_url().'myaccount/address/'; ?>">Address</a></li>
<li><a <?php if (strpos($uri,'/myaccount/change_password') !== false) echo 'class="act"';?> href="<?php echo base_url().'myaccount/change_password'; ?>">Change Password</a></li>
<li><a href="<?php echo base_url()?>secure/logout">Logout</a></li>
</ul>
</div>
</div>
</div><file_sep><?php
class UploadImage extends Front_Controller {
var $customer;
function __construct()
{
parent::__construct();
force_ssl();
$this->load->model(array('location_model'));
$this->customer = $this->go_cart->customer();
}
function index()
{
show_404();
echo "hello";
}
public function upload_Image(){
$targetFolder = 'uploads/images/full'; // Relative to the root
$verifyToken = md5('<PASSWORD>' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $targetFolder;
$rand = rand(22222,333333333);
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$targetFile = rtrim($targetPath,'/') . '/'.$verifyToken .$rand.'.'.$fileParts['extension'];// $_FILES['Filedata']['name'];
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
// crop image
$upload_data['file_name'] = $verifyToken.$rand.'.'.$fileParts['extension'];//$_FILES['Filedata']['name'];
$this->load->library('image_lib');
/*
I find that ImageMagick is more efficient that GD2 but not everyone has it
if your server has ImageMagick then you can change out the line
$config['image_library'] = 'gd2';
with
$config['library_path'] = '/usr/bin/convert'; //make sure you use the correct path to ImageMagic
$config['image_library'] = 'ImageMagick';
*/
//this is the larger image
$config['image_library'] = 'gd2';
$config['source_image'] = 'uploads/images/full/'.$upload_data['file_name'];
$config['new_image'] = 'uploads/images/medium/'.$upload_data['file_name'];
$config['maintain_ratio'] = TRUE;
$config['width'] = 600;
$config['height'] = 500;
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
//small image
$config['image_library'] = 'gd2';
$config['source_image'] = 'uploads/images/medium/'.$upload_data['file_name'];
$config['new_image'] = 'uploads/images/small/'.$upload_data['file_name'];
$config['maintain_ratio'] = TRUE;
$config['width'] = 235;
$config['height'] = 235;
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
//cropped thumbnail
$config['image_library'] = 'gd2';
$config['source_image'] = 'uploads/images/small/'.$upload_data['file_name'];
$config['new_image'] = 'uploads/images/thumbnails/'.$upload_data['file_name'];
$config['maintain_ratio'] = TRUE;
$config['width'] = 150;
$config['height'] = 150;
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
echo $upload_data['file_name'] ;
// end crop image
} else {
echo 'Invalid file type.';
}
}
}
public function remove_image(){
$image_name = $this->input->post('img_name');
unlink('uploads/images/small/'.$image_name);
unlink('uploads/images/thumbnails/'.$image_name);
unlink('uploads/images/medium/'.$image_name);
unlink('uploads/images/full/'.$image_name);
echo 1;
}
}<file_sep>/*HTML by <NAME>*/
ul, ol {
margin: 0;
padding: 0; }
body {
background: url("../images/gradient.png") repeat-x left top; }
.logo {
margin: 18px 0; }
.account_overview {
margin-top: 30px; }
.account_overview span.pull-right, .account_overview a {
color: #77777e;
padding: 0 5px;
font-size: 12px; }
.account_overview span.pull-right span, .account_overview a span {
padding-right: 3px; }
.account_overview span.pull-right {
font-size: 14px; }
.checkout_buttons {
text-align: right;
margin-top: 26px; }
.btnn {
padding: 10px 15px;
color: #fff;
border-radius: 2px; }
.red {
background: #b41717;
color: #fff; }
.red:hover {
background: #871111;
text-decoration: none;
color: #fff; }
.black-white-gradient {
background-color: #a6a4a3;
*zoom: 1;
filter: progid:DXImageTransform.Microsoft.gradient(gradientType=0, startColorstr='#FFA6A4A3', endColorstr='#FF3F3F3E');
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #a6a4a3), color-stop(13%, #9c9b9a), color-stop(24%, #909191), color-stop(53%, #666c72), color-stop(74%, #4b5259), color-stop(87%, #41464a), color-stop(100%, #3f3f3e));
background-image: -webkit-linear-gradient(top, #a6a4a3 0%, #9c9b9a 13%, #909191 24%, #666c72 53%, #4b5259 74%, #41464a 87%, #3f3f3e 100%);
background-image: -moz-linear-gradient(top, #a6a4a3 0%, #9c9b9a 13%, #909191 24%, #666c72 53%, #4b5259 74%, #41464a 87%, #3f3f3e 100%);
background-image: -o-linear-gradient(top, #a6a4a3 0%, #9c9b9a 13%, #909191 24%, #666c72 53%, #4b5259 74%, #41464a 87%, #3f3f3e 100%);
background-image: linear-gradient(top, #a6a4a3 0%, #9c9b9a 13%, #909191 24%, #666c72 53%, #4b5259 74%, #41464a 87%, #3f3f3e 100%);
background: -ms-linear-gradient(top, #a6a4a3 0%, #9c9b9a 13%, #909191 24%, #666c72 53%, #4b5259 74%, #41464a 87%, #3f3f3e 100%);
/* IE10+ */ }
.white-button {
background: #fff;
color: #77777e; }
.white-button:hover {
text-decoration: none; }
.small-btn {
padding: 3px 5px;
border-radius: 2px; }
.space-left-right {
padding-left: 15px;
padding-right: 15px;
margin-left: 15px; }
.space-left-right .white-button {
margin-left: 10px; }
.dark-black-gradient {
background-color: #5a5a5a;
*zoom: 1;
filter: progid:DXImageTransform.Microsoft.gradient(gradientType=0, startColorstr='#FF5A5A5A', endColorstr='#FF222222');
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #5a5a5a), color-stop(30%, #4c4c4c), color-stop(81%, #2a2a2a), color-stop(100%, #222222));
background-image: -webkit-linear-gradient(top, #5a5a5a 0%, #4c4c4c 30%, #2a2a2a 81%, #222222 100%);
background-image: -moz-linear-gradient(top, #5a5a5a 0%, #4c4c4c 30%, #2a2a2a 81%, #222222 100%);
background-image: -o-linear-gradient(top, #5a5a5a 0%, #4c4c4c 30%, #2a2a2a 81%, #222222 100%);
background-image: linear-gradient(top, #5a5a5a 0%, #4c4c4c 30%, #2a2a2a 81%, #222222 100%);
background: -ms-linear-gradient(top, #5a5a5a 0%, #4c4c4c 30%, #2a2a2a 81%, #222222 100%);
/* IE10+ */
border-radius: 3px;
margin-bottom: 3px; }
.dark-black-gradient .nav {
padding: 7px 0;
float: none;
display: inline-block; }
.dark-black-gradient .nav li {
text-align: center;
margin-right: 5px;
text-align: center;
position: relative; }
.dark-black-gradient .nav li a {
font-size: 12px;
background: #262626;
font-weight: bold;
padding: 5px 5.9px;
border: 1px solid #5b5b5b;
border-radius: 5px;
width: 90px;
height: 71px; }
.dark-black-gradient .nav li a .text {
position: absolute;
bottom: 5px;
left: 0;
width: 100%; }
.mar-top{ margin-top:10px;}
.list_inline {
padding: 8px 15px 15px 0; }
.list_inline.inline {
text-align: center;
padding: 0 0 5px; }
.list_inline.inline li {
float: none;
display: inline-block;
padding: 0 5px; }
.list_inline.inline li a {
font-weight: bold;
font-size: 14px;
cursor: pointer; }
.list_inline li {
float: right;
color: #b41717;
padding: 0 45px 0 0;
list-style-type: disc;
width: auto;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box; }
.list_inline a {
color: #fff;
font-size: 17px;
cursor: text; }
.list_inline a:hover {
text-decoration: none; }
.red_text {
color: #ff0908;
padding-top: 15px;
font: bold 18px arial;
text-transform: uppercase;
text-align: center; }
.white-black-border {
margin: 15px 0;
background: #ffffff;
/* Old browsers */
background: -ms-linear-gradient(top, white 0%, #f3f3f3 26%, #d1d1d1 72%, #c3c3c3 100%);
/* IE10+ */
*zoom: 1;
filter: progid:DXImageTransform.Microsoft.gradient(gradientType=0, startColorstr='#FFFFFFFF', endColorstr='#FFC3C3C3');
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #ffffff), color-stop(26%, #f3f3f3), color-stop(72%, #d1d1d1), color-stop(100%, #c3c3c3));
background-image: -webkit-linear-gradient(top, #ffffff 0%, #f3f3f3 26%, #d1d1d1 72%, #c3c3c3 100%);
background-image: -moz-linear-gradient(top, #ffffff 0%, #f3f3f3 26%, #d1d1d1 72%, #c3c3c3 100%);
background-image: -o-linear-gradient(top, #ffffff 0%, #f3f3f3 26%, #d1d1d1 72%, #c3c3c3 100%);
background-image: linear-gradient(top, #ffffff 0%, #f3f3f3 26%, #d1d1d1 72%, #c3c3c3 100%);
color: #ff0000;
text-transform: uppercase;
font-size: 18px;
border: 2px solid #000;
border-radius: 5px;
font-weight: bold; }
.white-black-border:hover {
color: #cc0000;
text-decoration: none; }
.btnn-big {
padding: 13px 36px; }
.sidebar {
margin-left: 0; }
.widget_box {
margin-bottom: 20px; }
.black {
background: #000; }
.black .widget_body {
background: url("../images/black-bg.png") no-repeat left top; }
.widget_title {
background: #bf1819;
font-size: 16px;
padding-left: 19px;
font-weight: bold;
line-height: 37px;
color: #fff;
text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.75); }
.widget_body {
background: #f1f1f1; }
.light_blue {
background: #c5d3dc;
padding:10px; }
.styled li { display:block;
list-style: disc inside;
color: #b41717;
padding-right: 8px; }
.styled a {
color: #393939;
line-height: 35px;
border-bottom: 1px solid #d7d7d7;
display: block;
padding-left: 19px; }
.styled a:hover {
text-decoration: none;
color: #060606; }
.sm-bn {
padding: 5px 3px;
border-radius: 3px; }
.padding-offset {
padding: 6px; }
.clear {
clear: both; }
.button_wrap {
padding-top: 13px; }
.button_wrap .blue_underline {
text-decoration: underline;
margin-left: 5px; }
.shop_box {
margin: 5px 0;
text-align: center;
border: 1px solid #eae7e7; }
.shop_box img {
margin-bottom: 10px; }
.shop_box .title {
background: url("../images/shape.png") no-repeat center top;
width: 175px;
padding-top: 10px;
height: 71px;
color: #5b5b5b;
font-size: 14px;
font-weight: bold; }
.shop_box .info {
padding-left: 10px;
text-align: left; }
.shop_box .info span {
font-size: 11px;
color: #474747;
line-height: 1.24;
display: block; }
.shop_box .info .size {
font-size: 12px;
text-transform: uppercase;
padding-bottom: 5px; }
.shop_box .info .discount {
color: #ff5f1d; }
.price {
background: #e6e6e4;
padding: 10px;
color: #3da24f;
margin-top: 10px;
text-align: right;
font-weight: bold; }
.sub-title {
padding-left: 10px;
font-weight: bold;
color: #767676;
text-align: left;
line-height: 16px;
font-size: 13px;
padding-bottom: 10px; }
.about {
padding-top: 33px;
padding-bottom: 20px;
margin-bottom: 20px;
border: 1px solid #d9e2ec;
background: #e8eff7;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box; margin-top:15px; }
.pd0 {
padding: 0; }
.mr0 {
margin: 0; }
.title_red {
color: #bf1819;
font-size: 21px;
padding-top: 10px;
font-weight: bold;
padding-bottom: 10px; }
p {
color: #5b5b5b;
line-height: 20px;
padding-bottom: 10px; }
.read_more {
color: #bf1819;
font-size: 15px;
font-weight: bold; }
.footer {
background: #bf1819;
padding: 25px 0; }
span.block {
text-align: center;
display: block;
font-size: 13px;
color: #fff; }
@media (max-width: 1199px) {
.shop_box .title {
width: auto; }
.span7.mr0 {
padding: 0 10px; }
.account_overview a {
float: right; } }
@media (max-width: 1199px) and (min-width: 980px) {
.sidebar.span3 {
width: 26%; }
.content_body.span9 {
width: 71%; }
.content_body .span2 {
width: 30.3%; } }
@media (max-width: 979px) and (min-width: 768px) {
.sidebar.span3 {
width: 34%; }
.content_body.span9 {
width: 63.3%; }
.content_body .span2 {
width: 45.91%; } }
@media (min-width: 768px) {
.brand {
display: none !important; } }
@media (max-width: 767px) {
.account_overview {
text-align: center; }
.account_overview a {
float: none; }
.list_inline.inline li {
display: block;
padding: 5px; }
.list_inline {
padding-left: 35px; }
.logo {
text-align: center; }
.account_overview a {
text-align: center;
font-size: 9px; }
.account_overview span.pull-right {
text-align: center;
width: 100%; }
.btnn {
padding: 10px 15px;
display: block;
text-align: center;
margin-bottom: 5px; }
.space-left-right {
margin-left: 0; }
.space-left-right .white-button {
margin-left: 0; }
.checkout_buttons {
margin: 10px 0; }
.account_overview {
margin-top: 0; }
.list_inline li {
float: none;
list-style: disc inside; }
.red_text {
font-size: 14px; }
.list_inline li {
padding: 0; }
.list_inline li a {
font-size: 12px; }
.navbar .brand {
font-size: 16px;
padding: 11px 20px 5px; }
.white-black-border {
width: 94%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
margin: 8px auto;
display: block;
float: none; }
.dark-black-gradient .nav {
width: 100%; }
.dark-black-gradient .nav li {
width: 46.5%;
float: left; }
.dark-black-gradient .nav li:nth-child(even) {
float: right; }
.dark-black-gradient .nav li a {
width: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box; } }
<file_sep>
<?=$this->load->view('header.php');?>
<?=$this->load->view('myaccount_left_menu.php');?>
<?=$this->load->view($file);?>
<?=$this->load->view('footer.php');?><file_sep><!DOCTYPE html>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title><?php echo (!empty($seo_title)) ? $seo_title .' - ' : ''; echo $this->config->item('company_name'); ?></title>
<?php if(isset($meta)):?>
<?php echo $meta;?>
<?php else:?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<?php endif; ?>
<?php echo theme_css('bootstrap.css', true);?>
<?php echo theme_css('bootstrap-responsive.css', true);?>
<?php echo theme_css('style.css', true);?>
<?php echo theme_js('jquery.js', true);?>
<?php echo theme_js('bootstrap.js', true);?>
<!-- Le 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">
<div class="row">
<div class="span5">
<div class="logo"><?php echo theme_img('siteimg/logo.png', 'swap moto');?></div>
</div>
<div class="span6">
<div class="account_overview clearfix">
<a href="<?php echo base_url()?>secure/my_account"><span class="icon-pencil"> </span>MY ACCOUNT</a>
<a href="#"><span class="icon-star"> </span>WISHLIST</a>
<a href="<?php echo base_url()?>secure/sale"><span class="icon-pencil"> </span>Sale</a>
<!-- custom menu by Garun-->
<?php if(!$this->Customer_model->is_logged_in(false, false)):?>
<a href="<?php echo base_url()?>secure/login"><span class="icon-pencil"> </span>Login</a>
<?php else : ?>
<a href="<?php echo base_url()?>secure/logout"><span class="icon-pencil"> </span>Logout</a>
<?php endif;?>
<!-- end custom menu !-->
</div>
<!-- .account_overview -->
<div class="checkout_buttons clearfix">
<a href="#" class="btnn red"><span class="icon-shopping-cart icon-white"> </span> VIEW CART</a>
<span href="#" class="btnn black-white-gradient space-left-right">0 Items $0.00 <a href="#" class="small-btn white-button">Checkout</a></span>
</div>
</div>
</div>
</div>
<file_sep><?php
/*
*
*/
class seller extends Front_Controller {
function __construct()
{
parent::__construct();
//make sure we're not always behind ssl
remove_ssl();
}
public function index(){
}
/*
*
*/
public function seller_listed_items($id, $order_by = "name", $sort_order = "ASC", $code = 0, $page = 0, $rows = 15){
$base_url = $this->uri->segment_array();
$data['base_url'] = $base_url;
$post = array('user_id' => $id);
$term = json_encode($post);
$data['products'] = $this->Product_model->get_my_products(array('term' => $term, 'order_by' => $order_by, 'sort_order' => $sort_order, 'rows' => $rows, 'page' => $page));
$data['page_title'] = '';
$data["file"] = "seller_listed_items";
$this->load->view('category', $data);
}
}
?><file_sep>4111111111111111
<?php echo $this->common_model->getMessage();?>
<div class="span9 pull-right">
<div class="page-header" style="height:40px;">
<h2 class="fl"><?php echo lang('address_manager');?></h2>
<div class="span6">
<a href="<?php echo base_url(); ?>myaccount/add_address" class="btn fr edit_address"><?php echo lang('add_address');?></a>
</div>
</div>
<div class="row">
<div class="span9 sidebar" id='address_list'>
<?php if(count($addresses) > 0):?>
<table class="table table-bordered table-striped">
<?php
$c = 1;
foreach($addresses as $a):?>
<tr id="address_<?php echo $a['id'];?>">
<td>
<?php
$b = $a['field_data'];
echo format_address($b, true);
?>
</td>
<td>
<div class="row-fluid">
<div class="span12">
<div class="btn-group pull-right">
<input type="button" class="btn edit_address" rel="<?php echo $a['id'];?>" value="<?php echo lang('form_edit');?>" />
<input type="button" class="btn btn-danger delete_address" rel="<?php echo $a['id'];?>" value="<?php echo lang('form_delete');?>" />
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<div class="pull-right" style="padding-top:10px;">
<input type="radio" name="bill_chk" onClick="set_default(<?php echo $a['id'] ?>, 'bill')" <?php if($customer['default_billing_address']==$a['id']) echo 'checked="checked"'?> /> <?php echo lang('default_billing');?>
<input type="radio" name="ship_chk" onClick="set_default(<?php echo $a['id'] ?>,'ship')" <?php if($customer['default_shipping_address']==$a['id']) echo 'checked="checked"'?>/> <?php echo lang('default_shipping');?>
</div>
</div>
</div>
</td>
</tr>
<?php endforeach;?>
</table>
<?php endif;?>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.delete_address').click(function(){
if($('.delete_address').length > 1)
{
if(confirm('<?php echo lang('delete_address_confirmation');?>'))
{
$.post("<?php echo site_url('myaccount/delete_address');?>", { id: $(this).attr('rel') },
function(data){
$('#address_'+data).remove();
$('#address_list .my_account_address').removeClass('address_bg');
$('#address_list .my_account_address:even').addClass('address_bg');
});
}
}
else
{
alert('<?php echo lang('error_must_have_address');?>');
}
});
$('.edit_address').click(function(){
$.post('<?php echo site_url('secure/address_form'); ?>/'+$(this).attr('rel'),
function(data){
$('#address-form-container').html(data).modal('show');
}
);
// $.fn.colorbox({ href: '<?php echo site_url('secure/address_form'); ?>/'+$(this).attr('rel')});
});
if ($.browser.webkit) {
$('input:password').attr('autocomplete', 'off');
}
});
function set_default(address_id, type)
{
$.post('<?php echo site_url('secure/set_default_address') ?>/',{id:address_id, type:type});
}
</script>
<file_sep><?php echo plugins_js('lightbox/js/jquery-1.11.0.min.js');?>
<?php echo plugins_js('lightbox/js/lightbox.js');?>
<?php // echo plugins_css('lightbox/css/screen.css');?>
<?php echo plugins_css('lightbox/css/lightbox.css');?>
<?php
//set "code" for searches
if(!$code)
{
$code = '';
}
else
{
$code = '/'.$code;
}
function sort_url($lang, $by, $sort, $sorder, $code, $admin_folder)
{
if ($sort == $by)
{
if ($sorder == 'asc')
{
$sort = 'desc';
$icon = ' <i class="icon-chevron-up"></i>';
}
else
{
$sort = 'asc';
$icon = ' <i class="icon-chevron-down"></i>';
}
}
else
{
$sort = 'asc';
$icon = '';
}
$return = site_url($admin_folder.'/products/index/'.$by.'/'.$sort.'/'.$code);
echo '<a href="'.$return.'">'.lang($lang).$icon.'</a>';
} ?>
<script type="text/javascript">
function areyousure()
{
return confirm('<?php echo lang('confirm_delete_product');?>');
}
</script>
<style type="text/css">
.pagination {
margin:0px;
margin-top:-3px;
}
</style>
<div class="row">
<div class="span9" >
<?php echo $this->common_model->getMessage(); ?>
<div class="row">
<div class="span4">
<?php //echo $this->pagination->create_links();?>
</div>
<div class="span3 sidebar fr"><a class="pull-right btnn red" href="<?php echo site_url('secure/add_item');?>">Update list item</a></div>
<table class="table table-striped">
<thead>
<tr>
<th><?php echo lang('name'); ?></th>
<th>Category <?php //echo lang('price'); ?></th>
<th>Subcategory<?php //echo lang('saleprice');?></th>
<th> <?php echo lang('quantity');?></th>
<th> status </th>
<th> Admin Approve</th>
<th>
Action
</th>
</tr>
</thead>
<tbody>
<?php echo (count($products) < 1)?'<tr><td style="text-align:center;" colspan="7">'.lang('no_products').'</td></tr>':''?>
<?php foreach ($products as $product):?>
<tr>
<td><?php echo $product->name ;?></td>
<td><?php echo $product->categoriname;?></td>
<td><?php echo $product->subcategoriname;?></td>
<td><?php echo $product->quantity;?></td>
<td>
<?php
echo ($product->enabled==0?theme_img('siteimg/cross.png',true):theme_img('siteimg/tick.png',true));
?>
</td>
<td>
<?php echo ($product->admin_approve==0?theme_img('siteimg/cross.png',true):theme_img('siteimg/tick.png',true));?>
</td>
<td>
<span class="btn-group pull-right">
<a style=" padding:6px 25px 5px 25px;" class="btn" href="<?php echo base_url().'secure/add_item/' .$product->id;?>">
<?php //echo theme_img('siteimg/c_edit.png',true);?> <?php echo'edit';?></a>
<a style=" padding:5px 25px;" class="btn btn-danger" href="<?php echo base_url().'myaccount/remove_item/' .$product->id; ?>" onclick="return areyousure();"><i class="icon-trash icon-white"></i> <?php echo 'delete';?></a>
</span>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div><file_sep><div class="span3 sidebar">
<div class="widget_box">
<div class="widget_title">Select a Motercycle</div>
<div class="widget_body light_blue">
<form method="get" action="<?php echo base_url(); ?>" >
<?php
$company_list = $this->Product_model->get_company_list();
?>
<select name="company_id" id="company_id" class="text-box">
<option value=''>Select Brand</option>
<?php
foreach($company_list as $company_val):
?>
<option value="<?php echo $company_val->company_id; ?>"
<?php if(isset($company_id) && $company_id==$company_val->company_id){ ?>selected="selected" <?php } ?>><?php echo( $company_val->company_name); ?></option>
<?php
endforeach;
?>
</select>
<div id="modelContener">
<select name="modelid" id="modelid">
<option selected="selected" value="">Select Model</option>
<?php
if(isset($subcatlist)):
foreach($subcatlist as $subcatval):
?>
<option value="<?php echo $subcatval->model_id; ?>"
<?php if(isset($model_id) && $subcatval->model_id==$model_id){ ?> selected="selected" <?php } ?>>
<?php echo $subcatval->model_name; ?>
</option>";
<?php endforeach; ?>
<?php
endif;
?>
</select>
</div>
<input value="Search By Radius" type="text">
<div class="button_wrap">
<input type="submit" name="search" value="search" />
<a href="#" class="red sm-bn">Shop this Motercycle</a> <a href="#" class="blue_underline">All models</a>
</div>
</div>
</div>
<!-- widget_box -->
<div class="widget_box">
<?php if(!empty($category)){ ?>
<div class="widget_title"><?php echo $category->name;?></div>
<div class="widget_body">
<ul class="styled">
<?php if(isset($subcategories) && count($subcategories) > 0): ?>
<?php foreach($subcategories as $subcategory) { ?>
<li><a href="<?php echo site_url(implode('/', $base_url).'/'.$subcategory->slug); ?>"><?php echo $subcategory->name;?></a></li>
<?php
}
endif;?>
</ul>
</div>
<?php } ?>
</div>
<!-- widget_box -->
<div class="widget_box">
<div class="widget_title">We Accept</div>
<div class="widget_body pagination-centered padding-offset">
<a href="#"><?php echo theme_img('siteimg/visa.png','visa');?> </a>
<a href="#"><?php echo theme_img('siteimg/american-express.png','american-express');?></a>
<a href="#"><?php echo theme_img('siteimg/discover.png','discover');?> </a>
<a href="#"><?php echo theme_img('siteimg/master-card.png','master-card');?></a>
<a href="#"><?php echo theme_img('siteimg/paypal.png','paypal');?></a>
</div>
</div>
<!-- widget_box -->
<div class="widget_box black">
<div class="widget_title">We Accept</div>
<div class="widget_body pagination-centered padding-offset">
<a href="#"><?php echo theme_img('siteimg/facebook.png','facebook');?></a>
<a href="#"><?php echo theme_img('siteimg/twitter.png','twitter');?></a>
<a href="#"><?php echo theme_img('siteimg/pinterest.png','twitter');?></a>
<a href="#"><?php echo theme_img('siteimg/googleplus.png','googleplus');?></a>
<a href="#"><?php echo theme_img('siteimg/linkedin.png','linkedin');?></a>
</div>
</div>
<!-- widget_box -->
</div>
<script language="javascript">
$('#company_id').change( function(){
var catval = $('#company_id').val();
if(catval!=''){ //else{
// show model
$.post("<?php echo site_url('secure/get_model_list');?>", { id: catval},
function(data) {
$('#modelContener').html(data).show();
}
});
//
//}
});
</script><file_sep><?php
/**
* this is common model All common method are avilabe here
* @author <NAME> <<EMAIL>>
*/
Class Common_model extends CI_Model
{
//this is the expiration for a non-remember session
var $session_expire = 7200;
function __construct()
{
parent::__construct();
}
function setMessage($type = NULL ,$message = NULL)
{
if($type != NULL && $message != NULL)
{
$this->session->set_flashdata('message_type', $type);//message
$this->session->set_flashdata('message', $message);
}
}
function getMessage()
{
if($this->session->flashdata('message_type') != ''){
$type = $this->session->flashdata('message_type');
} else {
$type = NULL;
}
if($this->session->flashdata('message') != ''){
$message = $this->session->flashdata('message');
} else {
$message = NULL;
}
if($type != NULL && $message != NULL)
{
if($type == 1) {
echo '<div id="closeMeRapper" class="alert alert-success">'.$message.'<a id="closeMe" class="close" data-dismiss="alert">x</a></div>';
} elseif($type == 2) {
echo '<div id="closeMeRapper" class="alert alert-warning">'.$message.'<a id="closeMe" class="close" data-dismiss="alert">x</a></div>';
} elseif($type == 3){
echo '<div id="closeMeRapper" class="alert alert-danger">'.$message.'<a id="closeMe" class="close" data-dismiss="alert">x</a></div>';
}
}
}
public function word_crop($string, $length=4, $dots = "..."){
return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}
}<file_sep><?php
Class faq_model extends CI_Model
{
// we will store the group discount formula here
// and apply it to product prices as they are fetched
var $group_discount_formula = false;
function __construct()
{
parent::__construct();
// check for possible group discount
$customer = $this->session->userdata('customer');
}
public function save_faq($data){
$this->db->insert('faq',$data);
$id = $this->db->insert_id();
if($id) return $id ; else return false;
}
public function get_faq_count($condetion=null){
return $totalconversetion = $this->db->select('count(id) totalrow')->from('faq')->count_all_results();
}
public function get_faq_list(){
$this->customer = $this->go_cart->customer();
$return['unread_result'] = $this->db->query('select m1.id, m1.title, m1.timestamp, count(m2.id) as reps, users.id as userid, users.firstname from prefix_faq as m1, prefix_faq as m2,prefix_customers users where ((m1.user1="'.$this->customer['id'].'" and m1.user1read="no" and users.id=m1.user2) or (m1.user2="'.$this->customer['id'].'" and m1.user2read="no" and users.id=m1.user1)) and m1.id2="1" and m2.id=m1.id group by m1.id order by m1.id desc')->result();
$return['read_result'] = $this->db->query('select m1.id, m1.title, m1.timestamp, count(m2.id) as reps, users.id as userid, users.firstname from prefix_faq as m1, prefix_faq as m2,prefix_customers users where ((m1.user1="'.$this->customer['id'].'" and m1.user1read="yes" and users.id=m1.user2) or (m1.user2="'.$this->customer['id'].'" and m1.user2read="yes" and users.id=m1.user1)) and m1.id2="1" and m2.id=m1.id group by m1.id order by m1.id desc')->result();
return $return;
}
public function get_faq_by_id($id){
$this->db->select('title, user1, user2,product_id');
return $this->db->get_where('faq',array('id'=>$id,'id2'=>1))->row();
}
public function save($data,$condetion=array()){
if(!empty($condetion)){ // check for update query
$this->db->where($condetion);
$this->db->update('faq', $data);
return true;
} else{
// is use to insert data in faq
$this->db->insert('faq', $data);
$id = $this->db->insert_id();
return $id;
}
}
public function get_message_by_id($id){
return $this->db->query('select pm.timestamp, pm.message, users.id as userid, users.firstname username from prefix_faq pm, prefix_customers users where pm.id="'.$id.'" and users.id=pm.user1 order by pm.id2')->result();
}
public function save_feedback($data){
$this->db->insert('feedback', $data);
$id = $this->db->insert_id();
return $id;
}
}<file_sep><!DOCTYPE html>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title><?php echo (!empty($seo_title)) ? $seo_title .' - ' : ''; echo $this->config->item('company_name'); ?></title>
<?php if(isset($meta)):?>
<?php //echo $meta;?>
<?php else:?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<?php endif; ?>
<?php echo theme_css('bootstrap.css', true);?>
<?php echo theme_css('bootstrap-responsive.css', true);?>
<?php echo theme_css('style.css', true);?>
<?php echo theme_js('jquery.js', true);?>
<?php echo theme_js('bootstrap.min.js', true);?>
<?php echo theme_js('squard.js', true);?>
<?php echo theme_js('equal_heights.js', true);?>
<?php //echo theme_js('bootstrap.js', true);?>
<?php //echo theme_js('jquery_1.7.1_js.js', true);?>
<?php echo theme_js('common.js', true);?>
<?php echo theme_js('jquery.form.js', true); ?>
<!-- Le 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">
<div class="row">
<div class="span5">
<div class="logo"><a href="<?php echo base_url();?>"><?php echo theme_img('siteimg/logo.png', 'swap moto');?></a></div>
</div>
<div class="span5 sidebar fr">
<div class="account_overview clearfix fr">
<?php
$cust = $this->go_cart->customer();
if(!empty($cust['firstname'])) {
?>
<a><span class="icon-pencil"> </span>Welcome, <?php echo $cust['firstname']; ?></a>
<?php
}
?>
<a href="<?php echo base_url()?>myaccount/"><span class="icon-pencil"> </span>MY ACCOUNT</a>
<a href="#"><span class="icon-search"> </span>TRACK ORDER</a>
<!--<a href="#"><span class="icon-star"> </span>WISHLIST</a>-->
<?php if(!$this->Customer_model->is_logged_in(false, false)):?>
<a href="<?php echo base_url()?>secure/login"><span class="icon-pencil"> </span>Login</a>
<?php else : ?>
<a href="<?php echo base_url()?>secure/logout"><span class="icon-pencil"> </span>Logout</a>
<?php endif;?>
</div>
<!-- .account_overview -->
<div class="checkout_buttons clearfix">
<a href="<?php echo site_url('cart/view_cart');?>" class="btnn red"><span class="icon-shopping-cart icon-white"> </span> VIEW CART</a>
<span href="#" class="btnn black-white-gradient space-left-right">
<?php
if($this->go_cart->total_items() > 1)
{
echo $this->go_cart->total_items().' items';
}
else
{
echo $this->go_cart->total_items().' item';
}
?>
<a href="<?php echo base_url();?>checkout/" class="small-btn white-button">Checkout</a></span>
</div>
</div>
</div>
<!-- .row -->
<div class="row dark-black-gradient">
<div class="span4">
<a href="<?php echo base_url()?>secure/add_item" class="btnn-big white-black-border pull-left">SELL YOUR PARTS AND GEAR</a>
</div>
<div class="span8">
<div class="red_text">Recycle your parts or gear in $$</div>
<ul class="list_inline">
<li><a href="#">List your item for year</a></li>
<li><a href="#">Unlimited photos</a></li>
<li><a href="#">No images or listing fees</a></li>
</ul>
</div>
</div>
<!-- .row -->
<div class="row navbar dark-black-gradient">
<div class="navbar-inner">
<div class="container">
<a href="#" class="brand">Select your choice</a>
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<div class="nav-collapse pagination-centered">
<ul class="nav">
<?php
foreach($this->categories as $cat_menu):?>
<li <?php if($cat_menu['category']->slug==$this->uri->segment(1)){ ?> class="active" <?php } ?>><a href="<?php echo site_url($cat_menu['category']->slug);?>">
<?php echo get_img('uploads/images/thumbnails/'.$cat_menu['category']->image,true); ?>
<span class="text"><?php echo $cat_menu['category']->name;?></span></a> </li>
<?php endforeach;?>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
</div>
<file_sep><?php
/**
* this is common model All common method are avilabe here
* @author <NAME> <<EMAIL>>
*/
Class Email_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->library('email');
}
function changePassword($newPassword,$customer)
{
$template = $this->getEmailTemplate('change_password');
$subject = $template[0]['subject'];
$message=$template[0]['content'];
$this->email->from(ADMIN_FROME_EMAIL, ADMIN_FROME_NAME);
$this->email->to($customer['email']);
$this->email->subject($subject);
$message=str_replace('{customer_name}',$customer['firstname'],$message);
$message=str_replace('{password}',$newPassword,$message);
$this->email->message($message);
if($this->email->send())
return true;
else
return false;
}
function getEmailTemplate($name)
{
$sqlteml="select * from prefix_canned_messages where name ='$name'";
$queryteml=$this->db->query($sqlteml);
return $queryteml->result_array();
}
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Authorize_net
{
var $CI;
//this can be used in several places
var $method_name = 'Charge by Credit Card';
function __construct()
{
$this->CI =& get_instance();
$this->CI->load->helper("credit_card");
$this->CI->load->library('authorize_net_lib');
$this->CI->lang->load('authorize_net');
}
/*
checkout_form()
this function returns an array, the first part being the name of the payment type
that will show up beside the radio button the next value will be the actual form if there is no form, then it should equal false
there is also the posibility that this payment method is not approved for this purchase. in that case, it should return a blank array
*/
//these are the front end form and check functions
function checkout_form($post = false)
{
$settings = $this->CI->Settings_model->get_settings('Authorize_net');
$enabled = $settings['enabled'];
$form = array();
$form['name'] = $this->method_name;
// Retrieve any previously stored cc data to redisplay in case of errors
$cc_data = $this->CI->session->userdata('cc_data');
if($enabled)
{
$form['form'] = $this->CI->load->view('customer_card', array('cc_data'=>$cc_data), true);
return $form;
} else return array();
}
function checkout_check()
{
$error_msg = lang('please_fix_errors').'<BR><UL>';
$error_list = "";
//Verify name field
if( empty($_POST["x_first_name"]) || empty($_POST["x_last_name"]))
$error_list .= '<LI>'.lang('enter_card_name').'</LI>';
//Verify date
if( !card_expiry_valid($_POST["x_exp_date_mm"], $_POST["x_exp_date_yy"]) )
$error_list .= '<LI>'.lang('invalid_card_exp').'</LI>';
//Verify card number
if( empty($_POST["x_card_num"]) || !card_number_valid($_POST["x_card_num"]) )
$error_list .= '<LI>'.lang('invalid_card_num').'</LI>';
//Verify security code
if( empty($_POST["x_card_code"]))
$error_list .= '<LI>'.lang('enter_card_code').'</LI>';
// We need to store the credit card information temporarily
$cc_tmp_data["cc_data"] = $_POST;
$this->CI->session->set_userdata($cc_tmp_data);
if( $error_list )
return $error_msg . $error_list . "</UL>";
else
{
return false;
}
}
function description()
{
//create a description from the session which we can store in the database
//this will be added to the database upon order confirmation
/*
access the payment information with the $_POST variable since this is called
from the same place as the checkout_check above.
*/
// return 'Authorize.net Credit Card Instant Processing';
return 'Credit Card';
/*
for a credit card, this may look something like
$payment['description'] = 'Card Type: Visa
Name on Card: <NAME><br/>
Card Number: XXXX-XXXX-XXXX-9976<br/>
Expires: 10/12<br/>';
*/
}
//back end installation functions
function install()
{
//set default settings
// -These will be user-editable
$config['authorize_net_test_mode'] = 'TRUE'; // Set this to FALSE for live processing
$config['authorize_net_live_x_login'] = '';
$config['authorize_net_live_x_tran_key'] = '';
$config['authorize_net_test_x_login'] = '';
$config['authorize_net_test_x_tran_key'] = '';
// Lets setup some other values so we dont have to do it everytime we process a transaction
// - These are not user editable
$config['authorize_net_test_api_host'] = 'https://test.authorize.net/gateway/transact.dll';
$config['authorize_net_live_api_host'] = 'https://secure.authorize.net/gateway/transact.dll';
$config['authorize_net_x_version'] = '3.1';
$config['authorize_net_x_type'] = 'AUTH_CAPTURE';
$config['authorize_net_x_relay_response'] = 'FALSE';
$config['authorize_net_x_delim_data'] = 'TRUE';
$config['authorize_net_x_delim_char'] = '|';
$config['authorize_net_x_encap_char'] = '';
$config['authorize_net_x_url'] = 'FALSE';
$config['authorize_net_x_method'] = 'CC';
$config['enabled'] = '0';
$this->CI->Settings_model->save_settings('Authorize_net', $config);
}
function uninstall()
{
$this->CI->Settings_model->delete_settings('Authorize_net');
}
//payment processor
function process_payment()
{
// Get previously entered customer info
$cc_data = $this->CI->session->userdata('cc_data');
$customer = $this->CI->go_cart->customer();
// Set our authnet fields
$this->CI->authorize_net_lib->add_x_field('x_first_name', $cc_data["x_first_name"]);
$this->CI->authorize_net_lib->add_x_field('x_last_name', $cc_data["x_last_name"]);
$this->CI->authorize_net_lib->add_x_field('x_address', $customer['bill_address']["address1"]. $customer['bill_address']["address2"]);
$this->CI->authorize_net_lib->add_x_field('x_city', $customer['bill_address']["city"]);
$this->CI->authorize_net_lib->add_x_field('x_state', $customer['bill_address']["zone"]);
$this->CI->authorize_net_lib->add_x_field('x_zip', $customer['bill_address']["zip"]);
$this->CI->authorize_net_lib->add_x_field('x_country', $customer['bill_address']["city"]);
$this->CI->authorize_net_lib->add_x_field('x_email', $customer['bill_address']["email"]);
$this->CI->authorize_net_lib->add_x_field('x_phone', $customer['bill_address']["phone"]);
/**
* To test:
* Use credit card number 4111111111111111 for a good transaction
* Use credit card number 4111111111111122 for a bad card
*/
$this->CI->authorize_net_lib->add_x_field('x_card_num', $cc_data["x_card_num"]);
$this->CI->authorize_net_lib->add_x_field('x_amount', $this->CI->go_cart->total());
$this->CI->authorize_net_lib->add_x_field('x_exp_date', $cc_data["x_exp_date_mm"] . $cc_data["x_exp_date_yy"]); // MM.YY
$this->CI->authorize_net_lib->add_x_field('x_card_code', $cc_data["x_card_code"]);
// Send info to authorize.net and receive a response
$this->CI->authorize_net_lib->process_payment();
$authnet_response = $this->CI->authorize_net_lib->get_all_response_codes();
// Forward results
if($authnet_response['Response_Code'] == '1')
{
// payment success, we can destroy our tmp card data
$this->CI->session->unset_userdata('cc_data');
return $authnet_response; // false == no error
}
else
{
// payment declined, return our user to the form with an error.
//return lang('transaction_declined');
switch($authnet_response['Card_Code_CVV_Response Code'])
{
case 'N' :
$ccresponse= 'The card code verification (CCV) Not Matched';
break;
case 'P' :
$ccresponse= 'The card code verification (CCV) Not Processed';
break;
case 'S' :
$ccresponse= 'The card code verification (CCV) Not Matched';
break;
case 'U' :
$ccresponse= 'The card code verification (CCV) Issuer unable to process request';
break;
case '' :
$ccresponse= 'The card code verification (CCV) Not Processed';
break;
}
switch($authnet_response['AVS_Result_Code'])
{
case 'A' :
$avsresponse= 'The Address Verification Service (AVS) Address (Street) matches, ZIP does not';
break;
case 'B' :
$avsresponse= 'Address information not provided for AVS check';
break;
case 'E' :
$avsresponse= 'AVS error';
break;
case 'G' :
$avsresponse= 'Non-U.S. Card Issuing Bank';
break;
case 'N' :
$avsresponse= 'No Match on Address (Street) or ZIP';
break;
case 'P' :
$avsresponse= 'AVS not applicable for this transaction';
break;
case 'R' :
$avsresponse= 'Retry—System unavailable or timed out';
break;
case 'S' :
$avsresponse= 'Service not supported by issuer';
break;
case 'U' :
$avsresponse= 'Address information is unavailable';
break;
case 'W' :
$avsresponse= 'Nine digit ZIP matches, Address (Street) does not';
break;
case 'X' :
$avsresponse= 'Address (Street) and nine digit ZIP match';
break;
case 'Y' :
$avsresponse= 'Address (Street) and five digit ZIP match';
break;
case 'Z' :
$avsresponse= 'Five digit ZIP matches, Address (Street) does not';
break;
case '' :
$avsresponse= 'AVS error';
break;
}
switch($authnet_response['Response_Code'])
{
case '3' :
$responseCode= 'Error in Transaction, Some Thing Went Wrong';
break;
case '4' :
$responseCode= 'Transaction is Held for Review';
break;
}
switch($authnet_response['Cardholder_Authentication_Verification_Value_CAVV_Response_Code'])
{
case '0' :
$cavvResponse= 'CAVV not validated because erroneous data was submitted';
break;
case '1' :
$cavvResponse= 'CAVV failed validation';
break;
case '3' :
$cavvResponse= 'CAVV validation could not be performed; issuer attempt incomplete';
break;
case '4' :
$cavvResponse= 'CAVV validation could not be performed; issuer system error';
break;
case '5' :
$cavvResponse= 'Reserved for future use';
break;
case '6' :
$cavvResponse= 'Reserved for future use';
break;
case '7' :
$cavvResponse= 'CAVV attempt – failed validation – issuer available (U.S.- issued card/non-U.S acquirer)';
break;
case '8' :
$cavvResponse= 'CAVV attempt – passed validation – issuer available (U.S.- issued card/non-U.S. acquirer)';
break;
case '9' :
$cavvResponse= 'CAVV attempt – failed validation – issuer unavailable (U.S.- issued card/non-U.S. acquirer)';
break;
case 'A' :
$cavvResponse= 'CAVV attempt – passed validation – issuer unavailable (U.S.- issued card/non-U.S. acquirer)';
break;
case 'B' :
$cavvResponse= 'CAVV passed validation, information only, no liability shift';
break;
case '' :
$cavvResponse= 'Cardholder Authentication Verification Value(CAVV) not validated';
break;
}
$response=array('done'=>'0',
'error'=>$responseCode,
'cavvResponse'=>$cavvResponse,
'avsResponse'=>$avsresponse,
'ccResponse'=>$ccresponse,
'whole_responce'=>$authnet_response);
return $response;
}
}
//admin end form and check functions
function form($post = false)
{
//this same function processes the form
// what about check() ?? - GDA
if(!$post)
{
$settings = $this->CI->Settings_model->get_settings('Authorize_net');
}
else
{
$settings = $post;
}
return $this->CI->load->view('auth_net_form', array('settings'=>$settings), true);
}
function check()
{
$error = false;
if ( $_POST["authorize_net_test_mode"]=="TRUE" )
{
if(empty($_POST["authorize_net_test_x_login"]) || empty($_POST["authorize_net_test_x_tran_key"]) )
{
$error = lang('enter_test_mode_credentials');
}
}
else
{
if(empty($_POST["authorize_net_live_x_login"]) || empty($_POST["authorize_net_live_x_tran_key"]) )
{
$error = lang('enter_live_mode_credentials');
}
}
//forward the error
if($error)
{
return $error;
}
else
{
//Save
$this->CI->Settings_model->save_settings('Authorize_net', $_POST);
return false;
}
}
}<file_sep><div class="span9">
<?php echo $this->common_model->getMessage(); ?>
<div class="page-header">
<h3>Unread Messages(<?php echo count($inbox['unread_result']); ?>):</h3>
<table class="table">
<tr>
<th class="title_cell">Title</th>
<th>Nb. Replies</th>
<th>Participant</th>
<th>Date of creation</th>
</tr>
<?php
foreach($inbox['unread_result'] as $unread_inbox){
?>
<tr>
<td class="left"><a href="<?php echo base_url('/myaccount/view_message/'.$unread_inbox->id); ?>"><?php echo htmlentities($unread_inbox->title, ENT_QUOTES, 'UTF-8'); ?></a></td>
<td><?php echo $unread_inbox->reps-1; ?></td>
<td><a style="cursor:default"><?php echo htmlentities($unread_inbox->firstname, ENT_QUOTES, 'UTF-8'); ?></a></td>
<td><?php echo date('Y/m/d H:i:s' ,$unread_inbox->timestamp); ?></td>
</tr>
<?php } ?>
<?php if(intval($inbox['unread_result'])==0) {
?>
<tr>
<td colspan="4" class="center">You have no unread message.</td>
</tr>
<?php
}
?>
</table>
<div class="page-header"> <h3>Read Messages(<?php echo count($inbox['read_result']); ?>):</h3>
</div>
<table class="table">
<tr>
<th class="title_cell">Title</th>
<th>Nb. Replies</th>
<th>Participant</th>
<th>Date of creation</th>
</tr>
<?php
foreach($inbox['read_result'] as $read_inbox){
?>
<tr>
<td class="left"><a href="<?php echo base_url('/myaccount/view_message/'.$read_inbox->id); ?>"><?php echo htmlentities($read_inbox->title, ENT_QUOTES, 'UTF-8'); ?></a></td>
<td><?php echo $read_inbox->reps-1; ?></td>
<td><?php echo htmlentities($read_inbox->firstname, ENT_QUOTES, 'UTF-8'); ?></td>
<td><?php echo date('Y/m/d H:i:s' ,$read_inbox->timestamp); ?></td>
</tr>
<?php } ?>
<?php if(intval($inbox['read_result'])==0) {
?>
<tr>
<td colspan="4" class="center">You have no read message.</td>
</tr>
<?php
}
?>
</table>
</div></div></div>
<script language="javascript">
$('#faq_btn').click(function(){
var faq = $('#faq_box').val().trim();
var product_id = '<?php echo $product->id?>';
$.post("<?php echo site_url('myaccount/save_faq');?>", { faq: faq, product_id:product_id},
function(data,status) {
if(data==1){
$('#showmsg').html('Your question has been sent to seller, They will tuch very soon.').show();
} else{
$('#showmsg').html('Opps ! try again to ask question.').show();
}
});
});
</script>
<file_sep>/* this is a common js file
*
*/
$(document).ready(function()
{
// this is use for close the message box
$('#closeMe').click(function()
{
$('#closeMeRapper').fadeOut( "slow");
});
});
<file_sep><div class="span9">
<?php echo $this->common_model->getMessage(); ?>
<div class="content">
<div class="page-header"> <h1><?php echo $message->title; ?></h1></div>
<table class="table">
<tr>
<th>User</th>
<th>Message</th>
<th>Date</th>
</tr>
<?php
foreach($convertion as $cvalue){
?>
<tr>
<td class="author center">
<a href="profile.php?id=<?php echo $cvalue->userid; ?>"><?php echo $cvalue->username; ?></a></td>
<td class="left">
<?php echo $cvalue->message; ?></td>
<td><div class="date">Sent: <?php echo date('m/d/Y H:i:s' ,$cvalue->timestamp); ?></div></td>
</tr>
<?php
}
//We display the reply form
?>
</table>
<div class="page-header">
<h2>Reply</h2>
</div>
<div class="center">
<form action="<?php echo base_url('/myaccount/view_message/'.$id); ?>" method="post">
<label for="message" class="center">Message</label><br />
<textarea class="textarea span_textarea" cols="40" rows="5" name="message" id="message"></textarea><br />
<input type="submit" value="Send" class="pull-right btnn red" />
</form>
</div>
</div>
</div>
</div>
<file_sep><?php
class Myaccount extends Front_Controller {
var $customer;
function __construct() {
parent::__construct();
force_ssl();
$this->load->model(array('location_model'));
$this->customer = $this->go_cart->customer();
}
function index($offset = 0) {
//make sure they're logged in
$this->Customer_model->is_logged_in('secure/login/');
$data['gift_cards_enabled'] = $this->gift_cards_enabled;
$data['customer'] = (array) $this->Customer_model->get_customer($this->customer['id']);
$data['addresses'] = $this->Customer_model->get_address_list($this->customer['id']);
$data['page_title'] = 'Welcome ' . $data['customer']['firstname'] . ' ' . $data['customer']['lastname'];
$data['customer_addresses'] = $this->Customer_model->get_address_list($data['customer']['id']);
// load other page content
//$this->load->model('banner_model');
$this->load->model('order_model');
$this->load->helper('directory');
$this->load->helper('date');
//if they want to limit to the top 5 banners and use the enable/disable on dates, add true to the get_banners function
// $data['banners'] = $this->banner_model->get_banners();
// $data['ads'] = $this->banner_model->get_banners(true);
$data['categories'] = $this->Category_model->get_categories_tierd(0);
// paginate the orders
$this->load->library('pagination');
$config['base_url'] = site_url('secure/my_account');
$config['total_rows'] = $this->order_model->count_customer_orders($this->customer['id']);
$config['per_page'] = '15';
$config['first_link'] = 'First';
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['last_link'] = 'Last';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['full_tag_open'] = '<div class="pagination"><ul>';
$config['full_tag_close'] = '</ul></div>';
$config['cur_tag_open'] = '<li class="active"><a href="#">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['prev_link'] = '«';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
$config['next_link'] = '»';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$this->pagination->initialize($config);
$data['orders_pagination'] = $this->pagination->create_links();
$data['orders'] = $this->order_model->get_customer_orders($this->customer['id'], $offset);
//if they're logged in, then we have all their acct. info in the cookie.
/*
This is for the customers to be able to edit their account information
*/
$this->load->library('form_validation');
$this->form_validation->set_rules('company', 'Company', 'trim|max_length[128]');
$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|max_length[32]');
$this->form_validation->set_rules('lastname', 'Last Name', 'trim|required|max_length[32]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|max_length[128]|callback_check_email');
$this->form_validation->set_rules('phone', 'Phone', 'trim|required|max_length[32]');
$this->form_validation->set_rules('email_subscribe', 'Subscribe', 'trim|numeric|max_length[1]');
if ($this->input->post('password') != '' || $this->input->post('confirm') != '') {
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|sha1');
$this->form_validation->set_rules('confirm', 'Confirm Password', 'required|matches[password]');
} else {
$this->form_validation->set_rules('password', '<PASSWORD>');
$this->form_validation->set_rules('confirm', 'Confirm Password');
}
if ($this->form_validation->run() == FALSE) {
$data["title"] = "";
$data["file"] = "my_account";
$this->load->view('myaccount_template', $data);
} else {
$customer = array();
$customer['id'] = $this->customer['id'];
$customer['company'] = $this->input->post('company');
$customer['firstname'] = $this->input->post('firstname');
$customer['lastname'] = $this->input->post('lastname');
$customer['email'] = $this->input->post('email');
$customer['phone'] = $this->input->post('phone');
$customer['email_subscribe'] = intval((bool) $this->input->post('email_subscribe'));
if ($this->input->post('password') != '') {
$customer['password'] = $this->input->post('password');
}
// $this->go_cart->save_customer($this->customer);
$this->Customer_model->save($customer);
//$this->session->set_flashdata('message', 'Profile has been updated');
$this->common_model->setMessage(1, 'Profile has been updated');
redirect('myaccount');
}
}
public function list_item($order_by = "name", $sort_order = "ASC", $code = 0, $page = 0, $rows = 15) {
//make sure they're logged in
$this->Customer_model->is_logged_in('secure/login/');
$this->load->model('Product_model');
$this->load->helper('form');
$this->lang->load('product');
$data['page_title'] = lang('products');
$data['code'] = $code;
$term = false;
$category_id = false;
//get the category list for the drop menu
//$data['categories'] = $this->Category_model->get_categories_tierd();
//$post = $this->input->post(null, false);
$customer = $this->go_cart->customer();
$post = array('user_id' => $customer['id']);
$this->load->model('Search_model');
if ($post) {
$term = json_encode($post);
$code = $this->Search_model->record_term($term);
}
//store the search term
$data['term'] = $term;
$data['order_by'] = $order_by;
$data['sort_order'] = $sort_order;
$data['products'] = $this->Product_model->get_my_products(array('term' => $term, 'order_by' => $order_by, 'sort_order' => $sort_order, 'rows' => $rows, 'page' => $page));
//total number of products
$data['total'] = $this->Product_model->get_my_products(array('term' => $term, 'order_by' => $order_by, 'sort_order' => $sort_order), true);
$this->load->library('pagination');
$config['base_url'] = site_url($this->config->item('admin_folder') . '/products/index/' . $order_by . '/' . $sort_order . '/' . $code . '/');
$config['total_rows'] = $data['total'];
$config['per_page'] = $rows;
$config['uri_segment'] = 7;
$config['first_link'] = 'First';
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['last_link'] = 'Last';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['full_tag_open'] = '<div class="pagination"><ul>';
$config['full_tag_close'] = '</ul></div>';
$config['cur_tag_open'] = '<li class="active"><a href="#">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['prev_link'] = '«';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
$config['next_link'] = '»';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$this->pagination->initialize($config);
$data["title"] = "";
$data["file"] = "list_item";
$this->load->view('myaccount_template', $data);
}
function thanks() {
echo "Product Has been saved successfully";
echo "<br>This page is under cunstruction";
echo "<br><a href='" . base_url() . "secure/sale'>Go to Sale Page</a>";
}
public function remove_item($product_id = NULL) {
if (empty($product_id)) {
//$this->session->set_flashdata('error', lang('error_not_found'));
$this->common_model->setMessage(3,"Item not exist");
}
$customer = $this->go_cart->customer();
$product = $this->Product_model->get_user_product($product_id, $customer['id']);
if ($product == false) {
//$this->session->set_flashdata('error', lang('error_not_found'));
$this->common_model->setMessage(3, lang('error_not_found'));
$this->common_model->setMessage(3,"Item not exist");
} else {
$this->Product_model->delete_product($product_id);
//$this->session->set_flashdata('message', lang('message_deleted_product'));
$this->common_model->setMessage(1, "Item successfully removed");
}
redirect('/myaccount/list_item');
}
function order($offset = 0) {
//make sure they're logged in
$this->Customer_model->is_logged_in('secure/login/');
$this->load->model('order_model');
$this->load->helper('directory');
$this->load->helper('date');
$this->load->library('pagination');
$config['base_url'] = site_url('secure/my_account');
$config['total_rows'] = $this->order_model->count_customer_orders($this->customer['id']);
$config['per_page'] = '10';
$config['first_link'] = 'First';
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['last_link'] = 'Last';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['full_tag_open'] = '<div class="pagination"><ul>';
$config['full_tag_close'] = '</ul></div>';
$config['cur_tag_open'] = '<li class="active"><a href="#">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['prev_link'] = '«';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
$config['next_link'] = '»';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$this->pagination->initialize($config);
$data['orders_pagination'] = $this->pagination->create_links();
$data['orders'] = $this->order_model->get_customer_orders($this->customer['id'], $offset);
$data["title"] = "";
$data["file"] = "customer_order";
$this->load->view('myaccount_template', $data);
}
public function address() {
$this->Customer_model->is_logged_in('myaccount/my_account/');
$data['gift_cards_enabled'] = $this->gift_cards_enabled;
$data['customer'] = (array) $this->Customer_model->get_customer($this->customer['id']);
$data['addresses'] = $this->Customer_model->get_address_list($this->customer['id']);
$data["title"] = "";
$data["file"] = "addresses";
$this->load->view('myaccount_template', $data);
}
public function add_address($id = 0) {
$customer = $this->go_cart->customer();
//grab the address if it's available
$data['id'] = false;
$data['company'] = $customer['company'];
$data['firstname'] = $customer['firstname'];
$data['lastname'] = $customer['lastname'];
$data['email'] = $customer['email'];
$data['phone'] = $customer['phone'];
$data['address1'] = '';
$data['address2'] = '';
$data['city'] = '';
$data['country_id'] = '';
$data['zone_id'] = '';
$data['zip'] = '';
if ($id != 0) {
$a = $this->Customer_model->get_address($id);
if ($a['customer_id'] == $this->customer['id']) {
$data = $a['field_data'];
$data['id'] = $id;
} else {
redirect('/'); // don't allow cross-customer editing
}
$data['zones_menu'] = $this->location_model->get_zones_menu($data['country_id']);
}
//get the countries list for the dropdown
$data['countries_menu'] = $this->location_model->get_countries_menu();
if ($id == 0) {
//if there is no set ID, the get the zones of the first country in the countries menu
$data['zones_menu'] = $this->location_model->get_zones_menu(array_shift(array_keys($data['countries_menu'])));
} else {
$data['zones_menu'] = $this->location_model->get_zones_menu($data['country_id']);
}
$data["title"] = "";
$data["file"] = "add_address";
$this->load->view('myaccount_template', $data);
}
public function change_password() {
//echo "<pre>";print_r($this->customer);
// user authantication
$this->Customer_model->is_logged_in('secure/login/');
if ('update' == 'update') {
$haserror = true;
$customer = $this->go_cart->customer();
if ($this->input->post('current_password') != '') {
if ($customer['password'] === sha1($this->input->post('current_password'))) {
$haserror = false;
} else {
$this->common_model->setMessage(3,'Password not match.');
redirect('myaccount/change_password');
}
} elseif(isset($_POST['current_password']) && $_POST['current_password']==''){
$this->common_model->setMessage(3,'Enter current password.');
redirect('myaccount/change_password');
}
if ($haserror == false) {
if (!empty($_REQUEST['password'])) {
$password = $this->input->post('password');
$confirm = $this->input->post('confirm');
if ($password === $confirm) {
$customer = array();
$customer['id'] = $this->customer['id'];
$customer['password'] = <PASSWORD>($this->input->post('password'));
$this->go_cart->save_customer($this->customer);
if ($this->Customer_model->save($customer)) {
$this->common_model->setMessage(1, 'Password has been updated');
//$this->email_model->changePassword($this->input->post('password'),$this->customer);
}
$this->common_model->setMessage(3,'Sorry ! try again.');
redirect('myaccount/change_password');
}
} else {
$this->common_model->setMessage(3,'Please enter password.');
redirect('myaccount/change_password');
}
}
}
$data["title"] = "";
$data["file"] = "change_pass";
$this->load->view('myaccount_template', $data);
}
function address_form($id = 0)
{
$customer = $this->go_cart->customer();
//grab the address if it's available
$data['id'] = false;
$data['company'] = $customer['company'];
$data['firstname'] = $customer['firstname'];
$data['lastname'] = $customer['lastname'];
$data['email'] = $customer['email'];
$data['phone'] = $customer['phone'];
$data['address1'] = '';
$data['address2'] = '';
$data['city'] = '';
$data['country_id'] = '';
$data['zone_id'] = '';
$data['zip'] = '';
if($id != 0)
{
$a = $this->Customer_model->get_address($id);
if($a['customer_id'] == $this->customer['id'])
{
//notice that this is replacing all of the data array
//if anything beyond this form data needs to be added to
//the data array, do so after this portion of code
$data = $a['field_data'];
$data['id'] = $id;
} else {
redirect('/'); // don't allow cross-customer editing
}
$data['zones_menu'] = $this->location_model->get_zones_menu($data['country_id']);
}
//get the countries list for the dropdown
$data['countries_menu'] = $this->location_model->get_countries_menu();
if($id==0)
{
//if there is no set ID, the get the zones of the first country in the countries menu
$data['zones_menu'] = $this->location_model->get_zones_menu(array_shift(array_keys($data['countries_menu'])));
} else {
$data['zones_menu'] = $this->location_model->get_zones_menu($data['country_id']);
}
$this->load->library('form_validation');
//$this->form_validation->set_rules('company', 'Company', 'trim|max_length[128]');
$this->form_validation->set_rules('firstname', '<NAME>', 'trim|required|max_length[32]');
$this->form_validation->set_rules('lastname', '<NAME>', 'trim|required|max_length[32]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|max_length[128]');
$this->form_validation->set_rules('phone', 'Phone', 'trim|required|max_length[32]');
$this->form_validation->set_rules('address1', 'Address', 'trim|required|max_length[128]');
$this->form_validation->set_rules('address2', 'Address', 'trim|max_length[128]');
$this->form_validation->set_rules('city', 'City', 'trim|required|max_length[32]');
$this->form_validation->set_rules('country_id', 'Country', 'trim|required|numeric');
$this->form_validation->set_rules('zone_id', 'State', 'trim|required|numeric');
$this->form_validation->set_rules('zip', 'Zip', 'trim|required|max_length[32]');
if ($this->form_validation->run() == FALSE)
{
if(validation_errors() != '')
{
echo validation_errors();
}
else
{
$this->load->view('address_form', $data);
}
}
else
{
$a = array();
$a['id'] = ($id==0) ? '' : $id;
$a['customer_id'] = $this->customer['id'];
$a['field_data']['company'] = $this->input->post('company');
$a['field_data']['firstname'] = $this->input->post('firstname');
$a['field_data']['lastname'] = $this->input->post('lastname');
$a['field_data']['email'] = $this->input->post('email');
$a['field_data']['phone'] = $this->input->post('phone');
$a['field_data']['address1'] = $this->input->post('address1');
$a['field_data']['address2'] = $this->input->post('address2');
$a['field_data']['city'] = $this->input->post('city');
$a['field_data']['zip'] = $this->input->post('zip');
// get zone / country data using the zone id submitted as state
$country = $this->location_model->get_country(set_value('country_id'));
$zone = $this->location_model->get_zone(set_value('zone_id'));
if(!empty($country))
{
$a['field_data']['zone'] = $zone->code; // save the state for output formatted addresses
$a['field_data']['country'] = $country->name; // some shipping libraries require country name
$a['field_data']['country_code'] = $country->iso_code_2; // some shipping libraries require the code
$a['field_data']['country_id'] = $this->input->post('country_id');
$a['field_data']['zone_id'] = $this->input->post('zone_id');
}
$this->Customer_model->save_address($a);
$this->common_model->setMessage(1, 'Address has been saved');
echo 1;
}
}
function delete_address()
{
$id = $this->input->post('id');
// use the customer id with the addr id to prevent a random number from being sent in and deleting an address
$customer = $this->go_cart->customer();
$this->Customer_model->delete_address($id, $customer['id']);
echo $id;
}
/*
@auther : <NAME>
@DAte : 4-april- 2014
@desc : save query asked by visiter or user and send notfication to seller, called using ajax
@input : message, product_id
*/
public function save_faq(){
$this->load->model(array('faq_model'));
$message = $this->input->post('faq');
$product_id = $this->input->post('product_id');
$customer = $this->go_cart->customer();
$condetion = array('id'=>$product_id);
$product = $this->Product_model->get_similar_product($condetion,1);
$tatalfaq = $this->faq_model->get_faq_count();
$product = $product[0];
$product_title = "FAQ";
$save = array();
$save['id'] = $tatalfaq+1;
$save['id2'] = 1;
$save['product_id'] = $product->id;
$save['title'] = $product_title;
$save['user1'] = $customer['id'];
$save['user2'] = $product->user_id;
$save['timestamp'] = time();
$save['message'] = $message;
$save['user1read'] = 'yes';
$save['user2read'] = 'no';
$faqrs = $this->faq_model->save_faq($save);
if($faqrs!=false){
echo "1";
} else {
echo 0;
}
}
/*
@auther : <NAME>
@DAte : 4-april- 2014
@desc : seller Inbox, out box , send rply
@input : null
*/
public function inbox(){
$this->load->model(array('faq_model'));
$return = $this->faq_model->get_faq_list();
$data['inbox'] = $return;
$data["file"] = "inbox";
$this->load->view('myaccount_template', $data);
}
public function view_message($id){
$this->customer = $this->go_cart->customer();
$this->load->model(array('faq_model'));
$result = $this->faq_model->get_faq_by_id($id);
if(count($result)<=0){
// set error message to send return to inbox
$this->common_model->setMessage(3, 'This discussion does not exists.');
redirect('/myaccount/inbox');
}
//We check if the user have the right to read this discussion
if($result->user1==$this->customer['id'] || $result->user2==$this->customer['id']){
if($result->user1==$this->customer['id']){
$save['user1read'] = 'yes';
$user_partic = 2;
} elseif($result->user2==$this->customer['id']){
$save['user2read'] = 'yes';
$user_partic = 1;
}
$condetion = array('id'=>$id, 'id2'=>1);
$this->faq_model->save($save,$condetion);
$req2 = $this->faq_model->get_message_by_id($id);
// send message in rply
if(isset($_POST['message']) and $_POST['message']!='')
{
$message = $_POST['message'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$message = stripslashes($message);
}
//We protect the variables
$message = mysql_real_escape_string(nl2br(htmlentities($message, ENT_QUOTES, 'UTF-8')));
//We send the message and we change the status of the discussion to unread for the recipient
$savedata = array();
$savedata['id'] = $id;
$savedata['id2'] = count($req2)+1;
$savedata['product_id'] = $result->product_id;
$savedata['title'] = '';
$savedata['user1'] = $this->customer['id'];
$savedata['user2'] = '';
$savedata['message'] = $message;
$savedata['timestamp'] = time();
$savedata['user1read'] = '';
$savedata['user2read'] = '';
$this->faq_model->save($savedata);
$save = array();
$save['user'.$user_partic.'read']="yes";
$this->faq_model->save($save, $condetion);
$this->common_model->setMessage(1, 'Your message sent.');
redirect('/myaccount/view_message/'.$id);
}elseif(isset($_POST['message']) and $_POST['message']==''){
$this->common_model->setMessage(3, 'Please enter message.');
redirect('/myaccount/view_message/'.$id);
}
$data['convertion'] = $req2;
$data['message'] = $result;
}
else {
$this->common_model->setMessage(3, 'You dont have the rights to access this page.');
redirect('/myaccount/inbox');
}
$data['id'] = $id;
$data['file'] = 'view_message';
$this->load->view('myaccount_template', $data);
}
function save_feedback(){
$haserror = false;
$message = "";
$this->load->model(array('faq_model'));
$feedback_msg = $this->input->post('feedback_msg');
$product_id = $this->input->post('product_id');
$reting = $this->input->post('reting');
$customer = $this->go_cart->customer();
$condetion = array('id'=>$product_id);
$product = $this->Product_model->get_similar_product($condetion,1);
$product = $product[0];
//print_r($product);
$save['feedback'] = $feedback_msg;
$save['product_id'] = $product_id;
$save['rate'] = $reting;
$save['feedback_by'] = $customer['id'];
$save['feedback_to'] = $product->user_id;
$save['type'] = "B2S";
$save['feedback_on'] = time();
if($customer['id']==$product->user_id){
$message = "You are not allow to share feedback.";
$haserror = true;
}
if($haserror==false){
$feedback = $this->faq_model->save_feedback($save);
} else $feedback = false;
if($feedback!=false){
$result = array('status'=>'1','message'=>'Thanks for sharing your feedback');
} else{
if($message==''){
$message = "Sorry ! Some error occured";
}
$result = array('status'=>'0','message'=>$message);
}
echo json_encode($result);
}
public function open(){
echo "hello";
}
}
<file_sep><?php include('header.php'); ?>
<!-- .container -->
<div class="container mar-top">
<div class="row">
<?php include('left.php'); ?>
<!-- span4 -->
<?php include('display.php') ?>
<!-- .span8 -->
</div>
<!-- row -->
<?php include('feature.php'); ?>
<!-- .row -->
</div> <!-- /container -->
<?php include('footer.php'); ?><file_sep><div class="footer">
<div class="container">
<ul class="list_inline inline">
<?php foreach($this->pages as $menu_page):?>
<li>
<?php if(empty($menu_page->content)):?>
<a href="<?php echo $menu_page->url;?>" <?php if($menu_page->new_window ==1){echo 'target="_blank"';} ?>><?php echo $menu_page->menu_title;?></a>
<?php else:?>
<a href="<?php echo site_url($menu_page->slug);?>"><?php echo $menu_page->menu_title;?></a>
<?php endif;?>
</li>
<?php endforeach;?>
</ul>
<span class="block"> Copyright © 2004 - <?php echo date('Y');?> Swap Moto, Inc. All Rights Reserved</span>
</div>
</div>
</body>
</html>
<file_sep><?php
class Secure extends Front_Controller {
var $customer;
function __construct()
{
parent::__construct();
force_ssl();
$this->load->model(array('location_model'));
$this->customer = $this->go_cart->customer();
}
function index()
{
show_404();
}
function login($ajax = false)
{
//find out if they're already logged in, if they are redirect them to the my account page
$redirect = $this->Customer_model->is_logged_in(false, false);
//if they are logged in, we send them back to the my_account by default, if they are not logging in
if ($redirect)
{
redirect(base_url().'myaccount/');
}
$data['page_title'] = 'Login';
$data['gift_cards_enabled'] = $this->gift_cards_enabled;
$this->load->helper('form');
$data['redirect'] = $this->session->flashdata('redirect');
$submitted = $this->input->post('submitted');
if ($submitted)
{
$email = $this->input->post('email');
$password = $<PASSWORD>->post('<PASSWORD>');
$remember = $this->input->post('remember');
$redirect = $this->input->post('redirect');
$login = $this->Customer_model->login($email, $password, $remember);
if ($login)
{
if ($redirect == '')
{
//if there is not a redirect link, send them to the my account page
$redirect = 'myaccount/';
}
//to login via ajax
if($ajax)
{
die(json_encode(array('result'=>true)));
}
else
{
redirect($redirect);
}
}
else
{
//this adds the redirect back to flash data if they provide an incorrect credentials
//to login via ajax
if($ajax)
{
die(json_encode(array('result'=>false)));
}
else
{
$this->session->set_flashdata('redirect', $redirect);
$this->session->set_flashdata('error', lang('login_failed'));
$this->common_model->setMessage(3,lang('login_failed'));
redirect('secure/login');
}
}
}
// load other page content
//$this->load->model('banner_model');
$this->load->helper('directory');
//if they want to limit to the top 5 banners and use the enable/disable on dates, add true to the get_banners function
//$data['banners'] = $this->banner_model->get_banners();
//$data['ads'] = $this->banner_model->get_banners(true);
$data['categories'] = $this->Category_model->get_categories_tierd(0);
$this->load->view('login', $data);
}
function logout()
{
$this->Customer_model->logout();
redirect('secure/login');
}
function register()
{
$redirect = $this->Customer_model->is_logged_in(false, false);
//if they are logged in, we send them back to the my_account by default
if ($redirect)
{
redirect('secure/my_account');
}
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div>', '</div>');
/*
we're going to set this up early.
we can set a redirect on this, if a customer is checking out, they need an account.
this will allow them to register and then complete their checkout, or it will allow them
to register at anytime and by default, redirect them to the homepage.
*/
$data['redirect'] = $this->session->flashdata('redirect');
$data['page_title'] = lang('account_registration');
$data['gift_cards_enabled'] = $this->gift_cards_enabled;
//default values are empty if the customer is new
$data['company'] = '';
$data['firstname'] = '';
$data['lastname'] = '';
$data['email'] = '';
$data['phone'] = '';
$data['address1'] = '';
$data['address2'] = '';
$data['city'] = '';
$data['state'] = '';
$data['zip'] = '';
$this->form_validation->set_rules('company', 'Company', 'trim|max_length[128]');
$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|max_length[32]');
$this->form_validation->set_rules('lastname', 'Last Name', 'trim|required|max_length[32]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|max_length[128]|callback_check_email');
$this->form_validation->set_rules('phone', 'Phone', 'trim|required|max_length[32]');
$this->form_validation->set_rules('password', '<PASSWORD>', '<PASSWORD>');
$this->form_validation->set_rules('confirm', 'Confirm Password', 'required|matches[password]');
$this->form_validation->set_rules('email_subscribe', 'Subscribe', 'trim|numeric|max_length[1]');
if ($this->form_validation->run() == FALSE)
{
//if they have submitted the form already and it has returned with errors, reset the redirect
if ($this->input->post('submitted'))
{
$data['redirect'] = $this->input->post('redirect');
}
// load other page content
//$this->load->model('banner_model');
$this->load->helper('directory');
$data['categories'] = $this->Category_model->get_categories_tierd(0);
$data['error'] = validation_errors();
$this->common_model->setMessage(3,$data['error']);
$this->load->view('register', $data);
}
else
{
$save['id'] = false;
$save['firstname'] = $this->input->post('firstname');
$save['lastname'] = $this->input->post('lastname');
$save['email'] = $this->input->post('email');
$save['phone'] = $this->input->post('phone');
$save['company'] = $this->input->post('company');
$save['active'] = $this->config->item('new_customer_status');
$save['email_subscribe'] = intval((bool)$this->input->post('email_subscribe'));
$save['password'] = $<PASSWORD>('<PASSWORD>');
$redirect = $this->input->post('redirect');
//if we don't have a value for redirect
if ($redirect == '')
{
$redirect = 'myaccount';
}
// save the customer info and get their new id
$id = $this->Customer_model->save($save);
/* send an email */
// get the email template
$res = $this->db->where('id', '1')->get('canned_messages');
$row = $res->row_array();
// set replacement values for subject & body
// {customer_name}
$row['subject'] = str_replace('{customer_name}', $this->input->post('firstname').' '. $this->input->post('lastname'), $row['subject']);
$row['content'] = str_replace('{customer_name}', $this->input->post('firstname').' '. $this->input->post('lastname'), $row['content']);
// {url}
$row['subject'] = str_replace('{url}', $this->config->item('base_url'), $row['subject']);
$row['content'] = str_replace('{url}', $this->config->item('base_url'), $row['content']);
// {site_name}
$row['subject'] = str_replace('{site_name}', $this->config->item('company_name'), $row['subject']);
$row['content'] = str_replace('{site_name}', $this->config->item('company_name'), $row['content']);
$this->load->library('email');
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->from($this->config->item('email'), $this->config->item('company_name'));
$this->email->to($save['email']);
$this->email->bcc($this->config->item('email'));
$this->email->subject($row['subject']);
$this->email->message(html_entity_decode($row['content']));
$this->email->send();
$this->session->set_flashdata('message', sprintf( lang('registration_thanks'), $this->input->post('firstname') ) );
$this->common_model->setMessage(1,"Thanks for registering ".$this->input->post('firstname'));
//lets automatically log them in
$this->Customer_model->login($save['email'], $this->input->post('confirm'));
//we're just going to make this secure regardless, because we don't know if they are
//wanting to redirect to an insecure location, if it needs to be secured then we can use the secure redirect in the controller
//to redirect them, if there is no redirect, the it should redirect to the homepage.
redirect($redirect);
}
}
function check_email($str)
{
if(!empty($this->customer['id']))
{
$email = $this->Customer_model->check_email($str, $this->customer['id']);
}
else
{
$email = $this->Customer_model->check_email($str);
}
if ($email)
{
$this->form_validation->set_message('check_email', lang('error_email'));
return FALSE;
}
else
{
return TRUE;
}
}
function forgot_password()
{
$data['page_title'] = lang('forgot_password');
$data['gift_cards_enabled'] = $this->gift_cards_enabled;
$submitted = $this->input->post('submitted');
if ($submitted)
{
$this->load->helper('string');
$email = $this->input->post('email');
$reset = $this->Customer_model->reset_password($email);
if ($reset)
{
$this->common_model->setMessage(1,'Your New Password has been send to registered email id');
}
else
{
$this->common_model->setMessage(2,'You are not registered with us');
}
redirect('secure/forgot_password');
}
// load other page content
//$this->load->model('banner_model');
$this->load->helper('directory');
//if they want to limit to the top 5 banners and use the enable/disable on dates, add true to the get_banners function
//$data['banners'] = $this->banner_model->get_banners();
//$data['ads'] = $this->banner_model->get_banners(true);
$data['categories'] = $this->Category_model->get_categories_tierd();
$this->load->view('forgot_password', $data);
}
function my_downloads($code=false)
{
if($code!==false)
{
$data['downloads'] = $this->Digital_Product_model->get_downloads_by_code($code);
} else {
$this->Customer_model->is_logged_in();
$customer = $this->go_cart->customer();
$data['downloads'] = $this->Digital_Product_model->get_user_downloads($customer['id']);
}
$data['gift_cards_enabled'] = $this->gift_cards_enabled;
$data['page_title'] = lang('my_downloads');
$this->load->view('my_downloads', $data);
}
function download($link)
{
$filedata = $this->Digital_Product_model->get_file_info_by_link($link);
// missing file (bad link)
if(!$filedata)
{
show_404();
}
// validate download counter
if(intval($filedata->downloads) >= intval($filedata->max_downloads))
{
show_404();
}
// increment downloads counter
$this->Digital_Product_model->touch_download($link);
// Deliver file
$this->load->helper('download');
force_download('uploads/digital_uploads/', $filedata->filename);
}
function set_default_address()
{
$id = $this->input->post('id');
$type = $this->input->post('type');
$customer = $this->go_cart->customer();
$save['id'] = $customer['id'];
if($type=='bill')
{
$save['default_billing_address'] = $id;
$customer['bill_address'] = $this->Customer_model->get_address($id);
$customer['default_billing_address'] = $id;
} else {
$save['default_shipping_address'] = $id;
$customer['ship_address'] = $this->Customer_model->get_address($id);
$customer['default_shipping_address'] = $id;
}
//update customer db record
$this->Customer_model->save($save);
//update customer session info
$this->go_cart->save_customer($customer);
echo "1";
}
// this is a form partial for the checkout page
function checkout_address_manager()
{
$customer = $this->go_cart->customer();
$data['customer_addresses'] = $this->Customer_model->get_address_list($customer['id']);
$this->load->view('address_manager', $data);
}
// this is a partial partial, to refresh the address manager
function address_manager_list_contents()
{
$customer = $this->go_cart->customer();
$data['customer_addresses'] = $this->Customer_model->get_address_list($customer['id']);
$this->load->view('address_manager_list_content', $data);
}
// function add by Rameshwar
function add_item($id = false, $duplicate = false){
$this->Customer_model->is_logged_in('secure/add_item/');
$this->load->model('Product_model');
$this->load->helper('form');
$this->lang->load('product');
$this->product_id = $id;
$this->load->library('form_validation');
$this->load->model(array('Option_model', 'Category_model', 'Digital_Product_model'));
//$this->lang->load('digital_product');
// $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$customer = $this->go_cart->customer();
$data['page_title'] = lang('product_form');
$data['file_list'] = $this->Digital_Product_model->get_list();
//default values are empty if the product is new
$data['id'] = '';
$data['sku'] = '';
$data['name'] = '';
$data['slug'] = '';
$data['description'] = '';
$data['excerpt'] = '';
$data['price'] = '';
$data['saleprice'] = '';
$data['weight'] = '';
$data['track_stock'] = '';
$data['seo_title'] = '';
$data['meta'] = '';
$data['shippable'] = '';
$data['taxable'] = '';
$data['fixed_quantity'] = '';
$data['quantity'] = '';
$data['enabled'] = '';
$data['condition'] = '';
$data['company_id'] ='';
$data['related_products'] = array();
$data['product_categories'] = array();
$data['images'] = array();
$data['product_files'] = array();
//create the photos array for later use
$data['photos'] = array();
///////////////////////////////////////////////////////////////////////////////////////
$data['category_list'] = $this->Category_model->get_categories();
$data['company_list'] = $this->Product_model->get_company_list();
if ($id)
{
// get the existing file associations and create a format we can read from the form to set the checkboxes
//$pr_files = $this->Digital_Product_model->get_associations_by_product($id);
//foreach($pr_files as $f)
// {
// $data['product_files'][] = $f->file_id;
// }
// get product & options data
$data['product_options'] = $this->Option_model->get_product_options($id);
$product = $this->Product_model->get_product($id);
//if the product does not exist, redirect them to the product list with an error
if (!$product)
{
//$this->session->set_flashdata('error', lang('error_not_found'));
$this->common_model->setMessage(3,lang('error_not_found'));
redirect('/myaccount/list_item');
}
//helps us with the slug generation
//$this->product_name = $this->input->post('slug', $product->slug);
//set values to db values
$data['id'] = $id;
$data['sku'] = $product->sku;
$data['name'] = $product->name;
$data['seo_title'] = $product->seo_title;
$data['meta'] = $product->meta;
$data['slug'] = $product->slug;
$data['description'] = $product->description;
$data['excerpt'] = $product->excerpt;
$data['price'] = $product->price;
$data['saleprice'] = $product->saleprice;
$data['weight'] = $product->weight;
$data['track_stock'] = $product->track_stock;
$data['shippable'] = $product->shippable;
$data['quantity'] = $product->quantity;
$data['taxable'] = $product->taxable;
$data['fixed_quantity'] = $product->fixed_quantity;
$data['enabled'] = $product->enabled;
$data['cat_id'] = $product->cat_id;
$data['sub_category_id'] = $product->sub_category_id;
$data['company_id'] = $product->company_id;
$data['model_id'] = $product->model_id;
$data['condition'] = $product->condition;
$data['sub_category_data'] = $this->ajaxrequest($product->cat_id,'getsubcat',true,$product->sub_category_id);
$data['model_data'] = $this->ajaxrequest($product->company_id,'getmodelcat',true,$product->model_id);
//make sure we haven't submitted the form yet before we pull in the images/related products from the database
if(!$this->input->post('submit'))
{
$data['product_categories'] = $product->categories;
$data['related_products'] = $product->related_products;
$data['images'] = (array)json_decode($product->images);
}
}
//if $data['related_products'] is not an array, make it one.
if(!is_array($data['related_products']))
{
$data['related_products'] = array();
}
if(!is_array($data['product_categories']))
{
$data['product_categories'] = array();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//no error checking on these
//$this->form_validation->set_rules('caption', 'Caption');
//$this->form_validation->set_rules('primary_photo', 'Primary');
//$this->form_validation->set_rules('sku', 'lang:sku', 'trim');
//$this->form_validation->set_rules('seo_title', 'lang:seo_title', 'trim');
//$this->form_validation->set_rules('meta', 'lang:meta_data', 'trim');
$this->form_validation->set_rules('name', 'lang:name', 'trim|required|max_length[64]');
//$this->form_validation->set_rules('slug', 'lang:slug', 'trim');
$this->form_validation->set_rules('description', 'lang:description', 'trim');
//$this->form_validation->set_rules('excerpt', 'lang:excerpt', 'trim');
//$this->form_validation->set_rules('price', 'lang:price', 'trim|numeric|floatval');
//$this->form_validation->set_rules('saleprice', 'lang:saleprice', 'trim|numeric|floatval');
//$this->form_validation->set_rules('weight', 'lang:weight', 'trim|numeric|floatval');
//$this->form_validation->set_rules('track_stock', 'lang:track_stock', 'trim|numeric');
//$this->form_validation->set_rules('quantity', 'lang:quantity', 'trim|numeric');
//$this->form_validation->set_rules('shippable', 'lang:shippable', 'trim|numeric');
//$this->form_validation->set_rules('taxable', 'lang:taxable', 'trim|numeric');
//$this->form_validation->set_rules('fixed_quantity', 'lang:fixed_quantity', 'trim|numeric');
//$this->form_validation->set_rules('enabled', 'lang:enabled', 'trim|numeric');
if($duplicate)
{
$data['id'] = false;
}
if($this->input->post('submit') == 'submit')
{
//reset the product options that were submitted in the post
//$data['product_options'] = $this->input->post('option');
//$data['related_products'] = $this->input->post('related_products');
$data['product_categories'] = $this->input->post('categories');
$data['images'] = $this->input->post('images');
//$data['product_files'] = $this->input->post('downloads');
}
$data['customer'] = $customer;
if ($this->form_validation->run() == FALSE)
{
$this->load->view('add_item', $data);
}
else {
$this->load->helper('text');
//first check the slug field
$slug = $this->input->post('slug');
//if it's empty assign the name field
if(empty($slug) || $slug=='')
{
$slug = $this->input->post('name');
}
$slug = url_title(convert_accented_characters($slug), 'dash', TRUE);
//validate the slug
$this->load->model('Routes_model');
if($id)
{
$slug = $this->Routes_model->validate_slug($slug, $product->route_id);
$route_id = $product->route_id;
}
else
{
$slug = $this->Routes_model->validate_slug($slug);
$route['slug'] = $slug;
$route_id = $this->Routes_model->save($route);
$save['sku'] = $this->randomNumber(16);
$save['taxable'] = 0;
$save['enabled'] = 1;
}
$save['user_id'] = $customer['id'];
$save['id'] = $id;
$save['name'] = $this->input->post('name');
$save['seo_title'] = $this->input->post('seo_title');
$save['meta'] = $this->input->post('meta');
$save['description'] = $this->input->post('description');
$save['excerpt'] = $this->input->post('excerpt');
$save['price'] = $this->input->post('price');
$save['saleprice'] = $this->input->post('saleprice');
$save['weight'] = $this->input->post('weight');
$save['track_stock'] = $this->input->post('track_stock');
$save['fixed_quantity'] = $this->input->post('fixed_quantity');
$save['quantity'] = $this->input->post('quantity');
$save['shippable'] = $this->input->post('shippable');
$save['condition'] = $this->input->post('condition');
$post_images = $this->input->post('images');
$save['slug'] = $slug;
//$save['route_id'] = $route_id;
$save['cat_id'] = $this->input->post('category');
$save['sub_category_id'] = $this->input->post('subcatlist');
// check for exist other insert
if($this->input->post('company_id')=='other'){
$companyNmae = $this->input->post('newcompany');
if($companyNmae!=''){
$save['company_id']= $this->Product_model->get_compnyIdbyname($companyNmae);
}
} else $save['company_id'] = $this->input->post('company_id');
if($this->input->post('modellist')=='other' || $this->input->post('modellist')==''){
$modelNmae = $this->input->post('newmodelname');
$save['model_id']= $this->Product_model->get_modelIdbyname($modelNmae,$save['company_id']);
} else $save['model_id'] = $this->input->post('modellist');
if($save['model_id']==NULL){
$save['model_id'] = 0;
}
$save['images'] = json_encode($post_images);
if($this->input->post('related_products'))
{
$save['related_products'] = json_encode($this->input->post('related_products'));
}
else
{
$save['related_products'] = '';
}
//save categories
$categories = $this->input->post('categories');
if(!$categories)
{
$categories = array();
}
// format options
$options = array();
if($this->input->post('option'))
{
foreach ($this->input->post('option') as $option)
{
$options[] = $option;
}
}
// save product
$product_id = $this->Product_model->save($save, $options, $categories);
// add file associations
// clear existsing
$this->Digital_Product_model->disassociate(false, $product_id);
// save new
//$downloads = $this->input->post('downloads');
// if(is_array($downloads))
// {
// foreach($downloads as $d)
// {
// $this->Digital_Product_model->associate($d, $product_id);
// }
// }
////save the route
$route['id'] = $route_id;
$route['slug'] = $slug;
$route['route'] = 'cart/product/'.$product_id;
$this->Routes_model->save($route);
//
// set message template message
if($id){
$res = $this->db->where('id', '12')->get('canned_messages');
$row = $res->row_array();
// set replacement values for subject & body
// {customer_name}
$row['subject'] = str_replace('{customer_name}', $customer['firstname'].' '. $customer['lastname'], $row['subject']);
$row['content'] = str_replace('{customer_name}', $customer['firstname'].' '. $customer['lastname'], $row['content']);
// {url}
$row['subject'] = str_replace('{url}', $this->config->item('base_url'), $row['subject']);
$row['content'] = str_replace('{url}', $this->config->item('base_url'), $row['content']);
// {site_name}
$row['subject'] = str_replace('{site_name}', $this->config->item('company_name'), $row['subject']);
$row['content'] = str_replace('{site_name}', $this->config->item('company_name'), $row['content']);
$row['content'] = str_replace('{product_name}', "<b>".$product->name."</b>", $row['content']);
$this->load->library('email');
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->from($this->config->item('email'), $this->config->item('company_name'));
$this->email->to($customer['email']);
$this->email->bcc($this->config->item('email'));
$this->email->subject($row['subject']);
$this->email->message(html_entity_decode($row['content']));
$this->email->send();
// send mail to admin for approval notification
$res = $this->db->where('id', '13')->get('canned_messages');
$row = $res->row_array();
// set replacement values for subject & body
// {customer_name}
$row['subject'] = str_replace('{customer_name}', $customer['firstname'].' '. $customer['lastname'], $row['subject']);
$row['content'] = str_replace('{customer_name}', $customer['firstname'].' '. $customer['lastname'], $row['content']);
// {url}
$row['subject'] = str_replace('{url}', $this->config->item('base_url'), $row['subject']);
$row['content'] = str_replace('{url}', $this->config->item('base_url'), $row['content']);
// {site_name}
$row['subject'] = str_replace('{site_name}', $this->config->item('company_name'), $row['subject']);
$row['content'] = str_replace('{site_name}', $this->config->item('company_name'), $row['content']);
$row['content'] = str_replace('{product_name}', "<b>".$product->name."</b>", $row['content']);
$this->load->library('email');
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->from($this->config->item('email'), $this->config->item('company_name'));
$this->email->to($customer['email']);
$this->email->bcc($this->config->item('email'));
$this->email->subject($row['subject']);
$this->email->message(html_entity_decode($row['content']));
$this->email->send();
}
// end template sending
//$this->session->set_flashdata('message', lang('message_saved_product'));
$this->common_model->setMessage(1,lang('message_saved_product'));
//go back to the product list
redirect('/myaccount/list_item');
}
}
public function ajaxrequest($id=false,$type=false, $returnType=false,$subcatid=false){
$this->load->model(array('Option_model', 'Category_model','Product_model'));
$id = ($this->input->post('id')==''?$id:$this->input->post('id'));
$type = ($this->input->post('type')==''? $type:$this->input->post('type'));
if($type=='getsubcat'){
$subcatlist = $this->Category_model->get_categories($id);
$str = null;
if(count($subcatlist)>0){
$str .= "<select name='subcatlist' id='subcatlist' class='text-box'>";
$str .= "<option value=''>Select Sub Category</option>";
foreach($subcatlist as $subcatval):
$str.="<option value=".$subcatval->id."". (($returnType==true && $subcatval->id==$subcatid)?" selected":"").">".$subcatval->name."</option>";
endforeach;
$str .= "</select>";
}
if($str!=null){
if($returnType==false){echo $str;} else {return $str;}
}
}
if($type=='getmodelcat'){
$subcatlist = $this->Product_model->get_model_list($id);
$str = null;
if(count($subcatlist)>0){
$str = '<div class="styled-select"><select name="modellist" id="modelid" class="text-box" onChange="addNewModel(this.value)">';
foreach($subcatlist as $subcatval):
$str.="<option value=".$subcatval->model_id."". (($returnType==true && $subcatval->model_id==$subcatid)?" selected":"").">".$subcatval->model_name."</option>";
endforeach;
$str.= "<option value='other'>Other</option>";
$str.= "</select></div>";
}
if($str!=null){
if($returnType==false){echo $str;} else {return $str;} ;
} else {
$str = '<input type="text" name="newmodelname" id="newmodelname" class="text-box" placeholder="Enter Model">';
if($returnType==false){echo $str;} else {return $str;};
}
}
}
// end
public function list_item($order_by="name", $sort_order="ASC", $code=0, $page=0, $rows=15){
$this->load->model('Product_model');
$this->load->helper('form');
$this->lang->load('product');
$data['page_title'] = lang('products');
$data['code'] = $code;
$term = false;
$category_id = false;
//get the category list for the drop menu
$data['categories'] = $this->Category_model->get_categories_tierd();
//$post = $this->input->post(null, false);
$customer = $this->go_cart->customer();
$post = array('user_id'=>$customer['id']);
$this->load->model('Search_model');
if($post)
{
$term = json_encode($post);
$code = $this->Search_model->record_term($term);
}
//store the search term
$data['term'] = $term;
$data['order_by'] = $order_by;
$data['sort_order'] = $sort_order;
$data['products'] = $this->Product_model->get_my_products(array('term'=>$term, 'order_by'=>$order_by, 'sort_order'=>$sort_order, 'rows'=>$rows, 'page'=>$page));
//total number of products
$data['total'] = $this->Product_model->get_my_products(array('term'=>$term, 'order_by'=>$order_by, 'sort_order'=>$sort_order), true);
$this->load->library('pagination');
$config['base_url'] = site_url($this->config->item('admin_folder').'/products/index/'.$order_by.'/'.$sort_order.'/'.$code.'/');
$config['total_rows'] = $data['total'];
$config['per_page'] = $rows;
$config['uri_segment'] = 7;
$config['first_link'] = 'First';
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['last_link'] = 'Last';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['full_tag_open'] = '<div class="pagination"><ul>';
$config['full_tag_close'] = '</ul></div>';
$config['cur_tag_open'] = '<li class="active"><a href="#">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['prev_link'] = '«';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
$config['next_link'] = '»';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$this->pagination->initialize($config);
$this->load->view('list_item', $data);
}
function thanks()
{
echo "Product Has been saved successfully";
echo "<br>This page is under cunstruction";
echo "<br><a href='".base_url()."secure/sale'>Go to Sale Page</a>";
}
public function remove_item($product_id = NULL){
if(empty($product_id)){
$this->common_model->setMessage(3,'Item not exist');
}
$customer = $this->go_cart->customer();
$product = $this->Product_model->get_user_product($product_id,$customer['id']);
if($product==false){
$this->common_model->setMessage(3,'Item not exist');
} else{
$this->Product_model->delete_product($product_id);
$this->common_model->setMessage(1, 'Listed Item sucessfully deleted');
}
redirect('/myaccount/list_item');
}
public function randomNumber($length) {
$result = '';
for($i = 0; $i < $length; $i++) {
$result .= mt_rand(0, 9);
}
return $result;
}
public function get_model_list(){
$id = ($this->input->post('id')==''?$id:$this->input->post('id'));
if($id!=''){
$subcatlist = $this->Product_model->get_model_list($id);
$str = null;
if(count($subcatlist)>0){
$str = '<select name="modelid" id="modelid"><option value="">Select model</option>';
foreach($subcatlist as $subcatval):
$str.="<option value=".$subcatval->model_id.">".$subcatval->model_name."</option>";
endforeach;
$str.= "</select>";
echo $str;
}
}
}
public function open(){
echo "<b>Hello</b>";
}
}<file_sep><?php include('header.php'); ?>
<div class="container mar-top">
<div class="row">
<?php include('left.php'); ?>
<!-- span4 -->
<?php //include('catalog_mid.php') ?>
<?php $this->load->view($file); ?>
<!-- .span8 -->
</div>
<div style="text-align: center"><?php //echo $this->pagination->create_links();?></div>
<!-- row -->
<?php include('feature.php'); ?>
<!-- .row -->
</div> <!-- /container -->
<script type="text/javascript">
window.onload = function(){
$('.product').equalHeights();
}
</script>
<?php include('footer.php'); ?>
<file_sep><?php include('header.php'); ?>
<div class="container mar-top">
<a href="<?php echo site_url($menu['category_info']->slug);?>"><?php echo $menu['category_info']->name; ?></a>
<?php if(isset($menu['sub_category_info'])){
?>
>> <a href="<?php echo site_url($menu['sub_category_info']->slug);?>"><?php echo $menu['sub_category_info']->name; ?></a>
<?php } ?>
>> <a style="cursor:default; text-decoration:none"><?php echo $product->name;?></a>
<!-- popup code !-->
<div class="span5">
<div class="row primary-img tx-cntr">
<div id="primary-img" class="span5 sidebar ">
<?php
if(!isset($product->images[0]) || $product->images[0]==''){
$photo = '<img src="'.get_img('gocart/themes/default/assets/img/siteimg/no_picture.png').'" alt="'.$product->seo_title.'"/>' ;
} else {
$photo = '<img class="responsiveImage" src="'.base_url('uploads/images/medium/'.$product->images[0]).'" alt="'.$product->seo_title.'"/>';
}
echo $photo;
?>
</div>
</div>
<div class="row">
<div class="span5 product-images sidebar">
<?php
if(count($product->images) > 1):?>
<div class="row">
<div class="span4 product-images">
<?php foreach($product->images as $image):?>
<img class="span1" onclick="$(this).squard('390', $('#primary-img'));" src="<?php echo base_url('uploads/images/medium/'.$image);?>"/>
<?php endforeach;?>
</div>
</div>
<?php else: ?>
<div class="row">
<div class="span4 product-images">
<img class="span1" onclick="$(this).squard('390', $('#primary-img'));" src="<?php echo get_img('gocart/themes/default/assets/img/siteimg/no_picture.png'); ?>"/>
</div>
</div>
<?php endif;?>
</div>
</div>
</div>
<!-- end !-->
<div class="span18">
<div class="page-header mar-topn">
<h3 style="font-weight:normal"><?php echo $this->common_model->word_crop($product->name,'20','..');?></h3>
<div class="row">
<div class="fl">
Code: <span class="red12"><?php echo $product->sku;?></span>
</div>
</div>
</div>
<div class="page-header mar-topn pad-bot">
<div class="row">
<div class="fl blk18">Price: <span class="red18"><?php echo format_currency($product->price); ?></span></div>
<?php if($product->free_shipping==0){ ?><div class="fr"> Free Shipping! </div> <?php } ?>
</div>
</div>
<div class="row">
<h4>Product Information:</h4>
<p><?php echo $product->description; ?></p>
</div>
<div class="product-cart-form">
<?php echo form_open('cart/add_to_cart', 'class="form-horizontal"');?>
<input type="hidden" name="cartkey" value="<?php echo $this->session->flashdata('cartkey');?>" />
<input type="hidden" name="id" value="<?php echo $product->id?>"/>
<fieldset>
<?php if(count($options) > 0): ?>
<?php foreach($options as $option):
$required = '';
if($option->required)
{
$required = ' <p class="help-block">Required</p>';
}
?>
<div class="control-group">
<label class="control-label"><?php echo $option->name;?></label>
<?php
/*
this is where we generate the options and either use default values, or previously posted variables
that we either returned for errors, or in some other releases of Go Cart the user may be editing
and entry in their cart.
*/
//if we're dealing with a textfield or text area, grab the option value and store it in value
if($option->type == 'checklist')
{
$value = array();
if($posted_options && isset($posted_options[$option->id]))
{
$value = $posted_options[$option->id];
}
}
else
{
if(isset($option->values[0]))
{
$value = $option->values[0]->value;
if($posted_options && isset($posted_options[$option->id]))
{
$value = $posted_options[$option->id];
}
}
else
{
$value = false;
}
}
if($option->type == 'textfield'):?>
<div class="controls">
<input type="text" name="option[<?php echo $option->id;?>]" value="<?php echo $value;?>" class="span4"/>
<?php echo $required;?>
</div>
<?php elseif($option->type == 'textarea'):?>
<div class="controls">
<textarea class="span4" name="option[<?php echo $option->id;?>]"><?php echo $value;?></textarea>
<?php echo $required;?>
</div>
<?php elseif($option->type == 'droplist'):?>
<div class="controls">
<select name="option[<?php echo $option->id;?>]">
<option value=""><?php echo lang('choose_option');?></option>
<?php foreach ($option->values as $values):
$selected = '';
if($value == $values->id)
{
$selected = ' selected="selected"';
}?>
<option<?php echo $selected;?> value="<?php echo $values->id;?>">
<?php echo($values->price != 0)?'('.format_currency($values->price).') ':''; echo $values->name;?>
</option>
<?php endforeach;?>
</select>
<?php echo $required;?>
</div>
<?php elseif($option->type == 'radiolist'):?>
<div class="controls">
<?php foreach ($option->values as $values):
$checked = '';
if($value == $values->id)
{
$checked = ' checked="checked"';
}?>
<label class="radio">
<input<?php echo $checked;?> type="radio" name="option[<?php echo $option->id;?>]" value="<?php echo $values->id;?>"/>
<?php echo $option->name;?> <?php echo($values->price != 0)?'('.format_currency($values->price).') ':''; echo $values->name;?>
</label>
<?php endforeach;?>
<?php echo $required;?>
</div>
<?php elseif($option->type == 'checklist'):?>
<div class="controls">
<?php foreach ($option->values as $values):
$checked = '';
if(in_array($values->id, $value))
{
$checked = ' checked="checked"';
}?>
<label class="checkbox">
<input<?php echo $checked;?> type="checkbox" name="option[<?php echo $option->id;?>][]" value="<?php echo $values->id;?>"/>
<?php echo($values->price != 0)?'('.format_currency($values->price).') ':''; echo $values->name;?>
</label>
<?php endforeach; ?>
</div>
<?php echo $required;?>
<?php endif;?>
</div>
<?php endforeach;?>
<?php endif;?>
<div class="control-group">
<label class="control-label"><?php echo lang('quantity') ?></label>
<div class="controls">
<?php if(!config_item('inventory_enabled') || config_item('allow_os_purchase') || !(bool)$product->track_stock || $product->quantity > 0) : ?>
<?php if(!$product->fixed_quantity) : ?>
<input class="span2" type="text" name="quantity" value=""/>
<?php endif; ?>
<button class="btn btn-primary btn-large" type="submit" value="submit"><i class="icon-shopping-cart icon-white"></i> <?php echo lang('form_add_to_cart');?></button>
<?php endif;?>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<div class="container mar-top">
<div class="span5">
<div class="widget_box">
<div class="widget_title1">Questions</div>
<div class="widget_body1">
<div class="controls">
<div style="display:none"; id="showmsg"></div>
<textarea name="faq_box" id="faq_box" class="spanqp"></textarea>
<button class="btn btn-primary btn-large pull-right" id="faq_btn">Ask this seller A Question</button>
</div>
<!-- code for review and retting -->
<?php if(empty($feedback)){ ?>
<div style="display:none"; id="feedback_showmsg"></div>
<div id="feedback_cont">
<textarea name="feedback_box" id="feedback_box" class="span2 cart-inp1"></textarea>
<select name="reting" id="reting">
<option value="">Select reting</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<button class="btn btn-primary btn-large pull-right" id="feedback_btn">Send Feedback & reting</button>
</div>
<?php } else { ?>
reting : <?php echo $feedback->rate ?>
review : <?php echo $feedback->feedback; ?>
<?php } ?>
<!--=================Show feedback histry -->
<?php foreach($feedbacklist as $feedback){ ?>
<?php echo " Feedback : ".$feedback->feedback."<br>"; ?>
<?php } ?>
<!-- !-->
<!-- end -->
</div>
</div>
</div><div class="span18">
<div class="widget_box">
<div class="widget_title1">Seller Rating</div>
<div class="widget_body1">
<div class="row">
<div class="fl"><strong>Seller:</strong> <?php echo $product->firstname; ?></div>
<div class="fr"><strong>Ratings:</strong> 5</div>
</div>
<div class="row">
<div class="fl"><strong>Avg. Ship:</strong> 87.5 Hours</div>
</div>
<div class="row">
<div class="fl"><a href="#">Seller Statistics</a> <span> | </span> <a href="#">Seller Reviews</a> <span> | </span> <a href="<?php echo base_url('seller/seller_listed_items/'.$product->user_id); ?>">Seller's Other Items</a></div>
</div>
</div>
</div>
</div>
</div>
<div class="container mar-top">
<div class="span10 sidebar">
<div class="widget_title2">Similar Product</div>
<div class="widget_body2">
<div class="row">
<?php if(isset($similar_product) && count($similar_product>0)){
foreach($similar_product as $sproduct){
?>
<div class="span17 margin-right">
<div class="shop_box">
<div class="title">RECENTLY LISTED</div>
<img alt="" src="images/jacket.png">
<div class="sub-title"><?php echo $sproduct->name; ?></div>
<div class="info">
<span class="size">K2</span>
<span class="size_cm">Size: 160cm</span>
<span class="condition">Condition: Excellent</span>
<span class="discount">64% off of Retail</span>
</div>
<div class="price">$<?php echo $sproduct->sort_price;?></div>
</div>
</div>
<?php }
} ?>
</div></div>
</div>
</div>
<script language="javascript">
$('#faq_btn').click(function(){
var faq = $('#faq_box').val().trim();
var product_id = '<?php echo $product->id?>';
$.post("<?php echo site_url('myaccount/save_faq');?>", { faq: faq, product_id:product_id},
function(data,status) {
if(data==1){
$('#showmsg').html('Your question has been sent to seller, They will tuch very soon.').show();
} else{
$('#showmsg').html('Opps ! try again to ask question.').show();
}
});
});
$('#feedback_btn').click(function(){
var feedback_val = $('#feedback_box').val().trim();
var product_id = '<?php echo $product->id?>';
var reting = $('#reting').val().trim();
var haserror = false
if(feedback_val==''){
$('#feedback_showmsg').html('Enter feedback').show();
haserror = true;
}
if(reting==''){
$('#feedback_showmsg').html('Select reting').show();
haserror = true;
}
if(haserror==false){
var st = window.confirm('Are you sure want to submit feedback');
if(st==true){
$.post("<?php echo site_url('myaccount/save_feedback');?>", { feedback_msg: feedback_val, product_id:product_id, reting:reting},
function(data) {
var respose = JSON.parse(data);
if(respose.status==1){
$('#feedback_cont').hide();
$('#feedback_showmsg').html(respose.message).show();
} else{
$('#feedback_showmsg').html(respose.message).show();
}
});
}
}
});
</script>
<?php include('footer.php'); ?> | ce67d770fdc18afbd0c70c7e95b816f735806370 | [
"Hack",
"JavaScript",
"CSS",
"PHP"
] | 28 | Hack | garunmishra/swapmoto | b853a6b35083012960eb1626bed921be013fc5c7 | cd00ed07ffe97255cc27d8131620b8d3424d8834 |
refs/heads/master | <file_sep>import React from "react";
import InventoryList from "./InventoryList";
import RecipeIncrementer from "./RecipeIncrementer";
const RecipeModal = (props) => {
const isModalOpen = props.isModalOpen;
function close(e) {
e.preventDefault();
if (props.onClose) {
props.closeModal();
}
}
return (
<div>
{
isModalOpen ? (
<div className="modal-container">
<div className="modal-backDrop" onClick={ props.closeModal }></div>
<div className="modal">
<button className="modal-close" onClick={ props.closeModal }>X</button>
<header className="modal-header">
<h2>Ingredient List</h2>
</header>
<div className="modal-inner">
<div className="ingredientList">
{
props.ingredientList.map((item) => {
return (
<RecipeIncrementer key={`recipe-${item._id}`}
recipeIngredients={ props.recipeIngredients }
item={item}
removeIngredient={ props.removeIngredient }
addIngredient={ props.addIngredient }
incrementPortion={ props.incrementPortion }
decrementPortion={ props.decrementPortion }
/>
)
})
}
</div>
</div>
</div>
</div>
) : ( null )
}
</div>
)
}
export default RecipeModal;<file_sep>const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const RecipeIngredient = new mongoose.Schema({
ingredient: {
type: mongoose.Schema.Types.ObjectId,
ref: "Ingredient",
required: true,
},
portionSize: {
type: Number,
required: true
}
})
const RecipeSchema = new mongoose.Schema({
name: String,
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
ingredients: [RecipeIngredient]
});
RecipeSchema.index({
user: 1
});
module.exports = mongoose.model("Recipe", RecipeSchema);
<file_sep>import React from "react";
import { Route, Redirect, Link } from "react-router-dom";
import AddFoodForm from "../components/AddFoodForm";
import InventoryList from "../components/InventoryList";
import FilterBar from "../components/FilterBar";
// 👉 NOT IN USE YET
const AddIngredientRoute = (props) => {
return (
<Route { ...props } render={ () => (
props.isLoggedIn ? (
<div>
{/* ADD TYPEAHEAD */}
<Link className="addFormLink" to="/inventory/addfood">Add Foods</Link>
{/* <AddFoodForm fetchFoods={ props.fetchFoods }
fetchIngredients={ props.fetchIngredients }
/> */}
<InventoryList inventory={ props.inventory } deleteFood ={ props.deleteFood } fetchFoods={ props.fetchFoods } fetchIngredients={ props.fetchIngredients }/>
</div>
) : (
<Redirect to={{ pathname: '/login' }} />
)
)}
/>
)
}
export default AddIngredientRoute;<file_sep>const moment = require("moment");
// DON'T USE!!
const mongoose = require('mongoose');
const Ingredient = require('./models/IngredientModel');
const FoodItem = require('./models/FoodItemModel');
mongoose.connect('mongodb://localhost/meal-planner');
async function removeDocs() {
await Ingredient.remove({}, () => {
console.log('All foods removed');
});
await FoodItem.remove({}, () => {
console.log("All food Items removed");
});
}
const ingredients = {
milk: new Ingredient({ name: "Milk" }),
tomatoes: new Ingredient({ name: "Tomatoes" }),
pasta: new Ingredient({ name: "Pasta" }),
thaiChickenSoup: new Ingredient({ name: "Thai Chicken Soup" }),
sproutedGrainBread: new Ingredient({ name: "Sprouted Grain Bread" }),
orangeJuice: new Ingredient({ name: "OrangeJuice" }),
alfredoSauce: new Ingredient({ name: "Alfredo Sauce" }),
eggs: new Ingredient({ name: "Eggs" }),
mushrooms: new Ingredient({ name: "Mushrooms" }),
parmesean: new Ingredient({ name: "Parmesean Cheese" }),
chocoMuffin: new Ingredient({ name: "Chocolate Coconunt Muffins" }),
bannanas: new Ingredient({ name: "Bannanas" }),
gravy: new Ingredient({ name: "Gravy Mix" }),
onions: new Ingredient({ name: "Onions" }),
beef: new Ingredient({ name: "Ground Beef" }),
peppers: new Ingredient({ name: "Red Peppers" }),
spinach: new Ingredient({ name: "Spinach" })
}
async function populateIngredients() {
await Object.values(ingredients).forEach(i => i.save());
}
const foods = [
{
ingredient: ingredients.tomatoes._id,
quantity: 5,
portions: 2,
expiry: moment.unix(1514773072).format("MMM Do, YYYY")
},
{
ingredient: ingredients.milk._id,
quantity: 1,
portions: 10,
expiry: moment.unix(1514773072).format("MMM Do, YYYY")
},
{
ingredient: ingredients.pasta._id,
quantity: 3,
portions: 6,
expiry: null
},
{
ingredient: ingredients.thaiChickenSoup._id,
quantity: 1,
portions: 1,
expiry: null
},
{
ingredient: ingredients.sproutedGrainBread._id,
quantity: 1,
portions: 12,
expiry: moment.unix(1514773072).format("MMM Do, YYYY")
},
{
ingredient: ingredients.orangeJuice._id,
quantity: 1,
portions: 10,
expiry: moment.unix(1514773072).format("MMM Do, YYYY")
},
{
ingredient: ingredients.chocoMuffin._id,
quantity: 1,
portions: 4,
expiry: moment.unix(1514773072).format("MMM Do, YYYY")
},
{
ingredient: ingredients.parmesean._id,
quantity: 1,
portions: 12,
expiry: moment.unix(1514773072).format("MMM Do, YYYY")
},
{
ingredient: ingredients.gravy._id,
quantity: 1,
portions: 3,
expiry: moment.unix(1514773072).format("MMM Do, YYYY")
},
{
ingredient: ingredients.spinach._id,
quantity: 1,
portions: 8,
expiry: moment.unix(1514773072).format("MMM Do, YYYY")
},
{
ingredient: ingredients.peppers._id,
quantity: 1,
portions: 4,
expiry: moment.unix(1514773072).format("MMM Do, YYYY")
},
{
ingredient: ingredients.tomatoes._id,
quantity: 4,
portions: 1,
expiry: moment.unix(1514773072).format("MMM Do, YYYY")
},
{
ingredient: ingredients.bannanas._id,
expiry: null,
portions: 3,
quantity: 1
},
{
ingredient: ingredients.beef._id,
portions: 2,
quantity: 1,
expiry: moment.unix(1511849221).format("MMM Do, YYYY")
}
]
function populateFoodItems() {
foods.forEach((food) => {
const model = new FoodItem();
Object.assign(model, food);
model.save((err, doc) => {
if (err) {
console.log(err);
}
console.log("foodItem: ", doc);
});
return;
});
}
removeDocs()
.then(()=> populateIngredients())
.then(()=> populateFoodItems())
<file_sep>$dark: #0D1116;
$dark-v2: #354458;
$med-dark: #656c7a;
$background: #E9E0D6;
$light-background: #FBF9F7;
$med-background: #EFEDEB;
$primary: #29ABA4;
$secondary-light: #EB7260;
$secondary: #E43F25;
$tertiary-light: #77C5F7;
$tertiary: #0071BC;
// DATEPICKER COLORS
$datepicker__background-color: #f0f0f0 !default;
$datepicker__border-color: #aeaeae !default;
$datepicker__highlighted-color: #3dcc4a !default;
$datepicker__muted-color: #ccc !default;
$datepicker__selected-color: #77C5F7 !default;
$datepicker__text-color: #000 !default;
$datepicker__header-color: #000 !default;
$datepicker__border-radius: .3rem !default;
$datepicker__day-margin: .166rem !default;
$datepicker__font-size: .8rem !default;
$datepicker__font-family: "Helvetica Neue", Helvetica, Arial, sans-serif !default;
$datepicker__item-size: 1.7rem !default;
$datepicker__margin: .4rem !default;
$datepicker__navigation-size: .45rem !default;
$datepicker__triangle-size: 8px !default;
<file_sep>import React from "react";
import InventoryList from "./InventoryList";
// import IngredientModalList from "./IngredientModalList";
const MealPlanModal = (props) => {
const isModalOpen = props.isModalOpen;
function close(e) {
e.preventDefault();
if (props.onClose) {
props.closeModal();
}
}
function toggleRecipe(recipe) {
const recipeArray = props.recipeArray;
if (recipeArray.includes(recipe)) {
console.log("remove this recipe: ", recipe);
props.removeRecipe(recipe);
} else {
props.addRecipe(recipe);
}
}
function recipeClass(recipe) {
if (props.recipeArray.includes(recipe)) {
return "ingredient ingredient-selected";
}
return "ingredient";
}
return (
<div>
{
isModalOpen ? (
<div className="modal-container">
<div className="paleBackground-wrapper" onClick={props.closeModal}></div>
<div className="modal">
<div className="modal-close" onClick={props.closeModal}>X</div>
<header className="modal-header">
<h2>Recipe List</h2>
</header>
<div className="modal-inner">
<ul className="ingredientList">
{
props.recipes.map((recipe) => {
return (
<li key={`recipe-${recipe._id}`}
onClick={() => toggleRecipe(recipe)}
className={recipeClass(recipe)}>
{recipe.name}
</li>
)
})
}
</ul>
</div>
</div>
</div>
) : (null)
}
</div>
)
}
export default MealPlanModal;<file_sep>const mongoose = require('mongoose');
const Recipe = require('./models/RecipesModel');
mongoose.connect('mongodb://localhost/meal-planner');
const recipes = [
]
// Drop any existing data inside of the movies table
Recipe.remove({}, () => {
console.log('All foods removed');
});
if (recipes) {
recipes.forEach((recipe) => {
const model = new Recipe();
Object.assign(model, recipe);
model.save((err, doc) => {
if (err) {
console.log(err);
}
console.log(doc);
});
return;
});
} else {
console.log("sorry, recipes is an empty array")
}<file_sep>import React from 'react';
import { Router } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import Main from './Main';
const history = createBrowserHistory();
const router = (props) => {
return (
<Router history={history}>
<Main history={history} />
</Router>
)
}
export default router;
<file_sep>const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const IngredientSchema = new mongoose.Schema({
name: {
type: String,
trim: true,
lowercase: true,
required: "Please enter a name for your food items"
}
});
IngredientSchema.index({
name: "text",
});
// ***** expiry and portions will eventually be moved to FoodItem
module.exports = mongoose.model("Ingredient", IngredientSchema);<file_sep>import React, { Component } from "react";
import { Link, NavLink, withRouter } from "react-router-dom";
import HamburgerMenuSVG from "../svgs/burgermenu";
class Header extends Component {
constructor(props) {
super(props)
this.hamburgerToggleMenu = this.hamburgerToggleMenu.bind(this);
this.closeMobileMenu = this.closeMobileMenu.bind(this);
this.renderNavBar = this.renderNavBar.bind(this);
this.state = {
hamburgerOpen: false
}
}
hamburgerToggleMenu(e) {
e.preventDefault();
this.setState({ hamburgerOpen: !this.state.hamburgerOpen });
console.log("menu state", this.state);
}
mobileLogout() {
this.props.logout();
this.closeMobileMenu();
}
closeMobileMenu() {
this.setState({ hamburgerOpen: false });
console.log("close the menu")
}
renderNavBar() {
if (this.props.loggedIn) {
return (
<div>
<Link to="/">
<h2 className="app-logo">Mealer</h2>
</Link>
<div className="navBar-menu_wide">
<ul className="navBar-list">
<li className="navBar-link">
<NavLink to="/inventory" activeClassName="activeLink">Inventory</NavLink>
</li>
<li className="navBar-link">
<NavLink to="/mealplanner" activeClassName="activeLink">Meal Planner</NavLink>
</li>
<li className="navBar-link">
<NavLink to="/recipes" activeClassName="activeLink">Recipes</NavLink>
</li>
</ul>
<ul className="navBar-list navBar-list_right">
<li className="navBar-link">
<span>Welcome, {this.props.currentUser.name}</span>
</li>
<li className="navBar-link">
<a role="button" className="navBar-logout"
onClick={() => this.props.logout(this.props.history)}
>Log Out</a>
</li>
</ul>
</div>
<div className="navBar-menu_mobile">
<div className="hamburgerMenu-icon_wrapper">
<a className="hamburgerMenu-link"
onClick={(e) => this.hamburgerToggleMenu(e)}>
<HamburgerMenuSVG className="hamburgerMenu-icon" />
</a>
</div>
</div>
</div>
)
} else {
return (
<div>
<Link to="/">
<h2 className="app-logo">Mealer</h2>
</Link>
<ul className="navBar-list navBar-list_right">
<li className="navBar-link">
<NavLink className="navBar-login" to="/login">Log In</NavLink>
</li>
<li className="navBar-link">
<NavLink className="navBar-signup" to="/signup">Signup</NavLink>
</li>
</ul>
</div>
)
}
}
render() {
return (
<header className="header">
<nav className="navBar">
{this.renderNavBar()}
<ul className={this.state.hamburgerOpen ? "navBar-list_mobile open" : "navBar-list_mobile"}>
<li className="navBar-link_mobile">
<NavLink to="/inventory" activeClassName="activeLink"
onClick={() => this.closeMobileMenu()}>Inventory</NavLink>
</li>
<li className="navBar-link_mobile">
<NavLink to="/mealplanner" activeClassName="activeLink"
onClick={() => this.closeMobileMenu()}>Meal Planner</NavLink>
</li>
<li className="navBar-link_mobile">
<NavLink to="/recipes" activeClassName="activeLink"
onClick={() => this.closeMobileMenu()}>Recipes</NavLink>
</li>
<li className="navBar-link_mobile">
<NavLink to="/recipes" activeClassName="activeLink"
onClick={() => this.mobileLogout()}>Log Out</NavLink>
</li>
</ul>
</nav>
</header>
)
}
}
export default withRouter(Header);<file_sep>import React, { Component } from "react";
class SignUp extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
email: "",
password: ""
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const newUser = Object.assign({}, this.state);
this.props.signup(newUser);
}
handleChange(e) {
console.log(e.target.value);
this.setState({
[e.target.name]: e.target.value,
});
}
render() {
return (
<div>
<div className="login">
<form className="form" onSubmit={this.handleSubmit}>
<div className="form-row">
<h1>Sign Up</h1>
<label htmlFor="name">User Name:</label>
<input name="name" className="form-input" type="text" required
onChange={this.handleChange} />
<label htmlFor="email">User Email:</label>
<input name="email" className="form-input" type="email" required
onChange={this.handleChange} />
<label htmlFor="password">Password:</label>
<input name="password" className="form-input" type="password" required
onChange={this.handleChange} />
<input className="button button-green" type="submit" value="Submit" />
</div>
</form>
</div>
</div>
)
}
}
export default SignUp<file_sep>const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const FoodItemSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "User"
},
ingredient: {
type: mongoose.Schema.Types.ObjectId,
ref: "Ingredient"
},
expiry: {
type: String,
default: null,
},
quantity: {
type: Number,
default: 1,
required: [true, "Please add a quantity for your food items"]
},
portions: {
type: Number,
default: 1,
required: [true, "Please add portion sizes for your food items" ]
}
});
// Will need to remove indexes before moving to production for performance
FoodItemSchema.index({
expiry: 1,
ingredient: 1,
user: 1
});
// ***** expiry and portions will eventually be moved to FoodItem
module.exports = mongoose.model("FoodItem", FoodItemSchema);<file_sep>import React, { Component } from "react";
class LoginModal extends Component {
constructor(props) {
super(props);
this.state = {
// name: "",
email: "",
password: "",
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const user = Object.assign({}, this.state);
this.props.login(user);
}
handleChange(e) {
console.log(e.target.value);
this.setState({
[e.target.name]: e.target.value,
});
}
render() {
return (
<div className="login">
<form className="form" onSubmit={this.handleSubmit}>
<div className="form-row">
<h1>Log In</h1>
{/* <label htmlFor="name">User Name:</label>
<input name="name" className="loginModal-input" type="text" required
onChange={this.handleChange} /> */}
<label className="form-label" htmlFor="email">User Email:</label>
<input name="email" className="form-input" type="email" required
onChange={this.handleChange} />
<label className="form-label" htmlFor="password">Password:</label>
<input name="password" className="form-input" type="password" required
onChange={this.handleChange} />
<input className="button button-blue" type="submit" value="Submit" />
</div>
</form>
</div>
)
}
}
export default LoginModal;<file_sep>const mongoose = require('mongoose');
const Ingredient = require('./models/IngredientModel');
mongoose.connect('mongodb://localhost/meal-planner');
const foods = [
{
name: "Tomatoes"
},
{
name: "Milk"
},
{
name: "Pasta"
},
{
name: "Thai Chicken Soup"
},
{
name: "Sprouted Grain Bread"
},
{
name: "Orange Juice"
},
{
name: "<NAME>"
},
{
name: "Eggs"
},
{
name: "Mushrooms"
},
{
name: "Parmesan cheese"
},
{
name: "Chocolate Coconut Muffins"
},
{
name: "Bananas"
},
{
name: "gravy mix"
},
{
name: "ground beef"
},
{
name: "red peppers"
},
{
name: "spinach"
}
]
// Drop any existing data inside of the movies table
Ingredient.remove({}, () => {
console.log('All foods removed');
});
foods.forEach((food) => {
const model = new Ingredient();
Object.assign(model, food);
model.save((err, doc) => {
if (err) {
console.log(err);
}
console.log(doc);
});
return;
});<file_sep>import React, { Component } from "react";
import MealPlanModal from "./MealPlanModal";
class MealPlanForm extends Component {
constructor(props) {
super(props)
this.state = {
currentSelectValue: "",
recipeArray: [],
isModalOpen: false
}
this.addBodyClass = this.addBodyClass.bind(this);
this.removeBodyClass = this.removeBodyClass.bind(this);
this.baseState = this.state;
this.resetForm = this.resetForm.bind(this);
this.openModal = this.openModal.bind(this);
this.closeModal = this.closeModal.bind(this);
this.mapRecipes = this.mapRecipes.bind(this);
this.addRecipe = this.addRecipe.bind(this);
this.removeRecipe = this.removeRecipe.bind(this);
this.changeDaySelected = this.changeDaySelected.bind(this);
this.submitMeal = this.submitMeal.bind(this);
}
addBodyClass() {
document.querySelector("#react-container").classList.add("modalOpen");
}
removeBodyClass() {
document.querySelector("#react-container").classList.remove("modalOpen");
}
resetForm() {
this.setState(this.baseState);
}
openModal() {
this.setState({ isModalOpen: true })
}
closeModal() {
this.setState({ isModalOpen: false })
}
mapRecipes() {
// Map over the selected recipes and add them to the form view
return (
this.state.recipeArray.map((recipe) => <li key={`meal-${recipe._id}`}>{recipe.name}</li>)
);
}
addRecipe(recipe) {
// then add the recipe to the corresponding day
const mealPlan = this.state.recipeArray.concat(recipe);
this.setState({ recipeArray: mealPlan });
}
removeRecipe(recipe) {
const recipeArray = this.state.recipeArray;
let newRecipeList = [];
if (recipe) {
newRecipeList = recipeArray.filter(item => {
return item._id !== recipe._id
});
}
this.setState({ recipeArray: newRecipeList });
console.log(newRecipeList);
}
changeDaySelected(e) {
// const prevState = this.state.currentSelectValue;
// console.log(prevState);
const day = e.target.value;
this.setState({ currentSelectValue: e.target.value });
const currentPlan = this.props.mealPlan[day]
// maybe take the "meal plan" props and populate the recipeArray with the corresponding meals from that day that day has meals.
}
// SUBMITS THE MEAL PLAN FOR CERTAIN DAY TO BACKEND
submitMeal(e) {
e.preventDefault();
const day = this.state.currentSelectValue;
const recipeArray = this.state.recipeArray;
if ( day !== "" || recipeArray.length !== 0 ) {
this.props.postMealPlan(day, recipeArray);
this.resetForm();
} // TODO: ensure you handle error to tell user to update fields
}
render() {
return (
<div>
{ this.state.isModalOpen ? this.addBodyClass() : this.removeBodyClass() }
<form className="form" onSubmit={e => this.submitMeal(e)}>
{/* <button className="form-close">X</button> */}
<div className="form-row">
<h2>MealPlanForm</h2>
<select className="form-select" name="day" value={ this.state.currentSelectValue } onChange={ e => this.changeDaySelected(e) }>
<option value="" defaultValue disabled hidden>Choose a day</option>
<option value="monday">Monday</option>
<option value="tuesday">Tuesday</option>
<option value="wednesday">Wednesday</option>
<option value="thursday">Thursday</option>
<option value="friday">Friday</option>
<option value="saturday">Saturday</option>
<option value="sunday">Sunday</option>
</select>
<ul className="recipe-Ingredients">
{this.state.recipeArray ? this.mapRecipes() : null}
</ul>
<MealPlanModal isModalOpen={ this.state.isModalOpen }
closeModal={this.closeModal}
recipes={ this.props.recipes }
recipeArray = { this.state.recipeArray }
addRecipe={ this.addRecipe }
removeRecipe={ this.removeRecipe }
/>
<button className="button button-blue" type="button" onClick={ this.openModal }>Add Recipes</button>
</div>
<div className="form-row">
<button className="button button-green" type="submit">Add to Meal Plan</button>
</div>
</form>
</div>
)
}
}
export default MealPlanForm;
<file_sep>import React, { Component } from "react";
import RecipeModal from "./RecipeModal";
import { AsyncTypeahead } from "react-bootstrap-typeahead";
import { Link } from "react-router-dom";
class AddRecipeFormTypeAhead extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
ingredients: [],
isModalOpen: false,
isLoading: false,
options: []
}
this.searchIngredients = this.searchIngredients.bind(this);
this.addIngredientToState = this.addIngredientToState.bind(this);
this.handleChange = this.handleChange.bind(this);
this.resetForm = this.resetForm.bind(this);
this.openModal = this.openModal.bind(this);
this.closeModal = this.closeModal.bind(this);
this.addIngredient = this.addIngredient.bind(this);
this.removeIngredient = this.removeIngredient.bind(this);
this.incrementPortion = this.incrementPortion.bind(this);
this.decrementPortion = this.decrementPortion.bind(this);
this.mapIngredients = this.mapIngredients.bind(this);
this.packageRecipe = this.packageRecipe.bind(this);
this.postRecipe = this.postRecipe.bind(this);
this.submitRecipe = this.submitRecipe.bind(this);
this.incrementPortion = this.incrementPortion.bind(this);
this.decrementPortion = this.decrementPortion.bind(this);
this.portionCount = this.portionCount.bind(this);
}
searchIngredients(query) {
this.setState({ isLoading: true });
fetch(`/api/search/ingredientList?ingredient=${query}`)
.then(res => res.json())
.then(json => {
this.setState({ options: json, isLoading: false });
// console.log(this.state.options);
})
}
componentDidMount() {
document.querySelector("#react-container").classList.add("modalOpen");
}
componentWillUnmount() {
document.querySelector("#react-container").classList.remove("modalOpen");
}
addIngredientToState(name) {
if (name.length) {
const ingredient = Object.assign({}, name[0]);
ingredient["portionSize"] = 1;
console.log("ingredientWithPortion ", ingredient);
const ingredientsArray = Object.assign([], this.state.ingredients);
ingredientsArray.push(ingredient);
this.setState({ingredients: ingredientsArray});
this.refs.asyncTypeAhead.getInstance().clear();
} else {
return
}
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value,
});
}
resetForm() {
this.setState({
name: "",
ingredients: [],
daysUsed: [],
isModalOpen: false
})
}
openModal(e) {
e.preventDefault();
this.setState({ isModalOpen: true })
}
closeModal() {
this.setState({ isModalOpen: false })
}
addIngredient(ingredient) {
const recipeIngredients = this.state.ingredients;
if (ingredient) {
recipeIngredients.push(ingredient)
}
this.setState({ ingredients: recipeIngredients });
}
removeIngredient(ingredient) {
const ingredients = this.state.ingredients;
let newIngredientList = []
if (ingredient) {
newIngredientList = ingredients.filter(item => {
return item._id !== ingredient._id
});
}
this.setState({ ingredients: newIngredientList });
}
incrementPortion(e, id) {
e.preventDefault();
// check ingredient State for ingredient with id, then add 1 to portionSize
const ingredientArray = this.state.ingredients;
const ingredientList = ingredientArray.map((item) => {
if (item._id === id) {
const updateItem = Object.assign({}, item);
updateItem["portionSize"] += 1;
return updateItem;
}
return item
})
this.setState({ ingredients: ingredientList });
}
decrementPortion(e, id) {
e.preventDefault();
// check ingredient State for ingredient with id, then add 1 to portionSize
const ingredientArray = this.state.ingredients;
const ingredientList = ingredientArray.map((item) => {
if (item._id === id) {
const updateItem = Object.assign({}, item);
updateItem["portionSize"] -= 1;
return updateItem;
}
return item
})
this.setState({ ingredients: ingredientList });
}
portionCount(id) {
const ingredient = this.state.ingredients.filter(e => e._id === id)
const portion = ingredient[0] ? ingredient[0].portionSize : 0
return portion
}
mapIngredients() {
// console.log("AddRecipeForm state: ", this.state.ingredients)
return (
this.state.ingredients.map((item) => {
return (
<div className="ingredient" key={`ingredient-${item._id}`}>
<label htmlFor={`ingredient-${item._id}`}
onClick={() => toggleIngredient(item)}
className="">
{item.name}
</label>
<div className="recipeIncrementer">
{/* <input name={ `ingredient-${item._id}` } type="number" min="0" step="1" /> */}
<button className="recipeIncrementer-button"
onClick={(e) => this.decrementPortion(e, item._id)}
>-</button>
<div className="recipeIncrementer-counter">
{ this.portionCount(item._id) }
</div>
<button className="recipeIncrementer-button"
onClick={(e) => this.incrementPortion(e, item._id)}
>+</button>
</div>
</div>
)
})
);
}
// function used in submitRecipe
packageRecipe(recipe) {
const { name, ingredients } = recipe //this.state
const RecipeModel = {
name: name,
ingredients: ingredients,
}
return RecipeModel;
}
// function used in submitRecipe
postRecipe(model) {
fetch("/api/recipes", {
method: "POST",
credentials: "include",
body: JSON.stringify(model),
headers: {
"Content-type": "application/json",
}
})
// .then(() => this.props.fetchIngredients())
.then(() => this.props.fetchRecipes())
.then(() => this.resetForm())
this.resetForm();
}
submitRecipe(e) {
e.preventDefault();
const recipe = this.state;
const model = this.packageRecipe(recipe);
console.log(model);
this.postRecipe(model);
}
render() {
return (
// Should this be a form?
<form className="form" onSubmit={e => this.submitRecipe(e)}>
<Link role="button" to="/recipes" className="form-close" >X</Link>
<div className="form-row">
<h2>Make a New Recipe</h2>
<label className="form-label" htmlFor="name">Recipe Name: </label>
<input className="form-input" onChange={this.handleChange} name="name" required type="text" placeholder="Enter Recipe Name" value={this.state.name} />
<label className="form-label" htmlFor="ingredient">Add Ingredients</label>
<AsyncTypeahead className="form-input" labelKey={option => `${option.name}`}
inputProps={{ name: "ingredient" }}
placeholder="Enter an ingredients name"
ref="asyncTypeAhead"
bsSize="large"
options={this.state.options}
isLoading={this.state.isLoading}
onSearch={(query) => this.searchIngredients(query)}
onChange={(e) => this.addIngredientToState(e)}
/>
<ul className="recipe-Ingredients">
{this.state.ingredients ? this.mapIngredients().reverse() : null}
</ul>
<button className="button-blue" type="button" onClick={e => this.openModal(e)}>Add Ingredients</button>
</div>
<div className="form-row">
<button className="button-green" type="submit">Finish Recipe</button>
</div>
</form>
)
}
}
export default AddRecipeFormTypeAhead;
<file_sep>import React, { Component } from "react";
import RecipeModal from "./RecipeModal";
class AddRecipeForm extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
ingredients: [],
isModalOpen:false
}
this.handleChange = this.handleChange.bind(this);
this.resetForm = this.resetForm.bind(this);
this.openModal = this.openModal.bind(this);
this.closeModal = this.closeModal.bind(this);
this.addIngredient = this.addIngredient.bind(this);
this.removeIngredient = this.removeIngredient.bind(this);
this.incrementPortion = this.incrementPortion.bind(this);
this.decrementPortion = this.decrementPortion.bind(this);
this.mapIngredients = this.mapIngredients.bind(this);
this.packageRecipe = this.packageRecipe.bind(this);
this.postRecipe = this.postRecipe.bind(this);
this.submitRecipe = this.submitRecipe.bind(this);
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value,
});
}
resetForm() {
this.setState({
name: "",
ingredients: [],
daysUsed: [],
isModalOpen: false
})
}
openModal(e) {
e.preventDefault();
this.setState({ isModalOpen: true })
}
closeModal() {
this.setState({ isModalOpen: false })
}
addIngredient(ingredient) {
const recipeIngredients = this.state.ingredients;
if (ingredient) {
recipeIngredients.push(ingredient)
}
this.setState({ ingredients: recipeIngredients });
}
removeIngredient(ingredient) {
const ingredients = this.state.ingredients;
let newIngredientList = []
if (ingredient) {
newIngredientList = ingredients.filter(item => {
return item._id !== ingredient._id
});
}
this.setState({ ingredients: newIngredientList });
}
incrementPortion(e, id) {
e.preventDefault();
// check ingredient State for ingredient with id, then add 1 to portionSize
const ingredientArray = this.state.ingredients;
const ingredientList = ingredientArray.map((item) => {
if (item._id === id) {
const updateItem = Object.assign({}, item);
updateItem["portionSize"] += 1;
return updateItem;
}
return item
})
this.setState({ ingredients: ingredientList });
}
decrementPortion(e, id) {
e.preventDefault();
// check ingredient State for ingredient with id, then add 1 to portionSize
const ingredientArray = this.state.ingredients;
const ingredientList = ingredientArray.map((item) => {
if (item._id === id) {
const updateItem = Object.assign({}, item);
updateItem["portionSize"] -= 1;
return updateItem;
}
return item
})
this.setState({ ingredients: ingredientList });
}
mapIngredients() {
// console.log("AddRecipeForm state: ", this.state.ingredients)
return (
this.state.ingredients.map((ingredient) => {
return <li key={`ingredient-${ingredient._id}`}>{ingredient.name}</li>
})
);
}
// function used in submitRecipe
packageRecipe(recipe) {
const { name, ingredients } = recipe //this.state
const RecipeModel = {
name: name,
ingredients: ingredients,
}
return RecipeModel;
}
// function used in submitRecipe
postRecipe(model) {
fetch("/api/recipes", {
method: "POST",
credentials: "include",
body: JSON.stringify(model),
headers: {
"Content-type": "application/json",
}
})
// .then(() => this.props.fetchIngredients())
.then(() => this.props.fetchRecipes())
.then(() => this.resetForm())
this.resetForm();
}
submitRecipe(e) {
e.preventDefault();
const recipe = this.state;
const model = this.packageRecipe(recipe);
console.log(model);
this.postRecipe(model);
}
render() {
return (
// Should this be a form?
<form className="form" onSubmit={ e => this.submitRecipe(e) }>
<h2>Recipe Form</h2>
<div className="form-row">
<input className="form-input" onChange={this.handleChange} name="name" required type="text" placeholder="Enter Recipe Name" value={this.state.name} />
<ul className="recipe-Ingredients">
{ this.state.ingredients ? this.mapIngredients() : null }
</ul>
<RecipeModal
isModalOpen={ this.state.isModalOpen }
closeModal={ this.closeModal }
ingredientList={ this.props.ingredientList }
recipeIngredients={ this.state.ingredients }
addIngredient={ this.addIngredient }
removeIngredient={ this.removeIngredient }
incrementPortion={ this.incrementPortion }
decrementPortion={ this.decrementPortion }
/>
<button type="button button-blue" onClick={ e => this.openModal(e) }>Add Ingredients</button>
</div>
<div className="form-row">
<button type="submit">Finish Recipe</button>
</div>
</form>
)
}
}
export default AddRecipeForm;
<file_sep>const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const MealPlanSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "User"
},
monday: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Recipe"
}],
tuesday: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Recipe"
}],
wednesday: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Recipe"
}],
thursday: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Recipe"
}],
friday: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Recipe"
}],
saturday: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Recipe"
}],
sunday: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Recipe"
}]
});
MealPlanSchema.index({
user: 1
})
module.exports = mongoose.model("MealPlan", MealPlanSchema);<file_sep>import React from "react";
import { Route, Redirect } from "react-router-dom";
import AddRecipeFormTypeAhead from "../components/AddRecipeFormTypeAhead";
import RecipeList from "../components/RecipeList";
import { Link } from "react-router-dom";
const AddRecipeFormRoute = (props) => {
return (
<Route { ...props } render={() => (
props.isLoggedIn ? (
<div>
<div className="paleBackground-wrapper">
<AddRecipeFormTypeAhead ingredientList={props.ingredientList}
fetchRecipes={props.fetchRecipes} fetchFoods={props.fetchFoods}
fetchIngredients={props.fetchIngredients}
/>
</div>
<Link disabled className="addFormLink" to="/recipes/addrecipe">Make a New Recipe</Link>
<RecipeList deleteRecipe={props.deleteRecipe} recipes={props.recipes} />
</div>
) : (
<Redirect to={{ pathname: '/login' }} />
)
)}
/>
)
}
export default AddRecipeFormRoute;<file_sep>const express = require("express");
const router = express.Router();
const passport = require("passport");
// controllers
const userController = require("../controllers/userController");
const ingredientController = require("../controllers/ingredientController");
const foodItemController = require("../controllers/foodItemController");
const recipeController = require("../controllers/recipeController");
const mealPlanController = require("../controllers/mealPlanController");
// models
const User = require("../models/UserModel");
// USERS
router.get("/api/getme", userController.checkUser);
router.get('/api/users', (req, res) => {
User.find()
.then((docs) => res.send(docs));
});
router.post("/api/signup",
userController.sanitizeUser,
userController.registerUser,
passport.authenticate("local"),
mealPlanController.newUserMealPlan,
userController.sendUser
);
router.post("/api/login",
passport.authenticate("local"),
userController.sendUser
);
router.get("/api/logout", userController.logoutUser);
// INGREDIENTS LIST
router.get("/api/ingredientList", ingredientController.getIngredients);
router.get("/api/search/ingredientList", ingredientController.searchIngredients);
router.post("/api/ingredientList",
userController.isAuthorized,
ingredientController.postIngredient
);
// INVENTORY
router.get("/api/foods",
userController.isAuthorized,
foodItemController.getFoods
);
router.post("/api/foods/",
userController.isAuthorized,
foodItemController.checkIngredientExist,
foodItemController.checkByExpiry
);
router.delete("/api/foods/:id",
userController.isAuthorized,
foodItemController.deleteFood
);
// RECIPES
router.get("/api/recipes",
userController.isAuthorized,
recipeController.getRecipes
);
router.post("/api/recipes",
userController.isAuthorized,
recipeController.postRecipe
);
router.delete("/api/recipes/:id",
userController.isAuthorized,
recipeController.deleteRecipe
);
// MEAL PLAN
router.get("/api/mealPlan",
userController.isAuthorized,
mealPlanController.getMealPlan
);
router.put("/api/mealPlan/:day",
userController.isAuthorized,
mealPlanController.restoreUnusedFoodItems,
mealPlanController.updateFoodItems,
mealPlanController.updateMealPlan
);
module.exports = router;
<file_sep>import React from "react";
import { Route } from "react-router-dom";
import Login from "../components/Login";
const LoginRoute = (props) => {
return (
<Route { ...props } render={() => (
<div>
<Login login={ props.login }/>
</div>
)}
/>
)
}
export default LoginRoute<file_sep>const mongoose = require('mongoose');
const MealPlan = require('./models/MealPlanModel');
mongoose.connect('mongodb://localhost/meal-planner');
const mealPlans = [
{
user: mongoose.Types.ObjectId,
monday:[],
tuesday: [],
wednesday: [],
thursday:[],
friday:[],
saturday: [],
sunday: []
}
]
// Drop any existing data inside of the movies table
MealPlan.remove({}, () => {
console.log('All foods removed');
});
mealPlans.forEach((plan) => {
const model = new MealPlan();
Object.assign(model, plan);
model.save((err, doc) => {
if (err) {
console.log(err);
}
console.log(doc);
});
return;
});<file_sep>import React, { Component } from "react";
import { Route } from "react-router-dom";
import SignUp from "../components/SignUp";
const SignUpRoute = (props) => {
return (
<Route { ...props } render={() => (
<div>
<SignUp signup={props.signup} />
</div>
)}
/>
)
}
export default SignUpRoute<file_sep>const mongoose = require("mongoose");
const FoodItem = require("../models/FoodItemModel");
const Ingredient = require("../models/IngredientModel");
exports.getFoods = (req, res) => {
const userID = req.user._id;
// If no FoodItems for current user, send 204 status
FoodItem.find({ user: userID }).populate('ingredient').then((docs) => {
res.status(200).send(docs);
})
.catch((err) => {
res.status(400).send(err);
})
}
exports.postFoods = (req, res) => {
// post foodItem once checkIngredientExists middleware determines if Ingredient exists
console.log("postfoods", req.body);
const userID = mongoose.Types.ObjectId(req.user._id);
const foodItem = new FoodItem({
expiry: req.body.expiry,
quantity: req.body.quantity,
portions: req.body.portions,
ingredient: req.body.ingredientID,
user: userID
});
foodItem.save()
.then((doc) => {
res.status(200).send(doc);
})
.catch((err) => {
res.status(500).send(err);
})
}
// Add middleware to check the for an Ingredient name for the FoodItem being posted exists
exports.checkIngredientExist = (req, res, next) => {
const userID = mongoose.Types.ObjectId(req.user._id);
const foodItem = req.body;
const foodItemName = foodItem.name.trim().toLowerCase();
// will create a new ingredient with the name of req.body.name if does not already exist
Ingredient.findOneAndUpdate({
name: foodItemName,
}, {
$setOnInsert: { name: foodItemName }
},
{
upsert: true,
new: true
})
.then(doc => {
console.log("new Ingredient", doc );
req.body.ingredientID = doc._id;
next();
})
.catch(next);
}
// a middleware to check to see if foodItem with expiry already exists, if so update quantity or make new foodItem
exports.checkByExpiry = ( req, res ) => {
const userID = mongoose.Types.ObjectId(req.user._id);
const ingredientID = req.body.ingredientID;
let expiry = req.body.expiry;
if (typeof(expiry) === "string" && expiry.length === 0) { expiry = null; }
FoodItem.findOneAndUpdate({
ingredient: ingredientID,
user: userID,
expiry: expiry
},
{
expiry: req.body.expiry,
portions: req.body.portions,
$inc: { quantity: req.body.quantity },
ingredient: req.body.ingredientID,
user: userID
},
{
upsert: true,
new: true
})
.then((doc) => {
console.log("foodItem: ", doc);
res.status(200).send(doc);
doc.save();
})
.catch((err) => {
res.status(500).send(err);
})
}
exports.deleteFood = (req, res) => {
const foodItemId = req.params.id;
FoodItem.remove({ _id: foodItemId }).then((doc) => {
res.status(200).send(doc);
})
.catch((err) => {
res.status(400).send(err);
})
}<file_sep>import React from "react";
const RecipeListIngredient = (props) => {
return (
<li className="recipeIngredient">
<span className="recipeIngredient-name">{props.ingredient.ingredient.name}</span>
<span className="recipeIngredient-portion">{props.ingredient.portionSize}</span>
</li>
)
}
export default RecipeListIngredient;<file_sep>const mongoose = require("mongoose");
const Recipe = require("../models/RecipesModel");
exports.getRecipes = (req, res) => {
const userID = mongoose.Types.ObjectId(req.user._id);
Recipe.find({user: userID}).populate("ingredients.ingredient").exec().then((docs) => {
res.status(200).send(docs);
})
.catch((err) => {
res.status(400).send(err);
})
}
exports.postRecipe = (req, res) => {
console.log("post recipe: ", req.user);
const user = mongoose.Types.ObjectId(req.user._id);
const name = req.body.name.toLowerCase();
const ingredients = req.body.ingredients;
const formatIngredients = ingredients.map((ingredient) => {
const ingredientModel = {
ingredient: ingredient._id,
portionSize: ingredient.portionSize
}
return ingredientModel
})
const recipeModel = new Recipe();
const recipe = Object.assign(recipeModel, {
user: user,
name: name,
ingredients:formatIngredients
});
// console.log(recipe);
recipe.save()
.then((doc) => {
res.status(200).send(doc);
})
.catch((err) => {
console.log(err);
res.status(500).send(err);
});
}
exports.deleteRecipe = (req, res) => {
const recipeId = req.params.id;
Recipe.remove({ _id: recipeId }).then((doc) => {
res.status(200).send(doc);
})
.catch((err) => {
res.status(400).send(err);
})
}<file_sep>import React from "react";
import InventoryItem from "./InventoryItem";
const InventoryList = (props) => {
// add a onClick handler to Inventory Item
// make a function that checks if has "select" function prop
// then run function onClick
return (
<div className="inventoryList">
{ props.inventory ? (
props.inventory.map((item) => {
return (
<InventoryItem key={item._id} item={item} deleteFood={ props.deleteFood }/>
)
})
) : (
null
)
}
</div>
)
}
export default InventoryList;<file_sep>import React from "react";
import RecipeListIngredient from "./RecipeListIngredient";
const RecipeList = (props) => {
return (
<div className="recipeList">
{
props.recipes.map((recipe, i) => {
return (
<div className="recipe" key={`recipe-${recipe._id}`}>
<div className="recipeItem-header">
<h3>{recipe.name}</h3>
</div>
<ul>
{
recipe.ingredients.map((ingredient, index) => {
return <RecipeListIngredient key={ingredient._id} ingredient={ingredient}/>
})
}
</ul>
<span className="deleteRecipe" role="button" onClick={ () => props.deleteRecipe(recipe._id) }>Delete Recipe</span>
</div>
)
})
}
</div>
)
}
export default RecipeList<file_sep>import React from "react";
import { Route, Redirect } from "react-router-dom";
import MealPlanForm from "../components/MealPlanForm";
import MealPlanList from "../components/MealPlanList";
const MealPlanRoute = (props) => {
return (
<Route { ...props } render={() => (
props.isLoggedIn ? (
<div>
<MealPlanForm mealPlan={props.weekMealPlan}
recipes={props.recipes}
fetchMealPlan={props.fetchMealPlan}
postMealPlan={props.postMealPlan}
/>
<MealPlanList mealPlan={props.weekMealPlan} />
</div>
) : (
<Redirect to={{ pathname: '/login' }} />
)
)}
/>
)
}
export default MealPlanRoute;<file_sep>import React from "react";
import { Route, Redirect, Link } from "react-router-dom";
import AddFoodForm from "../components/AddFoodForm";
import InventoryList from "../components/InventoryList";
import FilterBar from "../components/FilterBar";
// 👉 NOT IN USE YET
const AddIngredientRoute = (props) => {
return (
<Route { ...props } render={() => (
props.isLoggedIn ? (
<div>
<Link disabled className="addFormLink" to="/inventory/addfood">Add Foods</Link>
<div className="paleBackground-wrapper">
<AddFoodForm fetchFoods={ props.fetchFoods }
fetchIngredients={ props.fetchIngredients }
/>
</div>
<InventoryList inventory={props.inventory} deleteFood={props.deleteFood} fetchFoods={props.fetchFoods} fetchIngredients={props.fetchIngredients} />
</div>
) : (
<Redirect to={{ pathname: '/login' }} />
)
)}
/>
)
}
export default AddIngredientRoute;<file_sep>// FORM
a.addFormLink {
position: relative;
color: $secondary;
font-family: 'Lobster', cursive;
letter-spacing: 2px;
padding-left: 50px;
font-size: 26px;
margin-top: 15px;
display: block;
&::before {
content: "";
position: absolute;
background: url("/add.svg");
background-size: contain;
background-repeat: no-repeat;
height: 30px;
width: 30px;
left: 15px;
top: 50%;
transform: translateY(-50%);
}
}
form.form h1,
form.form h2 {
margin-top: 0px;
}
form.form {
max-width: 375px;
background-color: $light-background;
margin: 20px auto;
padding: 30px 20px;
box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 1px 6px rgba(0, 0, 0, 0.23);
border-radius: 2px;
position: relative;
.form-close {
border: none;
cursor: pointer;
background-color: transparent;
color: $secondary;
position: absolute;
right: 10px;
top: 15px;
}
.form-label {
padding-left: 0px;
}
.form-select {
padding: 10px 15px;
border: 1px solid $dark;
-webkit-appearance: none;
min-width: 250px;
border-radius: 0px;
}
.form-input {
width: 100%;
display: block;
margin: 5px 0px 10px;
padding: 5px;
border: 1px solid $dark;
background-color: $light-background;
}
}<file_sep>.header, .footer {
background-color: $dark;
color: white;
position: relative;
&:before {
background-color: $dark;
position: absolute;
content: "";
height: 100%;
width: 100%;
top: 0px;
right: 100%;
}
&:after {
background-color: $dark;
position: absolute;
content: "";
height: 100%;
width: 100%;
top: 0px;
left: 100%;
}
div.navBar-menu_wide {
display: inline-block;
@include sm {
display: none;
}
}
div.navBar-menu_mobile {
display: none;
@include sm {
display: block
}
}
div.navBar-menu_mobile {
position: absolute;
right: 5px;
top: 0px;
margin: 20px 0;
a {
display: block;
cursor: pointer;
border: none;
background-color: transparent;
padding: 7px 0px;
}
svg.hamburgerMenu-icon {
height: 24px;
width: 24px;
fill: $light-background;
}
}
ul.navBar-list_mobile {
// display: none;
&.open {
@include sm {
// display: block;
visibility: visible;
opacity: 1;
z-index: 5;
transform: translateY(0%);
transition-delay: 0s, 0s, 0.3s;
}
}
}
ul.navBar-list_mobile {
padding-left: 0px;
// position: absolute;
z-index: 5;
position: absolute;
top: 100%;
left: 0;
width: 100%;
margin: 0px;
background: $med-dark;
visibility: hidden;
opacity: 0;
width: 100%;
// transform: translateY(-2em);
// z-index: -1;
transition: all 0.3s ease-in-out 0s,
visibility 0s linear 0.3s,
z-index 0s linear 0.01s;
}
li.navBar-link_mobile {
color: $light-background;
padding: 0px 0px;
text-align: center;
border-top: 1px solid $background;
a {
display: inline-block;
width: 100%;
padding: 10px 10px;
&.activeLink {
color: $tertiary-light;
}
&:active {
color: $tertiary-light;
background-color: $med-background;
}
}
}
ul.navBar-list {
display: inline-block;
}
ul.navBar-list_right {
position: absolute;
right: 0px;
bottom: 0px;
}
li.navBar-link {
display: inline-block;
padding: 10px 20px;
a {
padding: 5px 10px;
border: 1px solid $dark;
&:hover {
border: 1px solid $primary;
}
}
a.activeLink {
color: $light-background;
background-color: $primary;
border: 1px solid $primary;
}
a.navBar-login {
color: $light-background;
border: 1px solid $tertiary-light;
}
a.navBar-signup {
color: $light-background;
border: 1px solid $primary;
}
a.navBar-logout {
color: $light-background;
border: 1px solid $secondary-light;
}
}
}<file_sep>
const mongoose = require("mongoose");
const _ = require("lodash");
const MealPlan = require("../models/MealPlanModel");
const Recipe = require("../models/RecipesModel");
const FoodItem = require("../models/FoodItemModel");
exports.newUserMealPlan = (req, res, next) => {
console.log("new User MealPlan: ", req.user);
const userID = mongoose.Types.ObjectId(req.user._id);
const mealPlanModel = new MealPlan();
const mealPlan = Object.assign(mealPlanModel, {
user: userID,
monday: [],
tuesday: [],
wednesday: [],
thursday: [],
friday: [],
saturday: [],
sunday: []
})
mealPlan.save()
.then(()=> {
next();
})
.catch((err) => {
console.log(err);
res.status(500).send(err);
});
}
exports.getMealPlan = (req, res) => {
const userID = req.user._id;
// console.log("meal Controller; ", userID);
// excluding _id, __v and user from the response object
MealPlan.findOne({user: userID }, {_id: 0, __v: 0, user: 0})
.populate("monday tuesday wednesday thursday friday saturday sunday")
.exec()
.then((doc) => {
if (doc) {
res.status(200).send(doc);
}
})
.catch((err) => {
res.status(400).send(err);
})
}
// will need to remove recipes from meal plan and restore foodItems quantities
exports.restoreUnusedFoodItems = (req, res, next) => {
const day = req.params.day;
const userID = req.user._id;
let mealPlanRecipes;
MealPlan.findOne({ user: userID })
.then((doc)=> {
const recipes = doc[day]
const recipeIds = recipes.map(id => {
return mongoose.Types.ObjectId(id)
})
// console.log("restore recipeIds: ", recipeIds)
// then find the recipes used on that day and get recipes ingredients
Recipe.find({
_id: {
$in: recipeIds
}
})
.then((docs) => {
// console.log("recipes found: ", docs);
const ingredients = _.flatten(docs.map((doc) => {
return doc.ingredients.map((i) => {
const ingredient = { id: i.ingredient, portionSize: i.portionSize };
return ingredient;
})
}))
console.log("restore foodItems: ", ingredients);
function restoreItem(i) {
return new Promise((resolve, reject) => {
FoodItem.findOneAndUpdate({
ingredient: i.id,
user: userID
}, {
$inc: {
quantity: +i.portionSize
}
}, {
new: true
})
.then((doc) => {
if (!doc) {
return
} else if (doc.quantity === 0) {
// console.log("delete this doc: ", doc);
doc.remove();
}
})
.then(() => resolve("updated item :)"))
// TODO: if restoration quantity results to be zero, then remove the fooditem
.catch((err) => {
console.log(err);
reject("issue with updating item :(")
})
})
}
let updateAll = [];
// then with array of ingredients add back the portionSizes used in the recipe
ingredients.forEach((i) => {
updateAll.push(restoreItem(i));
})
// wait until all the food items used in the recipes have been updated
Promise.all(updateAll)
.then(() => console.log("foodItems have been restored!"))
// trigger next to then move on and update the "meal plan" document
.then(() => next())
})
})
.catch(err=> {
console.log(err);
res.status(500).send({message: "user mealplan not found"})
})
}
exports.updateMealPlan = (req, res, next) => {
const day = req.params.day;
const meals = req.body;
const userID = req.user._id;
const mealArray = meals.map((meal) => {
return meal._id;
});
MealPlan.findOne({user: userID}).then((doc) => {
// adding the _id of the recipes to the key "day" of the document
doc[day] = mealArray;
doc.save().then((saved) => {
res.status(200).send(saved)
next();
})
.catch((err) => {
res.status(500).send(err);
})
})
.catch((err) => {
res.status(400).send(err);
})
}
// 👇 This controller should probably be called before the save of the mealPlan document
exports.updateFoodItems = (req, res, next) => {
const userID = mongoose.Types.ObjectId(req.user._id);
const day = req.params.day;
const recipes = req.body;
const recipeIds = recipes.map(i => { return mongoose.Types.ObjectId(i._id)})
Recipe.find({
_id: {
$in: recipeIds
}
})
.then((docs) => {
// take the ingredients and portionSizes from recipes used in req.params.day and
// push them into flattened array
const ingredients = _.flatten(docs.map(doc => {
return doc.ingredients.map(i => {
const ingredient = { id: i.ingredient, portionSize: i.portionSize };
return ingredient;
})
}))
// function to update the foodItems used the recipes or insert if non already exists
function updateItem(i) {
return new Promise((resolve, reject) => {
const portionUpsert = 1 - i.portionSize;
// console.log("portionUpsert", portionUpsert);
FoodItem.findOneAndUpdate({
ingredient: i.id,
user: userID
}, {
$setOnInsert: {
user: userID,
ingredient: i.id,
expiry: null,
},
$inc: {
quantity: -i.portionSize
}
},
{
upsert: true,
setDefaultsOnInsert: true,
})
.then(()=> resolve("item update successful :)"))
.catch((err)=> reject(err))
})
}
let updateAll = []
ingredients.forEach((i) => {
updateAll.push(updateItem(i));
})
// wait until all the food items used in the recipes have been updated
Promise.all(updateAll)
.then(()=> console.log("they're all saved!"))
// trigger next to move on and to updateMealPlan controller
.then(()=> next())
})
}
<file_sep>const mongoose = require("mongoose");
const Ingredient = require("../models/IngredientModel");
exports.getIngredients = (req, res) => {
Ingredient.find().then((docs) => {
res.status(200).send(docs);
})
.catch((err) => {
res.status(400).send(err);
})
}
exports.searchIngredients = (req, res) => {
const ingredient = req.query.ingredient;
// TODO: set up conditional for empty query
const RegExpIngredient = new RegExp(`(?=${ingredient}*)+\\w+`, "gi");
Ingredient.find({
name: {
$regex: RegExpIngredient,
$options: "gi"
}
})
.then((docs) => {
res.status(200).send(docs);
})
.catch((err) => {
res.status(400).send(err);
})
}
exports.postIngredient = (req, res) => {
const IngredientModel = new Ingredient();
const ingredient = Object.assign(IngredientModel, req.body);
ingredient.save()
.then((doc) => {
res.status(200).send(doc);
})
.catch((err) => {
res.status(500).send(err);
});
}
// add Middleware to check ingredient being posted
exports.deleteIngredient = (req, res) => {
const foodId = req.params.id;
Ingredient.remove({ _id: foodId }).then((doc) => {
res.status(200).send(doc);
})
.catch((err) => {
res.status(400).send(err);
})
}
<file_sep>ul.dropdown-menu, ul.rbt-menu, ul.dropdown-menu-justify {
display: block;
max-height: 300px;
width: 100%;
overflow: auto;
position: absolute;
left: 0px;
background: lighten($med-dark, 50%);
margin: 6px auto 0px;
padding-left: 0px;
border: 1px solid;
li {
padding: 0px;
&:nth-of-type(even) {
background-color: $med-dark;
}
&:hover {
background: darken($tertiary-light, 0%);
}
a {
padding: 10px;
display: block;
}
}
}
.rbt-input-wrapper {
div:first-child {
display: block;
div:first-child {
display: block;
width: 100%;
}
}
input.rbt-input-main {
width: 100%;
}
}
mark.rbt-highlight-text {
background-color: lighten($secondary-light, 10%);
} | a0817e405b0ca8a25ab3fd4b3a2283703b64d33b | [
"SCSS",
"JavaScript"
] | 35 | SCSS | C-mccullo/mealer | 420e1b48844a886a0d2ffd8e45fc3e88b0321116 | 41e7f9ea1f41aecffa3d7e736715e4e021c7d055 |
refs/heads/master | <file_sep>#pragma once
#include "EngineCommon.h"
class ReflectionClass
{
public:
ReflectionClass() {}
~ReflectionClass() {}
private:
};
<file_sep>#pragma once
#include "RHI/IRHI.h"
#include "RHI/RHIResource.h"
class Shader
{
public:
enum class ShaderType : uint8_t
{
VS,
PS
};
public:
Shader(FString file, ShaderType type);
~Shader() {}
public:
ShaderType m_Type;
RHIResourceRef* m_pShader = nullptr;
RHIResourceRef* m_pShaderBlob = nullptr;
FString m_FileName;
};
<file_sep>#pragma once
#include "EngineCommon.h"
#include "RHI/IRHI.h"
class World
{
public:
World()
{
}
~World()
{
}
void Build(FArray<FString> levels);
void Tick();
void InitRHIResources();
public:
//levels
//FArray<class Map*> m_Levels;
//actors
FArray<class Actor*> m_Actors;
//sky
class SkySphere* m_pSky = nullptr;
//create light const buffer
struct PointLightInfo
{
Vector4D Color;
Vector4D Position;
};
struct DirectionLightInfo
{
Vector4D Color;
Vector4D Direction;
};
struct WorldBufferInfo
{
PointLightInfo PointLights[3];
DirectionLightInfo DirectionLight;
Vector4D Time;
};
//lights
class DirectionLight* m_pDirectionLight = nullptr;
FArray<class PointLight*> m_PointLights;
WorldBufferInfo m_WorldBufferInfo;
RHIResourceRef* m_pWorldConstBuffer = nullptr;
RHIResourceRef* m_pDepthStencileState = nullptr;
};
<file_sep>#include "IApplication.h"
<file_sep># GameEngine
..
TODO。。
<file_sep>#include "inc_forward.hlsl"
VertexOut VS(VertexIn VIn)
{
VertexOut VOut;
//out position
VOut.PosOut = float4(VIn.PosIn, 1.f);
VOut.PosOut = mul(float4(VIn.PosIn, 1.f), GWorld);
VOut.PosOut = mul(VOut.PosOut, GView);
VOut.PosOut = mul(VOut.PosOut, GProj);
VOut.PosOut = VOut.PosOut.xyww;
VOut.PosW = VIn.PosIn;
return VOut;
}<file_sep>#pragma once
class GUID
{
public:
GUID() {}
~GUID() {}
};
<file_sep>#include "DirectionLight.h"
<file_sep>#include "Camera.h"
extern IRHI* g_pRHI;
Camera::Camera()
{
MVPData.World = Matrix44::GetIdentity();
MVPData.View = GetCameraInverseMatrix();
MVPData.Proj = GetPerspectiveMatrix();
MVPData.WorldForNormal = Matrix44::GetIdentity();
MVPData.CamPos = Location;
g_pRHI->CreateConstBuffer(&MVPData, sizeof(MVPData), &m_pMVPConstBuffer);
}
<file_sep>#pragma once
#include "EngineCommon.h"
class StaticMesh
{
public:
StaticMesh() {}
~StaticMesh() {}
void LoadFromFile(const char* FileName);
void GetVertexData(uint8_t** VertexBuffer, uint32_t& VertexBSize, uint8_t** IndexBuffer, uint32_t& IndexBSize);
public:
struct Vertex
{
Vector3D Position;
Vector3D Normal;
Vector2D UV;
};
private:
FArray<Vertex> m_Vertexs;
FArray<uint32_t> m_Indexs;
//顶点布局类型
};
<file_sep>#include "Vector3D.h"
#include "Matrix44.h"
Matrix44 Vector3D::GetMatrix()
{
Matrix44 Ret = Matrix44::GetIdentity();
Ret[3][0] = X;
Ret[3][1] = Y;
Ret[3][2] = Z;
return Ret;
}<file_sep>#pragma once
#include "EngineCommon.h"
#include "RHI/IRHI.h"
class Texture2D
{
public:
Texture2D(FString file, int slot);
~Texture2D() {}
public:
RHIResourceRef* m_pTexture = nullptr;
RHIResourceRef* m_pTextureView = nullptr;
RHIResourceRef* m_pSamplerState = nullptr;
};
<file_sep>#include "IRHI.h"
extern IRHI* g_RHI = nullptr;<file_sep>#include "ReflectionManager.h"
<file_sep>#pragma once
#include "EngineCommon.h"
class Map
{
public:
Map(FString mapFile);
~Map() {}
public:
void Build(class World* world);
private:
FString m_MatFile;
};
<file_sep>#pragma once
#include "StaticMeshComponent.h"
class Actor
{
public:
Actor(FString name, FString meshName = "", FString materialName = "")
{
m_name = name;
Mesh = new StaticMeshComponent(meshName, materialName);
}
~Actor()
{
delete Mesh;
}
public:
void SetLocation(Vector3D location);
void SetRotation(Vector3D rotation);
class MeshDrawCommand* GetMeshDrawCommand();
public:
StaticMeshComponent* Mesh = nullptr;
Transform Trans;
FString m_name = "";
public:
Rotator m_Rotation{ 0,0,0 };
Vector3D m_Location{ 0, 0, 0 };
Matrix44 GetWorldMatrix()
{
auto Ret = Matrix44::GetIdentity();
Ret = m_Rotation.GetMatrix() * m_Location.GetMatrix();
return Ret;
}
};
<file_sep>#include "inc_forward.hlsl"
#include "inc_material_template.hlsl"
VertexOut VS(VertexIn VIn)
{
VertexOut VOut;
//out position
VOut.PosOut = float4(VIn.PosIn, 1.f);
VOut.PosOut = mul(float4(VIn.PosIn, 1.f), GWorld);
//world position
VOut.PosW = VOut.PosOut.xyz;
VOut.PosOut = mul(VOut.PosOut, GView);
VOut.PosOut = mul(VOut.PosOut, GProj);
//uv
VOut.TexCord = VIn.TexCord;
//world normal
//VOut.NormalW = VIn.Normal;
VOut.NormalW = normalize(mul(float4(VIn.Normal, 1.f), GWorldForNormal).xyz);
//VOut.NormalW = normalize(VIn.PosIn);
return VOut;
}<file_sep>#pragma once
#include "Render/IRenderer.h"
#include "RHI/IRHI.h"
class IApplication
{
public:
virtual void Launch() = 0;
virtual void Init() = 0;
virtual void Tick() = 0;
virtual void Exit() = 0;
virtual IRHI* GetRHI() = 0;
virtual IRenderer* GetRenderer() = 0;
};
<file_sep>#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <map>
#define FArray std::vector
#define CArray std::vector
#define FString std::string
#define CString std::string
#define CMap std::map
<file_sep>#include "RHIResource.h"
<file_sep>#pragma once
#include "EngineCommon.h"
#include "RHI/IRHI.h"
class TextureArray
{
public:
TextureArray(const FArray<FString>& files);
~TextureArray() {}
public:
RHIResourceRef* m_pTextureArray = nullptr;
RHIResourceRef* m_pTextureArrayView = nullptr;
RHIResourceRef* m_pSamplerState = nullptr;
};
<file_sep>#pragma once
#include "EngineCommon.h"
#include "IRenderer.h"
class ForwardRender : public IRenderer
{
public:
ForwardRender() {}
~ForwardRender(){}
virtual void PreRender() override;
virtual void Render() override;
};
<file_sep>#include "Texture2D.h"
Texture2D::Texture2D(FString file, int slot)
{
g_pRHI->CreateTexture2D(file, &m_pTexture, &m_pTextureView);
g_pRHI->CreateSamplerState(&m_pSamplerState);
}
<file_sep>#pragma once
#include "EngineCommon.h"
#include "ReflectionClass.h"
class ReflectionManager
{
private:
ReflectionManager() {};
public:
~ReflectionManager()
{
for (auto& pair : m_reflectionData)
{
delete pair.second;
}
}
public:
ReflectionManager GetSington()
{
static ReflectionManager sington;
return sington;
}
private:
CMap<FString, ReflectionClass*> m_reflectionData;
};
<file_sep>#pragma once
#include <Windows.h>
#include <iostream>
class Timer
{
public:
Timer()
{
memset(&Freq, 0, sizeof(Freq));
memset(&BeginCounter, 0, sizeof(BeginCounter));
memset(&EndCounter, 0, sizeof(EndCounter));
}
~Timer() {}
void Start()
{
QueryPerformanceFrequency(&Freq);
QueryPerformanceCounter(&BeginCounter);
}
double End()
{
QueryPerformanceCounter(&EndCounter);
double Duration = (double)(EndCounter.QuadPart - BeginCounter.QuadPart) / (double)Freq.QuadPart;
std::cout << "³ÖÐøʱ¼ä:" << Duration << "Ãë" << std::endl;
return Duration;
}
private:
LARGE_INTEGER Freq;
LARGE_INTEGER BeginCounter;
LARGE_INTEGER EndCounter;
};<file_sep>#pragma once
class PathUtils
{
};
<file_sep>#include "RHIDX11.h"
#include "Scene/Camera.h"
#include "Third/stb/stb_image.h"
#include "Third/stb/stb_image_resize.h"
#include "Third/stb/stb_image_write.h"
extern Camera* DefaultCamera;
#define ReleaseCOM(x) { if(x){ x->Release(); x = nullptr; } }
#define HR(Result) { if (FAILED(Result)) { return false;}}
#define CheckRet(exp) {if (!exp) return false;}
FRHIDX11::FRHIDX11(HWND InHWnd)
{
HWnd = InHWnd;
InitRHI();
}
FRHIDX11::~FRHIDX11()
{
ReleaseRHI();
}
bool FRHIDX11::InitRHI()
{
CheckRet(InitDeviceAndContext());
CheckRet(InitSwapChain());
CheckRet(InitResourceView());
InitViewPort();
return true;
}
void FRHIDX11::ReleaseRHI()
{
ReleaseCOM(Device);
ReleaseCOM(Context);
ReleaseCOM(SwapChain);
ReleaseCOM(RenderTargetView);
}
#include <codecvt>
static std::wstring ToWString(const FString& str)
{
std::wstring str_turned_to_wstr = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(str);
return str_turned_to_wstr;
//std::string wstr_turned_to_str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(input_wstr);
}
bool FRHIDX11::CompileShader(FString type, FString file, bool forceCompileFromFile, RHIResourceRef** shaderResource, RHIResourceRef** shaderBlobResources)
{
ID3DBlob* ShaderBlob;
std::wstring blobFileNameWStr(L"Shaders/bin/");
blobFileNameWStr = blobFileNameWStr + ToWString(file) + std::wstring(L".blob");
std::wstring hlslFileNameWStr(L"Shaders/");
hlslFileNameWStr = hlslFileNameWStr + ToWString(file) + L".hlsl";
const WCHAR* BlobFileName = blobFileNameWStr.c_str();
const WCHAR* HLSLFileName = hlslFileNameWStr.c_str();
LPCSTR EntryPoint = type.c_str();
LPCSTR ShaderModel = type == "VS" ? "vs_4_0" : "ps_4_0";
// 寻找是否有已经编译好的顶点着色器
if (!forceCompileFromFile && BlobFileName && D3DReadFileToBlob(BlobFileName, &ShaderBlob) == S_OK)
{
return true;
}
else
{
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#ifdef _DEBUG
// 设置 D3DCOMPILE_DEBUG 标志用于获取着色器调试信息。该标志可以提升调试体验,
// 但仍然允许着色器进行优化操作
dwShaderFlags |= D3DCOMPILE_DEBUG;
// 在Debug环境下禁用优化以避免出现一些不合理的情况
dwShaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION;
#endif
ID3DBlob* errorBlob = nullptr;
HRESULT Hr = D3DCompileFromFile(HLSLFileName, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, EntryPoint, ShaderModel, dwShaderFlags, 0, &ShaderBlob, &errorBlob);
if (FAILED(Hr))
{
if (errorBlob != nullptr)
{
auto str = reinterpret_cast<const char*>(errorBlob->GetBufferPointer());
OutputDebugStringA(str);
}
ReleaseCOM(errorBlob);
return false;
}
// 若指定了输出文件名,则将着色器二进制信息输出
if (BlobFileName)
{
HR(D3DWriteBlobToFile(ShaderBlob, BlobFileName, TRUE));
}
}
if (type == "VS")
{
ID3D11VertexShader* RawShader = nullptr;
HR(Device->CreateVertexShader(ShaderBlob->GetBufferPointer(), ShaderBlob->GetBufferSize(), NULL, &RawShader));
*shaderResource = new RHIResourceRef(RawShader);
}
else if(type == "PS")
{
ID3D11PixelShader* RawShader = nullptr;
HR(Device->CreatePixelShader(ShaderBlob->GetBufferPointer(), ShaderBlob->GetBufferSize(), NULL, &RawShader));
*shaderResource = new RHIResourceRef(RawShader);
}
*shaderBlobResources = new RHIResourceRef(ShaderBlob);
return true;
}
bool FRHIDX11::CreateConstBuffer(void* data, size_t size, RHIResourceRef** constBuffer)
{
D3D11_BUFFER_DESC BDS;
ZeroMemory(&BDS, sizeof(BDS));
BDS.Usage = D3D11_USAGE_DYNAMIC;
BDS.ByteWidth = size;
BDS.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
BDS.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
D3D11_SUBRESOURCE_DATA initData;
ZeroMemory(&initData, sizeof(initData));
initData.pSysMem = data;
ID3D11Buffer* Buffer;
HR(Device->CreateBuffer(&BDS, &initData, &Buffer));
*constBuffer = new RHIResourceRef(Buffer);
return true;
}
bool FRHIDX11::UpdateConstBuffer(void* data, size_t size, RHIResourceRef* constBuffer)
{
D3D11_MAPPED_SUBRESOURCE MappedData;
ID3D11Buffer* pBuffer = constBuffer->Get<ID3D11Buffer>();
HR(Context->Map(pBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedData));
memcpy_s(MappedData.pData, size, data, size);
Context->Unmap(pBuffer, 0);
return true;
}
bool FRHIDX11::CreateSamplerState(RHIResourceRef** sampler)
{
// 初始化采样器状态描述
D3D11_SAMPLER_DESC sampDesc;
ZeroMemory(&sampDesc, sizeof(sampDesc));
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampDesc.MinLOD = 0;
sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
ID3D11SamplerState* samplerState;
HR(Device->CreateSamplerState(&sampDesc, &samplerState));
*sampler = new RHIResourceRef(samplerState);
return true;
}
bool FRHIDX11::CreateTextureArray(const FArray<FString>& files, RHIResourceRef** textrueArray, RHIResourceRef** textureArrayView)
{
if (files.empty()) return false;
FString firstFileName = files[0];
int w, h, n;
unsigned char* data = stbi_load(firstFileName.c_str(), &w, &h, &n, 0);
// 创建纹理数组
D3D11_TEXTURE2D_DESC texArrayDesc;
texArrayDesc.Width = w;
texArrayDesc.Height = h;
texArrayDesc.MipLevels = 0;
texArrayDesc.ArraySize = files.size();
texArrayDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texArrayDesc.SampleDesc.Count = 1; // 不使用多重采样
texArrayDesc.SampleDesc.Quality = 0;
texArrayDesc.Usage = D3D11_USAGE_DEFAULT;
texArrayDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
texArrayDesc.CPUAccessFlags = 0;
texArrayDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS; // 指定需要生成mipmap
ID3D11Texture2D* pTexArray = nullptr;
HR(Device->CreateTexture2D(&texArrayDesc, nullptr, &pTexArray));
// 获取实际创建的纹理数组信息
pTexArray->GetDesc(&texArrayDesc);
for (UINT i = 0; i < texArrayDesc.ArraySize; ++i)
{
FString fileName = files[i];
int w, h, n;
unsigned char* data = stbi_load(fileName.c_str(), &w, &h, &n, 0);
D3D11_SUBRESOURCE_DATA sd;
sd.pSysMem = data;
sd.SysMemPitch = w * n;
sd.SysMemSlicePitch = w * h * n;
// 创建纹理
D3D11_TEXTURE2D_DESC texDesc;
texDesc.Width = w;
texDesc.Height = h;
texDesc.MipLevels = 1;
texDesc.ArraySize = 1;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texDesc.SampleDesc.Count = 1; // 不使用多重采样
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D11_USAGE_STAGING;
texDesc.BindFlags = 0;
texDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
texDesc.MiscFlags = 0;
ID3D11Texture2D* pTexture;
HR(Device->CreateTexture2D(&texDesc, &sd, &pTexture));
// 写入到纹理数组对应位置的首mip
D3D11_MAPPED_SUBRESOURCE mappedTex2D;
Context->Map(pTexture, 0, D3D11_MAP_READ, 0, &mappedTex2D);
Context->UpdateSubresource(pTexArray,
D3D11CalcSubresource(0, i, texArrayDesc.MipLevels), // i * mipLevel + j
nullptr, mappedTex2D.pData, mappedTex2D.RowPitch, mappedTex2D.DepthPitch);
// 停止映射
Context->Unmap(pTexture, 0);
ReleaseCOM(pTexture);
}
D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
viewDesc.Format = texArrayDesc.Format;
viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
viewDesc.Texture2DArray.MostDetailedMip = 0;
viewDesc.Texture2DArray.MipLevels = -1;
viewDesc.Texture2DArray.FirstArraySlice = 0;
viewDesc.Texture2DArray.ArraySize = texArrayDesc.ArraySize;
ID3D11ShaderResourceView* pTexArraySRV;
HR(Device->CreateShaderResourceView(pTexArray, &viewDesc, &pTexArraySRV));
Context->GenerateMips(pTexArraySRV);
*textrueArray = new RHIResourceRef(pTexArray);
*textureArrayView = new RHIResourceRef(pTexArraySRV);
return true;
}
bool FRHIDX11::CreateTexture2D(FString file, RHIResourceRef** textrue, RHIResourceRef** textureView)
{
int w, h, n;
unsigned char* data = stbi_load(file.c_str(), &w, &h, &n, 0);
//FArray<unsigned char> data4;
//if (n == 3)
//{
// for (int i = 0; i < h; i++)
// {
// for (int j = 0; j < w; j++)
// {
// for (int m = 0; m < 3; m++)
// {
// data4.push_back(data[i * w * n + j * n + m]);
// }
// data4.push_back(255);
// }
// }
//}
//if (n == 3)
//{
// //stbir_resize(idata, iw, ih, 0, odata, ow, oh, 0, STBIR_TYPE_UINT8, n, STBIR_ALPHA_CHANNEL_NONE, 0,
// // STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP,
// // STBIR_FILTER_BOX, STBIR_FILTER_BOX,
// // STBIR_COLORSPACE_SRGB, nullptr
// //);
// FString outputPath = file + ".png";
// // 写入图片
// stbi_write_png(outputPath.c_str(), w, h, 4, &data4[0], 0);
//}
D3D11_SUBRESOURCE_DATA sd;
sd.pSysMem = data;
sd.SysMemPitch = w * 4;
sd.SysMemSlicePitch = w * h * 4;
// 创建中间纹理
D3D11_TEXTURE2D_DESC tempTexDesc;
tempTexDesc.Width = w;
tempTexDesc.Height = h;
tempTexDesc.MipLevels = 1;
tempTexDesc.ArraySize = 1;
tempTexDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
tempTexDesc.SampleDesc.Count = 1; // 不使用多重采样
tempTexDesc.SampleDesc.Quality = 0;
tempTexDesc.Usage = D3D11_USAGE_STAGING;
tempTexDesc.BindFlags = 0;
tempTexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
tempTexDesc.MiscFlags = 0;
ID3D11Texture2D* pTempTexture;
HR(Device->CreateTexture2D(&tempTexDesc, &sd, &pTempTexture));
D3D11_TEXTURE2D_DESC texDesc;
texDesc.Width = w;
texDesc.Height = h;
texDesc.MipLevels = 0;
texDesc.ArraySize = 1;
texDesc.Format = tempTexDesc.Format;
texDesc.SampleDesc.Count = 1; // 不使用多重采样
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D11_USAGE_DEFAULT;
texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
texDesc.CPUAccessFlags = 0;
texDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
ID3D11Texture2D* pTexture;
HR(Device->CreateTexture2D(&texDesc, nullptr, &pTexture));
// 写入到目标纹理对应位置的首mip
D3D11_MAPPED_SUBRESOURCE mappedTex2D;
Context->Map(pTempTexture, 0, D3D11_MAP_READ, 0, &mappedTex2D);
Context->UpdateSubresource(pTexture, 0, nullptr, mappedTex2D.pData, mappedTex2D.RowPitch, mappedTex2D.DepthPitch);
Context->Unmap(pTempTexture, 0);
ReleaseCOM(pTempTexture);
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
srvDesc.Format = tempTexDesc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = -1;
srvDesc.Texture2D.MostDetailedMip = 0;
ID3D11ShaderResourceView* pTextureSRV;
HR(Device->CreateShaderResourceView(pTexture, &srvDesc, &pTextureSRV));
Context->GenerateMips(pTextureSRV);
*textrue = new RHIResourceRef(pTexture);
*textureView = new RHIResourceRef(pTextureSRV);
return true;
}
bool FRHIDX11::CreateVertexLayout(RHIResourceRef* VSBlob, RHIResourceRef** layout)
{
//定义顶点输入布局
D3D11_INPUT_ELEMENT_DESC Layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "UV", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
//创建输入布局
ID3D11InputLayout* VertexLayout;
HR(Device->CreateInputLayout(Layout, ARRAYSIZE(Layout), VSBlob->Get<ID3DBlob>()->GetBufferPointer(), VSBlob->Get<ID3DBlob>()->GetBufferSize(), &VertexLayout));
*layout = new RHIResourceRef(VertexLayout);
return true;
}
bool FRHIDX11::CreateTextureCube(const FArray<FString>& files, RHIResourceRef** textrueCube, RHIResourceRef** textureCubeView)
{
if (files.size() != 6) return false;
FString firstFileName = files[0];
int w, h, n;
unsigned char* data = stbi_load(firstFileName.c_str(), &w, &h, &n, 0);
//创建6张纹理
FArray<RHIResourceRef*> srcTexVec(6, nullptr);
FArray<RHIResourceRef*> srcTexSRVVec(6, nullptr);
for (int i = 0; i < 6; i++)
{
CreateTexture2D(files[i], &srcTexVec[i], &srcTexSRVVec[i]);
}
D3D11_TEXTURE2D_DESC srcTexDesc;
srcTexVec[0]->Get<ID3D11Texture2D>()->GetDesc(&srcTexDesc);
// 创建纹理数组
D3D11_TEXTURE2D_DESC texArrayDesc;
texArrayDesc.Width = w;
texArrayDesc.Height = h;
texArrayDesc.MipLevels = srcTexDesc.MipLevels;
texArrayDesc.ArraySize = 6;
texArrayDesc.Format = srcTexDesc.Format;
texArrayDesc.SampleDesc.Count = 1; // 不使用多重采样
texArrayDesc.SampleDesc.Quality = 0;
texArrayDesc.Usage = D3D11_USAGE_DEFAULT;
texArrayDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texArrayDesc.CPUAccessFlags = 0;
texArrayDesc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;
ID3D11Texture2D* pTexArray = nullptr;
HR(Device->CreateTexture2D(&texArrayDesc, nullptr, &pTexArray));
// 获取实际创建的纹理数组信息
pTexArray->GetDesc(&texArrayDesc);
for (int i = 0; i < texArrayDesc.ArraySize; ++i)
{
for (int j = 0; j < texArrayDesc.MipLevels; j++)
{
Context->CopySubresourceRegion(
pTexArray,
D3D11CalcSubresource(j, i, texArrayDesc.MipLevels),
0, 0, 0,
srcTexVec[i]->Get<ID3D11Texture2D>(),
j,
nullptr);
}
}
D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
viewDesc.Format = texArrayDesc.Format;
viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
viewDesc.TextureCube.MostDetailedMip = 0;
viewDesc.TextureCube.MipLevels = texArrayDesc.MipLevels;
ID3D11ShaderResourceView* pTexArraySRV;
HR(Device->CreateShaderResourceView(pTexArray, &viewDesc, &pTexArraySRV));
//release no use
for (int i = 0; i < 6; i++)
{
auto curTex = srcTexVec[i]->Get<ID3D11Texture2D>();
ReleaseCOM(curTex);
auto curTexSRV = srcTexSRVVec[i]->Get<ID3D11ShaderResourceView>();
ReleaseCOM(curTexSRV);
}
*textrueCube = new RHIResourceRef(pTexArray);
*textureCubeView = new RHIResourceRef(pTexArraySRV);
return true;
}
void FRHIDX11::PSSetConstantBuffers(uint32_t StartSlot, uint32_t NumBuffers, RHIResourceRef* ConstantBuffers)
{
ID3D11Buffer* pConstantBuffers = ConstantBuffers->Get<ID3D11Buffer>();
Context->PSSetConstantBuffers(StartSlot, NumBuffers, &pConstantBuffers);
}
void FRHIDX11::VSSetConstantBuffers(uint32_t StartSlot, uint32_t NumBuffers, RHIResourceRef* ConstantBuffers)
{
ID3D11Buffer* pConstantBuffers = ConstantBuffers->Get<ID3D11Buffer>();
Context->VSSetConstantBuffers(StartSlot, NumBuffers, &pConstantBuffers);
}
void FRHIDX11::SetPSShader(RHIResourceRef* shader)
{
Context->PSSetShader(shader->Get<ID3D11PixelShader>(), NULL, 0);
}
void FRHIDX11::SetVSShader(RHIResourceRef* shader)
{
Context->VSSetShader(shader->Get<ID3D11VertexShader>(), NULL, 0);
}
void FRHIDX11::SetVertexLayout(RHIResourceRef* layout)
{
Context->IASetInputLayout(layout->Get<ID3D11InputLayout>());
}
void FRHIDX11::SetSamplerState(RHIResourceRef* sampler, uint32_t slot)
{
ID3D11SamplerState* samplerState = sampler->Get<ID3D11SamplerState>();
Context->PSSetSamplers(slot, 1, &samplerState);
Context->VSSetSamplers(slot, 1, &samplerState);
}
void FRHIDX11::SetShaderResource(RHIResourceRef* resource, uint32_t slot)
{
ID3D11ShaderResourceView* SRV = resource->Get<ID3D11ShaderResourceView>();
Context->PSSetShaderResources(slot, 1, &SRV);
Context->VSSetShaderResources(slot, 1, &SRV);
}
bool FRHIDX11::CreateSkyDepthStencilState(RHIResourceRef** state)
{
D3D11_DEPTH_STENCIL_DESC dsDesc;
dsDesc.DepthEnable = true;
dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
dsDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
dsDesc.StencilEnable = false;
ID3D11DepthStencilState* pState;
HR(Device->CreateDepthStencilState(&dsDesc, &pState));
*state = new RHIResourceRef(pState);
return true;
}
bool FRHIDX11::CreateNormalDepthStencilState(RHIResourceRef** state)
{
D3D11_DEPTH_STENCIL_DESC dsDesc;
dsDesc.DepthEnable = true;
dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
dsDesc.DepthFunc = D3D11_COMPARISON_LESS;
dsDesc.StencilEnable = false;
ID3D11DepthStencilState* pState;
HR(Device->CreateDepthStencilState(&dsDesc, &pState));
*state = new RHIResourceRef(pState);
return true;
}
void FRHIDX11::SetDepthStencilState(RHIResourceRef* state)
{
Context->OMSetDepthStencilState(state->Get<ID3D11DepthStencilState>(), 0);
}
void FRHIDX11::ClearView()
{
// 清理 back buffer
float ClearColor[4] = { 0.2f, 0.3f, 0.3f, 1.0f };
Context->ClearRenderTargetView(RenderTargetView, ClearColor);
Context->ClearDepthStencilView(DepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
}
void FRHIDX11::FlushView()
{
// Present the information rendered to the back buffer to the front buffer (the screen)
SwapChain->Present(0, 0);
}
bool FRHIDX11::DrawIndex(uint8_t* VBuffer, uint32_t& VSize, uint8_t* IBuffer, uint32_t& ISize)
{
//缓冲描述
D3D11_BUFFER_DESC VBufferDes;
ZeroMemory(&VBufferDes, sizeof(VBufferDes));
VBufferDes.Usage = D3D11_USAGE_DEFAULT;
VBufferDes.ByteWidth = VSize;
VBufferDes.BindFlags = D3D11_BIND_VERTEX_BUFFER;
VBufferDes.CPUAccessFlags = 0;
D3D11_SUBRESOURCE_DATA InitData;
ZeroMemory(&InitData, sizeof(InitData));
InitData.pSysMem = VBuffer;
//创建顶点缓冲
ID3D11Buffer* VertexBuffer;
HR(Device->CreateBuffer(&VBufferDes, &InitData, &VertexBuffer));
UINT Stride = sizeof(float) * 8;
UINT Offset = 0;
//输入装配阶段(Input-Assembler Stage)设置顶点缓冲
Context->IASetVertexBuffers(0, 1, &VertexBuffer, &Stride, &Offset);
//创建索引缓冲
D3D11_BUFFER_DESC IBufferDes;
IBufferDes.Usage = D3D11_USAGE_IMMUTABLE;
IBufferDes.ByteWidth = ISize;
IBufferDes.BindFlags = D3D11_BIND_INDEX_BUFFER;
IBufferDes.CPUAccessFlags = 0;
IBufferDes.MiscFlags = 0;
IBufferDes.StructureByteStride = 0;
// 设定用于初始化索引缓冲的数据
D3D11_SUBRESOURCE_DATA IinitData;
IinitData.pSysMem = IBuffer;
// 创建索引缓冲
ID3D11Buffer* IndexBuffer;
HR(Device->CreateBuffer(&IBufferDes, &IinitData, &IndexBuffer));
Context->IASetIndexBuffer(IndexBuffer, DXGI_FORMAT_R32_UINT, 0);
//输入装配阶段(Input-Assembler Stage)设置拓扑结构
Context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// 渲染
Context->DrawIndexed(ISize / 4, 0, 0);
return true;
}
bool FRHIDX11::InitDeviceAndContext()
{
UINT CreateDeviceFlags = 0;
#if _DEBUG
CreateDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
HRESULT Result = D3D11CreateDevice(
0, // 默认显示适配器
D3D_DRIVER_TYPE_HARDWARE,
0, // 不使用软件设备
CreateDeviceFlags,
0, 0, // 默认的特征等级数组
D3D11_SDK_VERSION,
&Device,
&FeatureLevel,
&Context);
HR(Result);
if (FeatureLevel != D3D_FEATURE_LEVEL_11_0 && FeatureLevel != D3D_FEATURE_LEVEL_11_1)
{
return false;
}
return true;
}
bool FRHIDX11::InitSwapChain()
{
DXGI_SWAP_CHAIN_DESC SD;
SD.BufferDesc.Width = 800;
SD.BufferDesc.Height = 600;
SD.BufferDesc.RefreshRate.Numerator = 60;
SD.BufferDesc.RefreshRate.Denominator = 1;
SD.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
SD.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
SD.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
if (bEnableMSAA)
{
UINT MSAAQuality;
HR(Device->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &MSAAQuality));
SD.SampleDesc.Count = 4;
SD.SampleDesc.Quality = MSAAQuality - 1;
}
else
{
SD.SampleDesc.Count = 1;
SD.SampleDesc.Quality = 0;
}
SD.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
SD.BufferCount = 1;
SD.OutputWindow = HWnd;
SD.Windowed = true;
SD.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
SD.Flags = 0;//DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH可选,能在全屏下,手动指定分辨率,默认屏幕分辨率
IDXGIDevice* DXGIDevice = 0;
HR(Device->QueryInterface(__uuidof(IDXGIDevice), (void**)&DXGIDevice));
IDXGIAdapter* DXGIAdapter = 0;
HR(DXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&DXGIAdapter));
// 获得 IDXGIFactory 接口
IDXGIFactory* DXGIFactory = 0;
HR(DXGIAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&DXGIFactory));
HR(DXGIFactory->CreateSwapChain(Device, &SD, &SwapChain));
ReleaseCOM(DXGIDevice);
ReleaseCOM(DXGIAdapter);
ReleaseCOM(DXGIFactory);
return true;
}
bool FRHIDX11::InitResourceView()
{
ID3D11Texture2D* BackBuffer;
HR(SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&BackBuffer)));
if (BackBuffer)
{
HR(Device->CreateRenderTargetView(BackBuffer, 0, &RenderTargetView));
ReleaseCOM(BackBuffer);
}
D3D11_TEXTURE2D_DESC DepthStencilDesc;
DepthStencilDesc.Width = 800;
DepthStencilDesc.Height = 600;
DepthStencilDesc.MipLevels = 1;
DepthStencilDesc.ArraySize = 1;
DepthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
if (bEnableMSAA)
{
UINT MSAAQuality;
HR(Device->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, 4, &MSAAQuality));
DepthStencilDesc.SampleDesc.Count = 4;
DepthStencilDesc.SampleDesc.Quality = MSAAQuality - 1;
}
else
{
DepthStencilDesc.SampleDesc.Count = 1;
DepthStencilDesc.SampleDesc.Quality = 0;
}
DepthStencilDesc.Usage = D3D11_USAGE_DEFAULT;
DepthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
DepthStencilDesc.CPUAccessFlags = 0;
DepthStencilDesc.MiscFlags = 0;
ID3D11Texture2D* DepthStencilBuffer;
HR(Device->CreateTexture2D(&DepthStencilDesc, 0, &DepthStencilBuffer));
HR(Device->CreateDepthStencilView(DepthStencilBuffer, 0, &DepthStencilView));
Context->OMSetRenderTargets(1, &RenderTargetView, DepthStencilView);
D3D11_RASTERIZER_DESC rasterizerDesc;
ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc));
// 背面剔除模式
rasterizerDesc.FillMode = D3D11_FILL_SOLID;
rasterizerDesc.CullMode = D3D11_CULL_NONE;
rasterizerDesc.FrontCounterClockwise = false;
rasterizerDesc.DepthClipEnable = true;
ID3D11RasterizerState* RSState = nullptr;
HR(Device->CreateRasterizerState(&rasterizerDesc, &RSState));
Context->RSSetState(RSState);
ReleaseCOM(RSState);
return true;
}
void FRHIDX11::InitViewPort()
{
D3D11_VIEWPORT VP;
VP.TopLeftX = 0;
VP.TopLeftY = 0;
VP.Width = static_cast<float>(800);
VP.Height = static_cast<float>(600);
VP.MinDepth = 0.0f;
VP.MaxDepth = 1.0f;
Context->RSSetViewports(1, &VP);
}<file_sep>#include "EngineCommon.h"
#include "Application/IApplication.h"
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
//define something for Windows (32-bit and 64-bit, this part is common)
#include "Application/WinApp.h"
extern IApplication* GApp = new WinApp();
#ifdef _WIN64
//define something for Windows (64-bit only)
#else
//define something for Windows (32-bit only)
#endif
#elif __APPLE__
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR
// iOS Simulator
#elif TARGET_OS_IPHONE
// iOS device
#elif TARGET_OS_MAC
// Other kinds of Mac OS
#else
# error "Unknown Apple platform"
#endif
#elif __linux__
// linux
#elif __unix__ // all unices not caught above
// Unix
#elif defined(_POSIX_VERSION)
// POSIX
#else
# error "Unknown compiler"
#endif
int main(int argc, char** argv)
{
FString Path(argv[0]);
GApp->Launch();
}<file_sep>#include "FileUtils.h"
using namespace std;
bool FileUtils::SyncLoadFile(FString path, char** ppBuffer, size_t& size)
{
fstream fs(path, ios::binary | ios::in);
if (!fs)
{
size = 0;
return false;
}
fs.seekg(0, ios::end);
size = fs.tellg();
fs.seekg(0, ios::beg);
auto buffer = new char[size];
fs.read(buffer, size);
if (!fs)
{
return false;
}
ppBuffer = &buffer;
return true;
}
bool FileUtils::SyncSaveFile(FString path, char* buffer, size_t size)
{
fstream fs(path, ios::binary | ios::out);
if (!fs)
{
size = 0;
return false;
}
fs.write(buffer, size);
if (!fs)
{
return false;
}
return true;
}
<file_sep>#include "World.h"
#include "Map.h"
#include "Actor.h"
#include "DirectionLight.h"
#include "PointLight.h"
#include "time.h"
#include "SkySphere.h"
extern World* GWorld = new World();
extern IRHI* g_pRHI;
void World::Build(FArray<FString> levels)
{
for (const auto& file : levels)
{
Map* map = new Map(file);
map->Build(this);
delete map;
}
m_pSky = new SkySphere();
InitRHIResources();
}
void World::Tick()
{
m_WorldBufferInfo.Time = Vector4D(time(nullptr), 0, 0, 0);
if (m_pDirectionLight)
{
m_WorldBufferInfo.DirectionLight.Color = m_pDirectionLight->m_Color;
m_WorldBufferInfo.DirectionLight.Direction = m_pDirectionLight->m_Direction;
}
for (int i = 0; i < m_PointLights.size() && i < 5; i++)
{
m_WorldBufferInfo.PointLights[i].Color = m_PointLights[i]->m_Color;
m_WorldBufferInfo.PointLights[i].Position = m_PointLights[i]->m_Position;
}
}
void World::InitRHIResources()
{
m_WorldBufferInfo.Time = Vector4D(time(nullptr), 0, 0, 0);
if (m_pDirectionLight)
{
m_WorldBufferInfo.DirectionLight.Color = m_pDirectionLight->m_Color;
m_WorldBufferInfo.DirectionLight.Direction = m_pDirectionLight->m_Direction;
}
for (int i = 0; i < m_PointLights.size() && i < 3; i++)
{
m_WorldBufferInfo.PointLights[i].Color = m_PointLights[i]->m_Color;
m_WorldBufferInfo.PointLights[i].Position = m_PointLights[i]->m_Position;
}
g_pRHI->CreateConstBuffer(&m_WorldBufferInfo, sizeof(m_WorldBufferInfo), &m_pWorldConstBuffer);
g_pRHI->CreateNormalDepthStencilState(&m_pDepthStencileState);
}
<file_sep>#pragma once
#include "MathDefines.h"
#include "Vector3D.h"
#include "Rotator.h"
#include "Matrix44.h"
class Transform
{
public:
Transform()
{
}
Transform(const Vector3D& InLoc, const Rotator& InRot )
{
Loc = InLoc;
Rot = InRot;
}
~Transform() {}
Matrix44 GetMatrix();
public:
Vector3D Loc;
Rotator Rot;
};<file_sep>#pragma once
#include "EngineCommon.h"
#include "Shader/Shader.h"
class SkySphere
{
public:
SkySphere();
~SkySphere() {}
void Draw();
private:
class StaticMesh* Mesh;
RHIResourceRef* m_pVertexLayout = nullptr;
//shader
Shader* m_pVSShader = nullptr;
Shader* m_pPSShader = nullptr;
//texture cube
RHIResourceRef* m_pTextrueCube = nullptr;
RHIResourceRef* m_pTextrueCubeView = nullptr;
RHIResourceRef* m_pSamplerState = nullptr;
//pso
RHIResourceRef* m_pDepthStencileState = nullptr;
};
<file_sep>#include "TextureArray.h"
TextureArray::TextureArray(const FArray<FString>& files)
{
g_pRHI->CreateTextureArray(files, &m_pTextureArray, &m_pTextureArrayView);
g_pRHI->CreateSamplerState(&m_pSamplerState);
}
<file_sep>#include "inc_forward.hlsl"
#include "inc_common.hlsl"
TextureCube g_TexCube : register(t0);
SamplerState g_Sam : register(s0);
float4 PS(VertexOut PIn) : SV_TARGET
{
float4 texColor = g_TexCube.Sample(g_Sam, normalize(PIn.PosW));
//srgb to linenar
texColor = GammaToLinear(texColor);
//HDR
texColor = ToneMap(texColor);
//Gama Correction
texColor = LinearToGamma(texColor);
return texColor;
}<file_sep>#include "MeshDrawCommand.h"
#include "Scene/Camera.h"
#include "Scene/World.h"
extern IRHI* g_pRHI;
extern Camera* DefaultCamera;
void MeshDrawCommand::Execute()
{
g_pRHI->PSSetConstantBuffers(3, 1, m_pMaterialParamsConstBuffer);
g_pRHI->VSSetConstantBuffers(3, 1, m_pMaterialParamsConstBuffer);
DefaultCamera->MVPData.World = m_WorldMatrix;
DefaultCamera->MVPData.View = DefaultCamera->GetCameraInverseMatrix();
DefaultCamera->MVPData.WorldForNormal = m_WorldMatrix;//TODO:专门的法线矩阵
DefaultCamera->MVPData.WorldForNormal[3][0] = 0;
DefaultCamera->MVPData.WorldForNormal[3][1] = 0;
DefaultCamera->MVPData.WorldForNormal[3][2] = 0;
DefaultCamera->MVPData.CamPos = DefaultCamera->Location;
g_pRHI->UpdateConstBuffer(&DefaultCamera->MVPData, sizeof(DefaultCamera->MVPData), DefaultCamera->m_pMVPConstBuffer);
g_pRHI->SetVSShader(m_pVSShader->m_pShader);
g_pRHI->SetPSShader(m_pPSShader->m_pShader);
g_pRHI->SetVertexLayout(m_pVertexLayoutRef);
g_pRHI->SetSamplerState(m_pSamplerState, 0);
for (auto it = m_Textures.begin(); it != m_Textures.end(); it++)
{
g_pRHI->SetShaderResource(it->second, it->first);
}
g_pRHI->DrawIndex(m_pVertexBuffer, m_VertexSize, m_pIndexBuffer, m_IndexSize);
}
<file_sep>#include "WinApp.h"
#include "Render/ForwardRenderer.h"
#include "RHI/DX11/RHIDX11.h"
#include "Scene/World.h"
#include "Scene/InputManager.h"
#include "Scene/Camera.h"
extern Camera* DefaultCamera = nullptr;
extern IRHI* g_pRHI = nullptr;
LRESULT CALLBACK WinProc(HWND HWnd, UINT UMsg, WPARAM WParam, LPARAM LParam);
bool bCanExit = false;
void WinApp::Launch()
{
Init();
while (!bCanExit)
{
Tick();
}
Exit();
}
void WinApp::Init()
{
//get instance
HINSTANCE HInstance = (HINSTANCE)GetModuleHandle(nullptr);
//create WndClass
WNDCLASSEX WndClass;
WndClass.cbSize = sizeof(WndClass);
WndClass.cbClsExtra = 0;
WndClass.cbWndExtra = 0;
WndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
WndClass.hCursor = LoadCursor(nullptr, IDC_ARROW);
WndClass.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
WndClass.hIconSm = nullptr;
WndClass.hInstance = HInstance;
WndClass.lpfnWndProc = WinProc;
WndClass.lpszClassName = TEXT("MainWClass");
WndClass.lpszMenuName = nullptr;
WndClass.style = CS_VREDRAW | CS_HREDRAW;
//register WndClass
RegisterClassEx(&WndClass);
//create a window
HWnd = CreateWindowEx(
0,
TEXT("MainWClass"),
TEXT("GameEngine"),
WS_OVERLAPPEDWINDOW,
0,
0,
800,
600,
nullptr,
nullptr,
HInstance,
nullptr
);
//show window
ShowWindow(HWnd, SW_NORMAL);
//update window
UpdateWindow(HWnd);
//render
g_pRHI = new FRHIDX11(HWnd);
//init world
FArray<FString> maps{ "Content/Test_Map.json" };
GWorld->Build(maps);
//create default camera
DefaultCamera = new Camera();
Renderer = new ForwardRender();
Renderer->PreRender();
}
void WinApp::Tick()
{
//game logic
DefaultCamera->Update();
GWorld->Tick();
//render
Renderer->Render();
//dispatch message
MSG Msg;
while (PeekMessage(&Msg, nullptr, 0, 0, PM_NOREMOVE))
{
if (GetMessage(&Msg, nullptr, 0, 0))
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
}
}
void WinApp::Exit()
{
delete Renderer;
delete RHI;
}
LRESULT CALLBACK WinProc(HWND HWnd, UINT UMsg, WPARAM WParam, LPARAM LParam)
{
auto InputMng = InputManager::GetInstance();
switch (UMsg)
{
case WM_KEYUP:
{
if (WParam == VK_ESCAPE)
{
bCanExit = true;
}
else if (WParam == 'O')
{
}
else if (WParam == 'P')
{
}
else if (WParam == 'W')
{
InputMng->FrontDelta = 0;
}
else if (WParam == 'S')
{
InputMng->FrontDelta = 0;
}
else if (WParam == 'A')
{
InputMng->RightDelta = 0;
}
else if (WParam == 'D')
{
InputMng->RightDelta = 0;
}
else if (WParam == 'Q')
{
InputMng->UpDelta = 0;
}
else if (WParam == 'E')
{
InputMng->UpDelta = 0;
}
break;
}
case WM_KEYDOWN:
{
if (WParam == 'W')
{
InputMng->FrontDelta = 0.1;
}
else if (WParam == 'S')
{
InputMng->FrontDelta = -0.1;
}
else if (WParam == 'A')
{
InputMng->RightDelta = -0.1;
}
else if (WParam == 'D')
{
InputMng->RightDelta = 0.1;
}
else if (WParam == 'Q')
{
InputMng->UpDelta = 0.1;
}
else if (WParam == 'E')
{
InputMng->UpDelta = -0.1;
}
break;
}
case WM_MOUSEMOVE:
{
if (WParam == MK_LBUTTON)
{
float XPos = LOWORD(LParam);
float YPos = HIWORD(LParam);
if (InputMng->bStartTouchMove)
{
InputMng->DeltaMove = Vector2D(XPos - InputMng->LastMousePos.X, YPos - InputMng->LastMousePos.Y);
}
else
{
InputMng->bStartTouchMove = true;
}
InputMng->LastMousePos = Vector2D(XPos, YPos);
}
else
{
InputMng->bStartTouchMove = false;
InputMng->LastMousePos = Vector2D();
InputMng->DeltaMove = Vector2D();
}
break;
}
}
return DefWindowProc(HWnd, UMsg, WParam, LParam);
}<file_sep>#include "inc_forward.hlsl"
#include "inc_material_template.hlsl"
#include "inc_common.hlsl"
float4 PS(VertexOut PIn) : SV_TARGET
{
//float4 texColor = gTexSingle1.Sample(gSamLinear, PIn.TexCord);
float4 texColor = float4(0.5, 0.4, 0.1, 1);
//calculate light
float3 cameraPosW = GCameraPosition;
float3 normal = PIn.NormalW;
float3 baseColor = texColor.rgb;
float3 viewDir = normalize(cameraPosW - PIn.PosW);
//direction light
float3 lightDir = normalize(GDirectionLight.Direction.xyz);
float3 radiance = GDirectionLight.Color.rgb ;
float3 PBRDirectionLight = GetPBRColorDirect(GMetallic, GRoughness, radiance, baseColor, normal, lightDir, viewDir);
//point lights
float3 PBRPointLights = float3(0, 0, 0);
for (int i = 0; i < 3; i++)
{
PointLight curPLight = GPointLights[i];
float3 lightDir = normalize(curPLight.Position.xyz - PIn.PosW);
float dist = distance(curPLight.Position.xyz, PIn.PosW);
float attenuation = 10000.0 / (dist * dist);
float3 radiance = curPLight.Color.rgb * attenuation;
PBRPointLights = PBRPointLights + GetPBRColorDirect(GMetallic, GRoughness, radiance, baseColor, normal, lightDir, viewDir);;
}
//ambient
float ao = 1;
float3 sumPBR = PBRPointLights + PBRDirectionLight + float3(0.03, 0.03, 0.03) * baseColor * ao;
texColor.rgb = sumPBR;
//IBL
//reflection
//shadow
//transparency and refraction
//fog
//post process
//another shader
//HDR
//find a better curve
//texColor = ToneMap(texColor);
//Gama Correction
texColor = LinearToGamma(texColor);
return texColor;
}<file_sep>#pragma once
#include "MathDefines.h"
#include "Vector2D.h"
#include "Vector3D.h"
#include "Vector4D.h"
#include "Rotator.h"
#include "Matrix44.h"
#include "Transform.h"<file_sep>#include "ReflectionClass.h"
<file_sep>#pragma once
#include "MathDefines.h"
#include "Rotator.h"
#include "Vector3D.h"
class Matrix44
{
public:
Matrix44()
{
memset(Data, 0, sizeof(Data));
}
Matrix44(Vector3D Location, Rotator Rotation)
{
memset(Data, 0, sizeof(Data));
for (int i = 0; i < 4; i++)
{
Data[i][i] = 1.f;
}
Data[3][0] = Location.X;
Data[3][1] = Location.Y;
Data[3][2] = Location.Z;
}
float* operator[](size_t Index)
{
return Data[Index];
}
Matrix44 operator*(Matrix44 Other)
{
Matrix44 Ret;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
Ret[i][j] = Data[i][0] * Other[0][j] + Data[i][1] * Other[1][j] + Data[i][2] * Other[2][j] + Data[i][3] * Other[3][j];
}
}
return Ret;
}
static Matrix44 GetIdentity()
{
Matrix44 Identity;
for (int i = 0; i < 4; i++)
{
Identity[i][i] = 1.f;
}
return Identity;
}
public:
float Data[4][4];
};<file_sep>#pragma once
#include "StdCommon.h"
#include <fstream>
class FileUtils
{
public:
static bool SyncLoadFile(FString path, char** ppBuffer, size_t& size);
static bool SyncSaveFile(FString path, char* buffer, size_t size);
};
<file_sep>#include "Actor.h"
#include "Render/MeshDrawCommand.h"
#include "Material/TextureArray.h"
#include "Material/Texture2D.h"
void Actor::SetLocation(Vector3D location)
{
m_Location = location;
}
void Actor::SetRotation(Vector3D rotation)
{
m_Rotation = Rotator(rotation.X, rotation.Y, rotation.Z);
}
MeshDrawCommand* Actor::GetMeshDrawCommand()
{
uint8_t* VertexsBuffer;
uint32_t VBSize = 0;
uint8_t* IndexBuffer;
uint32_t IBSize = 0;
Mesh->Mesh->GetVertexData(&VertexsBuffer, VBSize, &IndexBuffer, IBSize);
auto material = Mesh->m_Material;
CMap<int, RHIResourceRef*> textures;
textures[0] = material->m_pTextureArray->m_pTextureArrayView;
for (int i = 0; i < material->m_Textures.size(); i++)
{
textures[i+1] = material->m_Textures[i]->m_pTextureView;
}
MeshDrawCommand* cmd = new MeshDrawCommand(
material->m_pVSShader,
material->m_pPSShader,
Mesh->m_pVertexLayout,
material->m_pTextureArray->m_pSamplerState,
textures,
material->m_pMaterialParamsConstBuffer,
GetWorldMatrix(),
VertexsBuffer,
VBSize,
IndexBuffer,
IBSize);
return cmd;
}
<file_sep>#include "Shader.h"
#include "RHI/IRHI.h"
extern IRHI* g_pRHI;
Shader::Shader(FString file, ShaderType type)
{
m_Type = type;
m_FileName = file;
g_pRHI->CompileShader(type == ShaderType::PS ? "PS" : "VS", file, true, &m_pShader, &m_pShaderBlob);
}
<file_sep>#include "StaticMesh.h"
#include <assimp/Importer.hpp> // C++ importer interface
#include <assimp/scene.h> // Output data structure
#include <assimp/postprocess.h> // Post processing flags
void StaticMesh::LoadFromFile(const char* FileName)
{
Assimp::Importer MeshImporter;
auto AssimpScene = MeshImporter.ReadFile(FileName, aiProcess_Triangulate);
if (!AssimpScene || AssimpScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !AssimpScene->mMeshes)
{
return;
}
for (int i = 0; i < AssimpScene->mNumMeshes; i++)
{
auto CurMesh = AssimpScene->mMeshes[i];
if (CurMesh)
{
auto Vertices = CurMesh->mVertices;
for (int j = 0; j < CurMesh->mNumVertices; j++)
{
//get uv
auto uvList0 = CurMesh->mTextureCoords[0];
auto uvChannelNum0 = CurMesh->mNumUVComponents[0];
auto UV = Vector2D(0, 0);
if (uvList0 && uvChannelNum0 == 2)
{
UV = Vector2D(uvList0[j].x, uvList0[j].y);
}
//get normal
auto normal = Vector3D(0, 0, 0);
if (CurMesh->HasNormals())
{
normal = Vector3D(CurMesh->mNormals[j].x, CurMesh->mNormals[j].y, CurMesh->mNormals[j].z);
}
//make vertex
m_Vertexs.push_back({ Vector3D(Vertices[j].x * 10, Vertices[j].y * 10, (Vertices[j].z * 10)), normal, UV});
}
for (int p = 0; p < CurMesh->mNumFaces; p++)
{
auto AssimpFace = CurMesh->mFaces[p];
for (int q = 0; q < AssimpFace.mNumIndices; q++)
{
m_Indexs.push_back(AssimpFace.mIndices[q]);
}
}
}
break;
}
}
void StaticMesh::GetVertexData(uint8_t** VertexBuffer, uint32_t& VertexBSize, uint8_t** IndexBuffer, uint32_t& IndexBSize)
{
if (!m_Vertexs.empty() && !m_Indexs.empty())
{
*VertexBuffer = (uint8_t*)&m_Vertexs[0];
VertexBSize = m_Vertexs.size() * sizeof(Vertex);
*IndexBuffer = (uint8_t*)&m_Indexs[0];
IndexBSize = m_Indexs.size() * 4;
}
}
<file_sep>#pragma once
#include "EngineCommon.h"
#include "Application/IApplication.h"
#include <Windows.h>
class WinApp : public IApplication
{
public:
WinApp() {}
~WinApp() {}
virtual void Launch() override;
virtual void Init() override;
virtual void Tick() override;
virtual void Exit() override;
virtual IRenderer* GetRenderer() override {return Renderer;}
virtual IRHI* GetRHI() override { return RHI; }
private:
HWND HWnd = nullptr;
IRenderer* Renderer = nullptr;
IRHI* RHI = nullptr;
};
<file_sep>#pragma once
#include "MathDefines.h"
class Vector3D
{
public:
Vector3D() : Vector3D(0, 0, 0) {}
Vector3D(float XIn, float YIn, float ZIn) :
X(XIn),
Y(YIn),
Z(ZIn)
{
}
~Vector3D() {}
class Matrix44 GetMatrix();
float Length()
{
return sqrtf(X * X + Y * Y + Z * Z);
}
Vector3D Normalize()
{
float Size = Length();
return Vector3D(X / Size, Y / Size, Z / Size);
}
Vector3D operator- (const Vector3D& Other) const
{
return Vector3D(X - Other.X, Y - Other.Y, Z - Other.Z);
}
Vector3D operator- () const
{
return Vector3D(-X, -Y, -Z);
}
Vector3D operator+ (const Vector3D& Other) const
{
return Vector3D(X + Other.X, Y + Other.Y, Z + Other.Z);
}
float Dot(const Vector3D& Other) const
{
return X * Other.X + Y * Other.Y + Z * Other.Z;
}
Vector3D Cross(const Vector3D& Other) const
{
return Vector3D(
Y * Other.Z - Other.Y * Z,
Other.X * Z - X * Other.Z,
X * Other.Y - Other.X * Y
);
}
Vector3D operator* (float Num) const
{
return Vector3D(X * Num, Y * Num, Z * Num);
}
public:
float X;
float Y;
float Z;
};
typedef Vector3D Point3D;
typedef Vector3D Color3;<file_sep>#pragma once
#include "EngineCommon.h"
#include "Material/Material.h"
class MeshDrawCommand
{
public:
MeshDrawCommand(Shader* VSShader, Shader* PSShader, RHIResourceRef* Layout, RHIResourceRef* SamplerState, CMap<int, RHIResourceRef*>& Textures, RHIResourceRef* MaterialParams, Matrix44 WorldMatrix, uint8_t* VertexBuffer, uint32_t VertexSize, uint8_t* IndexBuffer, uint32_t IndexSize) :
m_pVSShader(VSShader),
m_pPSShader(PSShader),
m_pVertexLayoutRef(Layout),
m_pVertexBuffer(VertexBuffer),
m_VertexSize(VertexSize),
m_pIndexBuffer(IndexBuffer),
m_IndexSize(IndexSize),
m_pMaterialParamsConstBuffer(MaterialParams),
m_pSamplerState(SamplerState),
m_WorldMatrix(WorldMatrix)
{
swap(m_Textures, Textures);
}
~MeshDrawCommand() {}
void Execute();
private:
Shader* m_pVSShader = nullptr;
Shader* m_pPSShader = nullptr;
RHIResourceRef* m_pVertexLayoutRef = nullptr;
CMap<int, RHIResourceRef*> m_Textures;
RHIResourceRef* m_pSamplerState = nullptr;
RHIResourceRef* m_pMaterialParamsConstBuffer = nullptr;
uint8_t* m_pVertexBuffer = nullptr;
uint32_t m_VertexSize = 0;
uint8_t* m_pIndexBuffer = nullptr;
uint32_t m_IndexSize = 0;
Matrix44 m_WorldMatrix;
};
<file_sep>#include "Vector4D.h"
#include "Matrix44.h"
Vector4D Vector4D::operator* (Matrix44 M)
{
return Vector4D(
X * M[0][0] + Y * M[1][0] + Z * M[2][0] + W * M[3][0],
X * M[0][1] + Y * M[1][1] + Z * M[2][1] + W * M[3][1],
X * M[0][2] + Y * M[1][2] + Z * M[2][2] + W * M[3][2],
X * M[0][3] + Y * M[1][3] + Z * M[2][3] + W * M[3][3]
);
}
Vector4D& Vector4D::operator=(const Vector3D& v3)
{
X = v3.X;
Y = v3.Y;
Z = v3.Z;
W = 1;
return *this;
}
<file_sep>#include "StaticMeshComponent.h"
extern IRHI* g_pRHI;
StaticMeshComponent::StaticMeshComponent(FString meshName, FString materialName)
{
Mesh = new StaticMesh();
if (meshName == "")
{
meshName = "Content/ball.fbx";
}
Mesh->LoadFromFile(meshName.c_str());
if (materialName == "")
{
materialName = "Content/M_Test.json";
}
m_Material = new Material(materialName);
g_pRHI->CreateVertexLayout(m_Material->m_pVSShader->m_pShaderBlob, &m_pVertexLayout);
}
<file_sep>#include "Rotator.h"
#include "Matrix44.h"
//for world to camera
Matrix44 Rotator::GetMatrix()
{
//Roll:Z axis
Matrix44 RollMat = Matrix44::GetIdentity();
RollMat[0][0] = cos(TO_RADIAN(Roll));
RollMat[0][1] = -sin(TO_RADIAN(Roll));
RollMat[1][0] = sin(TO_RADIAN(Roll));
RollMat[1][1] = cos(TO_RADIAN(Roll));
//Yaw:Y axis
Matrix44 YawMat = Matrix44::GetIdentity();
YawMat[0][0] = cos(TO_RADIAN(Yaw));
YawMat[0][2] = sin(TO_RADIAN(Yaw));
YawMat[2][0] = -sin(TO_RADIAN(Yaw));
YawMat[2][2] = cos(TO_RADIAN(Yaw));
//Pitch:X axis
Matrix44 PitchMat = Matrix44::GetIdentity();
PitchMat[1][1] = cos(TO_RADIAN(Pitch));
PitchMat[1][2] = -sin(TO_RADIAN(Pitch));
PitchMat[2][1] = sin(TO_RADIAN(Pitch));
PitchMat[2][2] = cos(TO_RADIAN(Pitch));
return RollMat * PitchMat * YawMat;
}
//for camera to world
Matrix44 Rotator::GetInverseMatrix()
{
//Roll:Z axis
Matrix44 RollMat = Matrix44::GetIdentity();
RollMat[0][0] = cos(TO_RADIAN(-Roll));
RollMat[0][1] = -sin(TO_RADIAN(-Roll));
RollMat[1][0] = sin(TO_RADIAN(-Roll));
RollMat[1][1] = cos(TO_RADIAN(-Roll));
//Yaw:Y axis
Matrix44 YawMat = Matrix44::GetIdentity();
YawMat[0][0] = cos(TO_RADIAN(-Yaw));
YawMat[0][2] = sin(TO_RADIAN(-Yaw));
YawMat[2][0] = -sin(TO_RADIAN(-Yaw));
YawMat[2][2] = cos(TO_RADIAN(-Yaw));
//Pitch:X axis
Matrix44 PitchMat = Matrix44::GetIdentity();
PitchMat[1][1] = cos(TO_RADIAN(-Pitch));
PitchMat[1][2] = -sin(TO_RADIAN(-Pitch));
PitchMat[2][1] = sin(TO_RADIAN(-Pitch));
PitchMat[2][2] = cos(TO_RADIAN(-Pitch));
return YawMat * PitchMat * RollMat;
}<file_sep>#pragma once
#include "EngineCommon.h"
class PointLight
{
public:
PointLight(Vector3D pos, Color3 color) :
m_Position(pos),
m_Color(color)
{}
~PointLight() {};
public:
Vector3D m_Position;
Color3 m_Color;
float m_Strength = 1.f;
};
<file_sep>#pragma once
#include "MathDefines.h"
class Vector2D
{
public:
Vector2D() : Vector2D(0, 0) {}
Vector2D(float XIn, float YIn) : X(XIn), Y(YIn) {}
bool operator==(const Vector2D& Other)
{
return X == Other.X && Y == Other.Y;
}
public:
float X;
float Y;
};
typedef Vector2D Point2D;<file_sep>#include "Map.h"
#include "Scene/PointLight.h"
#include "Scene/DirectionLight.h"
#include "World.h"
#include "Actor.h"
#include "Third/nlohmann_json/json.hpp"
#include "FileSystem/FileUtils.h"
using json = nlohmann::json;
#define JSON2VECTOR3(array) Vector3D(array[0], array[1], array[2])
Map::Map(FString mapFile)
{
m_MatFile = mapFile;
}
void Map::Build(World* world)
{
std::fstream mapFile(m_MatFile);
if (!mapFile)
{
return;
}
json mapConfig = json::parse(mapFile);
if (mapConfig.is_discarded())
{
return;
}
//create actors
auto jsonActors = mapConfig["actors"];
for (json::iterator it = jsonActors.begin(); it != jsonActors.end(); ++it)
{
FString name = it.key();
auto actorJson = it.value();
FString meshName = "";
if (actorJson["mesh"].is_string())
{
meshName = actorJson["mesh"];
}
FString materialName = "";
if (actorJson["material"].is_string())
{
materialName = actorJson["material"];
}
Actor* pActor = new Actor(name, meshName, materialName);
pActor->SetLocation(JSON2VECTOR3(actorJson["position"]));
world->m_Actors.push_back(pActor);
if (actorJson["rotation"].is_array())
{
pActor->SetRotation(JSON2VECTOR3(actorJson["rotation"]));
}
}
//create lights
auto jsonDLight = mapConfig["direction_light"];
auto dLightDir = JSON2VECTOR3(jsonDLight["direction"]);
auto dLightColor = JSON2VECTOR3(jsonDLight["color"]);
DirectionLight* pDLight = new DirectionLight(dLightDir, dLightColor);
world->m_pDirectionLight = pDLight;
auto jsonPLights = mapConfig["point_lights"];
for (json::iterator it = jsonPLights.begin(); it != jsonPLights.end(); ++it)
{
FString name = it.key();
auto lightJson = it.value();
auto position = JSON2VECTOR3(lightJson["position"]);
auto color = JSON2VECTOR3(lightJson["color"]);
PointLight* pPlight = new PointLight(position, color);
world->m_PointLights.push_back(pPlight);
}
}
<file_sep>cbuffer CBufferPerObject : register(b0)
{
row_major matrix GWorld;
row_major matrix GView;
row_major matrix GProj;
row_major matrix GWorldForNormal;
float4 GCameraPosition;
}
struct PointLight
{
float4 Color;
float4 Position;
};
struct DirectionLight
{
float4 Color;
float4 Direction;
};
cbuffer CBufferPerFrame : register(b1)
{
PointLight GPointLights[3];
DirectionLight GDirectionLight;
float4 Time;
}
cbuffer CBufferStable : register(b2)
{
}
struct VertexIn
{
float3 PosIn : POSITION;
float3 Normal : NORMAL;
float2 TexCord : UV;
};
struct VertexOut
{
float4 PosOut : SV_POSITION;
float3 PosW : POSITION;
float3 NormalW : NORMAL;
float2 TexCord : UV;
};<file_sep>#pragma once
#include "MathDefines.h"
class Rotator
{
public:
Rotator() {}
Rotator(float InPitch, float InYaw, float InRoll) :
Pitch(InPitch),
Yaw(InYaw),
Roll(InRoll)
{}
class Matrix44 GetMatrix();
class Matrix44 GetInverseMatrix();
public:
float Pitch = 0.f;
float Yaw = 0.f;
float Roll = 0.f;
};<file_sep>#include "Material.h"
#include "Third/nlohmann_json/json.hpp"
#include "FileSystem/FileUtils.h"
#include "RHI/IRHI.h"
#include "TextureArray.h"
#include "Texture2D.h"
using json = nlohmann::json;
#define JSON2VECTOR3(array) Vector3D(array[0], array[1], array[2])
extern IRHI* g_pRHI;
Material::Material(FString MatFile)
{
m_MatFile = MatFile;
Compile();
InitResources();
}
void Material::Compile()
{
//加载材质配置文件
std::fstream matFile(m_MatFile);
if (!matFile)
{
return;
}
json matConfig = json::parse(matFile);
if (matConfig.is_discarded())
{
return;
}
//配置文件暂时键值对,额外一段自定义代码
//提取参数,生成代码, 填充template
//暂时不生成代码
m_MaterialParams.texIndexBaseColor = 0;
m_MaterialParams.texIndexNormal = 1;
m_MaterialParams.emissiveColor = JSON2VECTOR3(matConfig["emissive_color"]);
m_MaterialParams.metallic = matConfig["metallic"];
m_MaterialParams.specular = matConfig["specular"];
m_MaterialParams.roughness = matConfig["roughness"];
m_TextureArrayFiles.push_back(matConfig["base_color"]);
m_TextureArrayFiles.push_back(matConfig["normal"]);
m_TextureFiles.push_back(matConfig["base_color"]);
m_TextureFiles.push_back(matConfig["normal"]);
//根据配置加入hlsl宏,编译着色器,材质名_GUID.blob保存
m_pVSShader = new Shader("vs_forward", Shader::ShaderType::VS);
m_pPSShader = new Shader("ps_forward", Shader::ShaderType::PS);
}
void Material::InitResources()
{
//根据序列化的GUID,加载blob,创建着色器
//创建贴图,按索引命名
m_pTextureArray = new TextureArray(m_TextureFiles);
for (int i = 0; i < m_TextureFiles.size() && i < 16; i++)
{
m_Textures.push_back(new Texture2D(m_TextureFiles[i], i+1));
}
//创建用于参数的Constbuffer(每个matrerial创建一个,对应template中自动生成的CBufferForMaterial,多个shader变体公用,在MeshDrawCommand中再每个shader变体单独赋值并绑定到着色器
g_pRHI->CreateConstBuffer(&m_MaterialParams, sizeof(m_MaterialParams), &m_pMaterialParamsConstBuffer);
}
void Material::SetFloatParams()
{
}
<file_sep>#pragma once
#include "EngineCommon.h"
#include "RHI/RHIResource.h"
class IRHI
{
public:
virtual bool InitRHI() = 0;
virtual void ReleaseRHI() = 0;
virtual bool CompileShader(FString type, FString file, bool forceCompileFromFile, RHIResourceRef** shaderResource, RHIResourceRef** shaderBlobResources) = 0;
virtual bool CreateConstBuffer(void* data, size_t size, RHIResourceRef** constBuffer) = 0;
virtual bool UpdateConstBuffer(void* data, size_t size, RHIResourceRef* constBuffer) = 0;
virtual bool CreateSamplerState(RHIResourceRef** sampler) = 0;
virtual bool CreateTextureArray(const FArray<FString>& files, RHIResourceRef** textrueArray, RHIResourceRef** textureArrayView) = 0;
virtual bool CreateTexture2D(FString file, RHIResourceRef** textrue, RHIResourceRef** textureView) = 0;
virtual bool CreateVertexLayout(RHIResourceRef* VSBlob, RHIResourceRef** layout) = 0;
virtual bool CreateTextureCube(const FArray<FString>& files, RHIResourceRef** textrueCube, RHIResourceRef** textureCubeView) = 0;
virtual void PSSetConstantBuffers(uint32_t StartSlot, uint32_t NumBuffers, RHIResourceRef* ConstantBuffers) = 0;
virtual void VSSetConstantBuffers(uint32_t StartSlot, uint32_t NumBuffers, RHIResourceRef* ConstantBuffers) = 0;
virtual void SetPSShader(RHIResourceRef* shader) = 0;
virtual void SetVSShader(RHIResourceRef* shader) = 0;
virtual void SetVertexLayout(RHIResourceRef* layout) = 0;
virtual void SetSamplerState(RHIResourceRef* sampler, uint32_t slot) = 0;
virtual void SetShaderResource(RHIResourceRef* resource, uint32_t slot) = 0;
virtual void ClearView() = 0;
virtual void FlushView() = 0;
//state
//temp
virtual bool CreateSkyDepthStencilState(RHIResourceRef** state) = 0;
virtual bool CreateNormalDepthStencilState(RHIResourceRef** state) = 0;
virtual void SetDepthStencilState(RHIResourceRef* state) = 0;
virtual bool DrawIndex(uint8_t* VBuffer, uint32_t& VSize, uint8_t* IBuffer, uint32_t& ISize) = 0;
};
<file_sep>#include "SkySphere.h"
#include "Engine/StaticMesh.h"
#include "Scene/Camera.h"
#include "Scene/World.h"
extern Camera* DefaultCamera;
SkySphere::SkySphere()
{
Mesh = new StaticMesh();
Mesh->LoadFromFile("Content/ball.fbx");
m_pVSShader = new Shader("vs_sky", Shader::ShaderType::VS);
m_pPSShader = new Shader("ps_sky", Shader::ShaderType::PS);
g_pRHI->CreateVertexLayout(m_pVSShader->m_pShaderBlob, &m_pVertexLayout);
FArray<FString> cubeFiles{"Content/skybox/right.jpg.png", "Content/skybox/left.jpg.png" , "Content/skybox/top.jpg.png" , "Content/skybox/bottom.jpg.png" , "Content/skybox/front.jpg.png" , "Content/skybox/back.jpg.png" };
//FArray<FString> cubeFiles(6, "Content/awesomeface.png");
g_pRHI->CreateTextureCube(cubeFiles , &m_pTextrueCube , &m_pTextrueCubeView);
g_pRHI->CreateSamplerState(&m_pSamplerState);
g_pRHI->CreateSkyDepthStencilState(&m_pDepthStencileState);
}
void SkySphere::Draw()
{
uint8_t* VertexsBuffer;
uint32_t VBSize = 0;
uint8_t* IndexBuffer;
uint32_t IBSize = 0;
Mesh->GetVertexData(&VertexsBuffer, VBSize, &IndexBuffer, IBSize);
DefaultCamera->MVPData.World = Matrix44::GetIdentity();
DefaultCamera->MVPData.View = DefaultCamera->GetSkyBoxCameraViewMatrix();
g_pRHI->UpdateConstBuffer(&DefaultCamera->MVPData, sizeof(DefaultCamera->MVPData), DefaultCamera->m_pMVPConstBuffer);
g_pRHI->SetVSShader(m_pVSShader->m_pShader);
g_pRHI->SetPSShader(m_pPSShader->m_pShader);
g_pRHI->SetVertexLayout(m_pVertexLayout);
g_pRHI->SetSamplerState(m_pSamplerState, 0);
g_pRHI->SetShaderResource(m_pTextrueCubeView, 0);
g_pRHI->SetDepthStencilState(m_pDepthStencileState);
g_pRHI->DrawIndex(VertexsBuffer, VBSize, IndexBuffer, IBSize);
}
<file_sep>#pragma once
#include <math.h>
#include <string.h>
#define TO_RADIAN(Degree) (Degree * 3.1415926535897932f / 180.f)<file_sep>#pragma once
#include "MathDefines.h"
class Vector4D
{
public:
Vector4D(float XIn, float YIn, float ZIn, float WIn = 1) :
X(XIn),
Y(YIn),
Z(ZIn),
W(WIn)
{
}
Vector4D() {};
Vector4D operator* (class Matrix44 M);
Vector4D& operator= (const class Vector3D& v3);
public:
float X = 0.f;
float Y = 0.f;
float Z = 0.f;
float W = 0.f;
};<file_sep>#pragma once
#include "Shader/Shader.h"
#include "Engine/GUID.h"
class Material
{
public:
Material(FString MatFile);
~Material() {}
void Compile();
void InitResources();
//set material params
void SetFloatParams();
public:
FString m_MatFile;
GUID m_GUID;
struct MaterialParams
{
float texIndexBaseColor;
float metallic;
float specular;
float roughness;
Vector3D emissiveColor;
float texIndexNormal;
};
MaterialParams m_MaterialParams;
CMap<FString, float> m_MaterialParamsFloat;
FArray<FString> m_TextureFiles;
FArray<FString> m_TextureArrayFiles;
/*RHI resources*/
//const buffers
RHIResourceRef* m_pMaterialParamsConstBuffer;
RHIResourceRef* m_pFloatParamsConstBuffer;
//shader
Shader* m_pVSShader = nullptr;
Shader* m_pPSShader = nullptr;
//textures
class TextureArray* m_pTextureArray = nullptr;
FArray<class Texture2D*> m_Textures;
};
<file_sep>#include "Transform.h"
Matrix44 Transform::GetMatrix()
{
return Matrix44();
}
<file_sep>#pragma once
#include "EngineCommon.h"
#include "InputManager.h"
#include "RHI/IRHI.h"
class Camera
{
public:
Camera();
~Camera() {}
void Update()
{
auto InputMng = InputManager::GetInstance();
Location.Z += InputMng->FrontDelta * ControlMoveSpeed;
Location.X += InputMng->RightDelta * ControlMoveSpeed;
Location.Y += InputMng->UpDelta * ControlMoveSpeed;
Rotation.Pitch += InputMng->DeltaMove.Y * ControlRotSpeed;
Rotation.Yaw += InputMng->DeltaMove.X * ControlRotSpeed;
MVPData.View = GetCameraInverseMatrix();
MVPData.Proj = GetPerspectiveMatrix();
}
Matrix44 GetPerspectiveMatrix()
{
Matrix44 Ret = Matrix44::GetIdentity();
Ret[0][0] = 1 / (WidthHeightRatio * tan(TO_RADIAN(FOV / 2)));
Ret[1][1] = 1.f / tan(TO_RADIAN(FOV / 2));
Ret[2][2] = FarPlane / (FarPlane - NearPlane);
Ret[2][3] = 1;
Ret[3][2] = -FarPlane * NearPlane / (FarPlane - NearPlane);
Ret[3][3] = 0;
return Ret;
}
Matrix44 GetCameraMatrix()
{
Matrix44 Ret = Matrix44::GetIdentity();
Ret[3][0] = Location.X;
Ret[3][1] = Location.Y;
Ret[3][2] = Location.Z;
Ret = Rotation.GetMatrix() * Ret;
return Ret;
}
Matrix44 GetCameraInverseMatrix()
{
Matrix44 Rot = Rotation.GetInverseMatrix();
Matrix44 Trans = Matrix44::GetIdentity();
Trans[3][0] = -Location.X;
Trans[3][1] = -Location.Y;
Trans[3][2] = -Location.Z;
return Trans * Rot;
}
Matrix44 GetSkyBoxCameraViewMatrix()
{
return Rotation.GetInverseMatrix();
}
public:
struct MVP
{
Matrix44 World;
Matrix44 View;
Matrix44 Proj;
Matrix44 WorldForNormal;
Vector4D CamPos;
};
float FOV = 90.f;//Height
float ViewDistance = 1.f;
float WidthHeightRatio = 1.33f;
float NearPlane = 10.f;
float FarPlane = 3000.f;
Vector3D Location{0, 0, -100};
Rotator Rotation{0, 0, 0};
float ControlMoveSpeed = 1.f;
float ControlRotSpeed = 0.02f;
MVP MVPData;
RHIResourceRef* m_pMVPConstBuffer = nullptr;
};<file_sep>#pragma once
class RHIResourceRef
{
public:
RHIResourceRef() {}
RHIResourceRef(void* pRes) : m_pRHIRes(pRes) {}
~RHIResourceRef() {}
template<class T>
static RHIResourceRef* Create(T* pRHIRes)
{
return new RHIResourceRef(pRHIRes);
}
template<class T>
T* Get()
{
return reinterpret_cast<T*>(m_pRHIRes);
}
bool IsValid() { return m_pRHIRes != nullptr; }
private:
void* m_pRHIRes = nullptr;
};
<file_sep>#pragma once
#include "EngineCommon.h"
class InputManager
{
public:
InputManager() {}
~InputManager() {}
static InputManager* GetInstance()
{
static InputManager* Instance = new InputManager();
return Instance;
}
public:
float FrontDelta = 0.f;
float RightDelta = 0.f;
float UpDelta = 0.f;
Vector2D LastMousePos;
Vector2D DeltaMove;
bool bStartTouchMove = false;
};<file_sep>#pragma once
#include "EngineCommon.h"
#include "Engine/StaticMesh.h"
#include "Material/Material.h"
#include "RHI/IRHI.h"
class StaticMeshComponent
{
public:
StaticMeshComponent(FString meshName, FString materialName);
~StaticMeshComponent() {}
public:
public:
StaticMesh* Mesh;
Material* m_Material = nullptr;
RHIResourceRef* m_pVertexLayout = nullptr;
};
<file_sep>#pragma once
#include "MathCommon.h"
class MathUtils
{
public:
static float LineLerp(float Low, float High, float Alpha)
{
Alpha = Alpha < 0 ? 0 : Alpha > 1 ? 1 : Alpha;
return Low + Alpha * (High - Low);
}
static float Clamp(float InVar, float Min, float Max)
{
return InVar < Min ? Min : InVar > Max ? Max : InVar;
}
};<file_sep>#pragma once
#include "EngineCommon.h"
class DirectionLight
{
public:
DirectionLight(Vector3D dir, Color3 color) :
m_Direction(dir),
m_Color(color)
{}
~DirectionLight() {};
public:
Vector3D m_Direction;
Color3 m_Color;
float m_Strength = 1.f;
};
<file_sep>#pragma once
#include "StdCommon.h"
#include "Math/MathCommon.h"
extern class World* GWorld;
extern class IRHI* g_pRHI;<file_sep>#pragma once
class IRenderer
{
public:
virtual void Render() = 0;
virtual void PreRender() = 0;
};
<file_sep>#include "ForwardRenderer.h"
#include "Scene/World.h"
#include "Render/MeshDrawCommand.h"
#include "Scene/Actor.h"
#include "RHI/IRHI.h"
#include "Scene/Camera.h"
#include "Scene/SkySphere.h"
extern Camera* DefaultCamera;
extern IRHI* g_pRHI;
void ForwardRender::PreRender()
{
//设置灯光constbuffer
g_pRHI->PSSetConstantBuffers(1, 1, GWorld->m_pWorldConstBuffer);
g_pRHI->VSSetConstantBuffers(1, 1, GWorld->m_pWorldConstBuffer);
//设置相机constbuffer
g_pRHI->PSSetConstantBuffers(0, 1, DefaultCamera->m_pMVPConstBuffer);
g_pRHI->VSSetConstantBuffers(0, 1, DefaultCamera->m_pMVPConstBuffer);
}
void ForwardRender::Render()
{
//clear view
g_pRHI->ClearView();
//update world constbuffer
g_pRHI->UpdateConstBuffer(&GWorld->m_WorldBufferInfo, sizeof(GWorld->m_WorldBufferInfo), GWorld->m_pWorldConstBuffer);
g_pRHI->SetDepthStencilState(GWorld->m_pDepthStencileState);
FArray<MeshDrawCommand*> commandList;
for (auto actor : GWorld->m_Actors)
{
commandList.push_back(actor->GetMeshDrawCommand());
}
for (auto cmd : commandList)
{
cmd->Execute();
}
GWorld->m_pSky->Draw();
g_pRHI->FlushView();
}
<file_sep>struct MaterialParams
{
float3 TexIndexBaseColor;
float Metallic;
float Specular;
float Roughness;
float3 EmissiveColor;
float3 TexIndexNormal;
};
cbuffer CBufferForMaterial : register(b3)
{
float GTexIndexBaseColor;
float GMetallic;
float GSpecular;
float GRoughness;
float3 GEmissiveColor;
float GTexIndexNormal;
}
Texture2DArray gTexArray : register(t0);
SamplerState gSamLinear : register(s0);
Texture2D gTexSingle1 : register(t1);
MaterialParams GetMaterialParams()
{
MaterialParams ret;
/*ret.TexIndexBaseColor = GTexIndexBaseColor
ret.Metallic = GMetallic;
ret.Specular = GSpecular;
ret.Roughness = GRoughness;
ret.EmissiveColor = GEmissiveColor;
ret.TexIndexNormal = GTexIndexNormal;*/
return ret;
}<file_sep>//common function
//gama correction
float Square(float root)
{
return root * root;
}
float4 LinearToGamma(float4 inColor)
{
return pow(inColor, 0.45);
}
float4 GammaToLinear(float4 inColor)
{
return pow(inColor, 2.2);
}
float4 ToneMap(float4 inColor)
{
float4 outColor = inColor / (float4(1, 1, 1, 1) + inColor);
outColor.a = 1.f;
return outColor;
}
float Get_D_GGX_TR(float3 normal, float3 inLightDir, float3 viewDir, float a)
{
const float PI = 3.14159265;
float3 h = normalize(inLightDir + viewDir);
float n_dot_h = max(dot(normal, h), 0);
float result = a * a / (PI * Square(Square(n_dot_h) * (a * a - 1) + 1));
return result;
}
float Get_G_GGX_Direct(float3 normal, float3 inLightDir, float3 viewDir, float a)
{
float k = Square(1 + a) / 8;
float n_dot_v = max(dot(normal, viewDir), 0);
float n_dot_l = max(dot(normal, inLightDir), 0);
float sub_view = n_dot_v / (k + n_dot_v * (1 - k));
float sub_light = n_dot_l / (k + n_dot_l * (1 - k));
return sub_view * sub_light;
}
float Get_G_GGX_IBL(float3 normal, float3 inLightDir, float3 viewDir, float a)
{
float k = Square(a) / 2;
float n_dot_v = max(dot(normal, viewDir), 0);
float n_dot_l = max(dot(normal, inLightDir), 0);
float sub_view = n_dot_v / (k + n_dot_v * (1 - k));
float sub_light = n_dot_l / (k + n_dot_l * (1 - k));
return sub_view * sub_light;
}
float3 Get_FrenelSchlick(float3 normal, float3 viewDir, float3 baseColor, float metallic)
{
float3 F0 = float3(0.04, 0.04, 0.04);
F0 = lerp(F0, baseColor, metallic);
float n_dot_v = max(dot(normal, viewDir), 0);
return F0 + (1 - F0) * pow(1 - n_dot_v, 5);
}
float3 GetBRDFValue(float D, float3 F, float G, float3 normal, float3 inLightDir, float3 viewDir)
{
return (D * F * G) / (4 * max(dot(normal, inLightDir), 0) * max(dot(normal, viewDir), 0) + 0.001);
}
float3 GetPBRColorDirect(float metallic, float a, float3 radiance, float3 baseColor, float3 normal, float3 inLightDir, float3 viewDir)
{
float D = Get_D_GGX_TR( normal, inLightDir, viewDir, a);
float G = Get_G_GGX_Direct(normal, inLightDir, viewDir, a);
float3 F = Get_FrenelSchlick(normal, viewDir, baseColor, metallic);
float3 BRDF = GetBRDFValue(D, F, G, normal, inLightDir, viewDir);
const float PI = 3.14159265;
float3 ks = F;
float3 kd = float3(1.0, 1.0, 1.0) - ks;
kd = kd * (1 - metallic);
return (kd * baseColor / PI + BRDF) * max(dot(normal, inLightDir), 0) * radiance;
}
float3 GetPBRColorIBL(float metallic, float a, float3 radiance, float3 baseColor, float3 normal, float3 inLightDir, float3 viewDir)
{
}<file_sep>#pragma once
#include "RHI/IRHI.h"
#include "d3d11.h"
#include "d3dcompiler.h"
class FRHIDX11 : public IRHI
{
public:
FRHIDX11() {}
FRHIDX11(HWND InHWnd);
~FRHIDX11();
virtual bool InitRHI() override;
virtual void ReleaseRHI() override;
virtual bool CompileShader(FString type, FString file, bool forceCompileFromFile, RHIResourceRef** shaderResource, RHIResourceRef** shaderBlobResources) override;
virtual bool CreateConstBuffer(void* data, size_t size, RHIResourceRef** constBuffer) override;
virtual bool UpdateConstBuffer(void* data, size_t size, RHIResourceRef* constBuffer) override;
virtual bool CreateSamplerState(RHIResourceRef** sampler) override;
virtual bool CreateTextureArray(const FArray<FString>& files, RHIResourceRef** textrueArray, RHIResourceRef** textureArrayView) override;
virtual bool CreateTexture2D(FString file, RHIResourceRef** textrue, RHIResourceRef** textureView) override;
virtual bool CreateVertexLayout(RHIResourceRef* VSBlob, RHIResourceRef** layout) override;
virtual bool CreateTextureCube(const FArray<FString>& files, RHIResourceRef** textrueCube, RHIResourceRef** textureCubeView) override;
virtual void PSSetConstantBuffers(uint32_t StartSlot, uint32_t NumBuffers, RHIResourceRef* ConstantBuffers) override;
virtual void VSSetConstantBuffers(uint32_t StartSlot, uint32_t NumBuffers, RHIResourceRef* ConstantBuffers) override;
virtual void SetPSShader(RHIResourceRef* shader) override;
virtual void SetVSShader(RHIResourceRef* shader)override;
virtual void SetVertexLayout(RHIResourceRef* layout) override;
virtual void SetSamplerState(RHIResourceRef* sampler, uint32_t slot) override;
virtual void SetShaderResource(RHIResourceRef* resource, uint32_t slot) override;
virtual bool CreateSkyDepthStencilState(RHIResourceRef** state) override;
virtual bool CreateNormalDepthStencilState(RHIResourceRef** state) override;
virtual void SetDepthStencilState(RHIResourceRef* state) override;
virtual void ClearView() override;
virtual void FlushView() override;
virtual bool DrawIndex(uint8_t* VBuffer, uint32_t& VSize, uint8_t* IBuffer, uint32_t& ISize) override;
private:
bool InitDeviceAndContext();
bool InitSwapChain();
bool InitResourceView();
void InitViewPort();
private:
ID3D11Device* Device = nullptr;
ID3D11DeviceContext* Context = nullptr;
D3D_FEATURE_LEVEL FeatureLevel = D3D_FEATURE_LEVEL_11_0;
IDXGISwapChain* SwapChain = nullptr;
ID3D11RenderTargetView* RenderTargetView = nullptr;
ID3D11DepthStencilView* DepthStencilView = nullptr;
HWND HWnd = nullptr;
bool bEnableMSAA = true;
};
| 41cf8d9c6fe9e94ebc87222ed3a27e053eeb529e | [
"Markdown",
"C++",
"C",
"HLSL"
] | 74 | Markdown | XuJinglong/GameEngine | 2b228d8e5115378a9f9c1c9da79f4cb8b4a4f1ea | bb3daf3c148b519e9be564d6a905d0e9be754a08 |
refs/heads/main | <repo_name>vcolofati/chat<file_sep>/lib/utils/hash_generator.dart
import 'dart:convert';
import 'package:crypto/crypto.dart';
class HashGenerator {
static String genHash(String s1, String s2) {
if (s1.compareTo(s2) > 0)
return md5
.convert(utf8.encode("$s1${s1.length}$s2${s2.length}"))
.toString();
else
return md5
.convert(utf8.encode("$s2${s2.length}$s1${s1.length}"))
.toString();
}
}
<file_sep>/lib/widgets/message_bubble.dart
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class MessageBubble extends StatelessWidget {
final Key? key;
final String message;
final DateTime hour;
final bool belongsToMe;
MessageBubble(this.message, this.hour, this.belongsToMe, {this.key})
: super(key: key);
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment:
belongsToMe ? MainAxisAlignment.end : MainAxisAlignment.start,
children: [
Container(
decoration: BoxDecoration(
color:
belongsToMe ? Colors.grey[300] : Theme.of(context).accentColor,
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(12),
topRight: const Radius.circular(12),
bottomLeft: belongsToMe
? const Radius.circular(12)
: const Radius.circular(0),
bottomRight: belongsToMe
? const Radius.circular(0)
: const Radius.circular(12),
),
),
width: 250,
margin: const EdgeInsets.symmetric(
vertical: 4,
horizontal: 8,
),
padding: const EdgeInsets.symmetric(
vertical: 10,
horizontal: 16,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: Text(
message,
style: TextStyle(
color: belongsToMe
? Colors.black
: Theme.of(context).accentTextTheme.headline1?.color,
),
textAlign: TextAlign.start,
),
),
Text(
DateFormat('HH:mm').format(hour),
style: TextStyle(
color: belongsToMe ? Colors.grey : Colors.amber,
),
)
],
),
)
],
);
}
}
<file_sep>/README.md
# chat
A simple chat project using Firestore.
## Installation
### Android
Requires Android app in Firebase, after that follow firebase instructions to register app,
download google-services.json to your project root and add firebase SDK to project.
### iOS
Requires iOS app in Firebase, after that follow firebase instructions to register app,
download GoogleService-info.plist to your project root and add firebase SDK to project.
Use flutter pub get to install packages required.
```
flutter pub get
```
<file_sep>/lib/widgets/custom_dropdown_menu.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class CustomDropDownMenu extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DropdownButtonHideUnderline(
child: DropdownButton(
icon: Icon(
Icons.more_vert,
color: Theme.of(context).primaryIconTheme.color,
),
items: [
DropdownMenuItem(
value: 'logout',
child: Container(
child: Row(
children: [
const Icon(
Icons.exit_to_app,
color: Colors.black,
),
const SizedBox(width: 8),
const Text('Sair'),
],
),
),
),
],
onChanged: (item) {
if (item == 'logout') FirebaseAuth.instance.signOut();
},
),
);
}
}
<file_sep>/lib/screens/chat_screen.dart
import 'package:chat/utils/hash_generator.dart';
import 'package:chat/widgets/custom_dropdown_menu.dart';
import 'package:chat/widgets/messages.dart';
import 'package:chat/widgets/new_message.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class ChatScreen extends StatelessWidget {
final User user;
final QueryDocumentSnapshot friend;
ChatScreen(this.user, this.friend);
@override
Widget build(BuildContext context) {
CollectionReference chat = FirebaseFirestore.instance
.collection('chats')
.doc(HashGenerator.genHash(user.uid, friend.id))
.collection('messages');
return Scaffold(
appBar: AppBar(
title: Text(friend.get('name')),
actions: [
CustomDropDownMenu(),
],
),
body: Container(
child: Column(
children: [
Expanded(child: Messages(chat, user)),
NewMessage(chat, user),
],
),
),
);
}
}
<file_sep>/lib/screens/chats_screen.dart
import 'package:chat/screens/chat_screen.dart';
import 'package:chat/widgets/custom_dropdown_menu.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class ChatsScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
CollectionReference users = FirebaseFirestore.instance.collection('users');
User user = FirebaseAuth.instance.currentUser!;
return Scaffold(
appBar: AppBar(
title: Text('Amigos'),
actions: [CustomDropDownMenu()],
),
body: StreamBuilder<QuerySnapshot>(
stream: users.orderBy('name').snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
final usersList = snapshot.data?.docs;
return ListView.builder(
itemCount: usersList!.length,
itemBuilder: (context, i) {
if (usersList[i].id == user.uid) {
return const SizedBox.shrink();
}
final QueryDocumentSnapshot friend = usersList[i];
return Card(
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChatScreen(user, friend),
),
);
},
child: Row(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: CircleAvatar(
backgroundImage:
NetworkImage(friend.get('imageUrl')),
),
),
Text(
friend.get('name'),
),
],
),
),
);
});
}),
);
}
}
<file_sep>/lib/widgets/messages.dart
import 'package:chat/widgets/message_bubble.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class Messages extends StatelessWidget {
final CollectionReference chat;
final User user;
Messages(this.chat, this.user);
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: chat.orderBy('createdAt', descending: true).snapshots(),
builder: (ctx, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
final chatDocs = snapshot.data?.docs;
return ListView.builder(
reverse: true,
itemCount: chatDocs?.length,
itemBuilder: (ctx, i) => MessageBubble(
chatDocs?[i].get('text'),
chatDocs?[i].get('createdAt').toDate(),
chatDocs?[i].get('userId') == user.uid,
key: ValueKey(chatDocs?[i].id),
),
);
},
);
}
}
| afc529e5cc05df4ed984758b1c8ccbc01f069d80 | [
"Markdown",
"Dart"
] | 7 | Markdown | vcolofati/chat | 0a663068975b7462dd5c3a8cf21f1b765b7f637d | 5080d75a62c5f2bd62512161c8f5547f6b9e8026 |
refs/heads/master | <file_sep>
+ [Security Analytics]
+ [Security Enforcement]
+ [ISV Syslog References]
+ [Embedded OCC]
[Security Enforcement]: ./security-enforcement.html "Security Enforcement"
[Security Analytics]: ./security-analytics.html "Security Analytics"
[Embedded OCC]: ./embedded-occ.html "Embedded OCC"
[ISV Syslog References]: ./isv-syslog-references.html "ISV Syslog References"
[Common Guidance]: #common-guidance-and-requirements "Common Guidance"
[API Test Client]: ../../docs/api/getting_started/api_test_client.html "test client"
[Auth Principals]: ../../docs/api/getting_started/design_principles.html#authentication "Authentication"
[User Agent]: ../../docs/api/getting_started/design_principles.html#user-agent "User-Agent"
[Pagination]: ../../docs/api/getting_started/design_principles.html#pagination "Pagination"
[Rate Limiting]: ../../docs/api/getting_started/design_principles.html#rate-limiting "Rate Limiting"
[System Log API]: ../../docs/api/resources/system_log.html "System Log API"
[Users API]: ../../docs/api/resources/users.html "Users API"
[Groups API]: ../../docs/api/resources/groups.html "Groups API"
[Apps API]: ../../docs/api/resources/apps.html "Apps API"
[appUser Object]: ../../docs/api/resources/apps.html#application-user-model "App User Object"
[appGroup Object]: ../../docs/api/resources/apps.html#application-group-model "App Group Object"
[API endpoints]: ../../documentation/index.html "API Endpoints"
[SCIM Standards]: ../../standards/SCIM/index.html "SCIM Standards"
[Okta Cloud Connect]: https://www.okta.com/partners/okta-cloud-connect "Okta Cloud Connect"
[Getting a token]: https://developer.okta.com/docs/api/getting_started/getting_a_token.html "Getting a token"
| 9b84afc354decf82b9534f7ec0894bfbfa593602 | [
"Markdown"
] | 1 | Markdown | johntomcy/okta.github.io | cd8a3a87323a9e3345b2de23c9c000a03dd4caa7 | 0e76b78a9690503705ea73eb23ba5260f50c7417 |
refs/heads/master | <file_sep>import { FW } from './fw';
const FWVAST = {};
FWVAST.hasDOMParser = function () {
if (typeof window.DOMParser !== 'undefined') {
return true;
}
return false;
};
FWVAST.vastReadableTime = function (time) {
if (typeof time === 'number' && time >= 0) {
let seconds = 0;
let minutes = 0;
let hours = 0;
let ms = Math.floor(time % 1000);
if (ms === 0) {
ms = '000';
} else if (ms < 10) {
ms = '00' + ms;
} else if (ms < 100) {
ms = '0' + ms;
} else {
ms = ms.toString();
}
seconds = Math.floor(time * 1.0 / 1000);
if (seconds > 59) {
minutes = Math.floor(seconds * 1.0 / 60);
seconds = seconds - (minutes * 60);
}
if (seconds === 0) {
seconds = '00';
} else if (seconds < 10) {
seconds = '0' + seconds;
} else {
seconds = seconds.toString();
}
if (minutes > 59) {
hours = Math.floor(minutes * 1.0 / 60);
minutes = minutes - (hours * 60);
}
if (minutes === 0) {
minutes = '00';
} else if (minutes < 10) {
minutes = '0' + minutes;
} else {
minutes = minutes.toString();
}
if (hours === 0) {
hours = '00';
} else if (hours < 10) {
hours = '0' + hours;
} else {
if (hours > 23) {
hours = '00';
} else {
hours = hours.toString();
}
}
return hours + ':' + minutes + ':' + seconds + '.' + ms;
} else {
return '00:00:00.000';
}
};
FWVAST.generateCacheBusting = function () {
let text = '';
let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 8; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
FWVAST.getNodeValue = function (element, http) {
let childNodes = element.childNodes;
let value = '';
// sometimes we have may several nodes - some of which may hold whitespaces
for (let i = 0, len = childNodes.length; i < len; i++) {
if (childNodes[i] && childNodes[i].textContent) {
value += childNodes[i].textContent.trim();
}
}
if (value) {
// in case we have some leftovers CDATA - mainly for VPAID
let pattern = /^<!\[CDATA\[.*\]\]>$/i;
if (pattern.test(value)) {
value = value.replace('<![CDATA[', '').replace(']]>', '');
}
if (http) {
let httpPattern = /^(https?:)?\/\//i;
if (httpPattern.test(value)) {
return value;
}
} else {
return value;
}
}
return null;
};
FWVAST.RFC3986EncodeURIComponent = function (str) {
return encodeURIComponent(str).replace(/[!'()*]/g, (c) => {
return '%' + c.charCodeAt(0).toString(16);
});
};
FWVAST.isValidDuration = function (duration) {
// HH:MM:SS or HH:MM:SS.mmm
let skipPattern = /^\d+:\d+:\d+(\.\d+)?$/i;
if (skipPattern.test(duration)) {
return true;
}
return false;
};
FWVAST.convertDurationToSeconds = function (duration) {
// duration is HH:MM:SS or HH:MM:SS.mmm
// remove .mmm
let splitNoMS = duration.split('.');
splitNoMS = splitNoMS[0];
let splitTime = splitNoMS.split(':');
let seconds = 0;
seconds = (parseInt(splitTime[0]) * 60 * 60) + (parseInt(splitTime[1]) * 60) +
parseInt(splitTime[2]);
return seconds;
};
FWVAST.isValidOffset = function (offset) {
// HH:MM:SS or HH:MM:SS.mmm
let skipPattern1 = /^\d+:\d+:\d+(\.\d+)?$/i;
// n%
let skipPattern2 = /^\d+%$/i;
if (skipPattern1.test(offset) || skipPattern2.test(offset)) {
return true;
}
return false;
};
FWVAST.convertOffsetToSeconds = function (offset, duration) {
// HH:MM:SS or HH:MM:SS.mmm
let skipPattern1 = /^\d+:\d+:\d+(\.\d+)?$/i;
// n%
let skipPattern2 = /^\d+%$/i;
let seconds = 0;
if (skipPattern1.test(offset)) {
// remove .mmm
let splitNoMS = offset.split('.');
splitNoMS = splitNoMS[0];
let splitTime = splitNoMS.split(':');
seconds = (parseInt(splitTime[0]) * 60 * 60) + (parseInt(splitTime[1]) * 60) + parseInt(splitTime[2]);
} else if (skipPattern2.test(offset) && duration > 0) {
let percent = offset.split('%');
percent = parseInt(percent[0]);
seconds = Math.round((duration * percent) / 100);
}
return seconds;
};
FWVAST.dispatchPingEvent = function (event) {
if (event) {
let element;
if (this.adIsLinear && this.vastPlayer) {
element = this.vastPlayer;
} else if (!this.adIsLinear && this.nonLinearContainer) {
element = this.nonLinearContainer;
}
if (element) {
if (Array.isArray(event)) {
event.forEach((currentEvent) => {
FW.createStdEvent(currentEvent, element);
});
} else {
FW.createStdEvent(event, element);
}
}
}
};
FWVAST.logPerformance = function (data) {
if (window.performance && typeof window.performance.now === 'function') {
let output = '';
if (data) {
output += data;
}
FW.log(output + ' - ' + Math.round(window.performance.now()) + ' ms');
}
};
FWVAST.logVideoEvents = function (video) {
let events = ['loadstart', 'durationchange',
'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough'];
events.forEach((value) => {
video.addEventListener(value, (e) => {
if (e && e.type) {
FW.log('RMP-VAST: content player event - ' + e.type);
}
});
});
};
FWVAST.filterParams = function (params) {
let defaultParams = {
ajaxTimeout: 8000,
creativeLoadTimeout: 10000,
ajaxWithCredentials: false,
maxNumRedirects: 4,
pauseOnClick: true,
skipMessage: 'Skip ad',
skipWaitingMessage: 'Skip ad in',
textForClickUIOnMobile: 'Learn more',
enableVpaid: true,
vpaidSettings: {
width: 640,
height: 360,
viewMode: 'normal',
desiredBitrate: 500
}
};
this.params = defaultParams;
if (params && !FW.isEmptyObject(params)) {
if (typeof params.ajaxTimeout === 'number' && params.ajaxTimeout > 0) {
this.params.ajaxTimeout = params.ajaxTimeout;
}
if (typeof params.creativeLoadTimeout === 'number' && params.creativeLoadTimeout > 0) {
this.params.creativeLoadTimeout = params.creativeLoadTimeout;
}
if (typeof params.ajaxWithCredentials === 'boolean') {
this.params.ajaxWithCredentials = params.ajaxWithCredentials;
}
if (typeof params.maxNumRedirects === 'number' && params.maxNumRedirects > 0 && params.maxNumRedirects !== 4) {
this.params.maxNumRedirects = params.maxNumRedirects;
}
if (typeof params.pauseOnClick === 'boolean') {
this.params.pauseOnClick = params.pauseOnClick;
}
if (typeof params.skipMessage === 'string') {
this.params.skipMessage = params.skipMessage;
}
if (typeof params.skipWaitingMessage === 'string') {
this.params.skipWaitingMessage = params.skipWaitingMessage;
}
if (typeof params.textForClickUIOnMobile === 'string') {
this.params.textForClickUIOnMobile = params.textForClickUIOnMobile;
}
if (typeof params.enableVpaid === 'boolean') {
this.params.enableVpaid = params.enableVpaid;
}
if (typeof params.vpaidSettings === 'object') {
if (typeof params.vpaidSettings.width === 'number') {
this.params.vpaidSettings.width = params.vpaidSettings.width;
}
if (typeof params.vpaidSettings.height === 'number') {
this.params.vpaidSettings.height = params.vpaidSettings.height;
}
if (typeof params.vpaidSettings.viewMode === 'string') {
this.params.vpaidSettings.viewMode = params.vpaidSettings.viewMode;
}
if (typeof params.vpaidSettings.desiredBitrate === 'number') {
this.params.vpaidSettings.desiredBitrate = params.vpaidSettings.desiredBitrate;
}
}
}
};
export { FWVAST };
<file_sep>const FW = {};
FW.nullFn = function () {
return null;
};
FW.addClass = function (element, className) {
if (element && typeof className === 'string') {
if (element.className) {
if (element.className.indexOf(className) === -1) {
element.className = (element.className + ' ' + className).replace(/\s\s+/g, ' ');
}
} else {
element.className = className;
}
}
};
FW.removeClass = function (element, className) {
if (element && typeof className === 'string') {
if (element.className.indexOf(className) > -1) {
element.className = (element.className.replace(className, '')).replace(/\s\s+/g, ' ');
}
}
};
FW.createStdEvent = function (eventName, element) {
let event;
if (element) {
if (typeof window.Event === 'function') {
try {
event = new Event(eventName);
element.dispatchEvent(event);
} catch (e) {
FW.trace(e);
}
} else {
try {
event = document.createEvent('Event');
event.initEvent(eventName, true, true);
element.dispatchEvent(event);
} catch (e) {
FW.trace(e);
}
}
}
};
var _getComputedStyle = function (element, style) {
let propertyValue = '';
if (element && typeof window.getComputedStyle === 'function') {
let cs = window.getComputedStyle(element, null);
if (cs) {
propertyValue = cs.getPropertyValue(style);
propertyValue = propertyValue.toString().toLowerCase();
}
}
return propertyValue;
};
var _getStyleAttributeData = function (element, style) {
let styleAttributeData = _getComputedStyle(element, style) || 0;
styleAttributeData = styleAttributeData.toString();
if (styleAttributeData.indexOf('px') > -1) {
styleAttributeData = styleAttributeData.replace('px', '');
}
return parseFloat(styleAttributeData);
};
FW.getWidth = function (element) {
if (element) {
if (typeof element.offsetWidth === 'number' && element.offsetWidth !== 0) {
return element.offsetWidth;
} else {
return _getStyleAttributeData(element, 'width');
}
}
return 0;
};
FW.show = function (element) {
if (element) {
element.style.display = 'block';
}
};
FW.hide = function (element) {
if (element) {
element.style.display = 'none';
}
};
FW.isEmptyObject = function (obj) {
if (Object.keys(obj).length === 0 && obj.constructor === Object) {
return true;
}
return false;
};
FW.ajax = function (url, timeout, returnData, withCredentials) {
return new Promise((resolve, reject) => {
if (window.XMLHttpRequest) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.timeout = timeout;
if (withCredentials) {
xhr.withCredentials = true;
}
xhr.onloadend = function () {
if (typeof xhr.status === 'number' && xhr.status >= 200 && xhr.status < 300) {
if (typeof xhr.responseText === 'string' && xhr.responseText !== '') {
if (returnData) {
resolve(xhr.responseText);
} else {
resolve();
}
} else {
reject();
}
} else {
reject();
}
};
xhr.ontimeout = function () {
FW.log('RMP: XMLHttpRequest timeout');
reject();
};
xhr.send(null);
} else {
reject();
}
});
};
FW.log = function (data) {
if (data && window.console && typeof window.console.log === 'function') {
window.console.log(data);
}
};
FW.trace = function (data) {
if (data && window.console && typeof window.console.trace === 'function') {
window.console.trace(data);
}
};
FW.playPromise = function (video) {
if (video) {
let playPromise = video.play();
// on Chrome 50+ play() returns a promise
// https://developers.google.com/web/updates/2016/03/play-returns-promise
// but not all browsers support this - so we just catch the potential Chrome error that
// may result if pause() is called in between - pause should overwrite play
// and in this case causes a promise rejection
if (playPromise !== undefined) {
playPromise.then(() => {
if (DEBUG) {
FW.log('RMP: playPromise on content has resolved');
}
}).catch((e) => {
if (DEBUG) {
FW.log(e);
FW.log('RMP: playPromise on content has been rejected');
}
});
}
}
};
export { FW }; | 6d7119c37d7903c0cb515aa77f65c280a86bce06 | [
"JavaScript"
] | 2 | JavaScript | DigitalsunrayMedia/rmp-vast | 1e94494213164415368b6d92d8c4e8450d4637ec | 7c75cf1d29aab7c1b4c8e8fad71184edaf69ccfd |
refs/heads/master | <repo_name>jonolsu/personalutilities<file_sep>/shapefileutilities.R
createshapefile <- function(inputfilepath, outputfilepath)
{
library(shapefiles)
df <- read.csv(inputfilepath)
dd <- getlongformat(df)
ddTable <- df[,c(1,1)]
names(ddTable) <- c("Id","Name")
ddShapefile <- shapefiles::convert.to.shapefile(dd,ddTable,"Id",5)
write.shapefile(ddShapefile,outputfilepath,arcgis=T)
}
getlongformat <- function(df)
{
dfout <- data.frame(Id=character(0),X=numeric(0),Y=numeric(0))
for(i in 1:nrow(df))
{
for(j in 1:4)
{
newrow <- df[i,c(1,(j*2):(j*2+1))]
names(newrow) <- c("Id","X","Y")
dfout <- rbind(dfout,newrow)
}
}
dfout
}
#createshapefile(inputfilepath="c:/temp/Block_Vertices.csv")<file_sep>/sacs.R
renwebfacts_wc <- function(pathname = "c:/temp/",filename="renwebfacts.csv")
{
# adapted from http://www.r-bloggers.com/building-wordclouds-in-r/
library(tm)
library(SnowballC)
library(wordcloud)
set.seed(42)
rf <- read.csv(paste0(pathname,filename), stringsAsFactors = FALSE)
#Question Word Cloud
png(paste0(pathname,"QuestionWC.png"), width=6, height=6, units="in", res=300)
questionCorpus <- tm::Corpus(VectorSource(rf$question[rf$type == "question"]))
questionCorpus <- tm::tm_map(questionCorpus, PlainTextDocument)
questionCorpus <- tm::tm_map(questionCorpus, removePunctuation)
questionCorpus <- tm::tm_map(questionCorpus, removeWords, stopwords('english'))
questionCorpus <- tm::tm_map(questionCorpus, stemDocument)
questionCorpus <- tm_map(questionCorpus, removeWords, c('can','Can', 'renweb', 'RenWeb', stopwords('english')))
wordcloud::wordcloud(questionCorpus, max.words = 200, random.order = FALSE, colors=brewer.pal(8, "Dark2"))
dev.off()
#Answer Word Cloud
png(paste0(pathname,"AnswerWC.png"), width=6, height=6, units="in", res=300)
answerCorpus <- tm::Corpus(VectorSource(rf$answer[rf$type == "question"]))
answerCorpus <- tm::tm_map(answerCorpus, PlainTextDocument)
answerCorpus <- tm::tm_map(answerCorpus, removePunctuation)
answerCorpus <- tm::tm_map(answerCorpus, removeWords, stopwords('english'))
answerCorpus <- tm::tm_map(answerCorpus, stemDocument)
answerCorpus <- tm_map(answerCorpus, removeWords, c('RenWeb', 'school','can','Can',stopwords('english')))
wordcloud::wordcloud(answerCorpus, max.words = 200, random.order = FALSE, colors=brewer.pal(8, "Dark2"))
dev.off()
#All Word Cloud
png(paste0(pathname,"AllWC.png"), width=6, height=6, units="in", res=300)
allCorpus <- tm::Corpus(VectorSource(paste(rf$question,rf$answer)))
allCorpus <- tm::tm_map(allCorpus, PlainTextDocument)
allCorpus <- tm::tm_map(allCorpus, removePunctuation)
allCorpus <- tm::tm_map(allCorpus, removeWords, stopwords('english'))
allCorpus <- tm::tm_map(allCorpus, stemDocument)
allCorpus <- tm_map(allCorpus, removeWords, c('RenWeb','can','Can',stopwords('english')))
wordcloud::wordcloud(allCorpus, max.words = 200, random.order = FALSE, colors=brewer.pal(8, "Dark2"))
dev.off()
}
| 0a57f714ab6615177375c65d147c55f8456da257 | [
"R"
] | 2 | R | jonolsu/personalutilities | 1dfd78f01ea8997fecebbfc0b13c66a0433567ef | 23da8d63f917b64578caa3191234e867a194c118 |
refs/heads/master | <file_sep>set nocompatible " be iMproved, required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'
Plugin 'scrooloose/nerdtree'
Plugin 'jistr/vim-nerdtree-tabs'
Plugin 'majutsushi/tagbar'
Plugin 'bling/vim-airline'
Plugin 'webdevel/tabulous'
Plugin 'ctrlpvim/ctrlp.vim'
Plugin 'tpope/vim-fugitive'
Plugin 'airblade/vim-gitgutter'
Plugin 'vim-scripts/SearchComplete'
Plugin 'scrooloose/syntastic'
Plugin 'davidhalter/jedi-vim'
Plugin 'ervandew/supertab'
Plugin 'tpope/vim-surround'
Plugin 'mileszs/ack.vim'
Plugin 'yggdroot/indentline'
" ...
call vundle#end() " required
filetype plugin indent on " required
" Map the leader to ','
let mapleader = ","
let g:mapleader = ","
" Sets how many lines of history VIM has to remember
set history=500
" Set to auto read when a file is changed from the outside
set autoread
" :W sudo saves the file
" (useful for handling the permission-denied error)
" command W w !sudo tee % > /dev/null
" turn syntax highlighting on by default
syntax on
set encoding=utf-8
" Set 7 lines to the cursor - when moving vertically using j/k
set so=7
" Turn on the WiLd menu for command <TAB> completion
set wildmenu
" Ignore compiled files and version control files
set wildignore=*.o,*~,*.pyc,*.javac,*/.git/*,*/.hg/*,*/.svn/*,*/.DS_Store
"Always show current position
set ruler
" Height of the command bar
set cmdheight=2
" A buffer becomes hidden when it is abandoned
set hid
" Configure backspace so it acts as it should act
set backspace=eol,start,indent
set whichwrap+=<,>,h,l
" Ignore case when searching
set ignorecase
" When searching try to be smart about cases
set smartcase
" Highlight search results
set hlsearch
" Makes search act like search in modern browsers
set incsearch
" Don't redraw while executing macros (good performance config)
set lazyredraw
" For regular expressions turn magic on
set magic
" Show matching brackets when text indicator is over them
set showmatch
" How many tenths of a second to blink when matching brackets
set mat=2
" Allow selecting by mouse
set mouse=a
" No annoying sound on errors
set noerrorbells
set novisualbell
set t_vb=
set tm=500
" do NOT put a carriage return at the end of the last line! if you are programming
" for the web the default will cause http headers to be sent. that's bad.
set binary noeol
" highlight same variable names
autocmd CursorMoved * exe printf('match IncSearch /\V\<%s\>/', escape(expand('<cword>'), '/\'))
" Properly disable sound on errors on MacVim
if has("gui_macvim")
autocmd GUIEnter * set vb t_vb=
endif
" Enable 256 colors palette in Gnome Terminal
if $COLORTERM == 'gnome-terminal'
set t_Co=256
endif
try
colorscheme desert
catch
endtry
set background=dark
" Set extra options when running in GUI mode
if has("gui_running")
set guioptions-=T
set guioptions-=e
set t_Co=256
set guitablabel=%M\ %t
endif
" Show line numbers + colour
set nu
highlight LineNr guifg=#666666
" Turn backup off, since most stuff is on version control
set nobackup
set nowb
set noswapfile
" Use spaces instead of tabs
set expandtab
" Be smart when using tabs ;)
set smarttab
" 1 tab == 4 spaces
set shiftwidth=4
set tabstop=4
" Linebreak on 500 characters
set lbr
set tw=500
set ai "Auto indent
set si "Smart indent
set wrap "Wrap lines
" Smart way to move between windows
map <C-j> <C-W>j
map <C-k> <C-W>k
map <C-h> <C-W>h
map <C-l> <C-W>l
" Close the current buffer
map <leader>bd :Bclose<cr>:tabclose<cr>gT
" Useful mappings for managing tabs
map <leader>tn :tabnew<cr>
map <leader>to :tabonly<cr>
map <leader>tc :tabclose<cr>
map <leader>tm :tabmove
map <leader><Right> :tabnext<cr><Esc>
map <leader><Left> :tabprevious<cr><Esc>
" Return to last edit position when opening files (You want this!)
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
" Always show the status line
set laststatus=2
" Format the status line
set statusline=\ %{HasPaste()}%F%m%r%h\ %w\ \ CWD:\ %r%{getcwd()}%h\ \ \ Line:\ %l\ \ Column:\ %c
" Remap VIM 0 to first non-blank character
map 0 ^
" Move a line of text using ALT+[jk] or Command+[jk] on mac
nmap <M-j> mz:m+<cr>`z
nmap <M-k> mz:m-2<cr>`z
vmap <M-j> :m'>+<cr>`<my`>mzgv`yo`z
vmap <M-k> :m'<-2<cr>`>my`<mzgv`yo`z
if has("mac") || has("macunix")
nmap <D-j> <M-j>
nmap <D-k> <M-k>
vmap <D-j> <M-j>
vmap <D-k> <M-k>
endif
" Delete trailing white space on save, useful for some filetypes ;)
fun! CleanExtraSpaces()
let save_cursor = getpos(".")
let old_query = getreg('/')
silent! %s/\s\+$//e
call setpos('.', save_cursor)
call setreg('/', old_query)
endfun
if has("autocmd")
autocmd BufWritePre *.txt,*.js,*.py,*.wiki,*.sh,*.java,*.yaml,*.ini,*.conf :call CleanExtraSpaces()
endif
" Pressing ,ss will toggle and untoggle spell checking
map <leader>ss :setlocal spell!<cr>
" Remove the Windows ^M - when the encodings gets messed up
noremap <Leader>m mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm
" Quickly open a buffer for scribble
map <leader>q :e ~/buffer<cr>
" Toggle paste mode on and off
map <leader>pp :setlocal paste!<cr>
" Returns true if paste mode is enabled
function! HasPaste()
if &paste
return 'PASTE MODE '
endif
return ''
endfunction
" Don't close window, when deleting a buffer
command! Bclose call <SID>BufcloseCloseIt()
function! <SID>BufcloseCloseIt()
let l:currentBufNum = bufnr("%")
let l:alternateBufNum = bufnr("#")
if buflisted(l:alternateBufNum)
buffer #
else
bnext
endif
if bufnr("%") == l:currentBufNum
new
endif
if buflisted(l:currentBufNum)
execute("bdelete! ".l:currentBufNum)
endif
endfunction
function! CmdLine(str)
exe "menu Foo.Bar :" . a:str
emenu Foo.Bar
unmenu Foo
endfunction
function! VisualSelection(direction, extra_filter) range
let l:saved_reg = @"
execute "normal! vgvy"
let l:pattern = escape(@", "\\/.*'$^~[]")
let l:pattern = substitute(l:pattern, "\n$", "", "")
if a:direction == 'gv'
call CmdLine("Ack '" . l:pattern . "' " )
elseif a:direction == 'replace'
call CmdLine("%s" . '/'. l:pattern . '/')
endif
let @/ = l:pattern
let @" = l:saved_reg
endfunction
" ipdb debug shortcut
ab ipdb import ipdb; ipdb.set_trace()
" Make window split movement easier (Ctrl+Shift+arrows)
noremap <C-S-Down> <C-w>j
noremap <C-S-Up> <C-w>k
noremap <C-S-Right> <C-w>l
noremap <C-S-Left> <C-w>h
""""""""""""""""""""""""""""""
" => Python section
""""""""""""""""""""""""""""""
let python_highlight_all = 1
au FileType python syn keyword pythonDecorator True None False self
au BufNewFile,BufRead *.jinja set syntax=htmljinja
au BufNewFile,BufRead *.mako set ft=mako
au FileType python map <buffer> F :set foldmethod=indent<cr>
au FileType python inoremap <buffer> $r return
au FileType python inoremap <buffer> $i import
au FileType python inoremap <buffer> $p print
au FileType python inoremap <buffer> $f #--- <esc>a
au FileType python map <buffer> <leader>1 /class
au FileType python map <buffer> <leader>2 /def
au FileType python map <buffer> <leader>C ?class
au FileType python map <buffer> <leader>D ?def
au FileType python set cindent
au FileType python set cinkeys-=0#
au FileType python set indentkeys-=0#
""""""""""""""""""""""""""""""
" => JavaScript section
"""""""""""""""""""""""""""""""
au FileType javascript call JavaScriptFold()
au FileType javascript setl fen
au FileType javascript setl nocindent
au FileType javascript imap <c-t> $log();<esc>hi
au FileType javascript imap <c-a> alert();<esc>hi
au FileType javascript inoremap <buffer> $r return
au FileType javascript inoremap <buffer> $f //--- PH<esc>FP2xi
function! JavaScriptFold()
setl foldmethod=syntax
setl foldlevelstart=1
syn region foldBraces start=/{/ end=/}/ transparent fold keepend extend
function! FoldText()
return substitute(getline(v:foldstart), '{.*', '{...}', '')
endfunction
setl foldtext=FoldText()
endfunction
""""""""""""""""""""""""""""""
" => Shell section
""""""""""""""""""""""""""""""
if exists('$TMUX')
if has('nvim')
set termguicolors
else
set term=screen-256color
endif
endif
""""""""""""""""""""""""""""""
" => Twig section
""""""""""""""""""""""""""""""
autocmd BufRead *.twig set syntax=html filetype=html
""""""""""""""""""""""""""""""
" => Nerd Tree
""""""""""""""""""""""""""""""
let g:NERDTreeWinPos = "left"
let NERDTreeShowHidden=1
let NERDTreeIgnore = ['\.pyc$', '__pycache__']
let g:NERDTreeWinSize=32
map <leader>nn :NERDTreeToggle<cr>
map <leader>nb :NERDTreeFromBookmark<Space>
map <leader>nf :NERDTreeFind<cr>
" Start NerdTree with vim
autocmd VimEnter * NERDTree
" Jump to the main window.
autocmd VimEnter * wincmd p
function! CustomizedTabLine()
let s = ''
let t = tabpagenr()
let i = 1
while i <= tabpagenr('$')
let buflist = tabpagebuflist(i)
let winnr = tabpagewinnr(i)
let s .= '%' . i . 'T'
let s .= (i == t ? '%1*' : '%2*')
let s .= ' '
let s .= i . ':'
let s .= '%*'
let s .= (i == t ? '%#TabLineSel#' : '%#TabLine#')
let file = bufname(buflist[winnr - 1])
let file = fnamemodify(file, ':p:t')
if file == ''
let file = '[No Name]'
endif
let s .= file
let s .= ' '
let i = i + 1
endwhile
let s .= '%T%#TabLineFill#%='
let s .= (tabpagenr('$') > 1 ? '%999XX' : 'X')
return s
endfunction
" Always show the tablilne
set stal=2
set tabline=%!CustomizedTabLine()
""""""""""""""""""""""""""""""
" => CtrlP
""""""""""""""""""""""""""""""
" Invoke CtrlP with ctrl+p
let g:ctrlp_map = '<c-f>'
let g:ctrlp_cmd = 'CtrlP'
" Start CtrlP in filename mode instead of full pathmode
let g:ctrlp_by_filename = 1
let g:ctrlp_max_files=0
let g:ctrlp_max_depth=40
let g:ctrlp_working_path_mode=''
let g:ctrlp_open_new_file = 't'
""""""""""""""""""""""""""""""
" => Tagbar
""""""""""""""""""""""""""""""
map <leader>b :TagbarToggle<CR>
""""""""""""""""""""""""""""""
" => Syntastic
""""""""""""""""""""""""""""""
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
let g:syntastic_always_populate_loc_list = 0
let g:syntastic_auto_loc_list = 1
let g:syntastic_loc_list_height=3
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0
let g:syntastic_enable_signs = 0
let g:syntastic_enable_balloons = 0
let g:syntastic_enable_highlighting = 0
let g:syntastic_echo_current_error = 0
let g:syntastic_python_checkers = ['flake8']
""""""""""""""""""""""""""""""
" => Gitgutter
""""""""""""""""""""""""""""""
hi GitGutterAdd guifg=#00ff00 gui=bold
hi GitGutterChange guifg=#ffff00 gui=bold
hi GitGutterDelete guifg=#ff0000 gui=bold
hi GitGutterChangeDelete guifg=#ffa500 gui=bold
hi SignColumn guibg=NONE
let g:gitgutter_sign_removed = '-'
let g:gitgutter_max_signs = 800
""""""""""""""""""""""""""""""
" => Ack!
""""""""""""""""""""""""""""""
if executable('ag')
let g:ackprg = 'ag --vimgrep'
endif
noreabbrev Ack Ack!
""""""""""""""""""""""""""""""
" => IndentLine
""""""""""""""""""""""""""""""
let g:indentLine_char = '|'<file_sep>Spell check(toggle): `,ss`
Paste mode (toggle): `,pp`
Search: `Ctrl+f` followed by:
- `ctrl+t`: open in new tab
- `ctrl+v`: open in vertical split
- `ctrl+x`: open in horizontal split
Move current cursor line (multiple lines with visual mode):
- up: `cmd+k`
- down: `cmd+j`
Python:
- completion: `ctrl+space`
- go to assignment: `,g`
- go to file of assignment (definition): `,d`
- go back: `ctrl+o` (default vim)
| 1d7eb92931b4438c2d7e046ec242dfc79fc7179f | [
"Markdown",
"Vim Script"
] | 2 | Markdown | mbelarbi/vim | babb5e0f6882acf533c327589affa047a25bd3ff | efb4b34e4bc238b5c0731ba41544dee94353c8cb |
refs/heads/master | <file_sep>import click
from vbox_randomizer import mac_randomizer, uuid_randomizer
@click.command()
@click.argument('vbox', required=True)
def main(vbox):
uuid_randomizer(vbox)
mac_randomizer(vbox)
<file_sep># Vbox Randomizer
Randomizes the UUID of an IDE mounted drive.
The point of this tool is to circumvent a room ban, by changing the
hardware fingerprint of the machine and getting a new TOR circuit.
The actual fingerprinting needs to be researched further, as this tool
doesn't work. TODO: complete me!
# Installation
If you don't use `pipsi`, you're missing out.
Here are [installation instructions](https://github.com/mitsuhiko/pipsi#readme).
Simply run:
$ pipsi install .
# Usage
To use it:
$ vbox-randomizer --help
<file_sep>import random
import re
import uuid
from subprocess import check_output
def parse_vbox_path(text):
"""Parse result of showinfo command"""
return text.split('Config file:')[1].split('\n')[0].strip()
def parse_vdi_path(text):
"""Parse result of showinfo command"""
return text.split('IDE').pop().split(':')[1].split('(UUID')[0].strip().split('').strip()
def parse_old_uuid(text):
"""Parse result of showinfo command"""
return text.split('IDE').pop().split(':')[2].split(')')[0].strip()
def parse_mac_addr(text):
"""Parse result of showinfo command"""
return text.split('NIC 1:').pop().strip().split('MAC:').pop().strip().split(',')[0]
def randomMAC():
mac = [ 0x00, 0x16, 0x3e,
random.randint(0x00, 0x7f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff) ]
return ':'.join(map(lambda x: "%02x" % x, mac))
def uuid_randomizer(vbox):
"""Randomize the UUID of IDE mounted drive of given VM."""
running_command = "vboxmanage list runningvms"
running_vms = check_output(running_command.split())
if vbox in running_vms:
print "Terminate vbox before continuing"
return
info_command = "vboxmanage showvminfo {}".format(vbox)
try:
result = check_output(info_command.split())
except:
print "Invalid vbox"
return
vbox_path = parse_vbox_path(result)
print "Found vbox at {}".format(vbox_path)
vdi_path = parse_vdi_path(result)
if "Empty"in vdi_path:
print "Failed to detect an IDE device."
return
print "Found vdi at {}".format(vdi_path)
old_uuid = parse_old_uuid(result)
print "Old uuid {}".format(old_uuid)
new_uuid = uuid.uuid4().__str__()
setuuid_command = "vboxmanage internalcommands sethduuid".split()
setuuid_command.append(vdi_path)
setuuid_command.append(new_uuid)
check_output(setuuid_command)
print "New uuid {}".format(new_uuid)
print "Reading vbox configuration"
with open(vbox_path, mode='r') as vbox_file:
vbox_config = vbox_file.read()
vbox_file.close()
print "Creating vbox backup"
if vbox_config:
with open(vbox_path + '.bak', mode='w') as vbox_bak:
vbox_bak.write(vbox_config)
vbox_bak.close()
print "Updating vbox"
if vbox_bak:
with open(vbox_path, mode='w') as vbox_new:
vbox_new.write(vbox_config.replace(old_uuid, new_uuid))
vbox_new.close()
print "Done"
def mac_randomizer(vbox):
"""Randomize the MAC Address of a VM."""
running_command = "vboxmanage list runningvms"
running_vms = check_output(running_command.split())
if vbox in running_vms:
print "Terminate vbox before continuing"
return
info_command = "vboxmanage showvminfo {}".format(vbox)
try:
result = check_output(info_command.split())
except:
print "Invalid Vbox"
return
vbox_path = parse_vbox_path(result)
print "Found vbox at {}".format(vbox_path)
print "Reading vbox configuration"
with open(vbox_path, mode='r') as vbox_file:
vbox_config = vbox_file.read()
vbox_file.close()
print "Creating vbox backup"
if vbox_config:
with open(vbox_path + '.bak', mode='w') as vbox_bak:
vbox_bak.write(vbox_config)
vbox_bak.close()
old_mac = parse_mac_addr(result)
new_mac = randomMAC().replace(':', '')
print "Updating vbox"
if vbox_bak:
with open(vbox_path, mode='w') as vbox_new:
vbox_new.write(vbox_config.replace(old_mac, new_mac))
vbox_new.close()
print "Done"
if __name__ == "__main__":
mac_randomizer("windows7")
| 5e68b4e46d0b586b1b3dd580b155c3ad408236a1 | [
"Markdown",
"Python"
] | 3 | Markdown | jashley82/vbox | 55466b6cba26e929588f03a4abd67429f0a65c5c | 140031935186d99f256c32e9d5c0eb8430b0bfe9 |
refs/heads/master | <repo_name>alexeperez/Modelos-Economia<file_sep>/README.md
# Modelos-Economia
Material utilizado en Modelos en Economia EPN
<file_sep>/Pruebas/script_correc_pruebaDA.R
#*-------- Correccion Prueba ----------------#
setwd("C:/Users/Toshiba/Desktop/Clases EPN/modelos en economia/Modelos-Economia/Pruebas")
library(readxl)
d <- read_excel("dataDA.xlsx",
sheet = 1,
col_names = TRUE,
na = "")
str(d)
# Corregir Deuda
d$Deuda <- as.numeric(d$Deuda)
# media variables numericas
media <- numeric(ncol(d))
for(i in 1:ncol(d)){
media[i] <- mean(d[,i], na.rm = TRUE)
}
df1 <- data.frame(colnames(d), media)
df2 <- df1[!is.na(df1[,2]),]
orden <- order(df2[,2],
decreasing = TRUE)
df2[orden, ]
# suma Deuda en estado civil
d$estadocivil <- factor(d$estadocivil)
nivel <- levels(d$estadocivil)
suma <- numeric(length(nivel))
for (i in 1:length(nivel)){
df<-subset(d,subset=estadocivil==nivel[i])
suma[i] <- sum(df$Deuda, na.rm = TRUE)
}
suma
df_sum <- data.frame(nivel, suma)
df_sum
# Funcion en R
tapply(X = d$Deuda,
INDEX = d$estadocivil,
FUN = sum,
na.rm=TRUE)
# Recodificar Ingreso con 345 dólares.
recod <- function(x, val){
x[is.na(x)] <- val
return (x)
}
d$Ingreso<-recod(x = d$Ingreso, val = 345)
# regresión lineal simple entre Ingreso y endeudprom
# en los niveles dados por la variable Region
Rregs <- function(df){
reg <- lm(Ingreso ~ endeudprom, df)
objsumry <- summary(reg)
R <- objsumry$r.squared
return(R)
}
Rregs(d)
x <- mtcars[,3]
y <- mtcars[,1]
reg <- lm(y ~ x)
sumry <- summary(reg)
str(sumry)
sumry$r.squared
d$Region <- factor(d$Region)
nivel <- levels(d$Region)
Rcuad <- numeric(length(nivel))
for (i in 1:length(nivel)){
df <- subset(d, subset=Region==nivel[i])
Rcuad[i] <- Rregs(df)
}
Rcuad
df_Rcuad <- data.frame(nivel, Rcuad)
df_Rcuad
# Funcion en R
split_d <- split(x = d, f = d$Region)
str(split_d)
sapply(X = split_d, FUN = Rregs)
str(lapply(X = d, FUN = typeof))
str(sapply(X = d, FUN = typeof))
# Estudiar Funciones apply
<file_sep>/TimeSeries/Script_Series_FB.R
library(tseries)
library(forecast)
ins <- "FB"
url1 <- "http://real-chart.finance.yahoo.com/table.csv?s="
url2 <- "&a=04&b=1&c=2012&d=11&e=31&f=2015&g=m&ignore=.csv"
url <- paste0(url1, ins, url2)
d <- read.table(url,
header = TRUE,
sep=",")
View(d)
obs <- d[nrow(d):1, "Close"]
mes <- seq(as.Date("2012/5/1"),
as.Date("2015/12/31"),
by = "month")
serie <- ts(obs,
frequency = 12,
start=c(2012,5),
end=c(2015, 12))
class(serie)
str(serie)
# Diag de Lineas
plot(serie, col="blue",xlab="Mes", ylab=names(data)[2])
# Metodologia BOX-JENKINS
# Serie Original
# FAC Y FACP de serie Original
# Retardos mostrados
retardo_max <- 40
par(mfrow=c(2,1))
pacf(serie,
lag.max=retardo_max,
main="Serie",
xlab="",
ylab='FACP',
col="red")
acf(serie,
lag.max=retardo_max,
xlab="Retardo serie",
main="",
ylab='FAC',
col="red")
# Diferenciacion Estacional
# D = ?
DIFERENCIAR="SI"
D = 1
periodo = 12
D_serie <-serie
if (DIFERENCIAR=="SI"){
D_serie <-diff(serie,
lag=periodo,
differences = D)
}
# FAC Y FACP Serie dif Estacional
par(mfrow=c(2,1))
pacf(D_serie, lag.max=retardo_max,main="D_Serie",
xlab="", ylab='FACP',col="red")
acf(D_serie,lag.max=retardo_max, xlab="Retardo D_serie",main="",
ylab='FAC',col="red")
par(mfrow=c(1,1))
plot(D_serie,col="blue",xlab="Trimestre", ylab=names(data)[2])
# Diferenciacion Esatacionaria
# Raices Unitarias: DICKEY FULLER TEST. para: D_serie
# H0: serie no estacionaria
# H1: serie estacionaria
# p_valor <= 5% se acepta estacionariedad
df <- adf.test(D_serie, alternative = c("stationary"))
df
# ADF en tabla
ADF<-data.frame(df$statistic,df$p.value)
colnames(ADF)<-c("Dickey Fuller","p_valor")
ADF
D_d_serie <- D_serie
if(ADF[1,2] > 0.05)
{
d=1
D_d_serie <- diff(D_serie,lag=1,differences=d)
}
# FAC Y FACP Serie dif Estacional y no Estacional
par(mfrow=c(2,1))
pacf(D_d_serie, lag.max=retardo_max,main=paste("d","D",names(data)[2],sep="_"),
xlab="", ylab='FACP',col="red")
acf(D_d_serie,lag.max=retardo_max, xlab="Retardo",main="",
ylab='FAC',col="red")
# Ajuste SARIMA
s_arima <-arima(serie,
order = c(1, 0, 1),
seasonal = list(order = c(0,1,0), period=4),
include.mean = TRUE)
par (mfrow=c(2,1))
pacf(residuals(s_arima), lag.max=retardo_max,main="Modelo Final",
xlab="", ylab='FACP',col="red")
acf(residuals(s_arima),lag.max=retardo_max, xlab="Retardo",main="",
ylab='FAC',col="red")
s_arima
# Predicciones o Pronosticos
# Horizonte Prediccion
h=3
prediccion<- predict(s_arima, n.ahead=h)
par(mfrow=c(1,1))
### INTERVALOS DE CONFIANZA PRONOSTICOS
U <- prediccion$pred + 1.96*prediccion$se
L <- prediccion$pred - 1.96*prediccion$se
ts.plot(serie, prediccion$pred, U, L, col=c("blue",2,3,3), lty = c(1,1,2,2))
legend("topleft",border = "white", c("Real", "Pronostico", "IC (95%)"),col=c("blue",2,3), lty=c(1,1,2))
PRONOSTICOS <- data.frame(prediccion[1],L,U)
colnames(PRONOSTICOS) <- c("PRONOSTICO","LIM INF","LIM SUP")
View(PRONOSTICOS)
<file_sep>/Regresion_lineal/Scriptrls.R
# prueba 11/10/2015
#-----------------------------------------------------#
# Modelos en Economia
# <NAME>
# Escuela Politécnica Nacional
#-----------------------------------------------------#
# directorio de trabajo
setwd("C:/Users/Toshiba/Desktop/Clases EPN/modelos en economia/Modelos-Economia/Regresion_lineal")
list.files()
# paquete lectura de archivos desde excel
install.packages("readxl", dependencies = TRUE)
library(readxl)
# data_rls_uti.xlsx
datarls <- read_excel("data_rls_uti.xlsx",
sheet = 1,
col_names = TRUE,
na = "")
View(datarls)
str(datarls)
colnames(datarls)
summary(datarls)
# grafico de dispersion
# Variables
utilidad <- datarls[,"Utilidad"]
ventas <- datarls[,"Ventas"]
plot(x = ventas,y = utilidad)
plot(x = ventas,y = utilidad,
main = "Utilidad vs Ventas")
plot(x = ventas,y = utilidad,
main = "Utilidad vs Ventas",
pch=16)
plot(x = ventas,y = utilidad,
main = "Utilidad vs Ventas",
pch=16, col="green")
# ggplot2
#install.packages("ggplot2", dependencies = TRUE)
library(ggplot2)
g <- ggplot(data = NULL, aes(x=ventas, y=utilidad))
g + geom_point(size=4, color="green")
# Correlacion
cor(x = utilidad, y= ventas)
#-----------------------------------------------------#
# Regresion lineal Simple
regs <- lm(utilidad ~ ventas)
summary(regs)
qt(0.975,df = 38)
qf(p = 0.95, df1 = 1,df2 = 38)
# ANOVA
anovas <- aov(regs)
summary(anovas)
# Objeto regs
str(regs)
names(regs)
# Residuos
u_t <- regs$residuals
# Hipotesis sobre los errores
mean(u_t)
hist(u_t)
# Pronosticos o predicciones
y_t <- regs$fitted.values
datafinal <- data.frame(datarls, y_t)
View(datafinal)
# Recta de regresion
library(ggplot2)
g <- ggplot(data = NULL, aes(x=ventas, y=utilidad))
g + geom_point(size=3, color="black")+
geom_smooth(method="lm", color="red")
# DEBER 09/10/2015
# Ajustar un modelo de regresion lineal simple entre
# ln(pib) e ln(inflacion) del archivo data_rls_pib.xlsx
# use la funcion log() para extraer el log natural de
# una variable
#-----------------------------------------------------#
# Regresion lineal multiple
# data_rls_uti.xlsx
library(readxl)
datarlm <- read_excel("data_rlm_pib.xlsx",
sheet = 1,
col_names = TRUE,
na = "")
View(datarlm)
str(datarlm)
colnames(datarlm)
summary(datarlm)
# Variables
pib <- datarlm[,"pib"]
infl <- datarlm[,"inflacion"]
ee <- datarlm[,"ee"]
# grafico de dispersion
# variable inflacion
plot(x = infl,y = pib,main = "pib vs inflacion",
pch=16, col="blue")
# variable ee
plot(x = ee,y = pib,main = "pib vs ee",
pch=16, col="blue")
# Relacion no lineal correccion
# transformar variables
ln_pib <- log(pib)
ln_infl <- log(infl)
ln_ee <- log(ee)
plot(x = ln_infl, y = ln_pib,main = "ln_pib vs ln_infl",
pch=16, col="blue")
plot(x = ln_ee,y = ln_pib, main = "pib vs ee",
pch=16, col="blue")
regm <- lm(ln_pib ~ ln_infl+ ln_ee)
dim(datarlm)
qt(p = 0.975,df = nrow(datarlm)-ncol(datarlm))
summary(regm)
qf(p = 0.95, df1 = 2, df2 = 47)
# ANOVA
anovam <- aov(regm)
summary(anovam)
# Objeto regm
names(regm)
# Pronosticos o predicciones
y_t <- regm$fitted.values
datafinal <- data.frame(datarlm,ln_pib, y_t,
exp(ln_pib),exp(y_t))
View(datafinal)
# intervalos de confianza
confint(regm, level = 0.95) | deff0756119ef2100434edb8a9694837b00d6a8d | [
"Markdown",
"R"
] | 4 | Markdown | alexeperez/Modelos-Economia | f7f2f09554895becea61507a64c19cff1863070d | 3cbd8d73abd8ba978ff739605df3931a46196f0a |
refs/heads/dev | <file_sep>using System;
using System.Collections.Generic;
using System.Text;
using Es.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;
namespace Sample
{
public class LoggerEnricher : ILogEventEnricher
{
public const string LoggerPropertyName = "Logger";
/// <summary>
/// Enrich the log event.
/// </summary>
/// <param name="logEvent">The log event to enrich.</param>
/// <param name="propertyFactory">Factory for creating new properties to add to the event.</param>
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
var loggerName = "Default";
if (logEvent.Properties.TryGetValue(Constants.SourceContextPropertyName, out LogEventPropertyValue sourceContext))
{
if (sourceContext is ScalarValue sv && sv.Value is string)
{
loggerName = (string)sv.Value;
}
}
logEvent.AddPropertyIfAbsent(new LogEventProperty(LoggerPropertyName, new ScalarValue(loggerName)));
}
}
class SeriLogDemo
{
private readonly LoggerFactory _logFactory;
public SeriLogDemo()
{
_logFactory = new LoggerFactory();
const string DefaultOutputTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss zzz}] {Logger} {Level:w} {Message:l}{NewLine}{Exception}";
Log.Logger = new LoggerConfiguration()
.Enrich.With<LoggerEnricher>()
.WriteTo.Console(
outputTemplate: DefaultOutputTemplate,
formatProvider: null,
standardErrorFromLevel: null,
theme: SystemConsoleTheme.Literate,
restrictedToMinimumLevel: LogEventLevel.Verbose)
.MinimumLevel.Verbose()
.CreateLogger();
_logFactory.AddSerilog(Log.Logger);
}
[Demo]
public void WriteLog()
{
var log = _logFactory.CreateLogger<SeriLogDemo>();
log.Trace("Trace....");
log.Debug("Verbose...");
log.Info("Information....");
log.Error("Error...");
log.Warn("Warning...");
log.Fatal("Fatal...");
var exception = new InvalidOperationException("Invalid value");
log.Error(exception);
int a = 10, b = 0;
try
{
Log.Logger.Debug("Dividing {A} by {B}", a, b);
Console.WriteLine(a / b);
}
catch (Exception ex)
{
log.Error(ex);
}
}
}
}
<file_sep>using MS = Microsoft.Extensions.Logging;
namespace Es.Logging
{
public class LoggerProvider : ILoggerProvider
{
private readonly MS.ILoggerFactory _logFactory;
public LoggerProvider(MS.ILoggerFactory logFactory)
{
_logFactory = logFactory;
}
public ILogger CreateLogger(string name)
{
return new Logger(_logFactory.CreateLogger(name));
}
public void Dispose()
{
}
}
}<file_sep>namespace Es.Logging
{
/// <summary>
/// 定义了可用的日志级别
/// </summary>
public enum LogLevel
{
/// <summary>
/// 包含最详细的日志信息。这些消息可能包含敏感的应用程序数据。这些消息都是默认禁用的,不应该在生产环境中启用。
/// </summary>
Trace = 1,
/// <summary>
/// 在开发过程中日志用于交互式调查。这些日志应该主要包含有用的调试信息。
/// </summary>
Debug = 2,
/// <summary>
/// 日志跟踪应用程序的通用流。这些日志应该长期显示。
/// </summary>
Info = 3,
/// <summary>
/// 应用程序流的异常或意外事件,但不会导致应用程序停止执行。
/// </summary>
Warn = 4,
/// <summary>
/// 强调在当前流的执行停止时由于失败。这些应该显示当前活动的失败,不是一个应用程序失败。
/// </summary>
Error = 5,
/// <summary>
/// 日志描述一个不可恢复的应用程序或系统崩溃,或者一个灾难性故障,需要立即注意。
/// </summary>
Fatal = 6,
}
}<file_sep>using NLog;
namespace Es.Logging
{
/// <summary>
/// Provider logger for NLog.
/// </summary>
public class NLogLoggerProvider : ILoggerProvider
{
private readonly LogFactory? _factory;
private bool _disposed = false;
/// <summary>
/// <see cref="NLogLoggerProvider"/> with default LogManager.
/// </summary>
public NLogLoggerProvider()
{
}
/// <summary>
/// <see cref="NLogLoggerProvider"/> with default LogFactory.
/// </summary>
/// <param name="logFactory"><see cref="LogFactory"/></param>
public NLogLoggerProvider(LogFactory logFactory)
{
_factory = logFactory;
}
/// <summary>
/// Create a logger with the name <paramref name="name"/>.
/// </summary>
/// <param name="name">Name of the logger to be created.</param>
/// <returns>New Logger</returns>
public ILogger CreateLogger(string name)
{
if (_factory is null)
{
//usage XmlLoggingConfiguration
//e.g LogManager.Configuration = new XmlLoggingConfiguration(fileName, true);
return new Logger(LogManager.GetLogger(name));
}
return new Logger(_factory.GetLogger(name));
}
/// <summary>
/// Cleanup
/// </summary>
public void Dispose()
{
if (_factory is not null && !_disposed)
{
_factory.Flush();
_factory.Dispose();
_disposed = true;
}
}
}
}<file_sep>using Es.Logging;
namespace LoggingTest
{
public class StaticLogger
{
private static ILogger _logger = LoggerFactory.GetLogger<StaticLogger>();
public bool IsEnabled(LogLevel logLevel)
{
return _logger.IsEnabled(logLevel);
}
}
}<file_sep>using System;
using System.Globalization;
#if !NET462
using System.Runtime.InteropServices;
#endif
namespace Es.Logging
{
internal class ConsoleLogger : ILogger
{
private static readonly IConsole _console;
private readonly string _name;
private readonly LogLevel _minLevel;
private readonly ConsoleColor? DefaultConsoleColor = null;
private static readonly OutPutQueue _outPutQueue;
static ConsoleLogger()
{
#if !NET462
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_console = new WindowsLogConsole();
}
else
{
_console = new UnixLogConsole();
}
#else
_console = new WindowsLogConsole();
#endif
_outPutQueue = new OutPutQueue()
{
Console = _console
};
}
public ConsoleLogger(string name, LogLevel minLevel)
{
_name = name;
_minLevel = minLevel;
}
public bool ColorEnable { get; set; } = true;
public bool IsEnabled(LogLevel logLevel)
{
return logLevel >= _minLevel;
}
public void Log(LogLevel logLevel, string message, Exception? exception)
{
if (!IsEnabled(logLevel))
{
return;
}
message = Formatter(message, exception);
if (string.IsNullOrEmpty(message))
return;
WriteLine(logLevel, _name, message);
}
protected virtual void WriteLine(LogLevel logLevel, string name, string message)
{
var color = ColorEnable ? GetColor(logLevel)
: new Color(DefaultConsoleColor, DefaultConsoleColor);
var levelString = GetLevelString(logLevel);
_outPutQueue.EnqueueMessage(new LogMessage
{
Message = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} {levelString} {name} {message}",
Background = color.Background,
Foreground = color.Foreground
});
}
private static string GetLevelString(LogLevel logLevel)
{
return logLevel switch
{
LogLevel.Trace => "trace",
LogLevel.Debug => "debug",
LogLevel.Info => "info",
LogLevel.Warn => "warn",
LogLevel.Error => "error",
LogLevel.Fatal => "fatal",
_ => throw new ArgumentOutOfRangeException(nameof(logLevel)),
};
}
private Color GetColor(LogLevel logLevel)
{
return logLevel switch
{
LogLevel.Fatal => new Color(ConsoleColor.Magenta, ConsoleColor.Black),
LogLevel.Error => new Color(ConsoleColor.Red, ConsoleColor.Black),
LogLevel.Warn => new Color(ConsoleColor.Yellow, ConsoleColor.Black),
LogLevel.Info => new Color(ConsoleColor.White, ConsoleColor.Black),
LogLevel.Trace => new Color(ConsoleColor.Gray, ConsoleColor.Black),
LogLevel.Debug => new Color(ConsoleColor.Gray, ConsoleColor.Black),
_ => new Color(ConsoleColor.White, ConsoleColor.Black),
};
}
private readonly struct Color
{
public Color(ConsoleColor? foreground, ConsoleColor? background)
{
Foreground = foreground;
Background = background;
}
public ConsoleColor? Foreground { get; }
public ConsoleColor? Background { get; }
}
private static string Formatter(string message, Exception? error)
{
if (message == null)
{
throw new InvalidOperationException("Not found the message information to create a log message.");
}
if (error == null)
{
return message;
}
return string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", message, Environment.NewLine, error.ToString());
}
}
}<file_sep>set /p ver=<VERSION
set sourceUrl=-s https://www.nuget.org/api/v2/package
dotnet nuget push artifacts/Es.Logging.%ver%.nupkg %sourceUrl%
dotnet nuget push artifacts/Es.Logging.Console.%ver%.nupkg %sourceUrl%
dotnet nuget push artifacts/Es.Logging.NLog.%ver%.nupkg %sourceUrl%
dotnet nuget push artifacts/Es.Logging.Log4.%ver%.nupkg %sourceUrl%
dotnet nuget push artifacts/Es.Logging.Serilog.%ver%.nupkg %sourceUrl%
dotnet nuget push artifacts/Es.Microsoft.Logging.%ver%.nupkg %sourceUrl%
pause<file_sep>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Es.Logging;
using Microsoft.Extensions.Logging;
namespace Sample
{
public class MicrosoftLogDemo
{
private readonly Es.Logging.LoggerFactory _logFactory;
public MicrosoftLogDemo()
{
_logFactory = new Es.Logging.LoggerFactory();
var logFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(builder =>
{
builder.AddConsole();
builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug);
});
_logFactory.AddMicrosoftLog(logFactory);
}
[Demo]
public void WriteLog()
{
var log = _logFactory.CreateLogger("MicrosoftLogDemo");
log.Trace("Trace....");
log.Debug("Debug...");
log.Info("Information....");
log.Error("Error...");
log.Warn("Warning...");
log.Fatal("Fatal...");
var exception = new InvalidOperationException("Invalid value");
log.Error(exception);
}
}
}<file_sep>#!/usr/bin/env bash
set -e
basepath=$(cd `dirname $0`; pwd)
artifacts=${basepath}/artifacts
if [[ -d ${artifacts} ]]; then
rm -rf ${artifacts}
fi
mkdir -p ${artifacts}
dotnet restore src/Es.Logging
dotnet restore src/Es.Logging.Console
dotnet restore src/Es.Logging.Log4
dotnet restore src/Es.Logging.NLog
dotnet restore src/Es.Microsoft.Log
dotnet build src/Es.Logging -f netstandard2.0 -c Release -o ${artifacts}/netstandard2.0
dotnet build src/Es.Logging.Console -f netstandard2.0 -c Release -o ${artifacts}/netstandard2.0
dotnet build src/Es.Logging.NLog -f netstandard2.0 -c Release -o ${artifacts}/netstandard2.0
dotnet build src/Es.Logging.Log4 -f netstandard2.0 -c Release -o ${artifacts}/netstandard2.0
dotnet build src/Es.Logging.Serilog -f netstandard2.0 -c Release -o ${artifacts}/netstandard2.0
dotnet build src/Es.Microsoft.Log -f netstandard2.0 -c Release -o ${artifacts}/netstandard2.0
<file_sep>namespace Es.Logging
{
/// <summary>
/// LoggerFactoryExtensions
/// </summary>
public static class LoggerFactoryExtensions
{
/// <summary>
/// Enable Serilog as logging provider
/// </summary>
/// <param name="factory"><see cref="ILoggerFactory"/></param>
/// <param name="logger"><see cref="Serilog.ILogger"/></param>
/// <returns></returns>
public static ILoggerFactory AddSerilog(this ILoggerFactory factory, Serilog.ILogger logger)
{
factory.AddProvider(new LoggerProvider(logger));
return factory;
}
}
}<file_sep>using Es.Logging;
using Xunit;
namespace LoggingTest
{
public class LoggerTest
{
[Fact]
public void Can_AddProvider_Create_Logger()
{
var factory = new LoggerFactory();
var provicer1 = new ConsoleLoggerProvider(LogLevel.Error);
var provicer2 = new ConsoleLoggerProvider(LogLevel.Debug);
factory.AddProvider(new[] { provicer1, provicer2 });
var logger = factory.CreateLogger(this.GetType().Name);
Assert.True(logger.IsEnabled(LogLevel.Debug));
}
[Fact]
public void Can_Create_Logger_And_Append_Provider_()
{
var factory = new LoggerFactory();
var provicer1 = new ConsoleLoggerProvider(LogLevel.Debug);
factory.AddProvider(provicer1);
var logger = factory.CreateLogger<LoggerTest>();
Assert.True(logger.IsEnabled(LogLevel.Debug));
var provicer2 = new ConsoleLoggerProvider(LogLevel.Warn);
//append provider
factory.AddProvider(provicer2);
Assert.True(logger.IsEnabled(LogLevel.Warn));
}
}
}<file_sep>namespace Sample
{
internal class Program
{
private static void Main(string[] args)
{
DemoExcute.Excute(typeof(Program));
}
}
}<file_sep>using System;
using System.Threading;
using System.Threading.Tasks;
using Es.Logging;
using NLog;
using NLog.Config;
using NLog.Targets;
namespace Sample
{
public class NLogDemo
{
private readonly LoggerFactory _logFactory;
public NLogDemo()
{
_logFactory = new LoggerFactory();
LoggingConfiguration config = new LoggingConfiguration();
ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
config.AddTarget("console", consoleTarget);
LoggingRule rule1 = new LoggingRule("*", NLog.LogLevel.Trace, consoleTarget);
config.LoggingRules.Add(rule1);
_logFactory.AddNLog(config.LogFactory);
}
[Demo]
public void WriteLog()
{
var log = _logFactory.CreateLogger("ConsoleDemo");
log.Trace("Trace....");
log.Debug("Verbose...");
log.Info("Information....");
log.Error("Error...");
log.Warn("Warning...");
log.Fatal("Fatal...");
var exception = new InvalidOperationException("Invalid value");
log.Error(exception);
}
}
}<file_sep>using System;
namespace Es.Logging
{
/// <summary>
/// 用于创建日志记录实例
/// </summary>
public interface ILoggerProvider : IDisposable
{
/// <summary>
/// 创建一个新的<see cref="ILogger"/>实例
/// </summary>
/// <param name="name">日志名</param>
/// <returns>返回<see cref="ILogger"/></returns>
ILogger CreateLogger(string name);
}
}<file_sep>using System;
using MS = Microsoft.Extensions.Logging;
namespace Es.Logging
{
public class Logger : ILogger
{
private readonly MS.ILogger _logger;
private static readonly Func<object, Exception?, string> _messageFormatter = MessageFormatter;
public Logger(MS.ILogger logger)
{
_logger = logger;
}
public bool IsEnabled(LogLevel logLevel)
{
return _logger.IsEnabled(Logger.GetLogLevel(logLevel));
}
private bool IsEnabled(MS.LogLevel logLevel)
{
return _logger.IsEnabled(logLevel);
}
public void Log(LogLevel logLevel, string message, Exception? exception)
{
var level = Logger.GetLogLevel(logLevel);
if (IsEnabled(level))
{
_logger.Log(Logger.GetLogLevel(logLevel), 0, message, exception, _messageFormatter);
}
}
private static MS.LogLevel GetLogLevel(LogLevel logLevel)
{
return logLevel switch
{
LogLevel.Trace => MS.LogLevel.Trace,
LogLevel.Debug => MS.LogLevel.Debug,
LogLevel.Info => MS.LogLevel.Information,
LogLevel.Warn => MS.LogLevel.Warning,
LogLevel.Error => MS.LogLevel.Error,
LogLevel.Fatal => MS.LogLevel.Critical,
_ => MS.LogLevel.None,
};
}
private static string MessageFormatter(object state, Exception? error)
{
return state?.ToString() ?? string.Empty;
}
}
}<file_sep>using System;
using System.Threading;
using System.Threading.Tasks;
using Es.Logging;
using NLog;
namespace Sample
{
public class NLogXmlConfigureDemo
{
private readonly LoggerFactory _logFactory;
public NLogXmlConfigureDemo()
{
_logFactory = new LoggerFactory();
string filename = AppContext.BaseDirectory + "/NLog.xml";
_logFactory.AddNLog(filename);
}
[Demo]
public void WriteLog()
{
var log = _logFactory.CreateLogger("ConsoleDemo");
log.Trace("Trace....");
log.Debug("Verbose...");
log.Info("Information....");
log.Error("Error...");
log.Warn("Warning...");
log.Fatal("Fatal...");
var exception = new InvalidOperationException("Invalid value");
log.Error(exception);
}
[Demo]
public void WriteLog2()
{
var log = _logFactory.CreateLogger("ConsoleDemo");
var menu = new ManualResetEvent(false);
for (int i = 0; i < 1000; i++)
{
Task.Run(() => {
menu.WaitOne();
log.Trace("Trace....");
log.Debug("Debug...");
log.Info("Information....");
log.Error("Error...");
log.Warn("Warning...");
log.Fatal("Fatal...");
var exception = new InvalidOperationException("Invalid value");
log.Error(exception);
});
}
menu.Set();
Thread.Sleep(2000);
}
}
}<file_sep># Es.Logging
[![Build Status](https://travis-ci.org/EsWork/Es.Logging.svg?branch=master)](https://travis-ci.org/EsWork/Es.Logging)
`Es.Logging`抽象出.Net平台的日志通用接口,自身并没有日志处理实现,默认实现了NLog、Log4net、Microsoft.Extensions.Logging和console standard output支持。
通常日志的实例我们都在构造函数中创建
```cs
public class Foo{
private readonly ILogger _logger;
public Foo(){
_logger = LoggerManager.GetLogger<Foo>();
}
}
```
但是很多时候我们也许会在静态类使用,也许`Logger`静态实例在没有`LoggerProvider`时候可能会失效,`Es.Logging`现在已经支持。
```cs
public static class Foo{
private static readonly ILogger _logger = LoggerManager.GetLogger<Foo>();
}
```
Features
---
- 聚合.NET平台常用日志类库
- 已有静态`Logger`实例支持后期追加的`LoggerProvider`
- 支持`Unix`&`Windows`控制台输出
- 支持`NLog`
- 支持`Log4net`
- 支持`Serilog`
- 支持`Microsoft.Extensions.Logging`
Packages & Status
---
Package | NuGet |
-------- | :------------ |
|**Es.Logging**|[![NuGet package](https://buildstats.info/nuget/Es.Logging)](https://www.nuget.org/packages/Es.Logging)
|**Es.Logging.Console**|[![NuGet package](https://buildstats.info/nuget/Es.Logging.Console)](https://www.nuget.org/packages/Es.Logging.Console)
|**Es.Logging.NLog**|[![NuGNuGet packageet](https://buildstats.info/nuget/Es.Logging.NLog)](https://www.nuget.org/packages/Es.Logging.NLog)
|**Es.Logging.Log4**|[![NuGet package](https://buildstats.info/nuget/Es.Logging.Log4)](https://www.nuget.org/packages/Es.Logging.Log4)
|**Es.Logging.Serilog**|[![NuGet package](https://buildstats.info/nuget/Es.Logging.Serilog)](https://www.nuget.org/packages/Es.Logging.Serilog)
|**Es.Microsoft.Logging**|[![NuGet package](https://buildstats.info/nuget/Es.Microsoft.Logging)](https://www.nuget.org/packages/Es.Microsoft.Logging)
Usage
---
标准控制台输出
```cs
using Es.Logging;
public static class Foo{
//static Logger instance
private static readonly ILogger _logger = LoggerManager.GetLogger<Foo>();
private static void Main(string[] args) {
//add console output
LoggerManager.Factory.AddConsole(LogLevel.Trace);
//logger info
_logger.Info("Es.Logging");
}
}
```
推荐使用`NLog`
```cs
using Es.Logging;
public static class Foo{
//static Logger instance
private static readonly ILogger _logger = LoggerManager.GetLogger<Foo>();
private static void Main(string[] args) {
//init NLog config
LoggingConfiguration config = new LoggingConfiguration();
ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
config.AddTarget("console", consoleTarget);
LoggingRule rule = new LoggingRule("*", NLog.LogLevel.Trace, consoleTarget);
config.LoggingRules.Add(rule);
LogFactory factory = new LogFactory(config);
//add NLog Provider
_logFactory.AddNLog(factory);
//logger info
_logger.Info("Es.Logging");
}
}
```
更多请查看[Sample](https://github.com/EsWork/Es.Logging/tree/master/src/Sample)
## License
See [LICENSE](https://github.com/EsWork/Es.Logging/tree/master/LICENSE) for details.
<file_sep>namespace Es.Logging
{
public class Log4LoggerProvider : ILoggerProvider
{
public ILogger CreateLogger(string name)
{
return new Log4(log4net.LogManager.GetLogger("Default", name));
}
public void Dispose()
{
log4net.LogManager.Shutdown();
}
}
}<file_sep>using Es.Logging;
using Xunit;
namespace LoggingTest
{
public class ConsoleLoggerTest
{
[Fact]
public void Create_ConsoleProvider_With_Level()
{
var provider = new ConsoleLoggerProvider(LogLevel.Debug);
var logger = provider.CreateLogger(this.GetType().FullName);
Assert.False(logger.IsEnabled(LogLevel.Trace));
Assert.True(logger.IsEnabled(LogLevel.Debug));
Assert.True(logger.IsEnabled(LogLevel.Info));
Assert.True(logger.IsEnabled(LogLevel.Warn));
Assert.True(logger.IsEnabled(LogLevel.Error));
Assert.True(logger.IsEnabled(LogLevel.Fatal));
}
}
}<file_sep>using Es.Logging;
namespace Sample
{
public class LoggerManagerDemo
{
private static ILogger _logger = LoggerFactory.GetLogger("LoggerManagerDemo");
[Demo]
public void Aggregate_And_AppendProvider()
{
//def console
LoggerFactory.Factory.AddConsole(LogLevel.Trace);
//print 1 line
_logger.Info("------- console -------");
var config = new NLog.Config.LoggingConfiguration();
var consoleTarget = new NLog.Targets.ColoredConsoleTarget();
config.AddTarget("console", consoleTarget);
var rule1 = new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, consoleTarget);
config.LoggingRules.Add(rule1);
//append NLog
LoggerFactory.Factory.AddNLog(config.LogFactory);
//print 2 line
_logger.Info("------- console & nlog -------");
}
}
}<file_sep>using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace Es.Logging
{
internal class OutPutQueue : IDisposable
{
private const int _maxQueuedMessages = 1024;
private readonly BlockingCollection<LogMessage> _messageQueue = new(_maxQueuedMessages);
private readonly Task _outputTask;
public IConsole? Console;
public OutPutQueue()
{
_outputTask = Task.Factory.StartNew(
ProcessQueue,
this,
TaskCreationOptions.LongRunning);
}
internal virtual void EnqueueMessage(LogMessage message)
{
if (!_messageQueue.IsAddingCompleted)
{
try
{
_messageQueue.Add(message);
return;
}
catch (InvalidOperationException) { }
}
WriteMessage(message);
}
internal virtual void WriteMessage(LogMessage message)
{
Console?.WriteLine(message.Message, message.Background, message.Foreground);
Console?.Flush();
}
private void ProcessQueue()
{
foreach (var message in _messageQueue.GetConsumingEnumerable())
{
WriteMessage(message);
}
}
private static void ProcessQueue(object? state)
{
var consoleLogger = (OutPutQueue)state!;
consoleLogger.ProcessQueue();
}
public void Dispose()
{
_messageQueue.CompleteAdding();
try
{
_outputTask.Wait(1500);
}
catch
{
}
}
}
internal class LogMessage
{
public ConsoleColor? Background;
public ConsoleColor? Foreground;
public string Message = default!;
}
}<file_sep>using System;
using System.Text;
namespace Es.Logging
{
internal class UnixLogConsole : IConsole
{
private readonly StringBuilder _messageBuilder = new StringBuilder();
private const string BACKGROUND = "\x1B[39m\x1B[22m";
private const string FOREGROUND = "\x1B[49m";
public void Flush()
{
Console.Write(_messageBuilder.ToString());
_messageBuilder.Clear();
}
public void Write(string logMessage, ConsoleColor? background, ConsoleColor? foreground)
{
if (background.HasValue)
{
_messageBuilder.Append(GetBackgroundColor(background.Value));
}
if (foreground.HasValue)
{
_messageBuilder.Append(GetForegroundColor(foreground.Value));
}
_messageBuilder.Append(logMessage);
if (foreground.HasValue)
{
_messageBuilder.Append(BACKGROUND);
}
if (background.HasValue)
{
_messageBuilder.Append(FOREGROUND);
}
}
public void WriteLine(string logMessage, ConsoleColor? background, ConsoleColor? foreground)
{
Write(logMessage, background, foreground);
_messageBuilder.AppendLine();
}
private static string GetForegroundColor(ConsoleColor color)
{
switch (color)
{
case ConsoleColor.Black:
return "\x1B[30m";
case ConsoleColor.DarkRed:
return "\x1B[31m";
case ConsoleColor.DarkGreen:
return "\x1B[32m";
case ConsoleColor.DarkYellow:
return "\x1B[33m";
case ConsoleColor.DarkBlue:
return "\x1B[34m";
case ConsoleColor.DarkMagenta:
return "\x1B[35m";
case ConsoleColor.DarkCyan:
return "\x1B[36m";
case ConsoleColor.Gray:
return "\x1B[37m";
case ConsoleColor.Red:
return "\x1B[1m\x1B[31m";
case ConsoleColor.Green:
return "\x1B[1m\x1B[32m";
case ConsoleColor.Yellow:
return "\x1B[1m\x1B[33m";
case ConsoleColor.Blue:
return "\x1B[1m\x1B[34m";
case ConsoleColor.Magenta:
return "\x1B[1m\x1B[35m";
case ConsoleColor.Cyan:
return "\x1B[1m\x1B[36m";
case ConsoleColor.White:
return "\x1B[1m\x1B[37m";
default:
return FOREGROUND;
}
}
private static string GetBackgroundColor(ConsoleColor color)
{
switch (color)
{
case ConsoleColor.Black:
return "\x1B[40m";
case ConsoleColor.Red:
return "\x1B[41m";
case ConsoleColor.Green:
return "\x1B[42m";
case ConsoleColor.Yellow:
return "\x1B[43m";
case ConsoleColor.Blue:
return "\x1B[44m";
case ConsoleColor.Magenta:
return "\x1B[45m";
case ConsoleColor.Cyan:
return "\x1B[46m";
case ConsoleColor.White:
return "\x1B[47m";
default:
return BACKGROUND;
}
}
}
}<file_sep>using System.Collections.Generic;
namespace Es.Logging
{
/// <summary>
/// 基于工厂创建日志记录实例
/// </summary>
public class LoggerFactory : ILoggerFactory
{
private readonly object lockObject = new();
internal readonly Dictionary<string, AggregateLogger> Loggers = new();
/// <summary>
/// Default Factory
/// </summary>
public readonly static ILoggerFactory Factory = new LoggerFactory();
/// <summary>
/// 创建日志记录实例的提供者集合
/// </summary>
public readonly List<ILoggerProvider> Providers = new()
{
EmptyLoggerProvider.Instance
};
/// <summary>
/// 添加创建日志记录实例的提供者
/// </summary>
/// <param name="providers">用于创建日志记录实例的提供者</param>
public void AddProvider(params ILoggerProvider[] providers)
{
lock (lockObject)
{
Providers.AddRange(providers);
//添加用于创建日志记录实例的提供者时,将已创建的日志记录集合追加新的日志提供者,
//这样我们可以确保每个日志记录实例包含完整多个不同的实现,
foreach (var logger in Loggers)
{
logger.Value.AddProvider(providers);
}
}
}
/// <summary>
/// 创建日志记录实例
/// </summary>
/// <param name="name">定义日志的名称</param>
/// <returns><see cref="ILogger"/></returns>
public ILogger CreateLogger(string name)
{
if (!Loggers.TryGetValue(name, out var logger))
{
lock (lockObject)
{
if (!Loggers.TryGetValue(name, out logger))
{
logger = new AggregateLogger(Providers.ToArray(), name);
Loggers[name] = logger;
}
}
}
return logger;
}
/// <summary>
/// 根据当前类名创建一个日志记录实例
/// </summary>
/// <returns><see cref="ILogger"/></returns>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static ILogger GetCurrentClassLogger()
{
System.Diagnostics.StackFrame frame = new(1, false);
return Factory.CreateLogger(frame.GetMethod()?.DeclaringType?.FullName ?? "StackFrame");
}
/// <summary>
/// 根据名称创建一个日志记录实例
/// </summary>
/// <param name="name">日志名称</param>
/// <returns><see cref="ILogger"/></returns>
public static ILogger GetLogger(string name)
{
return Factory.CreateLogger(name);
}
/// <summary>
/// 根据泛型参数类型创建一个日志记录实例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns><see cref="ILogger"/></returns>
public static ILogger GetLogger<T>()
{
return Factory.CreateLogger<T>();
}
}
}<file_sep>using System;
namespace Es.Logging
{
/// <summary>
/// 表示一个日志记录接口
/// </summary>
public interface ILogger
{
/// <summary>
/// 写到指定的级别日志。
/// </summary>
/// <param name="logLevel"><see cref="LogLevel"/></param>
/// <param name="message">日志信息</param>
/// <param name="exception">异常信息</param>
void Log(LogLevel logLevel, string message, Exception? exception);
/// <summary>
/// 检查给定日志级别是否启用。
/// </summary>
/// <param name="logLevel"><see cref="LogLevel"/></param>
/// <returns>指定的日志级别是否启用</returns>
bool IsEnabled(LogLevel logLevel);
}
}<file_sep>using System;
namespace Es.Logging
{
internal class WindowsLogConsole : IConsole
{
public void Flush()
{
//Do Nothing, data is sent directly to the console
}
public void Write(string logMessage, ConsoleColor? background, ConsoleColor? foreground)
{
SetColor(background, foreground);
Console.Out.Write(logMessage);
ResetColor();
}
public void WriteLine(string logMessage, ConsoleColor? background, ConsoleColor? foreground)
{
SetColor(background, foreground);
Console.Out.WriteLine(logMessage);
ResetColor();
}
private void SetColor(ConsoleColor? background, ConsoleColor? foreground)
{
if (background.HasValue)
{
Console.BackgroundColor = background.Value;
}
if (foreground.HasValue)
{
Console.ForegroundColor = foreground.Value;
}
}
private void ResetColor()
{
Console.ResetColor();
}
}
}<file_sep>namespace Es.Logging
{
public static class Log4Extensions
{
public static ILoggerFactory AddLog4net(this ILoggerFactory factory)
{
factory.AddProvider(new Log4LoggerProvider());
return factory;
}
}
}<file_sep>namespace Es.Logging
{
/// <summary>
/// 此类不是作为单元测试来使用,当使用<see cref="LoggerFactory"/>.GetLogger创建日志记录时候,
/// 可能会遇到预先在类的内部定义了静态的ILogger实例对象,
/// 如果没有默认的Logger处理器实例,<see cref="LoggerFactory"/>.CreateLogger创建的实例是不带任何Provider的,
/// 那后面追加Providers也不会更新这个静态的ILogger实例对象
/// </summary>
internal class EmptyLoggerProvider : ILoggerProvider
{
internal static EmptyLoggerProvider Instance = new();
/// <summary>
/// 创建一个新的<see cref="EmptyLogger"/>实例
/// </summary>
/// <param name="name">日志名</param>
/// <returns>返回<see cref="ILogger"/></returns>
public ILogger CreateLogger(string name)
{
return EmptyLogger.Instance;
}
/// <summary>
/// nothing
/// </summary>
public void Dispose()
{
}
}
}<file_sep>set artifacts=%~dp0artifacts
if exist %artifacts% rd /q /s %artifacts%
set /p ver=<VERSION
dotnet restore src/Es.Logging
dotnet restore src/Es.Logging.Console
dotnet restore src/Es.Logging.Log4
dotnet restore src/Es.Logging.NLog
dotnet restore src/Es.Microsoft.Log
dotnet pack -c release -p:Ver=%ver% src/Es.Logging -o %artifacts%
dotnet pack -c release -p:Ver=%ver% src/Es.Logging.Console -o %artifacts%
dotnet pack -c release -p:Ver=%ver% src/Es.Logging.Log4 -o %artifacts%
dotnet pack -c release -p:Ver=%ver% src/Es.Logging.NLog -o %artifacts%
dotnet pack -c release -p:Ver=%ver% src/Es.Logging.Serilog -o %artifacts%
dotnet pack -c release -p:Ver=%ver% src/Es.Microsoft.Log -o %artifacts%
pause<file_sep>using System;
namespace Es.Logging
{
internal interface IConsole
{
void Write(string logMessage, ConsoleColor? background, ConsoleColor? foreground);
void WriteLine(string logMessage, ConsoleColor? background, ConsoleColor? foreground);
void Flush();
}
}<file_sep>namespace Es.Logging
{
/// <summary>
/// Logger Factory Extensions
/// </summary>
public static class LoggerFactoryExtensions
{
/// <summary>
/// 创建日志记录实例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="factory"><see cref="ILoggerFactory"/></param>
/// <returns><see cref="ILogger"/></returns>
public static ILogger CreateLogger<T>(this ILoggerFactory factory)
{
return factory.CreateLogger(typeof(T).FullName!);
}
}
}<file_sep>namespace Es.Logging
{
/// <summary>
/// Console Logger Factory Extensions
/// </summary>
public static class ConsoleLoggerFactoryExtensions
{
/// <summary>
/// Add the Console output Logger.
/// </summary>
/// <param name="factory"><see cref="ILoggerFactory"/></param>
/// <param name="minLevel"><see cref="LogLevel"/></param>
/// <param name="colorEnable">Whether open font color</param>
/// <returns></returns>
public static ILoggerFactory AddConsole(this ILoggerFactory factory, LogLevel minLevel, bool colorEnable = true)
{
factory.AddProvider(new ConsoleLoggerProvider(minLevel, colorEnable));
return factory;
}
}
}<file_sep>using Serilog;
using Serilog.Core;
using System;
namespace Es.Logging
{
/// <summary>
/// Provider logger for Serilog.
/// </summary>
public class LoggerProvider : ILoggerProvider
{
private readonly Serilog.ILogger _logger;
private readonly Action _dispose;
/// <summary>
/// <see cref="LoggerProvider"/> with default ILogger.
/// </summary>
/// <param name="logger"><see cref="Serilog.ILogger"/></param>
public LoggerProvider(Serilog.ILogger logger)
{
_logger = logger;
if (logger != null)
_dispose = () => (logger as IDisposable)?.Dispose();
else
_dispose = Log.CloseAndFlush;
}
/// <summary>
/// Create a logger with the name <paramref name="name"/>.
/// </summary>
/// <param name="name">Name of the logger to be created.</param>
/// <returns>New Logger</returns>
public ILogger CreateLogger(string name)
{
return new Logger(_logger.ForContext(Constants.SourceContextPropertyName, name));
}
/// <summary>
/// Clean
/// </summary>
public void Dispose()
{
_dispose?.Invoke();
}
}
}<file_sep>namespace Es.Logging
{
/// <summary>
/// Provider from <see cref="ConsoleLogger"/>
/// </summary>
public class ConsoleLoggerProvider : ILoggerProvider
{
private readonly LogLevel _minLevel;
private readonly bool _colorEnable;
/// <summary>
/// Constructor parameters setup log to register
/// </summary>
/// <param name="minLevel">Setting <see cref="LogLevel"/></param>
/// <param name="colorEnable">Whether open font color</param>
public ConsoleLoggerProvider(LogLevel minLevel, bool colorEnable = true)
{
_minLevel = minLevel;
_colorEnable = colorEnable;
}
/// <summary>
/// create a <see cref="ConsoleLogger"/> instance
/// </summary>
/// <param name="name"></param>
/// <returns>return <see cref="ConsoleLogger"/> instance</returns>
public ILogger CreateLogger(string name)
{
return new ConsoleLogger(name, _minLevel) { ColorEnable = _colorEnable };
}
/// <summary>
/// Perform and release or reset unmanaged resources associated application defined tasks.
/// </summary>
public void Dispose()
{
//nothing
}
}
}<file_sep>using Serilog.Events;
using System;
namespace Es.Logging
{
internal class Logger : ILogger
{
private readonly Serilog.ILogger _logger;
public Logger(Serilog.ILogger logger)
{
_logger = logger;
}
public bool IsEnabled(LogLevel logLevel)
{
return _logger.IsEnabled(GetLogLevel(logLevel));
}
public void Log(LogLevel logLevel, string message, Exception? exception)
{
var level = GetLogLevel(logLevel);
if (!_logger.IsEnabled(level))
{
return;
}
if (string.IsNullOrEmpty(message) && exception == null)
return;
var logger = _logger;
logger.Write(level, exception, message);
}
private LogEventLevel GetLogLevel(LogLevel logLevel)
{
return logLevel switch
{
LogLevel.Debug => LogEventLevel.Debug,
LogLevel.Info => LogEventLevel.Information,
LogLevel.Warn => LogEventLevel.Warning,
LogLevel.Error => LogEventLevel.Error,
LogLevel.Fatal => LogEventLevel.Fatal,
_ => LogEventLevel.Verbose,
};
}
}
}<file_sep>// ==++==
//
// Copyright (c) . All rights reserved.
//
// ==--==
/* ---------------------------------------------------------------------------
*
* Author : v.la
* Email : <EMAIL>
* Created : 2015-08-27
* Class : TestExcute.cs
*
* ---------------------------------------------------------------------------
* */
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
/// <summary>
/// Class DemoAttribute.
/// </summary>
public class DemoAttribute : Attribute
{
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>The description.</value>
public string Description { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DemoAttribute"/> class.
/// </summary>
public DemoAttribute()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DemoAttribute"/> class.
/// </summary>
/// <param name="description">The description.</param>
public DemoAttribute(string description)
{
Description = description;
}
}
/// <summary>
/// Class DemoExcute.
/// </summary>
public static class DemoExcute
{
/// <summary>
/// Excutes the specified test assembly.
/// </summary>
/// <param name="t">The t.</param>
public static void Excute(Type t)
{
#if NETFULL
var dataAccess = t.Assembly;
#else
var dataAccess = t.GetTypeInfo().Assembly;
#endif
IList<ExecuteFunc> list = new List<ExecuteFunc>();
foreach (var type in dataAccess.GetTypes())
{
var clazz = type.GetConstructor(Type.EmptyTypes);
if (clazz == null) continue;
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
{
if (method.GetCustomAttributes(typeof(DemoAttribute), false).FirstOrDefault() is DemoAttribute attr)
{
object instance = Activator.CreateInstance(type);
ExecuteFunc func = new ExecuteFunc(instance, method, attr.Description);
list.Add(func);
}
}
}
if (list.Count > 0)
{
StringBuilder text = new StringBuilder();
LrTag("Select the use-case", "-", 20);
for (int i = 0; i < list.Count; i++)
{
text.AppendFormat("[{0}] {1}{2}", i + 1, list[i], Environment.NewLine);
}
text.AppendLine("\r\n[0] \texit. ");
string _display = text.ToString();
Console.Out.WriteLine(ConsoleColor.Green, _display);
Console.Out.Write("select>");
string input = Console.ReadLine();
while (input != "0" && input != "quit" && input != "q" && input != "exit")
{
if (input.Equals("cls", StringComparison.OrdinalIgnoreCase))
{
Console.Clear();
}
if (int.TryParse(input, out int idx))
{
if (idx > 0 && idx <= list.Count)
{
Console.Clear();
Console.Out.WriteLine(ConsoleColor.DarkCyan, list[idx - 1] + " Running...");
list[idx - 1].Execute();
Console.Out.WriteLine(ConsoleColor.DarkCyan, list[idx - 1] + " Complete...");
}
}
Console.Out.WriteLine();
LrTag("Select the use-case", "-", 20);
Console.Out.WriteLine(ConsoleColor.Green, _display);
Console.Out.Write("select>");
input = Console.ReadLine();
}
}
}
/// <summary>
/// The space
/// </summary>
private static readonly string SPACE = " ";
/// <summary>
/// Lrs the tag.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="tag">The tag.</param>
/// <param name="size">The size.</param>
private static void LrTag(string view, string tag, int size)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++)
{
sb.Append(tag);
}
Console.Out.WriteLine(ConsoleColor.Yellow, sb + SPACE + view + SPACE + sb);
}
/// <summary>
/// Writes the line.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="color">The color.</param>
/// <param name="format">The format.</param>
/// <param name="args">The arguments.</param>
private static void WriteLine(this TextWriter writer,
ConsoleColor color,
string format,
params object[] args)
{
Console.ForegroundColor = color;
writer.WriteLine(format, args);
Console.ResetColor();
}
/// <summary>
/// Class ExecuteFunc.
/// </summary>
private class ExecuteFunc
{
private readonly object _instance;
private MethodInfo _method;
private readonly string _description;
/// <summary>
/// Initializes a new instance of the <see cref="ExecuteFunc"/> class.
/// </summary>
/// <param name="instance">The instance.</param>
/// <param name="method">The method.</param>
/// <param name="description">The description.</param>
public ExecuteFunc(object instance, MethodInfo method, string description = "")
{
_instance = instance;
_method = method;
if (string.IsNullOrEmpty(description))
{
_description = string.Concat("\t", instance.GetType().FullName, ".", method.Name);
}
else
{
_description = string.Concat("\t", instance.GetType().FullName, "." + method.Name,
Environment.NewLine, "\t", description);
}
}
/// <summary>
/// Executes this instance.
/// </summary>
public void Execute()
{
_method.Invoke(_instance, null);
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
public override string ToString()
{
return _description;
}
}
}<file_sep>using System.IO;
using System.Reflection;
using NLog;
using NLog.Config;
namespace Es.Logging
{
/// <summary>
/// NLogLoggerFactoryExtensions
/// </summary>
public static class NLogLoggerFactoryExtensions
{
/// <summary>
/// Enable NLog as logging provider
/// </summary>
/// <param name="factory"><see cref="ILoggerFactory"/></param>
/// <param name="fileName">Configuration file to be read.</param>
/// <returns></returns>
public static ILoggerFactory AddNLog(this ILoggerFactory factory, string fileName = "")
{
if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
{
LogManager.Configuration = new XmlLoggingConfiguration(fileName);
}
#if NET462
LogManager.AddHiddenAssembly(typeof(NLogLoggerFactoryExtensions).Assembly);
#else
LogManager.AddHiddenAssembly(typeof(NLogLoggerFactoryExtensions).GetTypeInfo().Assembly);
#endif
using (var provider = new NLogLoggerProvider())
{
factory.AddProvider(provider);
}
return factory;
}
/// <summary>
/// Enable NLog as logging provider
/// </summary>
/// <param name="factory"><see cref="ILoggerFactory"/></param>
/// <param name="logFactory"><see cref="LogFactory"/></param>
/// <returns></returns>
public static ILoggerFactory AddNLog(this ILoggerFactory factory, LogFactory logFactory)
{
factory.AddProvider(new NLogLoggerProvider(logFactory));
return factory;
}
}
}<file_sep>using System;
using Es.Logging;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Layout;
using log4net.Repository;
namespace Sample
{
public class Log4Demo
{
private readonly LoggerFactory _logFactory;
public Log4Demo()
{
_logFactory = new LoggerFactory();
ILoggerRepository repo = LogManager.CreateRepository("Default");
BasicConfigurator.Configure(repo, new ConsoleAppender
{
Layout = new PatternLayout(
"%date [%thread] %-5level %logger - %message%newline"
)
});
_logFactory.AddLog4net();
}
[Demo]
public void WriteLog()
{
var log = _logFactory.CreateLogger("ConsoleDemo");
log.Trace("Trace....");
log.Debug("Verbose...");
log.Info("Information....");
log.Error("Error...");
log.Warn("Warning...");
log.Fatal("Fatal...");
var exception = new InvalidOperationException("Invalid value");
log.Error(exception);
}
}
}<file_sep>using System;
using System.Globalization;
namespace Es.Logging
{
/// <summary>
/// 日志记录的扩展功能
/// </summary>
public static class LoggerExtensions
{
/// <summary>
/// 调试指定的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="message">消息内容</param>
public static void Debug(this ILogger logger, string message)
{
Logger(logger, LogLevel.Debug, message);
}
/// <summary>
/// 调试指定的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="format">格式化内容</param>
/// <param name="args">格式化参数</param>
public static void Debug(this ILogger logger, string format, params object[] args)
{
Logger(logger, LogLevel.Debug, format, args);
}
/// <summary>
/// 跟踪指定的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="message">消息内容</param>
public static void Trace(this ILogger logger, string message)
{
Logger(logger, LogLevel.Trace, message);
}
/// <summary>
/// 跟踪指定的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="format">格式化内容</param>
/// <param name="args">格式化参数</param>
public static void Trace(this ILogger logger, string format, params object[] args)
{
Logger(logger, LogLevel.Trace, format, args);
}
/// <summary>
/// 输出指定的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="message">消息内容</param>
public static void Info(this ILogger logger, string message)
{
Logger(logger, LogLevel.Info, message);
}
/// <summary>
/// 输出指定的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="format">格式化内容</param>
/// <param name="args">格式化参数</param>
public static void Info(this ILogger logger, string format, params object[] args)
{
Logger(logger, LogLevel.Info, format, args);
}
/// <summary>
/// 指定警告的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="message">消息内容</param>
public static void Warn(this ILogger logger, string message)
{
Logger(logger, LogLevel.Warn, message);
}
/// <summary>
/// 指定警告的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="format">格式化内容</param>
/// <param name="args">格式化参数</param>
public static void Warn(this ILogger logger, string format, params object[] args)
{
Logger(logger, LogLevel.Warn, format, args);
}
/// <summary>
/// 指定警告的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="message">消息内容</param>
/// <param name="error">异常信息</param>
public static void Warn(this ILogger logger, string message, Exception error)
{
Logger(logger, LogLevel.Warn, message, error);
}
/// <summary>
/// 指定警告的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="error">异常信息</param>
public static void Warn(this ILogger logger, Exception error)
{
Logger(logger, LogLevel.Warn, error.Message, error);
}
/// <summary>
/// 指定错误的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="message">消息内容</param>
public static void Error(this ILogger logger, string message)
{
Logger(logger, LogLevel.Error, message);
}
/// <summary>
/// 指定错误的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="format">格式化内容</param>
/// <param name="args">格式化参数</param>
public static void Error(this ILogger logger, string format, params object[] args)
{
Logger(logger, LogLevel.Error, format, args);
}
/// <summary>
/// 指定错误的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="message">消息内容</param>
/// <param name="error">异常信息</param>
public static void Error(this ILogger logger, string message, Exception error)
{
Logger(logger, LogLevel.Error, message, error);
}
/// <summary>
/// 指定错误的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="error">异常信息</param>
public static void Error(this ILogger logger, Exception error)
{
Logger(logger, LogLevel.Error, error.Message, error);
}
/// <summary>
/// 指定严重的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="message">消息内容</param>
public static void Fatal(this ILogger logger, string message)
{
Logger(logger, LogLevel.Fatal, message);
}
/// <summary>
/// 指定严重的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="format">格式化内容</param>
/// <param name="args">格式化参数</param>
public static void Fatal(this ILogger logger, string format, params object[] args)
{
Logger(logger, LogLevel.Fatal, format, args);
}
/// <summary>
/// 指定严重的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="message">消息内容</param>
/// <param name="error">异常信息</param>
public static void Fatal(this ILogger logger, string message, Exception error)
{
Logger(logger, LogLevel.Fatal, message, error);
}
/// <summary>
/// 指定严重的日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="error">异常信息</param>
public static void Fatal(this ILogger logger, Exception error)
{
Logger(logger, LogLevel.Fatal, error.Message, error);
}
/// <summary>
/// 根据日志级别指定日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="logLevel">日志级别</param>
/// <param name="message">消息内容</param>
private static void Logger(ILogger logger, LogLevel logLevel, string message)
{
logger.Log(logLevel, message, null);
}
/// <summary>
/// 根据日志级别指定日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="logLevel">日志级别</param>
/// <param name="format">格式化内容</param>
/// <param name="args">格式化参数</param>
private static void Logger(ILogger logger, LogLevel logLevel, string format, params object[] args)
{
logger.Log(logLevel,
string.Format(CultureInfo.InvariantCulture, format, args), null);
}
/// <summary>
/// 根据日志级别指定日志消息
/// </summary>
/// <param name="logger"><see cref="ILogger"/></param>
/// <param name="logLevel">日志级别</param>
/// <param name="message">消息内容</param>
/// <param name="error">异常信息</param>
private static void Logger(ILogger logger, LogLevel logLevel, string message, Exception error)
{
logger.Log(logLevel, message, error);
}
}
}<file_sep>using System;
namespace Es.Logging
{
/// <summary>
/// EmptyLogger
/// </summary>
internal class EmptyLogger : ILogger
{
internal static EmptyLogger Instance = new EmptyLogger();
/// <summary>
/// nothing
/// </summary>
/// <param name="logLevel"></param>
/// <returns></returns>
public bool IsEnabled(LogLevel logLevel)
{
return false;
}
/// <summary>
/// nothing
/// </summary>
/// <param name="logLevel"></param>
/// <param name="message"></param>
/// <param name="exception"></param>
public void Log(LogLevel logLevel, string message, Exception? exception)
{
}
}
}<file_sep>using MS = Microsoft.Extensions.Logging;
namespace Es.Logging
{
public static class LoggerFactoryExtensions
{
public static ILoggerFactory AddMicrosoftLog(this ILoggerFactory factory,
MS.ILoggerFactory logFactory)
{
factory.AddProvider(new LoggerProvider(logFactory));
return factory;
}
}
}<file_sep>using System;
using log4net;
namespace Es.Logging
{
internal class Log4 : ILogger
{
private readonly ILog _log;
private readonly static Type ThisDeclaringType = typeof(Log4);
public Log4(ILog log)
{
_log = log;
}
public bool IsEnabled(LogLevel logLevel)
{
return _log.Logger.IsEnabledFor(GetLogLevel(logLevel));
}
public void Log(LogLevel logLevel, string message, Exception? exception)
{
if (!IsEnabled(logLevel))
return;
_log.Logger.Log(ThisDeclaringType,
GetLogLevel(logLevel),
message,
exception);
}
private log4net.Core.Level GetLogLevel(LogLevel logLevel)
{
return logLevel switch
{
LogLevel.Trace => log4net.Core.Level.Trace,
LogLevel.Debug => log4net.Core.Level.Debug,
LogLevel.Info => log4net.Core.Level.Info,
LogLevel.Warn => log4net.Core.Level.Warn,
LogLevel.Error => log4net.Core.Level.Error,
LogLevel.Fatal => log4net.Core.Level.Fatal,
_ => log4net.Core.Level.Off,
};
}
}
}<file_sep>using System;
using System.Collections.Generic;
namespace Es.Logging
{
/// <summary>
/// 日志记录的聚合类
/// </summary>
internal class AggregateLogger : ILogger
{
private readonly string _logName;
public AggregateLogger(ILoggerProvider[] providers, string logName)
{
_logName = logName;
AddProvider(providers);
}
public bool IsEnabled(LogLevel logLevel)
{
List<Exception>? exceptions = null;
foreach (var logger in Loggers)
{
try
{
if (logger.IsEnabled(logLevel))
{
return true;
}
}
catch (Exception ex)
{
exceptions ??= new List<Exception>();
exceptions.Add(ex);
}
}
if (exceptions != null && exceptions.Count > 0)
{
throw new AggregateException(
message: "An error occurred while writing to logger(s).",
innerExceptions: exceptions);
}
return false;
}
public void Log(LogLevel logLevel, string message, Exception? exception)
{
List<Exception>? exceptions = null;
foreach (var logger in Loggers)
{
try
{
logger.Log(logLevel, message, exception);
}
catch (Exception ex)
{
exceptions ??= new List<Exception>();
exceptions.Add(ex);
}
}
if (exceptions != null && exceptions.Count > 0)
{
throw new AggregateException(
message: "An error occurred while writing to logger(s).", innerExceptions: exceptions);
}
}
internal List<ILogger> Loggers { get; } = new List<ILogger>();
/// <summary>
/// 添加新的日志记录,如果当前日志记录器已经创建,
/// 后期可能会追加新的<see cref="ILoggerProvider"/>并且根据日志名创建不同的日志记录方式
/// </summary>
/// <param name="providers"></param>
internal void AddProvider(ILoggerProvider[] providers)
{
foreach (var provider in providers)
Loggers.Add(provider.CreateLogger(_logName));
}
}
}<file_sep>namespace Es.Logging
{
/// <summary>
/// 日志工厂接口
/// </summary>
public interface ILoggerFactory
{
/// <summary>
/// 创建日志记录实例
/// </summary>
/// <param name="name">定义日志的名称</param>
/// <returns><see cref="ILogger"/></returns>
ILogger CreateLogger(string name);
/// <summary>
/// 添加创建日志记录实例的提供者
/// </summary>
/// <param name="providers">用于创建日志记录实例的提供者</param>
void AddProvider(params ILoggerProvider[] providers);
}
}<file_sep>using System;
using System.Globalization;
namespace Es.Logging
{
internal class Logger : ILogger
{
private readonly NLog.Logger _logger;
public Logger(NLog.Logger logger)
{
_logger = logger;
}
public bool IsEnabled(LogLevel logLevel)
{
return _logger.IsEnabled(GetLogLevel(logLevel));
}
public void Log(LogLevel logLevel, string message, Exception? exception)
{
if (!IsEnabled(logLevel))
return;
if (string.IsNullOrEmpty(message) && exception == null)
return;
var eventInfo = NLog.LogEventInfo.Create(
GetLogLevel(logLevel),
_logger.Name,
exception,
CultureInfo.CurrentCulture,
message);
_logger.Log(eventInfo);
}
private NLog.LogLevel GetLogLevel(LogLevel logLevel)
{
return logLevel switch
{
LogLevel.Trace => NLog.LogLevel.Trace,
LogLevel.Debug => NLog.LogLevel.Debug,
LogLevel.Info => NLog.LogLevel.Info,
LogLevel.Warn => NLog.LogLevel.Warn,
LogLevel.Error => NLog.LogLevel.Error,
LogLevel.Fatal => NLog.LogLevel.Fatal,
_ => NLog.LogLevel.Off,
};
}
}
} | 5cdd66f4a2902466bca0e1f71415dd064ed00300 | [
"C#",
"Markdown",
"Batchfile",
"Shell"
] | 44 | C# | EsWork/Es.Logging | b72b83eb4d9ef0df51a59b42ee760d07bd8991db | a7d04169a0762e24d6028a1771b42d2f8ea10a82 |
refs/heads/master | <file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.col-xs-6 {
padding:0px;
}
.col-md-4{
padding:0px;
}
.container{
width:100%;
}
.jumbotron{
background-color:white;
margin-top: 0px;
margin-bottom: 0px;
padding-bottom: 0px;
padding-top:0px;
}
body {
font: normal 16px/1.5 "Helvetica Neue", sans-serif;
background: white;
color: black;
overflow-x: hidden;
padding-bottom: 50px;
}
h2 {
color:pink;
text-align:center;
font-size: 350%;
}
h3{
color:pink;
text-align:center;
font-family: papyrus;
font-size: 250%;
}
p{
text-align:center;
font-family: papyrus;
font-size: 120%;
margin-top:15px;
}
.menu {
position: absolute;
top: 300px;
width: 100%;
z-index: 5;
}
#navbar {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: pink;
text-align:center;
}
.fixed {
position: fixed;
top: 0;
}
.nav {
display:inline-block;
float: none;
text-align: center;
}
.nav a {
display:inline-block;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
.nav a:hover:not(.active) {
background-color: white;
}
.active {
background-color: white;
}
h1 {
font-size: 2.5rem;
color: pink
}
</style>
</head>
<body>
<div class="menu">
<ul id="navbar">
<li class="nav"><a href="finalproject.html">Home</a></li>
<li class="nav"><a href="stories.html">Stories</a></li>
<li class="nav active"><a href="lifehacks.html">Life Hacks</a></li>
<li class="nav"><a href="quotes.html">Quotes</a></li>
<li class="nav"><a href="services.html">Services</a></li>
<li class="nav"><a href="knowyourrights.html">Know Your Rights</a></li>
<li class="nav"><a href="aboutus.html">About Us</a></li>
<li class="nav"><a href="resources.html">Resources</a></li>
</ul>
</div>
<div class="jumbotron">
<center><img src="reallogo.png" alt="logo" style="width:340px;height:340px;"></center>
<p></p>
</div>
<div class="container">
<div class="row">
<div class="col-xs-6 col-md-4"><img src="nailpolish.jfif" alt="nails pic" style="width:280px;height:228px;margin:0px;float:left;" ></div>
<div class="col-xs-6 col-md-4"><h2><center><font color="pink"><br>Life Hacks</font></center></h2></div>
<div class="col-xs-6 col-md-4"><img src="jeans.jpg" alt="jeans pic" style="width:260px;height:228px; margin:0px; float:right;"></div>
<h3><center><font color ="pink">25 Tips To Help Get Through Life<br><br></font></center></h3>
</div>
<center>
<p>-----Paint your keys with nail polish so you remember which one opens which door-----</p>
<p>-----Applying a coat of clear polish will keep your rings from turning your fingers green-----</p>
<p>-----Clear nail polish will stop a tear in your stockings-----</p>
<p>-----Need to get someone a gift? Say you already did and let them guess...that is most likely what they want-----</p>
<p>-----Oatmeal is good for dry irritated skin-----</p>
<p>-----Clean out a sunscreen bottle when you go to a beach to put your money, keys, and etc-----</p>
<p>-----Use a muffin pan to put condiments in it for barbeques-----</p>
<p>-----Separate yoke with a water bottle-----</p>
<p>-----Almost done with your nutella? End it with some ice cream-----</p>
<p>-----Use a fork to keep your tacos upright-----</p>
<p>-----Keep boots upright with pool noodles-----</p>
<p>-----Cut open toilet paper rolls to use as a cuff to hold gift wrap paper-----</p>
<p>-----Use broken hangers a chip bag holders-----</p>
<p>-----Putting dry tea bags in smelling shoes will block out the odor-----</p>
<p>-----Put a cup of water in with your plate of leftover pizza to prevent sogginess-----</p>
<p>-----Rub a walnut on minor scratches on wooden furniture to cover up the damage-----</p>
<p>-----Chinese take out boxes are designed to fold out into plates-----</p>
<p>-----Need to get your shirt unwrinkled? Throw it in the dryer for about five minutes with an ice cube or spray some water on it and the wrinkles will disappear. Also you can blow dry the parts with the wrinkles for a quick fix if you’re running late-----</p>
<p>-----Keep extra feminine products in your bag or car for emergencies-----</p>
<p>-----Bring your own drink to parties and don’t set them down, if you’re feeling anxious-----</p>
<p>-----Use tape to perfect your winged eyeliner-----</p>
<p>-----If you accidentally buy a foundation too dark add some moisturizer to lighten it up-----</p>
<p>-----If you don't want to bother with fixing and refixing your hair all day long, spray your bobby pins with hairspray before you put them in-----</p>
<p>-----Shoes too tight? Put a bag half full of water in the shoe and freeze it to stretch it out-----</p>
<p>-----Put your jeans in a plastic bag and throw them in the freezer overnight to get rid of any bad odors-----</p>
</center>
</div>
<script>
var num = 300; //number of pixels before modifying styles
$(window).bind('scroll', function () {
if ($(window).scrollTop() > num) {
$('.menu').addClass('fixed');
} else {
$('.menu').removeClass('fixed');
}
});
</script>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.jumbotron{
background-color:white;
margin-top: 0px;
margin-bottom: 0px;
padding-bottom: 0px;
padding-top:0px;
}
body {
font: normal 16px/1.5 "Helvetica Neue", sans-serif;
background: white;
color: black;
overflow-x: hidden;
padding-bottom: 50px;
}
h2 {
color:pink;
text-align:center;
font-size: 350%;
}
h3{
color:pink;
text-align:center;
font-family: papyrus;
font-size: 250%;
}
p{
text-align:center;
font-family: papyrus;
font-size: 110%;
}
.menu {
position: absolute;
top: 300px;
width: 100%;
z-index: 5;
}
#navbar {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: pink;
text-align:center;
}
.fixed {
position: fixed;
top: 0;
}
.nav {
display:inline-block;
float: none;
text-align: center;
}
.nav a {
display:inline-block;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
.nav a:hover:not(.active) {
background-color: white;
}
.active {
background-color: white;
}
h1 {
font-size: 2.5rem;
color: pink
}
</style>
</head>
<body>
<div class="menu">
<ul id="navbar">
<li class="nav"><a href="finalproject.html">Home</a></li>
<li class="nav"><a href="stories.html">Stories</a></li>
<li class="nav"><a href="lifehacks.html">Life Hacks</a></li>
<li class="nav"><a href="quotes.html">Quotes</a></li>
<li class="nav"><a href="services.html">Services</a></li>
<li class="nav"><a href="knowyourrights.html">Know Your Rights</a></li>
<li class="nav"><a href="aboutus.html">About Us</a></li>
<li class="nav active"><a href="resources.html">Resources</a></li>
</ul>
</div>
<div class="jumbotron">
<center><img src="reallogo.png" alt="logo" style="width:340px;height:340px;"></center>
<p></p>
</div>
<div class="container">
<h2><center><font color="pink"><br>Resources</font></center></h2>
<p><br>The FemPwr Team couldn't have created this website without tremendous help from other people and websites.
First of all, we'd like to thank our wonderful teacher, <NAME>, and teacher's assistants,
<NAME> and <NAME> from the Girls Who Code EA program for helping us code the website. We would also
like to thank the following websites for helping us find quotes, facts, and people to feature on our site:
<br>
<br>
<a href="https://oag.ca.gov/publications/womansrights">California Department of Justice</a>
<br><br>
<a href="http://www.nwhp.org/resources/womens-rights-movement/history-of-the-womens-rights-movement/">National Women's History Project</a>
<br><br>
<a href="http://www.digitalhistory.uh.edu/timelines/timelinetopics.cfm?tltopicid=3">Digital History</a>
<br><br>
<a href="https://www.ted.com/">Ted Talks</a>
<br><br>
<a href="http://www.harpersbazaar.com/culture/features/a4056/empowering-female-quotes/">Harper's Bazaar<br><br></a>
This website was coded as the final project of the 7-week Girls Who Code Summer Immersion Program. We were four of 20 girls based at the Electronic Arts location
in Redwood City. Girls Who Code is a fantastic program for rising junior and senior girls who are interested in dabbling in coding, technology, and working at
a tech company. Click <a href="https://girlswhocode.com/">here</a> to learn more about the program!</p>
</div>
<script>
var num = 300; //number of pixels before modifying styles
$(window).bind('scroll', function () {
if ($(window).scrollTop() > num) {
$('.menu').addClass('fixed');
} else {
$('.menu').removeClass('fixed');
}
});
</script>
</body>
</html>
| bd378954622863dadcc83c42a0a52e65d0e00af8 | [
"HTML"
] | 2 | HTML | fempwr/project | 5245f7b26d7090d58779c1ba4ddf088812b9e40f | 1eb2b50c15f56adad093d9202c8f856e002c2c84 |
refs/heads/master | <file_sep>FROM rocker/shiny:3.5.2
RUN apt-get update -qq && apt-get -y --no-install-recommends install \
default-jre \
default-jdk \
lzma-dev \
liblzma-dev \
openssl \
libbz2-dev \
libicu-dev \
libxml2-dev \
libcairo2-dev \
libsqlite3-dev \
libmariadbd-dev \
libmariadb-client-lgpl-dev \
libpq-dev \
libssl-dev \
libcurl4-openssl-dev \
libssh2-1-dev \
libgeos-dev \
libgdal-dev \
libproj-dev \
libudunits2-dev \
unixodbc-dev \
libv8-dev \
&& R -e "source('https://bioconductor.org/biocLite.R')" \
&& install2.r --error \
--deps TRUE \
tidyverse \
dplyr \
devtools \
formatR \
remotes \
selectr \
caTools \
plotly \
DT \
readr \
randomForest \
forecast \
hydroGOF \
DataExplorer \
xlsx \
tictoc \
shinyjs \
readxl \
quantregForest
# not clear why selectr needs explicit re-install, see https://github.com/rocker-org/rocker-versioned/pull/63
<file_sep># mmfcordeiro/shiny-verse
fork from rocker/shiny
The `rocker/shiny-verse` image adds the `tidyverse` suite (and
`devtools` suite) of R packages to the `rocker:shiny` images.
Like the `rocker/shiny` images, this stack is versioned so
that a tag, such as `rocker/shiny-verse:3.5.0` will always
provide R v3.5.0, and likewise fix the version of all R
packages installed from CRAN to the [last date that version was
current](https://github.com/rocker-org/rocker-versioned/tree/master/VERSIONS.md).
Additional commonly used dependencies may be added to `shiny-verse`
when appropriate (or at least C libraries needed to ensure other common
packages can be installed from source). Please open an issue on GitHub
to discuss any such proposals.
"# shiny-verse"
| fbb5ee94fc25d34599a8d0e99894836d5b9e1685 | [
"Markdown",
"Dockerfile"
] | 2 | Markdown | mmfcordeiro/shiny-verse | e9483bc154b61383e4959f00b1b5e8cf53f81661 | cdab92cb667a52f4eb2935bc23f8837b4352e4fd |
refs/heads/master | <file_sep>import React,{Component} from 'react';
import {FilmsInfo} from './ui_components/info';
import Preloader from './ui_components/preloader';
import RelatedElement from './ui_components/relatedElement';
import {fetchData} from '../actions/fetchData';
import {getFilmName,getVehicleName,getPlanetName,getSpecieName,getStarshipName,getPeopleName} from '../actions/getName';
import {connect} from 'react-redux';
import axios from 'axios';
let imgPath='';
class PeopleDetail extends Component{
componentDidMount(){
let url =`https://swapi.co/api${this.props.match.url}`;
imgPath=`/images/films/${this.props.match.params.id}.jpg`;
this.props.fetchData(url);
axios.get(url).then((res)=>res.data).then((res)=>{
res.planets.map((planet)=>this.props.getPlanetName(planet));
res.species.map((specie)=>this.props.getSpecieName(specie));
res.characters.map((character)=>this.props.getPeopleName(character));
}
)
}
render(){
let detail=this.props.detail.data;
//console.log(this.props.match.params.id);
if(Object.keys(detail).length===0 ){return <div className='detail-page'><Preloader/></div>}
let species=this.props.detail.species;
let planets=this.props.detail.planets;
let people=this.props.detail.people;
//this.getName('https://swapi.co/api/films/2/');
//console.log(filmsUrl);
//console.log(this.props.detail);
return(
<div className='detail-page'>
<div className='info'>
<figure>
<img src={imgPath} alt={imgPath}/>
</figure>
<div className='detail'>
<FilmsInfo info={detail} />
</div>
</div>
<div className='related'>
<RelatedElement elements={people} name='characters'/>
<RelatedElement elements={species} name='species'/>
<RelatedElement elements={planets} name='planets'/>
</div>
</div>
)
}
}
const mapStatetoProps=state=>({
detail:state.sw_data.detail
})
export default connect(mapStatetoProps,{fetchData,getFilmName,getVehicleName,getPlanetName,getSpecieName,getStarshipName,getPeopleName})(PeopleDetail);<file_sep>import {OPEN_MENU} from './types';
export const openMenu=()=>dispatch=>{
dispatch({
type:OPEN_MENU,
payload:'open'
})
}<file_sep>import {FETCH_DATA} from './types';
import axios from 'axios';
export const fetchData=(url)=>dispatch=>{
axios.get(url).then((res)=>res.data)
.then((res)=>
dispatch({
type:FETCH_DATA,
payload:res
})
)
}<file_sep>import React from 'react';
export const PeopleInfo=({info,homeworld,specie})=>(
<React.Fragment>
<p>name: <span >{info.name}</span></p>
<p>height: <span >{info.height}cm</span></p>
<p>mass: <span >{info.mass}kg</span></p>
<p>gender: <span >{info.gender}</span></p>
<p>birthday: <span>{info.birth_year}</span></p>
<p>hair color: <span>{info.hair_color}</span></p>
<p>skin color: <span>{info.skin_color}</span></p>
<p>specie: <span>{specie}</span></p>
<p>homeworld: <span >{homeworld}</span></p>
</React.Fragment>
)
export const PlanetsInfo=({info})=>(
<React.Fragment>
<p>name: <span >{info.name}</span></p>
<p>diameter: <span>{info.diameter}km</span></p>
<p>climate: <span >{info.climate}</span></p>
<p>gravity: <span >{info.gravity}</span></p>
<p>population: <span>{info.population}</span></p>
</React.Fragment>
)
export const FilmsInfo=({info})=>(
<React.Fragment>
<p>title: <span >{info.title}</span></p>
<p>episode: <span>{info.episode_id}</span></p>
<p>director: <span >{info.director}</span></p>
<p>producer: <span >{info.producer}</span></p>
<p>data: <span>{info.release_date}</span></p>
<p>opening: <span>{info.opening_crawl}</span></p>
</React.Fragment>
)
export const SpeciesInfo=({info,homeworld})=>(
<React.Fragment>
<p>name: <span >{info.name}</span></p>
<p>classification: <span>{info.infoclassification}</span></p>
<p>average height: <span >{info.average_height}</span></p>
<p>average life: <span >{info.average_lifespan}</span></p>
<p>language: <span>{info.language}</span></p>
<p>designation: <span>{info.designation}</span></p>
<p>homeworld: <span >{homeworld}</span></p>
</React.Fragment>
)
export const VehiclesInfo=({info})=>(
<React.Fragment>
<p>name: <span >{info.name}</span></p>
<p>model: <span>{info.model}</span></p>
<p>cost: <span >{info.cost_in_credits}</span></p>
<p>crew: <span >{info.crew}</span></p>
<p>passengers: <span>{info.passengers}</span></p>
<p>cargo capacity: <span>{info.cargo_capacity}</span></p>
<p>vehicle class: <span>{info.vehicle_class}</span></p>
</React.Fragment>
)
export const StarshipsInfo=({info})=>(
<React.Fragment>
<p>name: <span >{info.name}</span></p>
<p>model: <span>{info.model}</span></p>
<p>cost: <span >{info.cost_in_credits}</span></p>
<p>crew: <span >{info.crew}</span></p>
<p>passengers: <span>{info.passengers}</span></p>
<p>consumables: <span>{info.consumables}</span></p>
<p>starship class: <span>{info.starship_class}</span></p>
</React.Fragment>
)<file_sep>export const FETCH_PEOPLE='FETCH_PEOPLE';
export const FETCH_PLANETS='FETCH_PLANETS';
export const FETCH_FILMS='FETCH_FILMS';
export const FETCH_SPECIES='FETCH_SPECIES';
export const FETCH_VEHICLES='FETCH_VEHICLES';
export const FETCH_STARSHIPS='FETCH_STARSHIPS';
export const FETCH_DATA='FETCH_DATA';
export const OPEN_MENU='OPEN_MENU';
export const CLOSE_MENU='CLSOE_MENU';
export const GET_FILM_NAME='GET_FILM_NAME';
export const GET_STARSHIP_NAME='GET_STARSHIP_NAME';
export const GET_SPECIE_NAME='GET_SPECIE_NAME';
export const GET_VEHICLE_NAME='GET_VEHICLE_NAME';
export const GET_PLANET_NAME='GET_PLANET_NAME';
export const GET_PEOPLE_NAME='GET_PEOPLE_NAME';
<file_sep>@import './sass_components/variables';
@import './sass_components/mixins';
@import './sass_components/header.scss';
@import './sass_components/nav.scss';
@import './sass_components/carrusel.scss';
@import './sass_components/detail-page.scss';
@import './sass_components/preloader.scss';
body{
background: #000 url('./images/bcg.jpg');
margin:0;
padding:0;
}
.App{
width:100%;
height: 100vh;
min-height: 680px;
overflow: hidden;
position: relative;
margin: 0 auto;
box-sizing: border-box;
padding: 30px;
display: grid;
grid-template-columns: 100%;
grid-template-rows: 100px 150px 1fr;
grid-template-areas: 'header' 'nav' 'carrusel';
@include breakHeight(0,800px){
grid-template-rows: 50px 100px 1fr;
}
@include break(0,599px){
grid-template-rows: 100px 1fr;
grid-template-areas: 'header' 'carrusel';
padding: 10px;
}
}
<file_sep>.carrusel{
width: 100%;
box-sizing: border-box;
white-space: nowrap;
overflow-x: scroll;
position: relative;
.item{
display: inline-block;
margin: 0 15px;
width: 250px;
height: 343px;
max-height: 550px;
position: relative;
&:hover figure::before{
transform: translateY(0)
}
&:hover figure img{
transform: scale(1.1);
}
&:hover .basic-info{
transform: translateY(0);
}
.item-inner{
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
display:inline-block;
}
figure{
margin:0;
border:4px solid $sw-color;
border-radius: 8px;
box-sizing: border-box;
height:100%;
overflow: hidden;
cursor: pointer;
position: relative;
&:before{
content: "";
position: absolute;
width: 100%;
height: 100%;
background: linear-gradient(0deg, rgba(0,0,0,1) 30%, rgba(0,0,0,0) 100%);
top:0;
left: 0;
transform: translateY(100%);
transition: transform 0.3s ease;
z-index: 2;
}
img{
width: 100%;
height:100%;
object-fit: cover;
transition: transform 0.5s ease;
}
}
.name{
color:#fff;
text-align: center;
font-family: $text-font;
font-size: 16px;
margin: 15px 0;
font-weight: 500;
}
.basic-info{
position: absolute;
bottom: 0;
left: 0;
padding-left: 15px;
padding-right: 15px;
padding-bottom: 10px;
z-index: 3;
transform: translateY(100%);
transition: transform 0.5s ease;
p{
color:$sw-color;
font-size: 12px;
margin: 5px 0;
font-family: $text-font;
font-weight: 500;
text-transform: capitalize;
white-space: normal;
display: none;
&:nth-child(2),&:nth-child(3),&:nth-child(4),&:nth-child(5){
display: block;
}
span{
color:#fff;
}
}
}
}
.pagination{
@include flexCenter(row);
margin-top: 25px;
position: fixed;
left: 50%;
transform: translateX(-50%);
.page{
color:#000;
list-style: none;
text-transform: uppercase;
font-size: 12px;
font-family: $text-font;
background-color: $sw-color;
display: inline-block;
padding: 5px 10px;
cursor: pointer;
border-radius: 8px;
& ~ .page{
margin-left: 25px;
}
}
}
}
/* width */
.carrusel::-webkit-scrollbar {
width: 1px;
}
/* Track */
.carrusel::-webkit-scrollbar-track {
box-shadow: inset 0 0 5px $sw-color;
border-radius: 10px;
}
/* Handle */
.carrusel::-webkit-scrollbar-thumb {
background: $sw-color;
border-radius: 10px;
} <file_sep>import React,{Component} from 'react';
import {VehiclesInfo} from './ui_components/info';
import Preloader from './ui_components/preloader';
import RelatedElement from './ui_components/relatedElement';
import {fetchData} from '../actions/fetchData';
import {getFilmName} from '../actions/getName';
import {connect} from 'react-redux';
import axios from 'axios';
let imgPath='';
class VehicleDetail extends Component{
componentDidMount(){
let url =`https://swapi.co/api${this.props.match.url}`;
imgPath=`/images/vehicles/${this.props.match.params.id}.jpg`;
this.props.fetchData(url);
axios.get(url).then((res)=>res.data).then((res)=>{
res.films.map((film)=>this.props.getFilmName(film));
}
)
}
render(){
let detail=this.props.detail.data;
//console.log(this.props.match.params.id);
if(Object.keys(detail).length===0 ){return <div className='detail-page'><Preloader/></div>}
let films=this.props.detail.films;
//this.getName('https://swapi.co/api/films/2/');
//console.log(filmsUrl);
//console.log(this.props.detail);
return(
<div className='detail-page'>
<div className='info'>
<figure>
<img src={imgPath} alt={imgPath}/>
</figure>
<div className='detail'>
<VehiclesInfo info={detail}/>
</div>
</div>
<div className='related'>
<RelatedElement elements={films} name='films'/>
<RelatedElement elements={[]} name='people'/>
<RelatedElement elements={[]} name='species'/>
</div>
</div>
)
}
}
const mapStatetoProps=state=>({
detail:state.sw_data.detail
})
export default connect(mapStatetoProps,{fetchData,getFilmName})(VehicleDetail);<file_sep>header{
display: flex;
justify-content: space-between;
align-items: flex-start;
grid-area: header;
position: relative;
@include break(0,599px){
flex-direction: column;
align-items: center;
}
h1{
color:$sw-color;
font-family: $sw-font;
font-weight: normal;
font-size: 24px;
display: inline-block;
margin: 0;
@include break(600px,999px){
font-size: 20px;
}
}
.history-button{
}
.search-bar{
display: inline-block;
input{
width: 250px;
border: none;
height: 20px;
border-radius: 8px;
padding-left:40px;
background: #fff url('./images/Search.svg') no-repeat 10px center;
background-size: 15px;
@include break(600px,999px){
width: 200px;
}
&::placeholder{
color:#4f4f4f;
font-size: 12px;
font-family: $sw-font;
}
}
}
.menu-icon{
width: 40px;
height: 40px;
position: absolute;
top:-10px;
right: 0;
z-index:100;
cursor: pointer;
display:none;
overflow: hidden;
@include break(0,599px){
display: block;
}
span{
display: inline-block;
position: absolute;
width: 18px;
height: 2px;
background: $sw-color;
left: 10px;
transition: transform 0.3s ease;
&:nth-child(1){
top:15px;
}
&:nth-child(2){
top:20px;
}
&:nth-child(3){
top:25px;
}
}
&.open span:nth-child(1){
transform: rotate(45deg);
top:20px;
}
&.open span:nth-child(2){
transform: translateX(300%);
}
&.open span:nth-child(3){
transform: rotate(-45deg);
top:20px;
}
}
}<file_sep>import React from 'react';
const Button=({name,className})=>(
<button className={className} style={Style}>
{name}
</button>
)
const Style={
'color':'#000',
'listStyle': 'none',
'textTransform': 'uppercase',
'fontSize': '12px',
'fontFamily': 'DeathStar,sans-serif',
'backgroundColor': '#F6DF20',
'display': 'inline-block',
'padding': '5px 10px',
'cursor': 'pointer',
'borderRadius': '8px',
'border':'none'
}
export default Button;<file_sep>import {FETCH_PEOPLE,FETCH_PLANETS,FETCH_SPECIES,FETCH_STARSHIPS,FETCH_VEHICLES,FETCH_FILMS,FETCH_DATA,GET_FILM_NAME,GET_VEHICLE_NAME,GET_STARSHIP_NAME,GET_PEOPLE_NAME,GET_SPECIE_NAME,GET_PLANET_NAME} from '../actions/types';
const initialState={
people:{
data:[],
next:'',
prev:'',
count:0
},
planets:{
data:[],
next:'',
prev:'',
count:0
},
species:{
data:[],
next:'',
prev:'',
count:0
},
vehicles:{
data:[],
next:'',
prev:'',
count:0
},
starships:{
data:[],
next:'',
prev:'',
count:0
},
films:{
data:[],
next:'',
prev:'',
count:0
},
detail:{data:{},films:[],vehicles:[],planets:[],starships:[],people:[],species:[]}
}
export default (state=initialState,action)=>{
switch(action.type){
case FETCH_PEOPLE:
return{
...state,
people:{
data:action.payload,
next:action.next,
prev:action.prev,
count:action.count
},
detail:{data:{},films:[],vehicles:[],planets:[],starships:[],people:[],species:[]}
}
case FETCH_PLANETS:
return{
...state,
planets:{
data:action.payload,
next:action.next,
prev:action.prev,
count:action.count
}
}
case FETCH_SPECIES:
return{
...state,
species:{
data:action.payload,
next:action.next,
prev:action.prev,
count:action.count
}
}
case FETCH_STARSHIPS:
return{
...state,
starships:{
data:action.payload,
next:action.next,
prev:action.prev,
count:action.count
}
}
case FETCH_VEHICLES:
return{
...state,
vehicles:{
data:action.payload,
next:action.next,
prev:action.prev,
count:action.count
}
}
case FETCH_FILMS:
return{
...state,
films:{
data:action.payload,
next:action.next,
prev:action.prev,
count:action.count
}
}
case FETCH_DATA:
return{
...state,
detail:{
...state.detail,
data:action.payload
}
}
case GET_FILM_NAME:
return{
...state,
detail:{
...state.detail,
films:[...state.detail.films,action.payload]
}
}
case GET_VEHICLE_NAME:
return{
...state,
detail:{
...state.detail,
vehicles:[...state.detail.vehicles,action.payload]
}
}
case GET_STARSHIP_NAME:
return{
...state,
detail:{
...state.detail,
starships:[...state.detail.starships,action.payload]
}
}
case GET_SPECIE_NAME:
return{
...state,
detail:{
...state.detail,
species:[...state.detail.species,action.payload]
}
}
case GET_PLANET_NAME:
return{
...state,
detail:{
...state.detail,
planets:[...state.detail.planets,action.payload]
}
}
case GET_PEOPLE_NAME:
return{
...state,
detail:{
...state.detail,
people:[...state.detail.people,action.payload]
}
}
default:
return state;
}
}<file_sep>import {CLOSE_MENU} from './types';
export const closeMenu=()=>dispatch=>{
dispatch({
type:CLOSE_MENU,
payload:'close'
})
}<file_sep>import React from 'react';
import DisplayContent from '../js_components/displayContent';
import Nav from '../js_components/nav';
export const People=()=>(
<React.Fragment>
<Nav/>
<DisplayContent content='people'/>
</React.Fragment>
)
export const Planets=()=>(
<React.Fragment>
<Nav/>
<DisplayContent content='planets'/>
</React.Fragment>
)
export const Species=()=>(
<React.Fragment>
<Nav/>
<DisplayContent content='species'/>
</React.Fragment>
)
export const Starships=()=>(
<React.Fragment>
<Nav/>
<DisplayContent content='starships'/>
</React.Fragment>
)
export const Vehicles=()=>(
<React.Fragment>
<Nav/>
<DisplayContent content='vehicles'/>
</React.Fragment>
)
export const Films=()=>(
<React.Fragment>
<Nav/>
<DisplayContent content='films'/>
</React.Fragment>
)
<file_sep>import {GET_FILM_NAME,GET_VEHICLE_NAME,GET_STARSHIP_NAME,GET_PEOPLE_NAME,GET_SPECIE_NAME,GET_PLANET_NAME} from './types';
import axios from 'axios';
export const getFilmName=(url)=>dispatch=>(
axios.get(url).then((res)=>
dispatch({
type:GET_FILM_NAME,
payload:res.data.title
})
)
)
export const getVehicleName=(url)=>dispatch=>(
axios.get(url).then((res)=>
dispatch({
type:GET_VEHICLE_NAME,
payload:res.data.name
})
)
)
export const getStarshipName=(url)=>dispatch=>(
axios.get(url).then((res)=>
dispatch({
type:GET_STARSHIP_NAME,
payload:res.data.name
})
)
)
export const getPlanetName=(url)=>dispatch=>(
axios.get(url).then((res)=>
dispatch({
type:GET_PLANET_NAME,
payload:res.data.name
})
)
)
export const getSpecieName=(url)=>dispatch=>(
axios.get(url).then((res)=>
dispatch({
type:GET_SPECIE_NAME,
payload:res.data.name
})
)
)
export const getPeopleName=(url)=>dispatch=>(
axios.get(url).then((res)=>
dispatch({
type:GET_PEOPLE_NAME,
payload:res.data.name
})
)
)<file_sep>import React ,{Component}from 'react';
export default class RelatedElement extends Component{
render(){
return(
<div className='related-element'>
<h3>related {this.props.name}</h3>
<ul>
{this.props.elements.length!==0?this.props.elements.map((element,index)=><li key={index}>{element}</li>):<li>There is no related {this.props.name}</li>}
</ul>
</div>
)
}
}
<file_sep>import React,{Component} from 'react';
import {openMenu} from '../actions/openMenu';
import {closeMenu} from '../actions/closeMenu';
import Button from './ui_components/button';
import {NavLink} from 'react-router-dom';
import {connect} from 'react-redux';
class Header extends Component{
render(){
return(
<header>
<NavLink to='/'>
<h1>star war pedia</h1>
</NavLink>
<Button name='history' className='history-button'/>
<form className='search-bar'>
<input placeholder='search'/>
</form>
<div className={`menu-icon ${this.props.menuState}`} onClick={this.props.menuState==='open'?this.props.closeMenu:this.props.openMenu}>
<span></span>
<span></span>
<span></span>
</div>
</header>
)
}
}
const mapStatetoProps=state=>({
menuState:state.menuState.menu
})
export default connect(mapStatetoProps,{openMenu,closeMenu})(Header);<file_sep>import React, {Component} from 'react';
import {NavLink} from 'react-router-dom';
import {connect} from 'react-redux';
const navItems=['people','species','planets','vehicles','starships','films'];
class Nav extends Component{
render(){
return(
<nav className={`nav ${this.props.menuState}`}>
{navItems.map((nav,index)=>(
<NavLink className='nav-button' activeClassName="active" to={`/${nav}`} key={nav}>{nav}</NavLink>
))}
</nav>
)
}
}
const mapStateToProps=state=>({
menuState:state.menuState.menu
})
export default connect(mapStateToProps)(Nav);
<file_sep>import React from 'react';
import {BrowserRouter, Route,Switch,Redirect} from 'react-router-dom';
import {People,Planets ,Species ,Starships ,Vehicles ,Films } from './category';
import PeopleDetail from '../js_components/peopleDetail';
import PlanetDetail from '../js_components/planetDetail';
import FilmDetail from '../js_components/filmDetail';
import SpecieDetail from '../js_components/specieDetail';
import VehicleDetail from '../js_components/vehicleDetail';
import StarshipDetail from '../js_components/starshipDetail';
import Header from '../js_components/header';
const Routes=()=>(
<BrowserRouter>
<React.Fragment>
<Header/>
<Switch>
<Redirect exact from="/" to="/people" component={People} />
<Route path="/people" exact component={People}/>
<Route path="/people/:id" exact component={PeopleDetail}/>
<Route path="/planets" exact component={Planets}/>
<Route path="/planets/:id" exact component={PlanetDetail}/>
<Route path="/starships" exact component={Starships}/>
<Route path="/starships/:id" exact component={StarshipDetail}/>
<Route path="/species" exact component={Species}/>
<Route path="/species/:id" exact component={SpecieDetail}/>
<Route path="/vehicles" exact component={Vehicles}/>
<Route path="/vehicles/:id" exact component={VehicleDetail}/>
<Route path="/films" exact component={Films}/>
<Route path="/films/:id" exact component={FilmDetail}/>
</Switch>
</React.Fragment>
</BrowserRouter>
)
export default Routes;<file_sep>.detail-page{
grid-area: 2/1/4/2;
display:grid;
grid-template-rows: 60% 40%;
grid-template-columns: 1fr;
grid-template-areas: 'info' 'related';
position: relative;
.info{
grid-area: info;
display: grid;
grid-template-columns: 300px 1fr;
grid-template-rows: 100%;
grid-column-gap: 30px;
grid-template-areas: 'img text';
padding: 15px 0;
border-bottom: 1px solid $sw-color;
figure{
grid-area: img;
margin: 0;
border: 4px solid #fff;
box-sizing: border-box;
img{
width: 100%;
height: 100%;
object-fit: cover;
}
}
.detail{
grid-area: text;
p{
color: #fff;
margin: 8px 0;
text-transform: capitalize;
color:$sw-color;
font-family: $text-font;
span{
color:#fff;
margin-left: 10px;
}
}
}
}
.related{
grid-area: related;
display:flex;
justify-content: space-between;
padding: 15px 0 0 0;
box-sizing: border-box;
.related-element{
width: 30%;
box-sizing: border-box;
background-color: #fff;
border-radius: 8px;
padding: 10px 15px;
overflow: scroll;
h3{
font-size: 14px;
margin: 0;
text-transform: capitalize;
}
ul{
margin: 0;
padding: 0;
margin-top: 15px;
li{
list-style: none;
font-size: 14px;
font-family: $text-font;
font-weight: normal;
margin-bottom: 3px;
}
}
}
}
}<file_sep>import React from 'react';
const Preloader=()=>(
<div className='preloader'>
<span className='loading-text'>Loading</span>
<div className='circles'>
<span className='circle'></span>
<span className='circle'></span>
<span className='circle'></span>
<span className='circle'></span>
</div>
</div>
)
export default Preloader; | a80fbbc67918883d36b5e6036cee63c338710236 | [
"SCSS",
"JavaScript"
] | 20 | SCSS | lucas1004jx/start-war-pedia | 27d5cb6dd239fbe41a2989f563725551b9d4f980 | 0276ffb084cec1aa58fe236e1d6299c1332d18ba |
refs/heads/master | <file_sep>#include "camera.h"
/*---------------------------------------------------------------------------*/
Camera::Camera( GLfloat screen_width, GLfloat screen_height,
GLfloat xcamera, GLfloat ycamera_height, GLfloat zcamera_distance,
GLfloat znear, GLfloat zfar,
GLfloat angle_view,
GLfloat mouse_sensitivity, GLfloat key_forward_sensitivity, GLfloat key_lateral_sensitivity, GLfloat key_height_sensitivity)
: yrotcamera(0.0), xrotcamera(0.0), zrotcamera(0.0)
{
this->screen_width = screen_width;
this->screen_height = screen_height;
this->xcamera = xcamera;
this->ycamera = ycamera_height;
this->zcamera = zcamera_distance;
this->znear = znear;
this->zfar = zfar;
this->angle_view = angle_view;
this->mouse_sensitivity = mouse_sensitivity;
this->key_forward_sensitivity = key_forward_sensitivity;
this->key_lateral_sensitivity = key_lateral_sensitivity;
this->key_height_sensitivity = key_height_sensitivity;
Init3dView();
}
/*---------------------------------------------------------------------------*/
void Camera::Init3dView()
{
glViewport(0, 0, this->screen_width, this->screen_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
perspectiveGL(angle_view, (GLdouble)this->screen_width/this->screen_height, znear, zfar);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity();
}
/*---------------------------------------------------------------------------*/
void Camera::ProcessMouse(float xoffset, float yoffset)
{
Yrotcamera( (GLfloat)(xoffset * this->mouse_sensitivity) );
Xrotcamera( (GLfloat)(yoffset * this->mouse_sensitivity) );
//ycamera += 10*mouse_z;
}
/*---------------------------------------------------------------------------*/
void Camera::ProcessKeyboard(bool forward, bool backward, bool left, bool right, bool up, bool down)
{
if(forward)
Walk( this->key_forward_sensitivity );
else if(backward)
Walk( -this->key_forward_sensitivity );
if(left)
Yrotcamera( this->key_lateral_sensitivity );
else if(right)
Yrotcamera( -this->key_lateral_sensitivity );
if(up)
ycamera += this->key_height_sensitivity;
else if(down)
ycamera -= this->key_height_sensitivity;
}
/*---------------------------------------------------------------------------*/
void Camera::Walk(GLfloat speed)
{
GLfloat yangle = (-yrotcamera - 90.0) * Deg2Rad;
GLfloat xangle = (-xrotcamera - 90.0) * Deg2Rad;
ycamera += -cos(xangle) * speed;
xcamera += cos(yangle) * -sin(xangle) * speed;
zcamera += sin(yangle) * -sin(xangle) * speed;
}
/*---------------------------------------------------------------------------*/
void Camera::Yrotcamera(GLfloat speed)
{
yrotcamera += speed;
}
void Camera::Xrotcamera(GLfloat speed)
{
xrotcamera += speed;
}
void Camera::Zrotcamera(GLfloat speed)
{
zrotcamera += speed;
}
/*---------------------------------------------------------------------------*/
void Camera::CameraTransformations()
{
glLoadIdentity();
glRotatef(-xrotcamera, 1.0, 0.0, 0.0);
glRotatef(-zrotcamera, 0.0, 0.0, 1.0);
glRotatef(-yrotcamera, 0.0, 1.0, 0.0);
glTranslatef(-xcamera, -ycamera, -zcamera);
}
/*---------------------------------------------------------------------------*/
void Camera::perspectiveGL( GLdouble fovY, GLdouble aspect, GLdouble znear, GLdouble zfar )
{
GLdouble fW, fH;
fH = tan( fovY / 180 * PI ) * znear / 2;
fW = fH * aspect;
glFrustum( -fW, fW, -fH, fH, znear, zfar );
}<file_sep># SDL2 OpenGL Camera (fixed pipeline, no shader)
Depends on SDL2 / OpenGL / GLEW
Usage:
git clone https://github.com/devpack/sdl2-opengl.git
cd sdl2-opengl
mkdir build
cd build
cmake ..
make
/.playfield
Move camera with the mouse, arrow keys, Q and W keys.
<file_sep>#ifndef __RENDER_H_
#define __RENDER_H_
#include "init_playfield.h"
/*---------------------------------------------------------------------------*/
class Render
{
public:
Render();
virtual ~Render();
public:
void Scene();
void DrawCube();
};
#endif<file_sep>cmake_minimum_required(VERSION 3.5)
project("playfield")
find_package(SDL2 REQUIRED)
#set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(SRC timer.cpp render.cpp camera.cpp init_playfield.cpp main.cpp)
add_executable(playfield ${SRC} )
target_link_libraries(playfield GLEW GL SDL2)
#target_include_directories(playfield BEFORE PUBLIC /usr/include)
<file_sep>#include "init_playfield.h"
#include "camera.h"
#include "render.h"
#include "timer.h"
#include <sstream>
/*---------------------------- EVENTS <=> Camera ----------------------------*/
void process_mouse(Camera *camera, const SDL_MouseMotionEvent & event) {
camera->ProcessMouse((float)event.xrel, (float)event.yrel);
}
/*--------------------------------- LOOP ------------------------------------*/
void game_loop(InitPlayfield *playfield, Camera *camera, Render *render) {
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//SDL_GL_SwapWindow(playfield->mainWindow);
// FPS timer
Timer fps_timer;
fps_timer.start();
int frame = 0;
// title timer
Timer title_timer;
title_timer.start();
// key camera motion
bool forward = false;
bool backward = false;
bool left = false;
bool right = false;
bool up = false;
bool down = false;
// main loop
bool loop = true;
while (loop)
{
// SDL2 events
SDL_Event event;
while (SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT) {
loop = false;
break;
}
// mouse
if(event.type == SDL_MOUSEMOTION) {
process_mouse(camera, event.motion);
}
// key up
if(event.type == SDL_KEYDOWN) {
if(event.key.keysym.sym == SDLK_ESCAPE) {
loop = false;
break;
}
if(event.key.keysym.sym == SDLK_UP)
forward = true;
if (event.key.keysym.sym == SDLK_DOWN)
backward = true;
if(event.key.keysym.sym == SDLK_LEFT)
left = true;
if(event.key.keysym.sym == SDLK_RIGHT)
right = true;
if(event.key.keysym.sym == SDLK_q)
up = true;
if(event.key.keysym.sym == SDLK_w)
down = true;
}
// key down
if(event.type == SDL_KEYUP) {
if(event.key.keysym.sym == SDLK_UP)
forward = false;
if (event.key.keysym.sym == SDLK_DOWN)
backward = false;
if(event.key.keysym.sym == SDLK_LEFT)
left = false;
if(event.key.keysym.sym == SDLK_RIGHT)
right = false;
if(event.key.keysym.sym == SDLK_q)
up = false;
if(event.key.keysym.sym == SDLK_w)
down = false;
}
} // end while poll event
// clear
glClear(GL_COLOR_BUFFER_BIT);
// camera moves
camera->ProcessKeyboard(forward, backward, left, right, up, down);
camera->CameraTransformations();
// scene
render->Scene();
// show back buffer
SDL_GL_SwapWindow(playfield->mainWindow);
// FPS
frame++;
// update once per sec
if( title_timer.get_ticks() > 1000 )
{
std::stringstream s;
s << "FPS: " << frame / ( fps_timer.get_ticks() / 1000.f );
SDL_SetWindowTitle(playfield->mainWindow, s.str().c_str());
title_timer.start();
}
} // end while loop
}
/*--------------------------------- MAIN ------------------------------------*/
// screen globals
const int screen_width = 1280;
const int screen_height = 800;
bool fullscreen = false;
bool vsync = true;
// camera globals
GLfloat xcamera = 0.0;
GLfloat ycamera_height = 0.0;
GLfloat zcamera_distance = 5.0;
GLfloat znear = 1.0; // Frustum culling znear
GLfloat zfar = 1000.0; // Frustum culling zfar
GLfloat angle_view = 45.0;
GLfloat mouse_sensitivity = 0.1;
GLfloat key_forward_sensitivity = 0.2;
GLfloat key_lateral_sensitivity = 1.0;
GLfloat key_height_sensitivity = 0.1;
int main(int argc, char* argv[])
{
// SDL screen: InitPlayfield(fullscreen, vsync)
InitPlayfield *playfield=new InitPlayfield(screen_width, screen_height, fullscreen, vsync);
// screen size
int actual_screen_width, actual_screen_height;
SDL_GetWindowSize(playfield->mainWindow, &actual_screen_width, &actual_screen_height);
std::cout << "Screen size: " << actual_screen_width << "x" << actual_screen_height << std::endl;
// Camera(actual_screen_width, actual_screen_height, xcamera, ycamera_height, zcamera_distance, znear, zfar, angle_view, mouse_sensitivity, key_forward_sensitivity, key_lateral_sensitivity, key_height_sensitivity);
Camera *camera = new Camera(actual_screen_width, actual_screen_height, xcamera, ycamera_height, zcamera_distance, znear, zfar, angle_view,
mouse_sensitivity, key_forward_sensitivity, key_lateral_sensitivity, key_height_sensitivity);
// render->Scene() used in the main loop
Render *render = new Render();
// main loop
game_loop(playfield, camera, render);
delete playfield;
delete camera;
return 0;
}
<file_sep>#include "render.h"
/*---------------------------------------------------------------------------*/
Render::Render()
{
}
Render::~Render()
{
}
/*---------------------------------------------------------------------------*/
void Render::Scene() {
this -> DrawCube();
}
/*---------------------------------------------------------------------------*/
void Render::DrawCube()
{
glColor4f(0.2, 0.2, 0.25, 1.0);
float XWORLD = 1.0f;
float YWORLD = 1.0f;
float ZWORLD = 1.0f;
// Front
glBegin(GL_LINE_LOOP);
glVertex3f(-XWORLD, YWORLD, ZWORLD);
glVertex3f( XWORLD, YWORLD, ZWORLD);
glVertex3f( XWORLD, -YWORLD, ZWORLD);
glVertex3f(-XWORLD, -YWORLD, ZWORLD);
glEnd();
// Back
glBegin(GL_LINE_LOOP);
glVertex3f(-XWORLD, YWORLD, -ZWORLD);
glVertex3f( XWORLD, YWORLD, -ZWORLD);
glVertex3f( XWORLD, -YWORLD, -ZWORLD);
glVertex3f(-XWORLD, -YWORLD, -ZWORLD);
glEnd();
// Side
glBegin(GL_LINES);
glVertex3f(-XWORLD, YWORLD, ZWORLD);
glVertex3f(-XWORLD, YWORLD, -ZWORLD);
glVertex3f(XWORLD, YWORLD, ZWORLD);
glVertex3f(XWORLD, YWORLD, -ZWORLD);
glVertex3f(XWORLD, -YWORLD, ZWORLD);
glVertex3f(XWORLD, -YWORLD, -ZWORLD);
glVertex3f(-XWORLD, -YWORLD, ZWORLD);
glVertex3f(-XWORLD, -YWORLD, -ZWORLD);
glEnd();
}
<file_sep>#ifndef __CAMERA_H_
#define __CAMERA_H_
#include "init_playfield.h"
const GLdouble PI = 3.1415926535897932384626433832795;
const GLdouble Deg2Rad = 0.0174532925199432957692369076848861;
/*---------------------------------------------------------------------------*/
class Camera
{
public:
GLfloat screen_width, screen_height;
GLfloat xcamera, ycamera, zcamera;
GLfloat znear, zfar;
GLfloat angle_view;
GLfloat speedwalk, speedrot;
GLfloat yrotcamera, xrotcamera, zrotcamera;
GLfloat mouse_sensitivity;
GLfloat key_forward_sensitivity;
GLfloat key_lateral_sensitivity;
GLfloat key_height_sensitivity;
;
public:
Camera( GLfloat screen_width, GLfloat screen_height,
GLfloat xcamera, GLfloat ycamera_height, GLfloat zcamera_distance,
GLfloat znear, GLfloat zfar,
GLfloat angle_view,
GLfloat mouse_sensitivity, GLfloat key_forward_sensitivity, GLfloat key_lateral_sensitivity, GLfloat key_height_sensitivity);
~Camera() {}
public:
void Init3dView();
void Walk(GLfloat speed);
void Yrotcamera(GLfloat speed);
void Xrotcamera(GLfloat speed);
void Zrotcamera(GLfloat speed);
void CameraTransformations();
void ProcessKeyboard(bool forward, bool backward, bool left, bool right, bool up, bool down);
void ProcessMouse(float xoffset, float yoffset);
void perspectiveGL(GLdouble fovY, GLdouble aspect, GLdouble znear, GLdouble zfar);
};
#endif<file_sep>#ifndef __INITPLAYFIELD_H_
#define __INITPLAYFIELD_H_
#include <string>
#include <iostream>
//#define GL3_PROTOTYPES 1
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include "math.h"
/*---------------------------------------------------------------------------*/
class InitPlayfield
{
public:
int screen_width;
int screen_height;
// Our SDL_Window
SDL_Window *mainWindow;
// Our opengl context handle
SDL_GLContext mainContext;
public:
InitPlayfield(int screen_width, int screen_height, bool fullscreen, bool vsync);
virtual ~InitPlayfield();
};
#endif
| 7f290ab552b7fd60a20a48e32d4a3077cb494a1f | [
"Markdown",
"C++",
"CMake"
] | 8 | Markdown | Tubbz-alt/sdl2-opengl | 8f00674bcb4fa6a2848d05b754a4747c6218518d | 2d067a5912eb5a4f9051fc06282a7ea33b36ee9c |
refs/heads/master | <file_sep># How to use with your own project
1. Add Firebase `.plist` and/or `google-services.json` files to your project.
3. Include `camera` and `firebase_ml_vision` plugin in your project and follow instructions on camera permissions.
3. Include `main.dart`, `utils.dart`, and `detector_painters.dart` in your lib folder.g
| 008dc54f87785d3069962fe4398e330d3ea574af | [
"Markdown"
] | 1 | Markdown | durfu/mlkit_demo | eadeab661cabe71151643e84a6917623163e037d | fa501c05ddc7e35e6d4067a089b5b888fb501377 |
refs/heads/master | <repo_name>mdavis88/ITM352_F19_repo<file_sep>/README.md
Repo for ITM352 Fall 2019 Labs and Assignments
| 884ab0c1d072988799557109ba9622fff3c8255c | [
"Markdown"
] | 1 | Markdown | mdavis88/ITM352_F19_repo | ca011518ae00d39e2199f3a6a6741414db815ea6 | d6322bf51b1ebbb4a5b56d9920712c8b61ec7eda |
refs/heads/master | <file_sep>//
// FooClass.swift
// SwiftRuntimeTest
//
// Created by <NAME> on 20/12/2015.
// Copyright © 2015 PADL Software Pty Ltd. All rights reserved.
//
class FooClass : SomeProtocol {
var string : String
var description : String {
get {
return "hello \(string)"
}
}
required init?(_ string: String) {
self.string = string
}
}
<file_sep>//
// SomeProtocol.swift
// SwiftRuntimeTest
//
// Created by <NAME> on 20/12/2015.
// Copyright © 2015 PADL Software Pty Ltd. All rights reserved.
//
protocol SomeProtocol : CustomStringConvertible {
init?(_ string: String)
}
<file_sep>A toy implementation of a function to dynamically instantiate a Swift class at runtime.
swift_classFromString() returns an optional metatype which can be unwrapped and cast to Some{Class,Protocol}.Type. The metatype can then be instantiated.
See main.swift for an example.
<file_sep>//
// SwiftClassFromString.swift
// SwiftRuntimeTest
//
// Created by <NAME> on 20/12/2015.
// Copyright © 2015 PADL Software Pty Ltd. All rights reserved.
//
import Foundation
#if os(OSX) || os(iOS)
private let RTLD_DEFAULT = UnsafeMutablePointer<Void>(bitPattern: -2)
#elseif os(Linux)
private let RTLD_DEFAULT = UnsafeMutablePointer<Void>(bitPattern: 0)
#endif
typealias MetadataAccessor = @convention(c) () -> AnyClass?
/**
Calls a metadata accessor given a metadata accessor symbol name.
*/
private func metadataFromAccessorName(mangledName : String) -> AnyClass?
{
let cf = mangledName // ._cfObject for SwiftFoundation
var str = CFStringGetCStringPtr(cf, kCFStringEncodingASCII)
let symbol : MetadataAccessor?
var buffer : UnsafeMutablePointer<CChar> = nil
var length : Int = 0
if str == nil {
length = CFStringGetLength(cf) + 1
buffer = UnsafeMutablePointer<CChar>.alloc(length)
CFStringGetCString(cf, buffer, length, kCFStringEncodingASCII)
// surely there's a better way to cast away mutability?
str = unsafeBitCast(buffer, UnsafePointer<CChar>.self)
}
symbol = unsafeBitCast(dlsym(RTLD_DEFAULT, str), MetadataAccessor.self);
if str == nil {
buffer.destroy(length)
buffer.dealloc(length)
}
return symbol != nil ? symbol!() : nil
}
/**
Returns mangled metadata accessor symbol name for a namespaced
Swift class.
*/
private func mangledTypeMetadataAccessorNameForClass(className : String) -> String
{
let components = CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault,
className,
".") as [AnyObject]
var mangledName = "_TMaC"
for component in components as! [CFString] {
let len = CFStringGetLength(component)
mangledName += "\(len)" + (component as String)
}
return mangledName
}
/**
Returns native class metadata for a string identifying a Swift class.
*/
func swift_classFromString_native(className : String) -> AnyClass?
{
return metadataFromAccessorName(mangledTypeMetadataAccessorNameForClass(className))
}
/**
Returns class metadata for a string identifying a Swift or Objective-C class.
*/
func swift_classFromString(className : String) -> AnyClass?
{
var metadata : AnyClass?
metadata = swift_classFromString_native(className)
#if _runtime(_ObjC)
if (metadata == nil) {
metadata = NSClassFromString(className)
}
#endif
return metadata
}
<file_sep>//
// main.swift
// SwiftRuntimeTest
//
// Created by <NAME> on 20/12/2015.
// Copyright © 2015 PADL Software Pty Ltd. All rights reserved.
//
import Foundation
func main() -> Int32 {
let fooClass : AnyClass? = swift_classFromString("SwiftRuntimeTest.FooClass")
let metatype = fooClass as? SomeProtocol.Type
let anInstance = metatype?.init("world")
if (anInstance != nil) {
print("\(anInstance!)")
} else {
print("Nada.")
}
#if _runtime(_ObjC)
// try an Objective-C class for OS X
let stringClass : AnyClass? = swift_classFromString("NSString")
let metatype2 = stringClass as? NSString.Type
let anInstance2 = metatype2?.init(UTF8String: "Hello NSString")
if (anInstance2 != nil) {
print("\(anInstance2!)")
}
#endif
return 0
}
exit(main())
| 2a777667bb079ad959c24bfdcf92b45484b72c57 | [
"Swift",
"Markdown"
] | 5 | Swift | lhoward/SwiftRuntimeTest | d8e78878967c5d128d568ec5786db8fb7bb85f7c | df811a99c38c44267f661fcf05c84f88a94c6379 |
refs/heads/master | <repo_name>rumourcy/WxUtils<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.trier</groupId>
<artifactId>WxUtils</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>WxUtils</name>
<url>http://maven.apache.org</url>
<properties>
<junit-version>4.11</junit-version>
<dom4j-version>1.6.1</dom4j-version>
<httpclient-version>4.5.3</httpclient-version>
<fastjson-version>1.2.33</fastjson-version>
<jetty-version>9.4.6.v20170531</jetty-version>
<javaee-version>7.0</javaee-version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>${dom4j-version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient-version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson-version}</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee-version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>WxUtils</finalName>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty-version}</version>
</plugin>
</plugins>
</build>
</project>
<file_sep>/readme.md
### 微信开发工具包
#### 实现功能
- 微信授权
- 用户基本信息获取
- 统一下单
- 微信支付
#### 依赖包
- dom4j
- HttpClient
- fastjson<file_sep>/src/main/webapp/jsp/wxPay.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="org.trier.wechat.pojo.pay.BrandWCPay" %>
<%@ page import="org.trier.wechat.pojo.order.UnifiedOrder" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/>
<script type="text/javascript" src="/WxUtils/js/adapt.js"></script>
<link rel="stylesheet" type="text/css" href="/WxUtils/css/weuix.min.css">
<link rel="stylesheet" href="/WxUtils/css/wxPay.css"/>
<title>支付</title>
</head>
<body>
<%
BrandWCPay brandWCPay = (BrandWCPay) request.getAttribute("wcpay");
UnifiedOrder unifiedOrder = (UnifiedOrder) request.getAttribute("order");
%>
<div class="topbar">
<a href="javascript:history.go(-1)">
<i class="icon icon-109"></i>
<span>返回</span>
</a>
</div>
<div class="order-info">
<div class="order-id">活动订单-<%= unifiedOrder.getOutTradeNo() %>
</div>
<div class="order-price">¥<%= unifiedOrder.getTotalFee() %>
</div>
</div>
<div class="order-receiver clearfloat">
<div class="receiver-txt">收款方</div>
<div class="receiver-name">TEST</div>
</div>
<div class="pay">
<a class="pay-btn" onclick="callpay()">立即支付</a>
</div>
<script type="text/javascript">
function onBridgeReady() {
WeixinJSBridge.invoke(
'getBrandWCPayRequest', {
"appId": "<%= brandWCPay.get("appId") %>",
"timeStamp": "<%= brandWCPay.get("timeStamp") %>",
"nonceStr":"<%= brandWCPay.get("nonceStr") %>",
"package":"<%= brandWCPay.get("package") %>",
"signType":"<%= brandWCPay.get("signType") %>",
"paySign":"<%= brandWCPay.get("paySign") %>"
},
function (res) {
if (res.err_msg == "get_brand_wcpay_request:fail") {
} // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回 ok,但并不保证它绝对可靠。
}
);
}
function callpay() {
if (typeof WeixinJSBridge == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
}
} else {
onBridgeReady();
}
}
</script>
</body>
</html>
<file_sep>/src/main/java/org/trier/wechat/pojo/pay/BrandWCPay.java
package org.trier.wechat.pojo.pay;
import org.trier.wechat.common.SignMap;
import org.trier.wechat.pojo.order.UnifiedOrderResult;
import org.trier.wechat.util.NonceStrUtil;
public class BrandWCPay extends SignMap {
public BrandWCPay(UnifiedOrderResult unifiedOrderResult) {
super();
put("appId", unifiedOrderResult.get("appid"));
put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
put("nonceStr", NonceStrUtil.getNonceStr(32));
put("package", "prepay_id=" + unifiedOrderResult.get("prepay_id"));
put("signType", "MD5");
put("paySign", makeSign());
}
}<file_sep>/src/main/java/org/trier/wechat/common/SignMap.java
package org.trier.wechat.common;
import org.trier.wechat.config.WeChatConfig;
import org.trier.wechat.exception.WxException;
import org.trier.wechat.util.MD5Util;
import org.trier.wechat.util.NumericUtil;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
/**
* 重写TreeMap,使之适合产生签名
*/
public class SignMap extends TreeMap<String, String> {
private final static String SIGN = "sign";
/**
* 设置签名,并返回签名的值
*
* @return
*/
public String setSign() {
if (get(SIGN) == null)
put(SIGN, makeSign());
return get(SIGN);
}
/**
* 获取签名
*
* @return
*/
public String getSign() {
return get(SIGN);
}
/**
* 判断签名是否设置
*
* @return
*/
public boolean isSignSet() {
return containsKey(SIGN);
}
/**
* 签名算法,该函数
*
* @return
*/
protected String makeSign() {
//签名生成第一步:按字典序排序参数
StringBuilder sb = new StringBuilder();
sb.append(toString());
//签名生成第二步:在字符串后面加上KEY
sb.append("&key=" + WeChatConfig.KEY);
//签名生成第三步:MD5加密
String str = MD5Util.getMessageDigest(sb.toString());
//签名生成第四步:所有字符转为大写
return str.toUpperCase();
}
/**
* 将订单数据转成xml
*
* @return
*/
public String toXml() throws WxException {
if (size() == 0)
throw new WxException("订单数据异常");
StringBuilder sb = new StringBuilder();
sb.append("<xml>");
Iterator<Map.Entry<String, String>> iterator = entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (NumericUtil.isNumeric(entry.getValue())) {
sb.append("<");
sb.append(entry.getKey());
sb.append(">");
sb.append(entry.getValue());
sb.append("</");
sb.append(entry.getKey());
sb.append(">");
} else {
sb.append("<");
sb.append(entry.getKey());
sb.append("><![CDATA[");
sb.append(entry.getValue());
sb.append("]]></");
sb.append(entry.getKey());
sb.append(">");
}
}
sb.append("</xml>");
return sb.toString();
}
@Override
public String toString() {
Iterator<Map.Entry<String, String>> i = entrySet().iterator();
if (!i.hasNext())
return "";
StringBuilder sb = new StringBuilder();
for (; ; ) {
Map.Entry<String, String> e = i.next();
String key = e.getKey();
if (key.equals(SIGN)) {
if (!i.hasNext()) {
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
continue;
}
String value = e.getValue();
sb.append(key);
sb.append('=');
sb.append(value);
if (!i.hasNext())
return sb.toString();
sb.append('&');
}
}
}
<file_sep>/src/main/java/org/trier/wechat/exception/WxException.java
package org.trier.wechat.exception;
/**
* 微信相关异常
*/
public class WxException extends Exception {
public WxException(String message) {
super(message);
}
}
<file_sep>/src/main/java/org/trier/wechat/service/UnifiedOrderService.java
package org.trier.wechat.service;
import org.trier.wechat.config.WeChatConfig;
import org.trier.wechat.exception.WxException;
import org.trier.wechat.pojo.order.UnifiedOrder;
import org.trier.wechat.pojo.order.UnifiedOrderResult;
import org.trier.wechat.util.HttpUtil;
import org.trier.wechat.util.NonceStrUtil;
/**
* 同一下单
*/
public class UnifiedOrderService {
private UnifiedOrder unifiedOrder;
public UnifiedOrderService(UnifiedOrder unifiedOrder) {
this.unifiedOrder = unifiedOrder;
}
public UnifiedOrderResult unifiedOrder() {
UnifiedOrderResult unifiedOrderResult = new UnifiedOrderResult();
try {
if (!unifiedOrder.isOutTradeNoSet())
throw new WxException("缺少统一支付接口必填参数out_trade_no!");
if (!unifiedOrder.isBodySet())
throw new WxException("缺少统一支付接口必填参数body!");
if (!unifiedOrder.isTotalFeeSet())
throw new WxException("缺少统一支付接口必填参数total_fee!");
if (!unifiedOrder.isTradeTypeSet())
throw new WxException("缺少统一支付接口必填参数trade_type!");
if (!unifiedOrder.isSpbillCreateIpSet())
throw new WxException("缺少统一支付接口必填参数spill_create_ip!");
if (unifiedOrder.getTradeType().equals("JSAPI") && !unifiedOrder.isOpenIdSet())
throw new WxException("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!");
} catch (WxException e) {
e.printStackTrace();
return null;
}
unifiedOrder.setAppid(WeChatConfig.APPID);
unifiedOrder.setMchId(WeChatConfig.MCHID);
unifiedOrder.setNonceStr(NonceStrUtil.getNonceStr(32));
unifiedOrder.setSign();
String resultXml;
try {
resultXml = HttpUtil.doPostXml(WeChatConfig.UNIFIEDORDERURL, unifiedOrder.toXml());
unifiedOrderResult.fromXml(resultXml);
} catch (WxException e) {
e.printStackTrace();
return null;
}
if(!unifiedOrderResult.checkSign()){
try {
throw new WxException("订单返回数据签名错误!");
} catch (WxException e) {
e.printStackTrace();
return null;
}
}
return unifiedOrderResult;
}
}<file_sep>/src/main/java/org/trier/wechat/pojo/order/UnifiedOrder.java
package org.trier.wechat.pojo.order;
import org.trier.wechat.common.SignMap;
/**
* 微信统一下单对象
*/
public class UnifiedOrder extends SignMap {
/**
* 字段名:公众账号ID
* 必填:是
* 示例值:wxd678efh567hg6787
* 描述:微信支付分配的公众账号ID(企业号corpid即为此appId)
*/
private final static String APPID = "appid";
/**
* 字段名:商户号
* 必填:是
* 示例值:1230000109
* 描述:微信支付分配的商户号
*/
private final static String MCH_ID = "mch_id";
/**
* 字段名:设备号
* 必填:否
* 示例值:013467007045764
* 描述:自定义参数,可以为终端设备号(门店号或收银设备ID),PC网页或公众号内支付可以传"WEB"
*/
private final static String DEVICE_INFO = "device_info";
/**
* 字段名:随机字符串
* 必填:是
* 示例值:5K8264ILTKCH16CQ2502SI8ZNMTM67VS
* 描述:随机字符串,长度要求在32位以内。推荐随机数生成算法
*/
private final static String NONCE_STR = "nonce_str";
/**
* 字段名:签名
* 必填:是
* 示例值:5K8264ILTKCH16CQ2502SI8ZNMTM67VS
* 描述:通过签名算法计算得出的签名值,详见签名生成算法
* https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3
*/
private final static String SIGN = "sign";
/**
* 字段名:签名类型
* 必填:否
* 示例值:HMAC-SHA256
* 描述:签名类型,默认为MD5,支持HMAC-SHA256和MD5。
*/
private final static String SIGN_TYPE = "sign_type";
/**
* 字段名:商品描述
* 必填:是
* 示例值:腾讯充值中心-QQ会员充值
* 描述:商品简单描述,该字段请按照规范传递,具体请见参数规定
*/
private final static String BODY = "body";
/**
* 字段名:商品详情
* 必填:否
* 描述:单品优惠字段(暂未上线)
*/
private final static String DETAIL = "detail";
/**
* 字段名:附加数据
* 必填:否
* 示例值:深圳分店
* 描述:附加数据,在查询API和支付通知中原样返回,可作为自定义参数使用
*/
private final static String ATTACH = "attach";
/**
* 字段名:商品订单号
* 必填:是
* 示例值:20150806125346
* 描述:商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@ ,且在同一个商户号下唯一。详见商户订单号
*/
private final static String OUT_TRADE_NO = "out_trade_no";
/**
* 字段名:标价币种
* 必填:否
* 示例值:CNY
* 描述:符合ISO 4217标准的三位字母代码,默认人民币:CNY,详细列表请参见货币类型
*/
private final static String FEE_TYPE = "fee_type";
/**
* 字段名:标价金额
* 必填:是
* 示例值:88
* 描述:订单总金额,单位为分,详见支付金额
*/
private final static String TOTAL_FEE = "total_fee";
/**
* 字段名:终端IP
* 必填:是
* 示例值:172.16.31.10
* 描述: APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP。
*/
private final static String SPBILL_CREATE_IP = "spbill_create_ip";
/**
* 字段名:交易起始时间
* 必填:否
* 示例值:20091225091010
* 描述:订单生成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
*/
private final static String TIME_START = "time_start";
/**
* 字段名:交易结束时间
* 必填:否
* 示例值:20091227091010
* 描述:订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。其他详见时间规则
*/
private final static String TIME_EXPIRE = "time_expire";
/**
* 字段名:订单优惠标记
* 必填:否
* 示例值:WXG
* 描述:订单优惠标记,使用代金券或立减优惠功能时需要的参数,说明详见代金券或立减优惠
*/
private final static String GOODS_TAG = "goods_tag";
/**
* 字段名:通知地址
* 必填:是
* 示例值:http://www.weixin.qq.com/wxpay/pay.php
* 描述:异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数
*/
private final static String NOTIFY_URL = "notify_url";
/**
* 字段名:交易类型
* 必填:是
* 示例值:JSAPI
* 描述:取值如下:JSAPI,NATIVE,APP等,说明详见参数规定
*/
private final static String TRADE_TYPE = "trade_type";
/**
* 字段名:商品ID
* 必填:否
* 示例值:12235413214070356458058
* 描述:trade_type=NATIVE时(即扫码支付),此参数必传。此参数为二维码中包含的商品ID,商户自行定义。
*/
private final static String PRODUCT_ID = "product_id";
/**
* 字段名:指定支付方式
* 必填:否
* 示例值:no_credit
* 描述:上传此参数no_credit--可限制用户不能使用信用卡支付
*/
private final static String LIMIT_PAY = "limit_pay";
/**
* 字段名:用户标识
* 必填:否
* 示例值:oUpF8uMuAJO_M2pxb1Q9zNjWeS6o
* 描述:trade_type=JSAPI时(即公众号支付),此参数必传,此参数为微信用户在商户对应appid下的唯一标识。openid如何获取,可参考【获取openid】。企业号请使用【企业号OAuth2.0接口】获取企业号内成员userid,再调用【企业号userid转openid接口】进行转换
*/
private final static String OPENID = "openid";
public void setAppid(String appid) {
put(APPID, appid);
}
public String getAppid() {
return get(APPID);
}
public boolean isAppidSet() {
return containsKey(APPID);
}
public void setMchId(String mch_id) {
put(MCH_ID, mch_id);
}
public String getMchId() {
return get(MCH_ID);
}
public boolean isMchIdSet() {
return containsKey(MCH_ID);
}
public void setDeviceInfo(String deviceInfo) {
put(DEVICE_INFO, deviceInfo);
}
public String getDeviceInfo() {
return get(DEVICE_INFO);
}
public boolean isDeviceInfoSet() {
return containsKey(DEVICE_INFO);
}
public void setNonceStr(String nonce_str) {
put(NONCE_STR, nonce_str);
}
public String getNonceStr() {
return get(NONCE_STR);
}
public boolean isNonceStrSet() {
return containsKey(NONCE_STR);
}
public void setSign(String sign) {
put(SIGN, sign);
}
public String getSign() {
return get(SIGN);
}
public boolean isSignSet() {
return containsKey(SIGN);
}
public void setSignType(String signType) {
put(SIGN_TYPE, signType);
}
public boolean isSignTypeSet() {
return containsKey(SIGN_TYPE);
}
public void setBody(String body) {
put(BODY, body);
}
public String getBody() {
return get(BODY);
}
public boolean isBodySet() {
return containsKey(BODY);
}
/**
* @param detail { "goods_detail":[ { "goods_id":"iphone6s_16G", "wxpay_goods_id":"1001", "goods_name":"iPhone6s 16G", "quantity":1, "price":528800, "goods_category":"123456", "body":"苹果手机" }, { "goods_id":"iphone6s_32G", "wxpay_goods_id":"1002", "goods_name":"iPhone6s 32G", "quantity":1, "price":608800, "goods_category":"123789", "body":"苹果手机" } ] }
*/
public void setDetail(String detail) {
put(DETAIL, detail);
}
public String getDetail() {
return get(DETAIL);
}
public boolean isDetailSet() {
return containsKey(DETAIL);
}
public void setAttach(String attach) {
put(ATTACH, attach);
}
public boolean isAttachSet() {
return containsKey(ATTACH);
}
public void setOutTradeNo(String outTradeNo) {
put(OUT_TRADE_NO, outTradeNo);
}
public String getOutTradeNo() {
return get(OUT_TRADE_NO);
}
public boolean isOutTradeNoSet() {
return containsKey(OUT_TRADE_NO);
}
public void setFeeType(String feeType) {
put(FEE_TYPE, feeType);
}
public String getFeeType() {
return get(FEE_TYPE);
}
public boolean isFeeTypeSet() {
return containsKey(FEE_TYPE);
}
public void setTotalFee(int totalFee) {
put(TOTAL_FEE, String.valueOf(totalFee));
}
public int getTotalFee() {
return Integer.parseInt(get(TOTAL_FEE));
}
public boolean isTotalFeeSet() {
return containsKey(TOTAL_FEE);
}
public void setSpbillCreateIp(String spbillCreateIp) {
put(SPBILL_CREATE_IP, spbillCreateIp);
}
public String getSpbillCreateIp() {
return get(SPBILL_CREATE_IP);
}
public boolean isSpbillCreateIpSet() {
return containsKey(SPBILL_CREATE_IP);
}
public void setTimeStart(String timeStart) {
put(TIME_START, timeStart);
}
public String getTimeStart() {
return get(TIME_START);
}
public boolean isTimeStartSet() {
return containsKey(TIME_START);
}
public void setTimeExpire(String timeExpire) {
put(TIME_EXPIRE, timeExpire);
}
public String getTimeExpire() {
return get(TIME_EXPIRE);
}
public boolean isTimeExpireSet() {
return containsKey(TIME_EXPIRE);
}
public void setGoodsTag(String goodsTag) {
put(GOODS_TAG, goodsTag);
}
public String getGoodsTag() {
return get(GOODS_TAG);
}
public boolean isGoodsTagSet() {
return containsKey(GOODS_TAG);
}
public void setNotifyUrl(String notifyUrl) {
put(NOTIFY_URL, notifyUrl);
}
public String getNotifyUrl() {
return get(NOTIFY_URL);
}
public boolean isNotifyUrlSet() {
return containsKey(NOTIFY_URL);
}
public void setTradeType(String tradeType) {
put(TRADE_TYPE, tradeType);
}
public String getTradeType() {
return get(TRADE_TYPE);
}
public boolean isTradeTypeSet() {
return containsKey(TRADE_TYPE);
}
public void setProductId(String productId) {
put(PRODUCT_ID, productId);
}
public String getProductId() {
return get(PRODUCT_ID);
}
public boolean isProductIdSet() {
return containsKey(PRODUCT_ID);
}
public void setLimitPay(String limitPay) {
put(LIMIT_PAY, limitPay);
}
public String getLimitPay() {
return get(LIMIT_PAY);
}
public boolean isLimitPaySet() {
return containsKey(LIMIT_PAY);
}
public void setOpenid(String openid) {
put(OPENID, openid);
}
public String getOpenid() {
return get(OPENID);
}
public boolean isOpenIdSet() {
return containsKey(OPENID);
}
}<file_sep>/src/main/java/org/trier/wechat/util/NonceStrUtil.java
package org.trier.wechat.util;
import java.util.Random;
/**
* 随机数生成算法
*/
public class NonceStrUtil {
public static String getNonceStr(int length) {
String chars = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random(System.currentTimeMillis());
StringBuilder sb = new StringBuilder();
int len = chars.length();
for (int i = 0; i < length; i++) {
int n = random.nextInt(len - 1);
sb.append(chars.substring(n, n + 1));
}
return sb.toString();
}
}
<file_sep>/src/main/webapp/jsp/person.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="org.trier.wechat.pojo.auth.UserInfo" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
<title>微信个人信息</title>
<script type="text/javascript" src="/WxUtils/js/adapt.js"></script>
<link rel="stylesheet" type="text/css" href="/WxUtils/css/weuix.min.css">
<link rel="stylesheet" type="text/css" href="/WxUtils/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/WxUtils/css/main.min.css">
</head>
<body>
<% UserInfo userInfo = (UserInfo) request.getAttribute("userInfo"); %>
<div class="content">
<div class="person-header">
<img src="<%= userInfo.getHeadimgurl() %>" class="person-photo"/>
<div class="person-name"><%= userInfo.getNickname() %></div>
</div>
</div>
</body>
</html>
<file_sep>/src/main/java/org/trier/wechat/util/HttpUtil.java
package org.trier.wechat.util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
/**
* Http请求util
*/
public class HttpUtil {
public static String doGet(String url) {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
String result = null;
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static String doPostXml(String url, String xml) {
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
String result = null;
try {
StringEntity stringEntity = new StringEntity(xml, Charset.forName("UTF-8"));
stringEntity.setContentEncoding("UTF-8");
// 发送xml格式的数据请求
stringEntity.setContentType("application/xml");
httpPost.setEntity(stringEntity);
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
| 17adb641089fa0923899425b6248e57155b0cbe9 | [
"Java",
"Markdown",
"Java Server Pages",
"Maven POM"
] | 11 | Java | rumourcy/WxUtils | b55bcd55df10156b2cd09c139e7336edb09b3726 | 0db1e4a5f7cac2ed658c6d10195984a2217aa019 |
refs/heads/main | <repo_name>anilkarakose/hands-on-aspnetcore-di<file_sep>/README.md
# Hands-On Asp.Net Core Dependency Injection
Asp.Net Core tarafında built-in DI mekanizmasının basit ve gösterişsiz bir örnek üstünden incelenmesi amacıyla açtığım alandır. Blogumdaki [şu](https://www.buraksenyurt.com/post/asp-net-core-a-nasil-merhaba-deriz)
yazı için destekleyicidir.
Konuyu daha iyi anlamak için farklı branch'leri kullanmaya karar verdim.
## initial: Projenin için Başlangıç Konumu
Bu başlangıç branch'i. Kod çalışıyor ama tightly-coupled durumu söz konusu. Oluşturmak için şunlar yapıldı.
```
cd
dotnet new sln
dotnet new mvc -o C64Portal
dotnet sln add C64Portal
```
[https://github.com/buraksenyurt/hands-on-aspnetcore-di/tree/initial](https://github.com/buraksenyurt/hands-on-aspnetcore-di/tree/initial)
Bağımlılık ihlali GameController içerisinde, GameRepository sınıfının örneklendiği yer.
## constructor-injection: Constructor Injection Uygulanmış Hal
Bir nesnenin oluşturulurken bağımlı olduğu diğer bileşenleri arayüz üstünden almasına odaklanır. GameManager'ı, GameController içerisinde nasıl kullandığımıza ve Startup->ConfigureServices metoduna odaklanalım.
[https://github.com/buraksenyurt/hands-on-aspnetcore-di/tree/constructor-injection](https://github.com/buraksenyurt/hands-on-aspnetcore-di/tree/constructor-injection)
## method-injection: Method Injection Uygulanmış Hal
Bir metodun bağımlı olduğu nesne çözümlemesinin metoda arayüz referansı olarak çekilerek sağlanmasını ele alır. IPublisher ve RabbitPublisher tipleri ile GameController->Create metoduna odaklanalım.
[https://github.com/buraksenyurt/hands-on-aspnetcore-di/tree/method-injection](https://github.com/buraksenyurt/hands-on-aspnetcore-di/tree/method-injection)
## property-injection: Property Injection Uygulanmış Hal
IPublisher üstünden gelen bileşen bağımlılıklarını tercihe bağlı kullandırmak istediğimiz durumdaki senaryo için. Create metodundaki değişikliğe dikkat edelim.
[https://github.com/buraksenyurt/hands-on-aspnetcore-di/tree/property-injection](https://github.com/buraksenyurt/hands-on-aspnetcore-di/tree/property-injection)
## view-injection: Asp.Net Core MVC 6 ve Sonrasına Özgü
View ile Controller logic'lerini ayrıştırmak istediğimiz durumlarda işe yarayan bir tekniktir. View tarafında DataCollectorService için @inject kullanımına ve Startup->ConfigureServices metodundaki Transient kullanımına dikkat edelim.
[https://github.com/buraksenyurt/hands-on-aspnetcore-di/tree/view-injection](https://github.com/buraksenyurt/hands-on-aspnetcore-di/tree/view-injection)
## lifetimes: DI Servis Yaşam Ömürlerini Anlamak Üzerine
Servisleri AddTransient, AddScoped ve AddSingleton olarak ekleyebiliyoruz. Aradaki farkları görmek için eklenmiş branch'tir.
[https://github.com/buraksenyurt/hands-on-aspnetcore-di/tree/lifetimes](https://github.com/buraksenyurt/hands-on-aspnetcore-di/tree/lifetimes)
![./assets/screenshot_1.png](./assets/screenshot_1.png)
Excel üstündeki GUID'ler, örneklenen GameRepository nesnesine aittir. Farklı yaşam ömürleri için nasıl ele alındığını gösterir.
![./assets/screenshot_2.png](./assets/screenshot_2.png) | 1eb82f93887324ddda8f0826353a85845640b336 | [
"Markdown"
] | 1 | Markdown | anilkarakose/hands-on-aspnetcore-di | 3ba5b115a0818f1455d1130977808a607862046b | 7dfb994220e56c3fcc6fb7844cf3a5521f3ce0c2 |
refs/heads/master | <repo_name>imnice/RenWork<file_sep>/app/src/main/java/android/xuewuyou/com/xuewuyou/DengLu.java
package android.xuewuyou.com.xuewuyou;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class DengLu extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chong_zhi);
}
}
<file_sep>/app/src/main/java/android/xuewuyou/com/xuewuyou/WanChengXxzy.java
package android.xuewuyou.com.xuewuyou;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.widget.TabHost;
/**
* Created by Lee on 2016/10/17.
*/
public class WanChengXxzy extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wancheng_xxzy);
TabHost th = (TabHost) findViewById(R.id.tabhost);
th.setup(); //初始化TabHost容器
//在TabHost创建标签,然后设置:标题/图标/标签页布局
th.addTab(th.newTabSpec("tab1").setIndicator("完成学校作业", null).setContent(R.id.tab1));
th.addTab(th.newTabSpec("tab2").setIndicator("完成自由作业", null).setContent(R.id.tab2));
//上面的null可以为getResources().getDrawable(R.drawable.图片名)设置图标
}
}
| e7753e637c7284df3134b0b593178f207c5b0b1f | [
"Java"
] | 2 | Java | imnice/RenWork | 52abb8038a8f1208b583fca3ba65b85a3d8a49fb | 3242602ff587a1ba23d4712d1f0e2719de59e099 |
refs/heads/master | <repo_name>krisnaprdn/My-New-App<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/domain/usecase/DeleteRecipeUseCase.kt
package com.example.mynewapplication.kotlinpackage.features.domain.usecase
import arrow.core.Either
import com.example.mynewapplication.kotlinpackage.core.exception.Failure
import com.example.mynewapplication.kotlinpackage.core.interactor.UseCase
import com.example.mynewapplication.kotlinpackage.features.data.repository.RecipesRepository
import javax.inject.Inject
class DeleteRecipeUseCase @Inject constructor(private val recipesRepository: RecipesRepository) :
UseCase<Boolean, DeleteRecipeUseCase.Params>() {
override suspend fun run(params: Params) = recipesRepository.deleteRecipe(params.href)
data class Params(val href: String)
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/domain/usecase/GetFavoriteRecipesUseCase.kt
package com.example.mynewapplication.kotlinpackage.features.domain.usecase
import com.example.mynewapplication.kotlinpackage.core.interactor.UseCase
import com.example.mynewapplication.kotlinpackage.features.data.repository.RecipesRepository
import com.example.mynewapplication.kotlinpackage.features.domain.model.Recipe
import javax.inject.Inject
class GetFavoriteRecipesUseCase @Inject constructor(private val recipesRepository: RecipesRepository) :
UseCase<List<Recipe>, UseCase.None>() {
override suspend fun run(params: None) = recipesRepository.favoriteRecipes()
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/utils/RetrofitClient.kt
package com.example.mynewapplication.kotlinpackage.utils
import com.example.mynewapplication.kotlinpackage.ApiServicesKotlin
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
private const val BASE_URL = "http://www.recipepuppy.com/"
val INSTANCE: ApiServicesKotlin by lazy {
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
retrofit.create(ApiServicesKotlin::class.java)
}
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/core/di/ApplicationComponent.kt
package com.example.mynewapplication.kotlinpackage.core.di
import com.example.mynewapplication.kotlinpackage.KotlinActivity.ContentListActivity
import com.example.mynewapplication.kotlinpackage.RecipePuppyApp
import com.example.mynewapplication.kotlinpackage.core.di.viewmodel.ViewModelModule
import com.example.mynewapplication.kotlinpackage.features.presentation.MainActivityKotlin
import com.example.mynewapplication.kotlinpackage.features.presentation.favoriterecipes.FavoriteRecipesFragment
import com.example.mynewapplication.kotlinpackage.features.presentation.recipedetails.RecipeDetailsFragment
import com.example.mynewapplication.kotlinpackage.features.presentation.recipes.RecipesFragment
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = [ApplicationModule::class, NetworkModule::class, DataModule::class, ViewModelModule::class, DatabaseModule::class])
interface ApplicationComponent {
fun inject(application: RecipePuppyApp)
fun inject(mainActivityKotlin: MainActivityKotlin)
fun inject(recipesFragment: RecipesFragment)
fun inject(recipeDetailsFragment: RecipeDetailsFragment)
fun inject(favoriteRecipesFragment: FavoriteRecipesFragment)
}
<file_sep>/app/src/main/java/com/example/mynewapplication/javapackage/fragments/HomepageItem3.java
package com.example.mynewapplication.javapackage.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.mynewapplication.javapackage.adapter.MainAdapter;
import com.example.mynewapplication.javapackage.model.MainModel;
import com.example.mynewapplication.javapackage.model.Results;
import com.example.mynewapplication.R;
import java.util.ArrayList;
import java.util.List;
public class HomepageItem3 extends Fragment {
private LinearLayoutManager layoutManager;
private MainAdapter mainAdapter;
private ArrayList<MainModel> list = new ArrayList<>();
private MainModel mainModel;
private RecyclerView recyclerView;
private List<Results> results = new ArrayList<>();
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public HomepageItem3() {
}
public static HomepageItem3 newInstance(String param1, String param2) {
HomepageItem3 fragment = new HomepageItem3();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_homepage_item3, container, false);
recyclerView = view.findViewById(R.id.rv_content3);
recyclerView = (RecyclerView) getActivity().findViewById(R.id.rv_content3);
initData();
initRecyclerView();
return view;
}
public void initRecyclerView(){
// RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
// recyclerView.setLayoutManager(mLayoutManager);
// mainAdapter = new MainAdapter(getActivity(), list);
// recyclerView.setAdapter(mainAdapter);
// mainAdapter.notifyDataSetChanged();
}
public void initData(){
mainModel = new MainModel();
mainModel.setIv_homepagecontent(R.drawable.food);
mainModel.setBtn_homepagecontent("Go To Detail");
list.add(mainModel);
mainModel = new MainModel();
mainModel.setIv_homepagecontent(R.drawable.food);
mainModel.setBtn_homepagecontent("Go To Detail");
list.add(mainModel);
mainModel = new MainModel();
mainModel.setIv_homepagecontent(R.drawable.food);
mainModel.setBtn_homepagecontent("Go To Detail");
list.add(mainModel);
mainModel = new MainModel();
mainModel.setIv_homepagecontent(R.drawable.food);
mainModel.setBtn_homepagecontent("Go To Detail");
list.add(mainModel);
mainModel = new MainModel();
mainModel.setIv_homepagecontent(R.drawable.food);
mainModel.setBtn_homepagecontent("Go To Detail");
list.add(mainModel);
mainModel = new MainModel();
mainModel.setIv_homepagecontent(R.drawable.food);
mainModel.setBtn_homepagecontent("Go To Detail");
list.add(mainModel);
}
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/domain/usecase/SaveRecipeUseCase.kt
package com.example.mynewapplication.kotlinpackage.features.domain.usecase
import com.example.mynewapplication.kotlinpackage.core.interactor.UseCase
import com.example.mynewapplication.kotlinpackage.features.data.repository.RecipesRepository
import com.example.mynewapplication.kotlinpackage.features.domain.model.Recipe
import com.example.mynewapplication.kotlinpackage.features.presentation.model.RecipeView
import javax.inject.Inject
class SaveRecipeUseCase @Inject constructor(private val recipesRepository: RecipesRepository) :
UseCase<Boolean, SaveRecipeUseCase.Params>() {
override suspend fun run(params: Params) =
recipesRepository.saveRecipe(Recipe(params.recipe.href, params.recipe.ingredients, params.recipe.thumbnail, params.recipe.title))
data class Params(val recipe: RecipeView)
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/presentation/favoriterecipes/FavoriteRecipesViewModel.kt
package com.example.mynewapplication.kotlinpackage.features.presentation.favoriterecipes
import androidx.lifecycle.MutableLiveData
import com.example.mynewapplication.kotlinpackage.core.interactor.UseCase
import com.example.mynewapplication.kotlinpackage.core.platform.BaseViewModel
import com.example.mynewapplication.kotlinpackage.features.domain.model.Recipe
import com.example.mynewapplication.kotlinpackage.features.domain.usecase.DeleteRecipeUseCase
import com.example.mynewapplication.kotlinpackage.features.domain.usecase.GetFavoriteRecipesUseCase
import com.example.mynewapplication.kotlinpackage.features.domain.usecase.SaveRecipeUseCase
import com.example.mynewapplication.kotlinpackage.features.presentation.model.RecipeView
import javax.inject.Inject
class FavoriteRecipesViewModel @Inject constructor(
private val getFavoriteRecipesUseCase: GetFavoriteRecipesUseCase,
private val saveRecipeUseCase: SaveRecipeUseCase,
private val deleteRecipeUseCase: DeleteRecipeUseCase
) : BaseViewModel() {
var favoriteRecipes: MutableLiveData<List<RecipeView>> = MutableLiveData()
fun getFavoriteRecipes() = getFavoriteRecipesUseCase(UseCase.None()) {
it.fold(::handleFailure, ::handleFavoriteRecipes)
}
fun saveRecipe(recipeView: RecipeView) = saveRecipeUseCase(SaveRecipeUseCase.Params(recipeView)) {
it.fold(::handleFailure, ::handleRecipeSaved)
}
fun deleteRecipe(href: String) = deleteRecipeUseCase(DeleteRecipeUseCase.Params(href)) {
it.fold(::handleFailure, ::handleRecipeDeleted)
}
private fun handleFavoriteRecipes(recipes: List<Recipe>) {
val recipesView = recipes.map { it.toRecipeView() }
recipesView.map { it.isFavorite = true }
favoriteRecipes.value = recipesView
}
private fun handleRecipeSaved(saved: Boolean) {
// not needed atm
}
private fun handleRecipeDeleted(saved: Boolean) {
// not needed atm
}
}
<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/presentation/recipes/RecipeItem.kt
package com.example.mynewapplication.kotlinpackage.features.presentation.recipes
import android.view.animation.OvershootInterpolator
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.example.mynewapplication.R
import com.example.mynewapplication.kotlinpackage.features.presentation.model.RecipeView
import com.xwray.groupie.kotlinandroidextensions.Item
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.layout_recyclerview_contentlist.view.*
class RecipeItem(
val recipeView: RecipeView,
private val clickListenerRecipe: (RecipeView) -> Unit = { _ -> },
private val clickListenerFav: (RecipeView, isFavorite: Boolean) -> Unit = { _, _ -> }
) : Item() {
override fun getLayout(): Int = R.layout.layout_recyclerview_contentlist
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.apply {
Glide.with(itemView.context)
.load(recipeView.thumbnail)
.transition(DrawableTransitionOptions.withCrossFade())
.into(itemView.iv_contentlist)
itemView.tv_titlecontentlist.text = recipeView.title
itemView.tv_desccontentlist.text = recipeView.ingredients
// if (recipeView.isFavorite) {
// itemView.recipe_favorite.setImageResource(R.mipmap.ic_heart_on)
// } else {
// itemView.recipe_favorite.setImageResource(R.mipmap.ic_heart_off)
// }
//
// if (recipeView.ingredients.contains("milk") or recipeView.ingredients.contains("cheese")) {
// animateLactoseLabel()
// itemView.recipe_lactose_image.visible()
// } else {
// itemView.recipe_lactose_image.gone()
// }
//
// itemView.setOnClickListener { clickListenerRecipe(recipeView) }
// itemView.recipe_favorite.setOnClickListener {
// recipeView.isFavorite = !recipeView.isFavorite
// animateFavIcon()
// clickListenerFav(recipeView, recipeView.isFavorite)
// }
}
}
// private fun ViewHolder.animateLactoseLabel() {
// itemView.recipe_lactose_image.apply {
// scaleX = 0f
// scaleY = 0f
// }
// if (itemView.recipe_lactose_image.animation != null) {
// itemView.recipe_lactose_image.animation.cancel()
// }
// itemView.recipe_lactose_image.animate()
// .scaleX(1f)
// .scaleY(1f)
// .setInterpolator(OvershootInterpolator(3.0f))
// .setDuration(500)
// .setStartDelay(300)
// .start()
// }
// private fun ViewHolder.animateFavIcon() {
// itemView.recipe_favorite.apply {
// scaleX = 0f
// scaleY = 0f
// }
// if (itemView.recipe_lactose_image.animation != null) {
// itemView.recipe_lactose_image.animation.cancel()
// }
// if (recipeView.isFavorite) {
// itemView.recipe_favorite.setImageResource(R.mipmap.ic_heart_on)
// } else {
// itemView.recipe_favorite.setImageResource(R.mipmap.ic_heart_off)
// }
// itemView.recipe_favorite.animate()
// .scaleX(1f)
// .scaleY(1f)
// .setInterpolator(OvershootInterpolator(3.0f))
// .setDuration(500)
// .setStartDelay(300)
// .start()
// }
}
<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/domain/usecase/GetRecipesUseCase.kt
package com.example.mynewapplication.kotlinpackage.features.domain.usecase
import arrow.core.Either
import arrow.core.getOrElse
import com.example.mynewapplication.kotlinpackage.core.exception.Failure
import com.example.mynewapplication.kotlinpackage.core.interactor.UseCase
import com.example.mynewapplication.kotlinpackage.features.data.repository.RecipesRepository
import com.example.mynewapplication.kotlinpackage.features.domain.model.Recipe
import com.example.mynewapplication.kotlinpackage.features.domain.model.RecipesResult
import javax.inject.Inject
class GetRecipesUseCase @Inject constructor(private val recipesRepository: RecipesRepository) :
UseCase<RecipesResult, GetRecipesUseCase.Params>() {
override suspend fun run(params: Params) = zip(recipesRepository.recipes(params.ingredients, params.page), recipesRepository.favoriteRecipes())
private fun zip(recipes: Either<Failure, List<Recipe>>, favoriteRecipes: Either<Failure, List<Recipe>>): Either<Failure, RecipesResult> {
return if (recipes.isRight() && favoriteRecipes.isRight()) {
val recipesResult = RecipesResult(recipes.getOrElse { emptyList() }, favoriteRecipes.getOrElse { emptyList() })
Either.right(recipesResult)
} else {
Either.left(Failure.GetRecipesError())
}
}
data class Params(val ingredients: String, val page: Int)
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/adapter/ContentListAdapter.kt
package com.example.mynewapplication.kotlinpackage.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.mynewapplication.kotlinpackage.KotlinModel.ListModel
import com.example.mynewapplication.R
class ContentListAdapter (private val data: ArrayList<ListModel>,
private var onItemClickListener: OnItemClickListener): RecyclerView.Adapter<ContentListAdapter.ContentListViewHolder>() {
private var btnContent: Button? = null
fun setOnclickListener(listener: OnItemClickListener){
this.onItemClickListener = onItemClickListener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContentListViewHolder {
val inflater: LayoutInflater = LayoutInflater.from(parent.context)
return ContentListViewHolder(inflater, parent)
}
override fun onBindViewHolder(holder: ContentListViewHolder, position: Int) {
holder.bind(data[position])
holder.itemView.setOnClickListener {
onItemClickListener.onClick(data[position]) }
btnContent?.setOnClickListener { onItemClickListener.onClick(data[position]) }
}
override fun getItemCount(): Int {
return data.size
}
class ContentListViewHolder(inflater: LayoutInflater, parent: ViewGroup):
RecyclerView.ViewHolder(inflater.inflate(R.layout.layout_recyclerview_contentlist, parent, false)) {
private var imgView: ImageView? = null
private var txtTitle: TextView? = null
private var txtDesc: TextView? = null
private var txtDetail1: TextView? = null
private var txtDetail2: TextView? = null
private var txtDetail3: TextView? = null
private var btnContent: Button? = null
init {
imgView = itemView.findViewById(R.id.iv_contentlist)
txtTitle = itemView.findViewById(R.id.tv_titlecontentlist)
txtDesc = itemView.findViewById(R.id.tv_desccontentlist)
// txtDetail1 = itemView.findViewById(R.id.tv_detail_list1)
// txtDetail2 = itemView.findViewById(R.id.tv_detail_list2)
// txtDetail3 = itemView.findViewById(R.id.tv_detail_list3)
// btnContent = itemView.findViewById(R.id.btn_contentlist)
}
fun bind(data: ListModel){
imgView?.setImageResource(data.imgView)
txtTitle?.text = data.txtTitle
txtDesc?.text = data.txtDesc
// txtDetail1?.text = data.txtDetail1
// txtDetail2?.text = data.txtDetail2
// txtDetail3?.text = data.txtDetail3
// btnContent?.text = data.btnContent
}
}
interface OnItemClickListener{
fun onClick(data: ListModel)
}
}<file_sep>/app/src/main/java/com/example/mynewapplication/javapackage/viewmodel/MainActivityVM.java
package com.example.mynewapplication.javapackage.viewmodel;
import android.content.Context;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.example.mynewapplication.javapackage.model.ResponseModel;
import com.example.mynewapplication.javapackage.model.Results;
import com.example.mynewapplication.javapackage.retrofit.ApiEndpoint;
import com.example.mynewapplication.javapackage.retrofit.ApiService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivityVM extends ViewModel {
private MutableLiveData<ResponseModel> results = new MutableLiveData<>();
public MutableLiveData<ResponseModel> getResults() {
return results;
}
public void fetchRecipe(Context context){
ApiEndpoint apiEndpoint = ApiService.getApiClient(context).create(ApiEndpoint.class);
Call<ResponseModel> apiCall;
apiCall = apiEndpoint.getRecipes();
apiCall.enqueue(new Callback<ResponseModel>() {
@Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
if (response.isSuccessful()){
results.setValue(response.body());
}
}
@Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
}
});
}
}
<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/KotlinModel/ListModel.kt
package com.example.mynewapplication.kotlinpackage.KotlinModel
data class ListModel(val imgView:Int, val txtTitle:String, val txtDesc:String, val txtDetail1:String, val txtDetail2:String, val txtDetail3:String, val btnContent:String)<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/domain/model/RecipesResult.kt
package com.example.mynewapplication.kotlinpackage.features.domain.model
data class RecipesResult(
val recipes: List<Recipe>,
val favRecipes: List<Recipe>
)<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/domain/model/Recipe.kt
package com.example.mynewapplication.kotlinpackage.features.domain.model
import com.example.mynewapplication.kotlinpackage.features.data.room.entity.RecipeInfo
import com.example.mynewapplication.kotlinpackage.features.presentation.model.RecipeView
data class Recipe(
private val href: String,
private val ingredients: String,
private val thumbnail: String,
private val title: String
) {
fun toRecipeView() = RecipeView(href, ingredients, thumbnail, title)
fun toRecipeInfo() = RecipeInfo(href, ingredients, thumbnail, title)
companion object {
fun empty() = Recipe("", "", "", "")
}
}
<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/presentation/favoriterecipes/FavoriteRecipesFragment.kt
package com.example.mynewapplication.kotlinpackage.features.presentation.favoriterecipes
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mynewapplication.R
import com.example.mynewapplication.kotlinpackage.core.exception.Failure
import com.example.mynewapplication.kotlinpackage.core.extension.*
import com.example.mynewapplication.kotlinpackage.core.platform.BaseFragment
import com.example.mynewapplication.kotlinpackage.features.presentation.model.RecipeView
import com.example.mynewapplication.kotlinpackage.features.presentation.recipes.RecipeItem
import com.google.android.material.snackbar.Snackbar
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.ViewHolder
import kotlinx.android.synthetic.main.fragment_favorite_recipes.*
import timber.log.Timber
class FavoriteRecipesFragment : BaseFragment() {
companion object {
private val TAG = FavoriteRecipesFragment::class.java.simpleName
}
override fun layoutId() = R.layout.fragment_favorite_recipes
private lateinit var viewModel: FavoriteRecipesViewModel
private val recipesAdapter = GroupAdapter<ViewHolder>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
appComponent.inject(this)
setHasOptionsMenu(true)
viewModel = viewModel(viewModelFactory) {
observe(favoriteRecipes, ::onRecipesFetched)
failure(failure, ::showError)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
rv_fav_recipes.apply {
layoutManager = LinearLayoutManager(context)
adapter = recipesAdapter
}
viewModel.getFavoriteRecipes()
}
private fun onRecipesFetched(recipes: List<RecipeView>?) {
progress_fav_recipes.gone()
if (recipes != null && recipes.isNotEmpty()) {
val items = recipes.map { recipeView ->
RecipeItem(recipeView,
clickListenerRecipe = { recipe ->
if (recipe.href.isNotEmpty()) {
val navDirections =
FavoriteRecipesFragmentDirections.actionFavoriteRecipesFragmentToRecipeDetailsFragment()
.apply {
href = recipe.href
name = recipe.title
}
findNavController().navigate(navDirections)
} else {
Snackbar.make(fav_recipes_root, R.string.recipe_details_no_href, Snackbar.LENGTH_LONG)
.show()
}
},
clickListenerFav = { recipe, isFavorite ->
if (isFavorite) {
viewModel.saveRecipe(recipe)
} else {
viewModel.deleteRecipe(recipe.href)
}
})
}
recipesAdapter.clear()
recipesAdapter.addAll(items)
rv_fav_recipes.visible()
} else {
notify(getString(R.string.recipes_no_fav_results))
}
}
private fun showError(failure: Failure?) {
progress_fav_recipes.gone()
when (failure) {
is Failure.DbGetFavoriteRecipesError -> {
Timber.tag(TAG).d("DbGetFavoriteRecipesError: ${failure.exception.message}")
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
fragmentManager?.popBackStack()
return true
}
}
return super.onOptionsItemSelected(item)
}
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/data/datasource/RecipesService.kt
package com.example.mynewapplication.kotlinpackage.features.data.datasource
import com.example.mynewapplication.kotlinpackage.features.data.model.RecipesEntity
import retrofit2.Call
import retrofit2.Retrofit
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class RecipesService @Inject constructor(retrofit: Retrofit) : Api {
private val api by lazy { retrofit.create(Api::class.java) }
override fun recipes(filters: Map<String, String>): Call<RecipesEntity> = api.recipes(filters)
}<file_sep>/app/src/main/java/com/example/mynewapplication/javapackage/adapter/MainAdapter.java
package com.example.mynewapplication.javapackage.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.mynewapplication.javapackage.ContentDetailActivity;
import com.example.mynewapplication.javapackage.model.Results;
import com.example.mynewapplication.R;
import java.util.ArrayList;
import java.util.List;
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> {
// private ArrayList<MainModel> dataList = new ArrayList<>();
private List<Results> dataList = new ArrayList<>();
private Context context;
public MainAdapter(Context context, List<Results> dataList) {
this.dataList = dataList;
this.context = context;
}
@NonNull
@Override
public MainViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.layout_recyclerview_homepagecontent, parent, false);
return new MainViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MainViewHolder holder, int position) {
final Results model = dataList.get(position);
holder.tv_title_homepage.setText(dataList.get(position).getTitle());
holder.tv_desc_homepage.setText(dataList.get(position).getIngredients());
holder.btn_homepagecontent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(holder.itemView.getContext(), ContentDetailActivity.class);
i.putExtra("href", model.getHref());
holder.itemView.getContext().startActivity(i);
}
});
Glide.with(context)
.load(dataList.get(position).getThumbnail())
.into(holder.iv_homepagecontent);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(holder.itemView.getContext(), ContentDetailActivity.class);
i.putExtra("href", model.getHref());
holder.itemView.getContext().startActivity(i);
}
});
}
@Override
public int getItemCount() {
return dataList.size();
}
public class MainViewHolder extends RecyclerView.ViewHolder{
private final ImageView iv_homepagecontent;
private final Button btn_homepagecontent;
private final TextView tv_title_homepage, tv_desc_homepage;
public MainViewHolder(@NonNull View itemView) {
super(itemView);
iv_homepagecontent = itemView.findViewById(R.id.iv_homepagecontent);
btn_homepagecontent = itemView.findViewById(R.id.btn_homepagecontent);
tv_title_homepage = itemView.findViewById(R.id.tv_title_homepage);
tv_desc_homepage = itemView.findViewById(R.id.tv_desc_homepage);
}
}
}
<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/data/model/RecipesEntity.kt
package com.example.mynewapplication.kotlinpackage.features.data.model
import com.example.mynewapplication.kotlinpackage.features.domain.model.Recipe
data class RecipesEntity(
val href: String,
val results: List<RecipeEntity>,
val title: String,
val version: Double
)
data class RecipeEntity(
val href: String,
val ingredients: String,
val thumbnail: String,
val title: String
) {
companion object {
fun empty() = RecipeEntity("", "", "", "")
}
fun toRecipe() = Recipe(href, ingredients, thumbnail, title)
}
<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/presentation/model/RecipeView.kt
package com.example.mynewapplication.kotlinpackage.features.presentation.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class RecipeView(
val href: String,
val ingredients: String,
val thumbnail: String,
val title: String,
var isFavorite: Boolean = false
) : Parcelable<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/presentation/MainActivityKotlin.kt
package com.example.mynewapplication.kotlinpackage.features.presentation
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.Navigation.findNavController
import androidx.navigation.ui.NavigationUI.setupActionBarWithNavController
import com.example.mynewapplication.R
import kotlinx.android.synthetic.main.activity_content_list.*
import kotlinx.android.synthetic.main.activity_kotlinmain.*
import kotlinx.android.synthetic.main.toolbar.*
class MainActivityKotlin : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kotlinmain)
setSupportActionBar(toolbar)
setupActionBar()
ib_back.setOnClickListener {
finish()
}
}
private fun setupActionBar() {
val navController = findNavController(this, R.id.nav_host_fragment)
setupActionBarWithNavController(this, navController)
}
}
<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/MainViewModel.kt
package com.example.mynewapplication.kotlinpackage
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.mynewapplication.kotlinpackage.KotlinModel.Result
class MainViewModel: ViewModel() {
val results = MutableLiveData<List<Result>>()
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/core/exception/Failure.kt
package com.example.mynewapplication.kotlinpackage.core.exception
import java.lang.Exception
sealed class Failure {
abstract class BaseFailure : Failure()
class NetworkConnection : BaseFailure()
class ServerError(val throwable: Throwable?) : BaseFailure()
class BodyNullError : BaseFailure()
class GetRecipesError : BaseFailure()
class DbGetFavoriteRecipesError(val exception: Exception) : BaseFailure()
class DbInsertError : BaseFailure()
class DbDeleteError : BaseFailure()
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/core/di/viewmodel/ViewModelModule.kt
package com.example.mynewapplication.kotlinpackage.core.di.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.mynewapplication.kotlinpackage.features.presentation.favoriterecipes.FavoriteRecipesViewModel
import com.example.mynewapplication.kotlinpackage.features.presentation.recipes.RecipesViewModel
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(RecipesViewModel::class)
abstract fun bindsRecipesViewModel(recipesViewModel: RecipesViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(FavoriteRecipesViewModel::class)
abstract fun bindsFavoriteRecipesViewModel(favoriteRecipesViewModel: FavoriteRecipesViewModel): ViewModel
@Binds
internal abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
}
<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/data/room/entity/RecipeInfo.kt
package com.example.mynewapplication.kotlinpackage.features.data.room.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.example.mynewapplication.kotlinpackage.features.domain.model.Recipe
@Entity(tableName = "recipes")
data class RecipeInfo(
@PrimaryKey
@ColumnInfo(name = "href") var href: String,
@ColumnInfo(name = "ingredients") var ingredients: String,
@ColumnInfo(name = "thumbnail") var thumbnail: String,
@ColumnInfo(name = "title") var title: String
) {
fun toRecipe() = Recipe(href, ingredients, thumbnail, title)
companion object {
fun empty() = RecipeInfo("", "", "", "")
}
}
<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/core/di/DataModule.kt
package com.example.mynewapplication.kotlinpackage.core.di
import com.example.mynewapplication.kotlinpackage.features.data.repository.RecipesRepository
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class DataModule {
@Provides
@Singleton
fun provideRecipesRepository(dataSource: RecipesRepository.Network): RecipesRepository = dataSource
}
<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/presentation/recipes/LoadingItem.kt
package com.example.mynewapplication.kotlinpackage.features.presentation.recipes
import com.example.mynewapplication.R
import com.xwray.groupie.kotlinandroidextensions.Item
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
class LoadingItem : Item() {
override fun getLayout(): Int = R.layout.layout_loader
override fun bind(viewHolder: ViewHolder, position: Int) {}
}
<file_sep>/app/src/main/java/com/example/mynewapplication/javapackage/fragments/HomepageItem1.java
package com.example.mynewapplication.javapackage.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.mynewapplication.javapackage.adapter.MainAdapter;
import com.example.mynewapplication.javapackage.model.MainModel;
import com.example.mynewapplication.javapackage.model.Results;
import com.example.mynewapplication.R;
import com.example.mynewapplication.javapackage.viewmodel.MainActivityVM;
import com.example.mynewapplication.javapackage.viewmodel.MainActivityVMF;
import java.util.ArrayList;
import java.util.List;
public class HomepageItem1 extends Fragment {
private LinearLayoutManager layoutManager;
private MainAdapter mainAdapter;
private ArrayList<MainModel> list = new ArrayList<>();
private MainModel mainModel;
private RecyclerView recyclerView;
public MainActivityVM viewModel;
public MainActivityVMF viewModelFactory;
private List<Results> results = new ArrayList<>();
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public HomepageItem1() {
}
public static HomepageItem1 newInstance(String param1, String param2) {
HomepageItem1 fragment = new HomepageItem1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
viewModelFactory = new MainActivityVMF(getActivity());
viewModel = ViewModelProviders.of(getActivity(), viewModelFactory).get(MainActivityVM.class);
recyclerView = (RecyclerView) getActivity().findViewById(R.id.rv_content1);
initData();
// layoutManager = new LinearLayoutManager(getActivity(), recyclerView.HORIZONTAL, false);
// recyclerView.setLayoutManager(layoutManager);
// MainAdapter mainAdapter = new MainAdapter(getActivity(), list);
// recyclerView.setAdapter(mainAdapter);
// mainAdapter.notifyDataSetChanged();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_homepage_item1, container, false);
recyclerView = view.findViewById(R.id.rv_content1);
recyclerView = (RecyclerView) getActivity().findViewById(R.id.rv_content1);
// initData();
// initRecyclerView();
// initLiveData();
// viewModel.fetchRecipe(getActivity());
return view;
}
// public void initRecyclerView(){
// layoutManager = new LinearLayoutManager(getActivity(), recyclerView.HORIZONTAL, false);
// recyclerView.setLayoutManager(layoutManager);
// MainAdapter mainAdapter = new MainAdapter(getActivity(), list);
// recyclerView.setAdapter(mainAdapter);
// mainAdapter.notifyDataSetChanged();
// }
// public void initLiveData(){
// viewModel.getResults().observe(this, new Observer<Response>() {
// @Override
// public void onChanged(Response response) {
// if (response != null){
//// JsonObject object = JsonParser().pars(response).getAsJsonObject().get("results").getAsJsonObject();
// if (!results .isEmpty()){
// results.clear();
// }
// results = response.getResults();
// initRecyclerView();
// }
// }
// });
// }
public void initData(){
mainModel = new MainModel();
mainModel.setIv_homepagecontent(R.drawable.food);
mainModel.setBtn_homepagecontent("Go To Detail");
list.add(mainModel);
mainModel = new MainModel();
mainModel.setIv_homepagecontent(R.drawable.food);
mainModel.setBtn_homepagecontent("Go To Detail");
list.add(mainModel);
mainModel = new MainModel();
mainModel.setIv_homepagecontent(R.drawable.food);
mainModel.setBtn_homepagecontent("Go To Detail");
list.add(mainModel);
mainModel = new MainModel();
mainModel.setIv_homepagecontent(R.drawable.food);
mainModel.setBtn_homepagecontent("Go To Detail");
list.add(mainModel);
mainModel = new MainModel();
mainModel.setIv_homepagecontent(R.drawable.food);
mainModel.setBtn_homepagecontent("Go To Detail");
list.add(mainModel);
mainModel = new MainModel();
mainModel.setIv_homepagecontent(R.drawable.food);
mainModel.setBtn_homepagecontent("Go To Detail");
list.add(mainModel);
}
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/KotlinActivity/ContentDetailActivity.kt
package com.example.mynewapplication.kotlinpackage.KotlinActivity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageButton
import com.example.mynewapplication.R
import kotlinx.android.synthetic.main.activity_content_detail.*
class ContentDetailActivity : AppCompatActivity() {
private lateinit var imageButton: ImageButton
private lateinit var webView: WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_content_detail)
// ib_back.setOnClickListener {
// startActivity(Intent(this, ContentListActivity::class.java))
// finish()
// }
wv_detail.settings.javaScriptEnabled = true
wv_detail.webViewClient = object : WebViewClient(){
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
view?.loadUrl(url)
return true
}
}
wv_detail.loadUrl("href")
}
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/data/datasource/Api.kt
package com.example.mynewapplication.kotlinpackage.features.data.datasource
import com.example.mynewapplication.kotlinpackage.features.data.model.RecipesEntity
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.QueryMap
interface Api {
@GET("api/")
fun recipes(@QueryMap(encoded=true) filters: Map<String, String>): Call<RecipesEntity>
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/data/room/dao/RecipeInfoDao.kt
package com.example.mynewapplication.kotlinpackage.features.data.room.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.mynewapplication.kotlinpackage.features.data.room.entity.RecipeInfo
@Dao
interface RecipeInfoDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(recipeInfo: RecipeInfo): Long
@Query("DELETE FROM recipes WHERE href = :href")
fun delete(href: String): Int
@get:Query("SELECT * FROM recipes")
val favoriteRecipes: List<RecipeInfo>
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/presentation/recipedetails/RecipeDetailsFragment.kt
package com.example.mynewapplication.kotlinpackage.features.presentation.recipedetails
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.webkit.*
import com.example.mynewapplication.R
import com.example.mynewapplication.kotlinpackage.core.extension.gone
import com.example.mynewapplication.kotlinpackage.core.platform.BaseFragment
import com.example.mynewapplication.kotlinpackage.features.presentation.recipedetails.RecipeDetailsFragmentArgs.fromBundle
import kotlinx.android.synthetic.main.activity_content_detail.*
import kotlinx.android.synthetic.main.fragment_recipe_details.*
import timber.log.Timber
class RecipeDetailsFragment : BaseFragment() {
override fun layoutId() = R.layout.activity_content_detail
companion object {
private val TAG = RecipeDetailsFragment::class.java.simpleName
private const val DELAY = 300L
}
private val href by lazy {
arguments?.let { fromBundle(it).href }
}
private val name by lazy {
// arguments?.let { fromBundle(it).name }
arguments?.let { fromBundle(it).name }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
appComponent.inject(this)
setHasOptionsMenu(true)
}
@SuppressLint("SetJavaScriptEnabled")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
wv_detail.settings.apply {
javaScriptEnabled = true
setSupportZoom(true)
}
wv_detail.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
// if (recipe_loader != null) {
// recipe_loader.gone()
// }
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
Timber.tag(TAG).d("onPageFinished")
}
override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
super.onReceivedError(view, request, error)
Timber.tag(TAG).d("onReceivedError: Your Internet Connection May not be active Or ${error?.description}")
}
override fun onReceivedHttpError(
view: WebView?,
request: WebResourceRequest?,
errorResponse: WebResourceResponse?
) {
super.onReceivedHttpError(view, request, errorResponse)
Timber.tag(TAG).d("onReceivedHttpError: $errorResponse")
}
override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
super.onReceivedSslError(view, handler, error)
Timber.tag(TAG).d("onReceivedSslError: $error")
}
override fun onReceivedClientCertRequest(view: WebView?, request: ClientCertRequest?) {
super.onReceivedClientCertRequest(view, request)
Timber.tag(TAG).d("onReceivedClientCertRequest $request")
}
}
Timber.tag(TAG).d("href: $href")
wv_detail.postDelayed({
wv_detail.loadUrl(href)
}, DELAY)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
if (wv_detail.canGoBack()) {
// If web view have back history, then go to the web view back history
wv_detail.goBack()
} else {
fragmentManager?.popBackStack()
}
return true
}
}
return super.onOptionsItemSelected(item)
}
}
<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/adapter/ListAdapter.kt
package com.example.mynewapplication.kotlinpackage.adapter
import android.content.Context
import android.media.Image
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.mynewapplication.kotlinpackage.KotlinModel.Result
import com.example.mynewapplication.R
class ListAdapter(val context: Context): RecyclerView.Adapter<ListAdapter.ListViewHolder>() {
private val recipes: MutableList<Result> = mutableListOf()
inner class ListViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val tv_titlecontentlist: TextView = itemView.findViewById(R.id.tv_titlecontentlist)
val tv_desccontentlist: TextView = itemView.findViewById(R.id.tv_desccontentlist)
// val tv_detail_list1: TextView = itemView.findViewById(R.id.tv_detail_list1)
// val tv_detail_list2: TextView = itemView.findViewById(R.id.tv_detail_list2)
// val tv_detail_list3: TextView = itemView.findViewById(R.id.tv_detail_list3)
// val iv_contentlist: Image = itemView.findViewById(R.id.iv_contentlist)
fun bind(result: Result){
tv_titlecontentlist.text = result.title
tv_desccontentlist.text = result.ingredients
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder {
return ListViewHolder(LayoutInflater.from(context).inflate(R.layout.layout_recyclerview_contentlist, parent, false))
}
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
holder.bind(recipes[position])
}
fun setResult(data: List<Result>){
recipes.clear()
recipes.addAll(data)
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return recipes.size
}
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/core/di/DatabaseModule.kt
package com.example.mynewapplication.kotlinpackage.core.di
import android.app.Application
import androidx.room.Room
import com.example.mynewapplication.kotlinpackage.features.data.room.RecipesDatabase
import com.example.mynewapplication.kotlinpackage.features.data.room.dao.RecipeInfoDao
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class DatabaseModule(application: Application) {
companion object {
private const val RECIPES_DB = "recipes_db"
}
private var database: RecipesDatabase =
Room.databaseBuilder(application, RecipesDatabase::class.java, RECIPES_DB).build()
@Singleton
@Provides
fun providesRecipesDatabase(): RecipesDatabase {
return database
}
@Singleton
@Provides
fun providesRecipeInfoDao(recipesDatabase: RecipesDatabase): RecipeInfoDao {
return recipesDatabase.recipeInfoDao()
}
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/data/room/RecipesDatabase.kt
package com.example.mynewapplication.kotlinpackage.features.data.room
import androidx.room.Database
import androidx.room.RoomDatabase
import com.example.mynewapplication.kotlinpackage.features.data.room.dao.RecipeInfoDao
import com.example.mynewapplication.kotlinpackage.features.data.room.entity.RecipeInfo
@Database(entities = [RecipeInfo::class], version = 1, exportSchema = false)
abstract class RecipesDatabase : RoomDatabase() {
abstract fun recipeInfoDao(): RecipeInfoDao
}
<file_sep>/app/src/main/java/com/example/mynewapplication/javapackage/viewmodel/MainActivityVMF.java
package com.example.mynewapplication.javapackage.viewmodel;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
public class MainActivityVMF implements ViewModelProvider.Factory {
private final Context context;
public MainActivityVMF(Context context) {
this.context = context;
}
@NonNull
@Override
@SuppressWarnings("unchecked")
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new MainActivityVM();
}
}
<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/ApiServicesKotlin.kt
package com.example.mynewapplication.kotlinpackage
import com.example.mynewapplication.kotlinpackage.KotlinModel.Result
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
interface ApiServicesKotlin {
@GET("api/")
fun getRecipes(): Call<List<Result>>
companion object{
operator fun invoke(): ApiServicesKotlin {
val requestInterceptor = Interceptor{chain ->
val url = chain.request()
.url()
.newBuilder()
.build()
val request = chain.request()
.newBuilder()
.url(url)
.build()
return@Interceptor chain.proceed(request)
}
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(requestInterceptor)
.build()
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl("http://www.recipepuppy.com")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiServicesKotlin::class.java)
}
}
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/presentation/recipes/RecipesFragment.kt
package com.example.mynewapplication.kotlinpackage.features.presentation.recipes
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import androidx.appcompat.widget.SearchView
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mynewapplication.R
import com.example.mynewapplication.kotlinpackage.core.exception.Failure
import com.example.mynewapplication.kotlinpackage.core.extension.*
import com.example.mynewapplication.kotlinpackage.core.platform.BaseFragment
import com.example.mynewapplication.kotlinpackage.features.presentation.model.RecipeView
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.ViewHolder
import kotlinx.android.synthetic.main.activity_content_list.*
import kotlinx.android.synthetic.main.fragment_recipes.*
import timber.log.Timber
class RecipesFragment : BaseFragment() {
companion object {
private val TAG = RecipesFragment::class.java.simpleName
private const val ITEMS_BEFORE_FETCHING_NEXT_PAGE = 3
private const val DELAY_AFTER_TYPING = 700L
private const val DELAY_INTERVAL = 100L
}
override fun layoutId() = R.layout.activity_content_list
private lateinit var viewModel: RecipesViewModel
private lateinit var searchView: SearchView
private lateinit var scrollListener: RecyclerView.OnScrollListener
private val recipesAdapter = GroupAdapter<ViewHolder>()
private var countDownTimer: CountDownTimer? = null
private var loadingNewItems = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
appComponent.inject(this)
setHasOptionsMenu(true)
viewModel = viewModel(viewModelFactory) {
observe(recipeList, ::onRecipesFetched)
observe(favoriteRecipes, ::onFavRecipesFetched)
observe(restartSearch, ::onRestartSearch)
failure(failure, ::showError)
}
}
private fun onRestartSearch(restart: Boolean?) {
restart?.let {
if (restart) {
loadingNewItems = false
recipesAdapter.clear()
removeScrollListener()
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
rv_contentlist.apply {
layoutManager = LinearLayoutManager(context)
adapter = recipesAdapter
}
addScrollListener()
fetchRecipes("")
viewModel.getFavoriteRecipes()
}
// override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
// super.onCreateOptionsMenu(menu, inflater)
// inflater.inflate(R.menu.menu_main, menu)
//
// val searchItem = menu.findItem(R.id.action_search)
// searchView = searchItem.actionView as SearchView
// searchView.apply {
// setOnQueryTextListener(this@RecipesFragment)
// }
// }
// override fun onOptionsItemSelected(item: MenuItem): Boolean {
// when (item.itemId) {
// R.id.action_favorites -> {
// findNavController().navigate(RecipesFragmentDirections.actionRecipesFragmentToFavoriteRecipesFragment())
// return true
// }
// }
// return super.onOptionsItemSelected(item)
// }
// override fun onQueryTextSubmit(query: String?): Boolean {
// query?.let {
// fetchRecipes(it)
// }
// return true
// }
// override fun onQueryTextChange(newText: String?): Boolean {
// countDownTimer?.cancel()
// countDownTimer = object : CountDownTimer(DELAY_AFTER_TYPING, DELAY_INTERVAL) {
// override fun onFinish() {
// newText?.let {
// if (it.length > 2) fetchRecipes(it)
// }
// }
//
// override fun onTick(millisUntilFinished: Long) {
// Timber.tag(TAG).d("Remaining: $millisUntilFinished")
// }
// }.start()
// return true
// }
private fun fetchRecipes(ingredients: String) {
viewModel.getRecipes(ingredients.trim())
}
private fun onRecipesFetched(recipes: List<RecipeView>?) {
progress_recipes.gone()
if (recipes != null && recipes.isNotEmpty()) {
val items = recipes.map { recipeView ->
RecipeItem(recipeView,
clickListenerRecipe = { recipe ->
if (recipe.href.isNotEmpty()) {
val navDirections =
RecipesFragmentDirections.actionRecipesFragmentToRecipeDetailsFragment().apply {
href = recipe.href
name = recipe.title
}
findNavController().navigate(navDirections)
} else {
notify(getString(R.string.recipe_details_no_href))
}
},
clickListenerFav = { recipe, isFavorite ->
if (isFavorite) {
viewModel.saveRecipe(recipe)
} else {
viewModel.deleteRecipe(recipe.href)
}
})
}
if (loadingNewItems) {
loadingNewItems = false
recipesAdapter.removeGroup(recipesAdapter.itemCount - 1)
}
recipesAdapter.addAll(items)
rv_contentlist.visible()
} else if (recipesAdapter.itemCount > 0) {
notify(getString(R.string.recipes_no_more_recipes))
} else {
notify(getString(R.string.recipes_no_results))
}
}
private fun onFavRecipesFetched(favRecipes: List<RecipeView>?) {
favRecipes?.let {
if (it.isNotEmpty()) {
for (i in 0 until recipesAdapter.itemCount) {
val recipeItem = recipesAdapter.getItem(i) as RecipeItem
recipeItem.recipeView.isFavorite =
favRecipes.find { favRecipe -> recipeItem.recipeView.href == favRecipe.href } != null
}
}
}
}
private fun addScrollListener() {
scrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
val isTimeToLoadMoreItems =
ITEMS_BEFORE_FETCHING_NEXT_PAGE >= recipesAdapter.itemCount - lastVisibleItemPosition
if (!loadingNewItems && isTimeToLoadMoreItems) {
loadingNewItems = true
recipesAdapter.add(recipesAdapter.itemCount, LoadingItem())
viewModel.getRecipesNextPage()
}
}
}
rv_contentlist.addOnScrollListener(scrollListener)
}
private fun removeScrollListener() {
rv_contentlist.removeOnScrollListener(scrollListener)
Timber.tag(TAG).d("removeScrollListener: ${Exception().printStackTrace()}")
}
private fun showError(failure: Failure?) {
when (failure) {
is Failure.ServerError -> {
Timber.tag(TAG).d("Server error: ${failure.throwable?.message}")
if (loadingNewItems) {
loadingNewItems = false
recipesAdapter.removeGroup(recipesAdapter.itemCount - 1)
removeScrollListener()
}
}
}
}
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/data/repository/RecipesRepository.kt
package com.example.mynewapplication.kotlinpackage.features.data.repository
import arrow.core.Either
import com.example.mynewapplication.kotlinpackage.core.exception.Failure
import com.example.mynewapplication.kotlinpackage.core.platform.NetworkHandler
import com.example.mynewapplication.kotlinpackage.features.data.datasource.RecipesService
import com.example.mynewapplication.kotlinpackage.features.data.room.dao.RecipeInfoDao
import com.example.mynewapplication.kotlinpackage.features.data.room.entity.RecipeInfo
import com.example.mynewapplication.kotlinpackage.features.domain.model.Recipe
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import retrofit2.Call
import javax.inject.Inject
interface RecipesRepository {
fun recipes(ingredients: String, page: Int): Either<Failure, List<Recipe>>
fun favoriteRecipes(): Either<Failure, List<Recipe>>
fun saveRecipe(recipe: Recipe): Either<Failure, Boolean>
fun deleteRecipe(href: String): Either<Failure, Boolean>
class Network @Inject constructor(
private val networkHandler: NetworkHandler,
private val service: RecipesService,
private val recipeInfoDao: RecipeInfoDao
) : RecipesRepository {
override fun recipes(ingredients: String, page: Int): Either<Failure, List<Recipe>> {
return when (networkHandler.isConnected) {
true -> request(
service.recipes(
mapOf(
"i" to ingredients,
//"q" to "omelet",
"p" to page.toString()
)
)
) { recipesEntity -> recipesEntity.results.map { it.toRecipe() } }
false, null -> Either.Left(Failure.NetworkConnection())
}
}
override fun favoriteRecipes(): Either<Failure, List<Recipe>> {
return runBlocking {
var result: List<RecipeInfo>? = null
launch { result = recipeInfoDao.favoriteRecipes }.join()
result?.let {
Either.Right(it.map { recipeInfo -> recipeInfo.toRecipe() })
} ?: Either.Left(Failure.DbGetFavoriteRecipesError(Exception("Couldn't get the recipes saved")))
}
}
override fun saveRecipe(recipe: Recipe): Either<Failure, Boolean> {
return runBlocking {
var result: Long? = null
launch { result = recipeInfoDao.insert(recipe.toRecipeInfo()) }.join()
result?.let {
Either.Right(true)
} ?: Either.Left(Failure.DbInsertError())
}
}
override fun deleteRecipe(href: String): Either<Failure, Boolean> {
return runBlocking {
var result: Int? = null
launch { result = recipeInfoDao.delete(href) }.join()
result?.let {
Either.Right(true)
} ?: Either.Left(Failure.DbDeleteError())
}
}
private fun <T, R> request(call: Call<T>, transform: (T) -> R): Either<Failure, R> {
return try {
val response = call.execute()
when (response.isSuccessful) {
true -> {
response.body()?.let { Either.Right(transform(it)) }
?: Either.Left(Failure.BodyNullError())
}
false -> Either.Left(Failure.ServerError(Throwable(response.errorBody()?.string())))
}
} catch (exception: Throwable) {
Either.Left(Failure.ServerError(exception))
}
}
}
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/KotlinActivity/ContentListActivity.kt
package com.example.mynewapplication.kotlinpackage.KotlinActivity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ImageButton
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mynewapplication.kotlinpackage.adapter.ListAdapter
import com.example.mynewapplication.R
import com.example.mynewapplication.kotlinpackage.ApiServicesKotlin
import com.google.gson.GsonBuilder
import kotlinx.android.synthetic.main.activity_content_list.*
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
class ContentListActivity : AppCompatActivity() {
private lateinit var imageButton: ImageButton
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: ListAdapter
// private var result: List<Result> = ArrayList()
var linearLayoutManager = LinearLayoutManager(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_content_list)
val apiServiceKotlin = ApiServicesKotlin()
// ib_back.setOnClickListener {
//// startActivity(Intent(this, MainActivity::class.java))
// finish()
// }
// init()
// initLiveData()
initView()
getData()
// rv_contentlist.setHasFixedSize(true)
// rv_contentlist.layoutManager = LinearLayoutManager(this)
// adapter = ListAdapter(this)
// rv_contentlist.adapter = adapter
}
fun initView(){
rv_contentlist.layoutManager = linearLayoutManager
adapter = ListAdapter(this)
rv_contentlist.adapter = adapter
}
fun getData(){
val request = Request.Builder()
.url("http://www.recipepuppy.com")
.build()
val client = OkHttpClient()
client.newCall(request).enqueue(object : okhttp3.Callback {
override fun onFailure(call: okhttp3.Call, e: IOException) {
Log.e("Failed", e.message)
}
override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
val body = response.body()?.string()
var gson = GsonBuilder().create()
// var resultGson = gson.fromJson(body, Array<Result>::class.java).toList()
// adapter.setResult(resultGson)
}
})
}
// private fun initLiveData(){
// RetrofitClient.INSTANCE.getRecipes().enqueue(object : Callback<List<Result>>{
// override fun onResponse(call: Call<List<Result>>, response: Response<List<Result>>) {
//// response.body()?.let { result.addAll(it)}
//// val adapter = ListAdapter(list)
//// rv_contentlist.adapter = adapter
// }
//
// override fun onFailure(call: Call<List<Result>>, t: Throwable) {
//
// }
//
// })
// }
// private fun init() {
// recyclerView = findViewById(R.id.rv_contentlist)
//
// val data = ArrayList<ListModel>()
// data.add(ListModel(R.drawable.food, "Food 1", "Food Desc", "Detail 1", "Detail 2", "Detail 3", "See Detail"))
// data.add(ListModel(R.drawable.food, "Food 1", "Food Desc", "Detail 1", "Detail 2", "Detail 3", "See Detail"))
// data.add(ListModel(R.drawable.food, "Food 1", "Food Desc", "Detail 1", "Detail 2", "Detail 3", "See Detail"))
// data.add(ListModel(R.drawable.food, "Food 1", "Food Desc", "Detail 1", "Detail 2", "Detail 3", "See Detail"))
// data.add(ListModel(R.drawable.food, "Food 1", "Food Desc", "Detail 1", "Detail 2", "Detail 3", "See Detail"))
// data.add(ListModel(R.drawable.food, "Food 1", "Food Desc", "Detail 1", "Detail 2", "Detail 3", "See Detail"))
// data.add(ListModel(R.drawable.food, "Food 1", "Food Desc", "Detail 1", "Detail 2", "Detail 3", "See Detail"))
// data.add(ListModel(R.drawable.food, "Food 1", "Food Desc", "Detail 1", "Detail 2", "Detail 3", "See Detail"))
// data.add(ListModel(R.drawable.food, "Food 1", "Food Desc", "Detail 1", "Detail 2", "Detail 3", "See Detail"))
// data.add(ListModel(R.drawable.food, "Food 1", "Food Desc", "Detail 1", "Detail 2", "Detail 3", "See Detail"))
// data.add(ListModel(R.drawable.food, "Food 1", "Food Desc", "Detail 1", "Detail 2", "Detail 3", "See Detail"))
//
// adapter = ContentListAdapter(data, object : ContentListAdapter.OnItemClickListener{
// override fun onClick(data: ListModel) {
// val intent = Intent(this@ContentListActivity, ContentDetailActivity::class.java)
// startActivity(intent)
// }
//
// })
// }
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/core/interactor/UseCase.kt
package com.example.mynewapplication.kotlinpackage.core.interactor
import arrow.core.Either
import com.example.mynewapplication.kotlinpackage.core.exception.Failure
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
abstract class UseCase<out Type, in Params> where Type : Any {
abstract suspend fun run(params: Params): Either<Failure, Type>
operator fun invoke(params: Params, onResult: (Either<Failure, Type>) -> Unit = {}) {
val job = GlobalScope.async(Dispatchers.Default) { run(params) }
GlobalScope.launch(Dispatchers.Main) { onResult(job.await()) }
}
class None
}<file_sep>/app/src/main/java/com/example/mynewapplication/kotlinpackage/features/presentation/recipes/RecipesViewModel.kt
package com.example.mynewapplication.kotlinpackage.features.presentation.recipes
import androidx.lifecycle.MutableLiveData
import com.example.mynewapplication.kotlinpackage.core.interactor.UseCase
import com.example.mynewapplication.kotlinpackage.core.platform.BaseViewModel
import com.example.mynewapplication.kotlinpackage.features.domain.model.Recipe
import com.example.mynewapplication.kotlinpackage.features.domain.model.RecipesResult
import com.example.mynewapplication.kotlinpackage.features.domain.usecase.DeleteRecipeUseCase
import com.example.mynewapplication.kotlinpackage.features.domain.usecase.GetFavoriteRecipesUseCase
import com.example.mynewapplication.kotlinpackage.features.domain.usecase.GetRecipesUseCase
import com.example.mynewapplication.kotlinpackage.features.domain.usecase.SaveRecipeUseCase
import com.example.mynewapplication.kotlinpackage.features.presentation.model.RecipeView
import javax.inject.Inject
class RecipesViewModel @Inject constructor(
private val getRecipesUseCase: GetRecipesUseCase,
private val getFavoriteRecipesUseCase: GetFavoriteRecipesUseCase,
private val saveRecipeUseCase: SaveRecipeUseCase,
private val deleteRecipeUseCase: DeleteRecipeUseCase
) : BaseViewModel() {
var recipeList: MutableLiveData<List<RecipeView>> = MutableLiveData()
var favoriteRecipes: MutableLiveData<List<RecipeView>> = MutableLiveData()
var restartSearch: MutableLiveData<Boolean> = MutableLiveData()
private var currentPage: Int = 1
private var currentIngredients: String = ""
fun getRecipes(ingredients: String) {
if (currentIngredients != ingredients) {
currentIngredients = ingredients
currentPage = 1
restartSearch.value = true
}
getRecipesUseCase(GetRecipesUseCase.Params(currentIngredients, currentPage)) {
it.fold(::handleFailure, ::handleRecipes)
}
}
fun getRecipesNextPage() = getRecipesUseCase(GetRecipesUseCase.Params(currentIngredients, currentPage)) {
it.fold(::handleFailure, ::handleRecipes)
}
fun getFavoriteRecipes() = getFavoriteRecipesUseCase(UseCase.None()) {
it.fold(::handleFailure, ::handleFavoriteRecipes)
}
fun saveRecipe(recipeView: RecipeView) = saveRecipeUseCase(SaveRecipeUseCase.Params(recipeView)) {
it.fold(::handleFailure) {}
}
fun deleteRecipe(href: String) = deleteRecipeUseCase(DeleteRecipeUseCase.Params(href)) {
it.fold(::handleFailure) {}
}
private fun handleRecipes(recipesResult: RecipesResult) {
val recipesView = recipesResult.recipes.map { it.toRecipeView() }
val favoriteRecipesView = recipesResult.favRecipes.map { it.toRecipeView() }
for (recipeView: RecipeView in recipesView) {
recipeView.isFavorite = favoriteRecipesView.find { recipeView.href == it.href } != null
}
recipeList.value = recipesView
currentPage++
}
private fun handleFavoriteRecipes(recipes: List<Recipe>) {
val recipesView = recipes.map { it.toRecipeView() }
recipesView.map { it.isFavorite = true }
favoriteRecipes.value = recipesView
}
}
| 9810a4f02b4f8285b0d43d61014b14937903950e | [
"Java",
"Kotlin"
] | 41 | Java | krisnaprdn/My-New-App | 9df576a276c14770287c73b2d367001694994238 | 023eb0c1d5d48aea1756efd41bb5355b0175c814 |
refs/heads/master | <repo_name>delaneyj/dart-force<file_sep>/lib/server/force_serveable.dart
part of dart_force_server_lib;
class Serveable {
BasicServer basicServer;
Stream<HttpRequest> serve(String name) {
return basicServer.router.serve(name);
}
void serveFile(String fileName, HttpRequest request) {
Uri fileUri = Platform.script.resolve(fileName);
basicServer.virDir.serveFile(new File(fileUri.toFilePath()), request);
}
}<file_sep>/lib/clientsocket/abstract_socket.dart
part of dart_force_client_lib;
class SocketEvent {
var data;
SocketEvent(this.data);
}
abstract class Socket {
// For subclasses
Socket._();
factory Socket(String url, {bool usePolling: false, int heartbeat: 2000}) {
print("choose a socket implementation!");
if (usePolling || !WebSocket.supported) {
return new PollingSocket(url, heartbeat);
} else {
return new WebSocketWrapper(url);
}
}
StreamController<ForceConnectEvent> _connectController;
StreamController<SocketEvent> _messageController;
void connect();
void send(data);
bool isOpen();
Stream<SocketEvent> get onMessage => _messageController.stream;
Stream<ForceConnectEvent> get onConnecting => _connectController.stream;
}<file_sep>/lib/server/basic_server.dart
part of dart_force_server_lib;
class BasicServer {
final Logger log = new Logger('BasicServer');
Router router;
String startPage = 'index.html';
var wsPath;
var port;
var buildDir;
var virDir;
var bind_address = InternetAddress.ANY_IP_V6;
PollingServer pollingServer;
BasicServer(this.wsPath, {port: 8080, host: null, buildPath: '../build' }) {
this.port = port;
if (host!=null) {
this.bind_address = host;
}
buildDir = Platform.script.resolve(buildPath).toFilePath();
if (!new Directory(buildDir).existsSync()) {
log.severe("The 'build/' directory was not found. Please run 'pub build'.");
return;
}
}
Future start(WebSocketHandler handleWs) {
Completer completer = new Completer.sync();
HttpServer.bind(bind_address, port).then((server) {
_onStart(server, handleWs);
completer.complete(const []);
});
return completer.future;
}
void _onStart(server, WebSocketHandler handleWs) {
log.info("Search server is running on "
"'http://${Platform.localHostname}:$port/'");
router = new Router(server);
// The client will connect using a WebSocket. Upgrade requests to '/ws' and
// forward them to 'handleWebSocket'.
router.serve(this.wsPath)
.transform(new WebSocketTransformer())
.listen((WebSocket ws) {
handleWs(new WebSocketWrapper(ws));
});
// long_polling();
pollingServer = new PollingServer(router, wsPath);
pollingServer.onConnection.listen((PollingSocket socket) {
handleWs(socket);
});
// Set up default handler. This will serve files from our 'build' directory.
virDir = new http_server.VirtualDirectory(buildDir);
// Disable jail-root, as packages are local sym-links.
virDir.jailRoot = false;
virDir.allowDirectoryListing = true;
virDir.directoryHandler = (dir, request) {
// Redirect directory-requests to index.html files.
var indexUri = new Uri.file(dir.path).resolve(startPage);
virDir.serveFile(new File(indexUri.toFilePath()), request);
};
// Add an error page handler.
virDir.errorPageHandler = (HttpRequest request) {
log.warning("Resource not found ${request.uri.path}");
request.response.statusCode = HttpStatus.NOT_FOUND;
request.response.close();
};
// Serve everything not routed elsewhere through the virtual directory.
virDir.serve(router.defaultStream);
}
}<file_sep>/pubspec.yaml
name: force
version: 0.3.0+4
author: <NAME> <<EMAIL>>
description: A real time web framework for dart, embracing websockets, making communication easier
homepage: https://github.com/jorishermans/dart-force
dependencies:
unittest: '>=0.9.0 <0.9.1'
http: '>=0.9.0 <0.10.0'
http_server: '>=0.9.0 <0.10.0'
logging: '>=0.9.0 <0.10.0'
route: '>=0.4.0 <0.5.0'
uuid: '0.2.1'<file_sep>/lib/server/polling_server.dart
part of dart_force_server_lib;
class PollingServer {
final Logger log = new Logger('PollingServer');
Router router;
String wsPath;
Map<String, PollingSocket> connections = new Map<String, PollingSocket>();
StreamController<PollingSocket> _socketController;
PollingServer(this.router, this.wsPath) {
print('start long polling server ... $wsPath/polling');
router.serve('$wsPath/polling', method: "GET").listen(polling);
router.serve('$wsPath/polling', method: "POST").listen(sendedData);
_socketController = new StreamController<PollingSocket>();
}
void polling(HttpRequest req) {
String pid = req.uri.queryParameters['pid'];
PollingSocket pollingSocket = retrieveSocket(pid);
var messages = pollingSocket.messages;
var response = req.response;
String data = JSON.encode(messages);
response
..statusCode = 200
..headers.contentType = new ContentType("application", "json", charset: "utf-8")
//..headers.contentLength = data.length
..write(data)
..close();
messages.clear();
}
void sendedData(HttpRequest req) {
req.listen((List<int> buffer) {
// Return the data back to the client.
String dataOnAString = new String.fromCharCodes(buffer);
print(dataOnAString);
var package = JSON.decode(dataOnAString);
var pid = package["pid"];
PollingSocket pollingSocket = retrieveSocket(pid);
pollingSocket.sendedData(package["data"]);
});
var response = req.response;
var dynamic = {"status" : "ok"};
String data = JSON.encode(dynamic);
response
..statusCode = 200
..headers.contentType = new ContentType("application", "json", charset: "utf-8")
..headers.contentLength = data.length
..write(data)
..close();
}
PollingSocket retrieveSocket(pid) {
PollingSocket pollingSocket;
if (connections.containsKey(pid)) {
pollingSocket = connections[pid];
} else {
print("new polling connection! $pid");
pollingSocket = new PollingSocket();
connections[pid] = pollingSocket;
_socketController.add(pollingSocket);
}
return pollingSocket;
}
Stream<PollingSocket> get onConnection => _socketController.stream;
} | ee0900c00c97da5f08ed452dab2b5b2f874997e4 | [
"Dart",
"YAML"
] | 5 | Dart | delaneyj/dart-force | 7a2325c412aee330751df81dbf29febfe21903bc | 4118a801154ae1025c02bcb15311ae543f7d1f02 |
refs/heads/master | <file_sep>Angular Mailer
==============
[![Build Status](https://travis-ci.org/utnas/angular-mailer.svg)](https://travis-ci.org/utnas/angular-mailer)
Deployed on firebase [https://angular-mailer.firebaseapp.com/](https://angular-mailer.firebaseapp.com/ "texte pour le titre, facultatif")
This project is just a warm-up on my road to learn Angular.JS.
The same application will be build with the most popular JavaScript frameworks: EmberJs, AngularJs and ReactJs.
Dependencies:
- AngularJS: "v1.2.23"
- Angular-Mock: "v1.2.23"
- Angular-Sanitize: "v1.2.23"
- Mustache: "0.8.2"
- Twitter Bootstrap: "v3.2.0"
- NodeJs: "v0.10.32"
![alt tag](https://github.com/utnas/angular-mailer/blob/master/xdoc/snapshot.png)<file_sep>(function () {
'use strict';
angular.module('MailServiceMock', [])
.factory('mailService', function () {
var folders = [
{
value: "MAILBOX", label: 'Email Box', emails: [
{
id: 1,
from: "Albator",
to: "Rudy",
subject: "I will be back",
date: new Date(2014, 2, 20, 15, 30),
content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent id ligula ac sem fringilla mattis. Nullam sodales mi vel semper volutpat. Phasellus lorem leo, luctus a lectus id, posuere aliquet orci. Praesent sit amet ipsum porttitor, tempus odio vel, bibendum mauris. Etiam magna lorem, rhoncus eget euismod ac, lobortis quis."
},
{
id: 2,
from: "<NAME>",
to: "Rudy",
subject: "Kiss from sky",
date: new Date(2014, 3, 18, 16, 12),
content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent consectetur elementum leo. Curabitur luctus, magna a tempor sodales, orci velit dictum magna, nec pharetra turpis ante vehicula ante. Sed sed libero suscipit, rutrum ligula vel, tempor lorem. Phasellus pulvinar dolor ac velit porttitor pulvinar. Mauris felis quam, consequat at <b>mauris</b>."
},
{
id: 3,
from: "Pikachu",
to: "Rudy",
subject: "Pika pika !",
date: new Date(2014, 2, 15, 16, 12),
content: "Pika pika ! Chuuuuuu. Pika pika ! Chuuuuuu. Pika pika ! Chuuuuuu. Pika pika ! Pika pika ? Piiiiika Chuuuuuu. Pika pika ! Pikachu. Pika pika pika."
},
{
id: 4,
from: "Barbapapa",
to: "Rudy",
subject: "Hulahup Barbatruc",
date: new Date(2014, 2, 15, 14, 15),
content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent consectetur elementum leo. Curabitur luctus, magna a tempor sodales, orci velit dictum magna, nec pharetra turpis ante vehicula ante. Sed sed libero suscipit, rutrum ligula vel, tempor lorem. Phasellus pulvinar dolor ac velit porttitor pulvinar. Mauris felis quam, consequat at <b>mauris</b>."
}
]
},
{
value: "SENT", label: "Sents", emails: [
{
id: 8,
from: "Rudy",
to: "Albator",
subject: "What price ?",
date: new Date(2014, 2, 15, 16, 12),
content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent id ligula ac sem fringilla mattis. Nullam sodales mi vel semper volutpat. Phasellus lorem leo, luctus a lectus id, posuere aliquet orci. Praesent sit amet ipsum porttitor, tempus odio vel, bibendum mauris. Etiam magna lorem, rhoncus eget euismod ac, lobortis quis."
},
{
id: 9,
from: "Rudy",
to: "Capitaine Flam",
subject: "Gloubiboulga Night",
date: new Date(2014, 2, 18, 16, 12),
content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent consectetur elementum leo. Curabitur luctus, magna a tempor sodales, orci velit dictum magna, nec pharetra turpis ante vehicula ante. Sed sed libero suscipit, rutrum ligula vel, tempor lorem. Phasellus pulvinar dolor ac velit porttitor pulvinar. Mauris felis quam, consequat at <b>mauris</b>."
}
]
},
{
value: "SPAM", label: "Spams", emails: [
{
id: 10,
from: "<NAME>",
to: "Rudy",
subject: "Need a new one",
date: new Date(2014, 2, 15, 16, 12),
content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent id ligula ac sem fringilla mattis. Nullam sodales mi vel semper volutpat. Phasellus lorem leo, luctus a lectus id, posuere aliquet orci. Praesent sit amet ipsum porttitor, tempus odio vel, bibendum mauris. Etiam magna lorem, rhoncus eget euismod ac, lobortis quis."
},
{
id: 11,
from: "Sofinnoga",
to: "Rudy",
subject: "Need money ?",
date: new Date(2014, 2, 18, 16, 12),
content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent consectetur elementum leo. Curabitur luctus, magna a tempor sodales, orci velit dictum magna, nec pharetra turpis ante vehicula ante. Sed sed libero suscipit, rutrum ligula vel, tempor lorem. Phasellus pulvinar dolor ac velit porttitor pulvinar. Mauris felis quam, consequat at <b>mauris</b>."
}
]
},
{
value: "TRASH", label: "Archives", emails: [
{
id: 5,
from: "Candy",
to: "Rudy",
subject: "Happy birthday",
date: new Date(2014, 2, 15, 16, 12),
content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent id ligula ac sem fringilla mattis. Nullam sodales mi vel semper volutpat. Phasellus lorem leo, luctus a lectus id, posuere aliquet orci. Praesent sit amet ipsum porttitor, tempus odio vel, bibendum mauris. Etiam magna lorem, rhoncus eget euismod ac, lobortis quis."
},
{
id: 6,
from: "<NAME>",
to: "Rudy",
subject: "Konichiwa",
date: new Date(2014, 2, 18, 16, 12),
content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent consectetur elementum leo. Curabitur luctus, magna a tempor sodales, orci velit dictum magna, nec pharetra turpis ante vehicula ante. Sed sed libero suscipit, rutrum ligula vel, tempor lorem. Phasellus pulvinar dolor ac velit porttitor pulvinar. Mauris felis quam, consequat at <b>mauris</b>."
},
{
id: 7,
from: "<NAME>",
to: "Rudy",
subject: "Do you come",
date: new Date(2014, 2, 15, 17, 50),
content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent id ligula ac sem fringilla mattis. Nullam sodales mi vel semper volutpat. Phasellus lorem leo, luctus a lectus id, posuere aliquet orci. Praesent sit amet ipsum porttitor, tempus odio vel, bibendum mauris. Etiam magna lorem, rhoncus eget euismod ac, lobortis quis."
}
]
}
];
return {
getFolders: function () {
return folders;
},
getFolder: function (folderName) {
var iterator = 0,
result = null;
for (iterator; iterator < folders.length; iterator++) {
result = folders[iterator];
if (result.value === folderName) {
return result;
}
}
return '';
},
getMail: function (folderName, idEmail) {
var folder = this.getFolder(folderName);
if (folder) {
var iterator = 0;
for (; iterator < folder.emails.length; iterator++) {
var email = folder.emails[iterator];
if (email.id === idEmail) {
return email;
}
}
}
return '';
},
deleteEmail: function (folderName, idEmail) {
var self = this;
var folder = this.getFolder(folderName);
if (folder) {
var iterator = 0;
for (; iterator < folder.emails.length; iterator++) {
var email = folder.emails[iterator];
if (email.id === idEmail) {
var indexOf = folder.emails.indexOf(email);
if (indexOf != -1) {
folder.emails.splice(indexOf, 1);
if (folder.value !== 'TRASH') {
var trash = self.getFolder('TRASH');
trash.emails.push(email);
}
}
}
}
}
},
sendEmail: function (email, from) {
var self = this;
var sentEmails = self.getFolder('SENT'),
newEmail = email;
newEmail.id = getNextEmailId();
newEmail.from = from;
newEmail.date = new Date();
sentEmails.emails.push(newEmail);
}
};
function getNextEmailId() {
var lastGreatId = 0;
folders.forEach(function (item) {
item.emails.forEach(function (email) {
if (email.id > lastGreatId) {
lastGreatId = email.id;
}
});
});
return lastGreatId + 1;
}
});
})();<file_sep>(function () {
'use strict';
angular.module('Mailer', ['ngSanitize', 'MailServiceMock', 'EmailFilter', 'EmailDirective'])
.controller('MainController', function ($scope, mailService) {
// Selection
$scope.currentFolder = mailService.getFolder('MAILBOX');
$scope.selectedEmail = null;
$scope.newEmail = null;
$scope.selectedEmails = [];
$scope.selectFolder = function (folderValue) {
$scope.currentFolder = mailService.getFolder(folderValue);
$scope.selectedEmail = null;
if (folderValue) {
$scope.newEmail = null;
}
};
//TODO: Should be moved into the class Email
function checkUnchecked(email) {
if (!$scope.selectedEmail) {
$scope.selectedEmail = email;
}
if ($scope.selectedEmail.status === 'checked') {
$scope.selectedEmail.status = '';
$scope.selectedEmails.splice($scope.selectedEmails.indexOf(email), 1);
} else {
$scope.selectedEmail.status = 'checked';
$scope.selectedEmails.push(email);
}
}
$scope.selectEmail = function (email) {
if (email) {
$scope.displayEmail(email);
checkUnchecked(email);
}
};
$scope.displayEmail = function (email) {
if (email) {
$scope.selectedEmail = email;
}
};
// Sorting
$scope.fieldSort = null;
$scope.sortDown = false;
$scope.sortEmail = function (field) {
if ($scope.fieldSort == field) {
$scope.sortDown = !$scope.sortDown;
} else {
$scope.fieldSort = field;
$scope.sortDown = false;
}
};
$scope.cssChevronSort = function (field) {
return {
glyphicon: $scope.fieldSort == field,
'glyphicon-chevron-up': $scope.fieldSort == field && !$scope.sortDown,
'glyphicon-chevron-down': $scope.fieldSort == field && $scope.sortDown
};
};
$scope.eraseSearch = function () {
$scope.search = null;
};
$scope.eraseNewEmail = function () {
$scope.currentFolder = null;
$scope.selectedEmail = null;
$scope.newEmail = eraseFields();
$scope.formNewEmail.$setPristine();
};
$scope.addEmail = function () {
$scope.selectedEmails = [];
$scope.eraseNewEmail();
$scope.newEmail = "";
};
$scope.sendEmail = function () {
var regExpValidEmail = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$', "gi");
if (!$scope.newEmail.to || !$scope.newEmail.to.match(regExpValidEmail)) {
window.alert('Invalid email provided it should looks like <EMAIL>.ext');
return;
}
if (!$scope.newEmail.subject || $scope.newEmail.subject === "") {
if (!window.confirm("Are you sure to send an email with empty subject ?")) {
return;
}
}
mailService.sendEmail($scope.newEmail, 'MySelf');
$scope.newEmail = null;
$scope.currentFolder = mailService.getFolder('MAILBOX');
};
$scope.deleteEmail = function () {
if ($scope.selectedEmails.length > 0) {
$scope.selectedEmails.forEach(function (email) {
mailService.deleteEmail($scope.currentFolder.value, email.id);
$scope.selectedEmail = null;
email.status = '';
});
$scope.selectedEmails = [];
}
};
$scope.folders = mailService.getFolders();
//private
var eraseFields = function () {
return {
from: null,
to: null,
subject: null,
content: null
};
}
});
})();<file_sep>'use strict';
describe('Unit: MainController', function () {
beforeEach(module('Mailer'));
var ctrl, scope;
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
ctrl = $controller('MainController', {
$scope: scope
});
}));
it('should create $scope.greeting when calling sayHello', function () {
expect(scope.selectFolder('MAILBOX').label).toEqual("Hello Ari");
});
});<file_sep>(function () {
'use strict';
angular.module('ApiService', [])
.factory('apiService', function () {
});
})();<file_sep>(function () {
'use strict';
var express = require('express');
var api = express();
// Get Folders
//GET /api/folders
api.get('/folders', function (req, res) {
res.send(
{}
);
});
// Get a folder
//GET /api/folders/idFolder
api.get('/folders/:idFolder', function (req, res) {
res.send(
{}
);
});
// Get Email
// GET /api/folders/folderId/idMail
api.get('/folders/:idFolder/:idEmail', function (req, res) {
res.send(
{}
);
});
// Send email
// POST /api/send
api.post('/send', function (req, res) {
res.send({succes: true, email: req.body});
});
module.exports = function () {
return api;
};
})();<file_sep>(function () {
'use strict';
angular.module('EmailDirective', [])
.directive('templateHeader', function () {
return {
restrict: 'E',
template: '<section class="fit-borders"><h1> Smart Mailer</h1><section><h4><small><em>Because people make mistakes when tey write an email.<br/>The SmartBox will store the email during 3 minutes and will send it automatically. </em> </small> </h4> </section> </section>'
};
})
.directive('mailContent', function () {
return {
restrict: 'E',
template: '<div class="well"><h1>{{email.subject}}</h1><p><label>Id:</label><span>{{email.id}}</span></p><p><label>From: </label><span>{{email.from}}</span></p><p><label>To: </label><span>{{email.to}}</span></p><p><label>Date: </label><span>{{email.date | date:\'dd/MM/yyyy HH:mm\'}}</span></p></div><p>{{email.content}}</p>',
scope: {
email: "="
}
};
})
.directive('newEmail', function () {
return {
restrict: 'E',
template: ''
};
});
})();<file_sep>
suite('Mailer', function () {
setup(function () {
var app = angular.module('MailServiceMock', []);
var injector = angular.injector(['MailServiceMock', 'ng']);
var service = injector.get('mailService');
});
suite('mailService', function () {
test('should return correct value', function () {
// perform test with an instance of service here
});
});
});<file_sep>(function () {
'use strict';
var http = require('http'),
express = require('express'),
serveStatic = require('serve-static'),
bodyParser = require('body-parser'),
api = require('./api/api.js'),
PORT = 3223,
app = express();
// Serve static resources
app.use(serveStatic(__dirname + '/'));
// Launch server
http.createServer(app).listen(PORT);
app.use(bodyParser.json());
app.get('/', function (req, res) {
res.redirect('/index.html');
console.log('Request from :\'' + req.url + '\' redirected to route login');
});
//API
app.use("/app/api", api);
console.log('The server is started on port ' + PORT);
var send404 = function (res) {
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Page not found</h1>');
var err = new Error('Content Not Found');
err.status = 404;
next(err);
};
})(); | bf9576616632265aa9832e3fce5c874c34472cfc | [
"Markdown",
"JavaScript"
] | 9 | Markdown | utnas/angular-mailer | 04925ee97589c646584a8ed044f1bc997c9f702d | cf5c33aa8cccc56ea8068860443c050965a1dab2 |