branch_name
stringclasses 22
values | content
stringlengths 18
81.8M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
36
| num_files
int64 1
7.38k
| repo_language
stringclasses 151
values | repo_name
stringlengths 7
101
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>k3nsalazar2012/MIL<file_sep>/README.md
# MIL
TFI - Media and Information Literacy
| 04c0148a18cf3c7e85d399fa8190406a9e0536d1 | [
"Markdown"
] | 1 | Markdown | k3nsalazar2012/MIL | d35cafe506682fd33ec40c807f39c9ca41e7a9bd | 52c8580c9b4bf0e149e43a99ba214ae63ec3af64 |
refs/heads/master | <repo_name>it-forever/mikrotik-ansible<file_sep>/README.md
# mikrotik-ansible
My settings ansible for mikrotik
| 5a06f212edea6c8735399037c468bc1e9602df96 | [
"Markdown"
] | 1 | Markdown | it-forever/mikrotik-ansible | 6b092fdbee51d25591f3dbc0eae66e23268b6a9c | 791a4ffdd3321446e0ea6c5700b5b42ddbd07353 |
refs/heads/main | <repo_name>davidsantosaros/Base-apparel-coming-soon<file_sep>/style/style.scss
* {
font-family: 'Josefin Sans', sans-serif;
margin: 0px;
padding: 0px;
text-decoration: none;
appearance: none;
box-sizing: border-box;
outline: none ;
}
:root {
--primary-desaturated-red: hsl(0,36%,70%);
--pirmary-soft-red: hsl(0,93%,68%);
--neutral-dark-grayish-red: hsl(0,6%,24%);
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
textarea:-webkit-autofill,
textarea:-webkit-autofill:hover,
textarea:-webkit-autofill:focus,
select:-webkit-autofill,
select:-webkit-autofill:hover,
select:-webkit-autofill:focus {
-webkit-text-fill-color: black;
background-color: transparent;
width: 50px;
font-weight: 500;
font-size: 0.6rem;
letter-spacing: 0.1rem;
}
body {
width: 100%;
height: 100%;
min-height: 100vh;
background-image: url('../assets/img/bg-pattern-desktop.svg');
overflow-x:hidden;
}
#nav {
width: 100%;
height: 50px;
position: absolute;
top:0px;
left:0px;
#logo {
margin-left: 80px;
width: 100px;
height: 50px;
background-image: url('../assets/img/logo.svg');
background-size: contain;
background-position: center left;
background-repeat: no-repeat;
}
}
main {
width: 100%;
min-height: 100vh;
height: 100%;
display:flex;
flex-flow: row wrap;
justify-content: space-between;
align-items: center;
margin:0px auto;
overflow-x:hidden;
#content {
width: 100%;
flex:1 1 60%;
padding: 80px;
#title {
width: 100%;
font-size: 3rem;
letter-spacing: 0.6rem;
margin-bottom: 20px;
p:nth-child(1) {
font-weight: 300;
color: var(--primary-desaturated-red);
line-height: 1.2;
}
p:nth-child(2) {
font-weight: 700;
color:black;
line-height: 1.2;
}
}
#description {
font-weight: 400;
font-size: 0.8rem;
color:var(--primary-desaturated-red);
line-height: 1.5;
margin-bottom: 30px;
}
#form {
width: calc(100% - 30px);
max-width: 300px;
height: 40px;
position: relative;
border: 2px solid rgba(0,0,0,0.1);
border-radius: 20px;
#email {
position: relative;
height: 38px;
width: 100%;
line-height: 38px;
border: none;
padding-left: 20px;
background-color: transparent;
border:none;
color: black;
&::placeholder {
width: 50px;
font-weight: 700;
font-size: 0.6rem;
letter-spacing: 0.1rem;
}
}
.submit {
position: absolute;
height: 40px;
width: 70px;
top: -2px;
right:0px;
transform: translateX(50%);
border:none;
border-radius: 20px;
background-image: linear-gradient(135deg, hsl(0,80%,86%), hsl(0, 74%,74%));
box-shadow: 3px 5px 15px rgba(0,0,0,0.2);
transition: all 0.3s ease;
&::before {
content: '';
display:block;
width: 15px;
height: 15px;
position: absolute;
background-image: url('../assets/img/icon-arrow.svg');
background-position: center center;
background-repeat: no-repeat;
background-size: contain;
top:50%;
left:50%;
transform: translate(-50%,-50%);
z-index: 2;
}
&::after {
content:'';
display:none;
position: absolute;
width: 15px;
height: 15px;
top:50%;
left:-30px;
transform: translateY(-50%);
background-image: url('../assets/img/icon-error.svg');
background-position: center center;
background-repeat: no-repeat;
background-size: contain;
}
&.error::after {
display:block;
}
&:hover, &:active, &:checked {
filter: saturate(80%) brightness(120%);
}
}
#submit {
display:none;
}
#error {
opacity: 0;
margin-top: 10px;
color:var(--pirmary-soft-red);
font-size: 0.7rem;
font-weight: 500;
padding-left: 20px;
transition: all 0.3s ease;
&.error {
opacity: 1;
}
}
}
}
#hero-image {
width: 100%;
flex: 1 1 40%;
height: 100vh;
background-image: url('../assets/img/hero-desktop.jpg');
background-position: center top;
background-repeat: no-repeat;
background-size: cover;
}
#popup {
overflow:hidden;
display:none;
width: 100%;
height: 100%;
min-height: 100vh;
position: absolute;
top:0px;
left:0px;
backdrop-filter: blur(5px) opacity(100%);
#popup-content {
position: absolute;
width: 100%;
max-width: 500px;
height: 300px;
top:50%;
left:50%;
transform: translate(-50%,-50%);
text-align: center;
border-radius: 5px;
background-color: white;
box-shadow: 0px 0px 5px rgba(0,0,0,0.2);
&::before{
content: '\254B';
width: 50px;
height: 50px;
display:block;
position: absolute;
top:5px;
right:5px;
transform: rotate(45deg);
}
p:nth-child(1) {
font-weight: 700;
font-size: 3rem;
color:var(--primary-desaturated-red);
margin-top: 80px;
margin-bottom: 20px;
}
p:nth-child(2) {
font-weight: 500;
font-size: 0.8rem;
}
}
&.show {
display:block;
}
}
}
@media only screen and (max-width: 740px) {
#nav {
position: relative;
#logo {
margin-left: 40px;
}
}
main {
flex-flow: column wrap;
#content {
padding:40px;
text-align: center;
#form {
margin:auto;
// transform: translateX(-30px);
#submit {
width: 60px;
}
}
}
#hero-image {
height: 300px;
order: -1;
background-image: url('../assets/img/hero-mobile.jpg');
background-position: left top;
flex:none;
}
}
}
@media only screen and (max-width: 425px) {
main {
#content {
#form {
margin:0px;
#submit {
width: 60px;
}
}
}
}
}
@media only screen and (max-width:350px) {
main {
#content {
#title {
font-size: 2rem;
}
}
}
}
#email:-internal-autofill-selected {
background-color:transparent !important;
background-image: none !important;
color: -internal-light-dark-color(black, white) !important;
}<file_sep>/js/index.js
const input = $('#email');
const submit = $('.submit');
const errorText = $('#error');
const popupText = $('#popup');
$("input[type='email']").bind('focus', function() {
$(this).css('background-color', 'transparent');
});
function getValueInput() {
var inputText = input.val();
return inputText;
}
function showError() {
submit.addClass('error');
errorText.addClass('error');
}
function hideError() {
submit.removeClass('error');
errorText.removeClass('error');
}
input.keydown(function(e) {
var keyCode = e.keyCode;
if(keyCode === 13) {
e.preventDefault();
var value = getValueInput();
if (value.length === 0 || value.indexOf('@') === -1) {
showError();
} else {
hideError();
input.val('');
input.blur();
popupText.addClass('show');
setTimeout(function(){
popupText.removeClass('show');
},4000);
}
}
})
popupText.on({
'click' : function(){
popupText.removeClass('show');
},
})
submit.click(function(e){
var value = getValueInput();
if (value.length === 0 || value.indexOf('@') === -1) {
showError();
} else {
hideError();
input.val('');
input.blur();
popupText.addClass('show');
setTimeout(function(){
popupText.removeClass('show');
},4000);
}
e.preventDefault();
}) | 045a2225c817f56248a6d03d2e99d48f9f78d348 | [
"SCSS",
"JavaScript"
] | 2 | SCSS | davidsantosaros/Base-apparel-coming-soon | 5d8ac6caea5b6c0f0e17a993dfaf0713a7dd7427 | 9e82af8dd9122f19d305c1c4041a3275fa98b138 |
refs/heads/master | <repo_name>Ikuzen/ToDoList<file_sep>/to-do-list/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HeroesComponent } from './heroes/heroes.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
import {TaskComponent} from './task/task.component';
import {ToDoComponent} from './to-do/to-do.component';
import {AllComponent} from './all/all.component'
import { ActiveComponent } from './active/active.component';
import { DoneComponent } from './done/done.component';
const routes: Routes = [
{ path: 'heroes', component: HeroesComponent },
{ path: 'dashboard', component: DashboardComponent },
{path: 'task', component: TaskComponent},
{ path: 'all', component: AllComponent },
{path: 'active', component: ActiveComponent},
{path: 'done', component: DoneComponent},
{ path: 'to-do', component: ToDoComponent },
{ path:'detail/:id',component: HeroDetailComponent},
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }, // default redirect to dashboard (when path is '')
];
@NgModule({
exports: [ RouterModule ],
imports: [ RouterModule.forRoot(routes) ],
})
export class AppRoutingModule {
}<file_sep>/README.md
# ToDoList
Using angular
<file_sep>/to-do-list/src/app/hero.ts
export class Hero {
id: number;
active:boolean;
done:boolean;
name: string;
description: string;
checked:boolean;
}<file_sep>/to-do-list/src/app/app.component.ts
import { Component } from '@angular/core';
import { of } from 'rxjs';
import { reduce} from 'rxjs/operators';
import { interval } from 'rxjs';
//emits any number of provided values in sequence
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'What to do.... What to do..?';
}
// const source = interval(1000);
// source.pipe(((acc, val) => acc + val));
// const subscribe = source.subscribe(val => console.log(val));
// console.log(subscribe)<file_sep>/to-do-list/src/app/newtask/newtask.component.ts
import { Component, OnInit } from '@angular/core';
import { HeroesComponent } from '../heroes/heroes.component';
import { HEROES } from '../mock-heroes';
@Component({
selector: 'app-newtask',
templateUrl: './newtask.component.html',
styleUrls: ['./newtask.component.css']
})
export class NewtaskComponent implements OnInit {
constructor() { }
ngOnInit() {
}
addTask(){
let newID = HEROES[HEROES.length-1].id+1
HEROES.push({ id:newID ,active:true,done:false,description:"", name: '<NAME> !',checked:false })
console.log("pushed")
}
}
<file_sep>/to-do-list/src/app/mock-heroes.ts
import { Hero } from './hero';
export let HEROES: Hero[] = [
{ id: 11,active:true,done:false,description:"",checked:false, name: '<NAME>' },
{ id: 12,active:true,done:false,description:"",checked:false, name: 'Narco' },
{ id: 13,active:true,done:false,description:"",checked:false, name: 'Bombasto' },
{ id: 14,active:true,done:false,description:"",checked:false, name: 'Celeritas' },
{ id: 15,active:true,done:false,description:"",checked:false, name: 'Magneta' },
{ id: 16,active:true,done:false,description:"",checked:false, name: 'RubberMan' },
{ id: 17,active:true,done:false,description:"",checked:false, name: 'Dynama' },
{ id: 18,active:true,done:false,description:"",checked:false, name: '<NAME>' },
{ id: 19,active:true,done:false,description:"",checked:false, name: 'Magma' },
{ id: 20,active:false,done:true,description:"",checked:false, name: 'Tornado' }
];
<file_sep>/to-do-list/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
import { MessagesComponent } from './messages/messages.component';
import { AppRoutingModule } from './app-routing.module';
import { DashboardComponent } from './dashboard/dashboard.component';
import {TaskComponent} from './task/task.component';
import {ToDoComponent} from './to-do/to-do.component';
import { AllComponent } from './all/all.component';
import { ActiveComponent } from './active/active.component';
import { DoneComponent } from './done/done.component';
import { NewtaskComponent } from './newtask/newtask.component';
// import { AngularFireModule } from 'angularfire2';
// import { AngularFireDatabaseModule } from 'angularfire2/database';
@NgModule({
declarations: [
AppComponent,
HeroesComponent,
HeroDetailComponent,
MessagesComponent,
DashboardComponent,
TaskComponent,
ToDoComponent,
AllComponent,
ActiveComponent,
DoneComponent,
NewtaskComponent,
],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
// AngularFireModule.initializeApp(environment.firebase),
// AngularFireDatabaseModule,
],
providers: [
// no need to place any providers due to the `providedIn` flag...
],
bootstrap: [ AppComponent ]
})
export class AppModule { } | f34b04b878b32e1d307a0b59de132b39d09c1f26 | [
"Markdown",
"TypeScript"
] | 7 | Markdown | Ikuzen/ToDoList | 247818791249f4d758636d9ad7ae55f0852c777f | 4616a7c388433aa9f6d599c2c8b65d777943b94d |
refs/heads/master | <file_sep># File-Transfer
File transfer using Java
<file_sep># updated-file-transfer-code | 7c73dabdc3df549864016e8eccb9003ba358e0e3 | [
"Markdown"
] | 2 | Markdown | 14IT-1093/File-Transfer | d4a79542a9b7b7951f8bbe2533ab396a2559b630 | 321e2ae47522d41872f93e73e548c37f0ec2c571 |
refs/heads/master | <file_sep>package com.winterbe.git;
/**
* 类名 :GitCommitShowCase
* 项目名称 :java8-tutorial
* 创建时间 :2016/12/30
* 作 者:<EMAIL>
* 版 本:v1
*/
public class GitCommitShowCase {
// commit_2
}
<file_sep>/*
* Copyright (c) 2019, SDCNCSI. All rights reserved.
*/
package com.winterbe.java8.samples.concurrent;
import java.util.concurrent.CountDownLatch;
/**
* @author <EMAIL>
*/
public class CountDownLatchDemo {
public static CountDownLatch countDownLatch = new CountDownLatch(5);
static class ThreadDemo extends Thread {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId() + "完成任务");
countDownLatch.countDown();
}
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 5; i++) {
new ThreadDemo().start();
}
countDownLatch.await();
System.out.println("全部完成任务");
}
}
<file_sep>/*
* Copyright (c) 2019, SDCNCSI. All rights reserved.
*/
package com.winterbe.java8.samples.concurrent;
import java.util.concurrent.locks.LockSupport;
public class LockSupportThreadDemo {
public static Thread thread;
static class WaitThreadDemo extends Thread {
@Override
public void run() {
System.out.println("WaitThread wait,time=" + System.currentTimeMillis());
thread = Thread.currentThread();
LockSupport.park();
System.out.println("WaitThread end,time=" + System.currentTimeMillis());
}
}
static class NotifyThreadDemo extends Thread {
@Override
public void run() {
System.out.println("NotifyThread notify,time=" + System.currentTimeMillis());
LockSupport.unpark(thread);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("NotifyThread end,time=" + System.currentTimeMillis());
}
}
public static void main(String[] args) {
WaitThreadDemo waitThreadDemo = new WaitThreadDemo();
NotifyThreadDemo notifyThreadDemo = new NotifyThreadDemo();
waitThreadDemo.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
notifyThreadDemo.start();
}
}
<file_sep>package com.winterbe.java8.samples.stream;
import java.util.stream.IntStream;
/**
* 描述
*
* @author 王太成
* @version 1.0.1
* @since 2015/11/23
*/
public class Streams14 {
public static void main(String[] args) {
IntStream.range(1,10).forEach(i->System.out.println(i));
}
}
<file_sep>package com.winterbe.java8.samples.concurrent;
import java.util.concurrent.atomic.AtomicInteger;
public class SellTickets {
AtomicInteger tickets = new AtomicInteger(100);
class Seller implements Runnable {
@Override
public void run() {
while (tickets.get() > 0) {
int tmp = tickets.get();
if (tickets.compareAndSet(tmp, tmp - 1)) {
System.out.println(Thread.currentThread().getName() + " " + tmp);
}
}
}
}
public static void main(String[] args) {
SellTickets st = new SellTickets();
new Thread(st.new Seller(), "SellerA").start();
new Thread(st.new Seller(), "SellerB").start();
}
}<file_sep>
### 在java8中,java.time包下主要包含下面几个主要的类
```
Instant:时间戳
Duration:持续时间,时间差
LocalDate:只包含日期,比如:2016-10-20
LocalTime:只包含时间,比如:23:12:10
LocalDateTime:包含日期和时间,比如:2016-10-20 23:14:21
Period:时间段
ZoneOffset:时区偏移量,比如:+8:00
ZonedDateTime:带时区的时间
Clock:时钟,比如获取目前美国纽约的时间
```
### java.time.format包中的
```
DateTimeFormatter:时间格式化
```
#### 1、获取今天的日期
```java
LocalDate todayDate = LocalDate.now();
System.out.println("今天的日期:"+todayDate);
//结果
今天的日期:2016-10-20
```
#### 2、指定日期,进行相应操作
```java
//取2016年10月的第1天
LocalDate firstDay = oneday.with(TemporalAdjusters.firstDayOfMonth());
System.out.println(firstDay);
//取2016年10月的第1天,另外一种写法
LocalDate firstDay2 = oneday.withDayOfMonth(1);
System.out.println(firstDay2);
//取2016年10月的最后1天,不用考虑大月,小月,平年,闰年
LocalDate lastDay = oneday.with(TemporalAdjusters.lastDayOfMonth());
System.out.println(lastDay);
//当前日期+1天
LocalDate tomorrow = oneday.plusDays(1);
System.out.println(tomorrow);
//判断是否为闰年
boolean isLeapYear = tomorrow.isLeapYear();
System.out.println(isLeapYear);
//运行结果
2016-10-20
2016-10-01
2016-10-01
2016-10-31
2016-10-21
true
```
#### 3、生日检查或者账单日检查
开发过程中,经常需要为过生日的用户送上一些祝福,例如,用户的生日为1990-10-12,如果今天是2016-10-12,那么今天就是用户的生日(按公历/身份证日期来算),那么通过java8新的日期库,我们该如何来进行判断?
在java8中,可以使用`MonthDay`,该类不包含年份信息,当然还有一个类是`YearMonth`
```java
LocalDate birthday = LocalDate.of(1990, 10, 12);
MonthDay birthdayMd = MonthDay.of(birthday.getMonth(), birthday.getDayOfMonth());
MonthDay today = MonthDay.from(LocalDate.of(2016, 10, 12));
System.out.println(today.equals(birthdayMd));
//结果
true
```
#### 4、获取当前的时间
日期主要是使用LocalTime,该类不包含日期,只有时间信息
```java
//获取当前的时间
LocalTime nowTime = LocalTime.now(); //结果14:29:40.558
//如果不想显示毫秒
LocalTime nowTime2 = LocalTime.now().withNano(0); //14:43:14
//指定时间
LocalTime time = LocalTime.of(14, 10, 21); //14:10:21
LocalTime time2 = LocalTime.parse("12:00:01"); // 12:00:01
//当前时间增加2小时
LocalTime nowTimePlus2Hour = nowTime.plusHours(2); //16:47:23.144
//或者
LocalTime nowTimePlus2Hour2 = nowTime.plus(2, ChronoUnit.HOURS);
```
#### 5、日期前后比较
比较2个日期哪个在前,哪个在后,java8 LocalDate提供了2个方法,`isAfter()`,`isBefore`
```java
LocalDate today = LocalDate.now();
LocalDate specifyDate = LocalDate.of(2015, 10, 20);
System.out.println(today.isAfter(specifyDate)); //true
```
#### 6、处理不同时区的时间
java8中,将日期,时间,时区都很好的进行了分离。
```java
//查看当前的时区
ZoneId defaultZone = ZoneId.systemDefault();
System.out.println(defaultZone); //Asia/Shanghai
//查看美国纽约当前的时间
ZoneId america = ZoneId.of("America/New_York");
LocalDateTime shanghaiTime = LocalDateTime.now();
LocalDateTime americaDateTime = LocalDateTime.now(america);
System.out.println(shanghaiTime); //2016-11-06T15:20:27.996
System.out.println(americaDateTime); //2016-11-06T02:20:27.996 ,可以看到美国与北京时间差了13小时
//带有时区的时间
ZonedDateTime americaZoneDateTime = ZonedDateTime.now(america);
System.out.println(americaZoneDateTime); //2016-11-06T02:23:44.863-05:00[America/New_York]
```
#### 7、比较两个日期之前时间差
在项目中,经常需要比较两个日期之间相差几天,或者相隔几个月,我们可以使用java8的Period来进行处理。
```java
LocalDate today = LocalDate.now();
LocalDate specifyDate = LocalDate.of(2015, 10, 2);
Period period = Period.between(specifyDate, today);
System.out.println(period.getDays()); //4
System.out.println(period.getMonths()); //1
System.out.println(specifyDate.until(today, ChronoUnit.DAYS)); //401
//输出结果
4
1
401
```
我们可以看到,我们使用Period类比较天数,比较奇怪,他返回的值,并不是2个日期之间总共的天数差,而是一个相对天数差,比如,5月1日,和10月2日,他比较的是仅仅2个天之间的差,那1号和2号,相差1天,而实际上,因为中间相差了好几个月,所以真正的天数差肯定不是1天,所以我们可以使用until,并指明精度单位是days,就可以计算真正的天数差了。
#### 8、日期时间格式解析、格式化
在java8之前,我们进行时间格式化主要是使用`SimpleDateFormat`,而在java8中,主要是使用`DateTimeFormatter`,java8中,预定义了一些标准的时间格式,我们可以直接将时间转换为标准的时间格式:
```java
String specifyDate = "20151011";
DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
LocalDate formatted = LocalDate.parse(specifyDate,formatter);
System.out.println(formatted);
//输出
2015-10-11
```
当然,很多时间标准的时间格式可能也不满足我们的要求,我们需要转为自定义的时间格式
```java
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("YYYY MM dd");
System.out.println(formatter2.format(LocalDate.now()));
//结果
2015 10 11
```
#### 9、java8 时间类与Date类的相互转化
在转换中,我们需要注意,因为java8之前Date是包含日期和时间的,而LocalDate只包含日期,LocalTime只包含时间,所以与Date在互转中,势必会丢失日期或者时间,或者会使用起始时间。如果转LocalDateTime,那么就不存在信息误差。
```java
//Date与Instant的相互转化
Instant instant = Instant.now();
Date date = Date.from(instant);
Instant instant2 = date.toInstant();
//Date转为LocalDateTime
Date date2 = new Date();
LocalDateTime localDateTime2 = LocalDateTime.ofInstant(date2.toInstant(), ZoneId.systemDefault());
//LocalDateTime转Date
LocalDateTime localDateTime3 = LocalDateTime.now();
Instant instant3 = localDateTime3.atZone(ZoneId.systemDefault()).toInstant();
Date date3 = Date.from(instant);
//LocalDate转Date
//因为LocalDate不包含时间,所以转Date时,会默认转为当天的起始时间,00:00:00
LocalDate localDate4 = LocalDate.now();
Instant instant4 = localDate4.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date date4 = Date.from(instant);
```
总结,其实想说的这,这篇文章是一篇难产很久的文章,自从十一假期后,一直找不到写代码的感觉,所以这篇文章拖了1个月。<file_sep>package com.winterbe.thread;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class TestGuaVA<K, V> {
private Cache<K, V> cache = CacheBuilder.newBuilder().maximumSize(2).expireAfterWrite(10, TimeUnit.MINUTES).build();
public Object getCache(K keyValue, final String ThreadName) {
Object value = null;
try {
System.out.println("ThreadName getCache==============" + ThreadName);
//从缓存获取数据
value = cache.get(keyValue, new Callable<V>() {
@SuppressWarnings("unchecked")
public V call() {
System.out.println("ThreadName 执行业务数据并返回处理结果的数据(访问数据库等)==============" + ThreadName);
return (V) "dataValue";
}
});
} catch (ExecutionException e) {
e.printStackTrace();
}
return value;
}
public static void main(String[] args) {
final TestGuaVA<String, String> TestGuaVA = new TestGuaVA<String, String>();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("T1======start========");
Object value = TestGuaVA.getCache("key", "T1");
System.out.println("T1 value==============" + value);
System.out.println("T1======end========");
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("T2======start========");
Object value = TestGuaVA.getCache("key", "T2");
System.out.println("T2 value==============" + value);
System.out.println("T2======end========");
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("T3======start========");
Object value = TestGuaVA.getCache("key", "T3");
System.out.println("T3 value==============" + value);
System.out.println("T3======end========");
}
});
t1.start();
t2.start();
t3.start();
}
}<file_sep>package com.winterbe.java8.samples.concurrent;
/**
* Created by 王太成 on 2016/9/23.
*/
public class Localthread1 {
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
protected Integer initialValue() {
return 0;
}
};
private static ThreadLocal<Integer> threadLocal1 =ThreadLocal.withInitial(()-> 0);
public static void main(String[] args) {
try {
plus();
plusWithLam();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void plus() throws Exception {
for (int i = 0; i < 100; i++) {
new Thread() {
public void run() {
//1
int a = threadLocal.get();
a++;
//2
threadLocal.set(a);
System.out.println("plus:" + Thread.currentThread().getName() + ": " + threadLocal.get());
}
}.start();
}
}
private static void plusWithLam() throws Exception {
for (int i = 0; i < 100; i++) {
new Thread( ()-> {
//1
int a = threadLocal1.get();
a++;
//2
threadLocal1.set(a);
System.out.println("plusLam:" + Thread.currentThread().getName() + ": " + threadLocal1.get());
}).start();
}
}
}
<file_sep>package com.winterbe.java8.study.lambda;
/**
* 类名 :Lesson3
* 项目名称 :java8-tutorial
* 创建时间 :2017/6/16
* 作 者:<EMAIL>
* 版 本:v1
*/
public class Lesson3 {
public static void main(String[] args) {
Runnable r1 = ()-> System.out.println("r1");
Runnable r2 = new Runnable() {
@Override
public void run() {
System.out.println("r2");
}
};
process(r1);
process(r2);
process(()-> System.out.println("r3"));
}
public static void process(Runnable r){
r.run();
}
}
<file_sep>package com.winterbe.java8.samples.lambda;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.function.Predicate;
/**
* 类名 :Lambda7
* 项目名称 :java8-tutorial
* 创建时间 :2016/12/30
* 作 者:<EMAIL>
* 版 本:v1
*/
public class Lambda7 {
public static void main(String[] args) {
threadTest();
listTest();
}
private static void threadTest() {
//Before Java 8:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Before Java8 ");
}
}).start();
//Java 8 way:
new Thread(() -> System.out.println("In Java8!")).start();
}
private static void listTest() {
List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
System.out.println("Languages which starts with J :");
filter(languages, (str) -> str.startsWith("J"));
System.out.println("Languages which ends with a ");
filter(languages, (str) -> str.endsWith("a"));
System.out.println("Print all languages :");
filter(languages, (str) -> true);
System.out.println("Print no language : ");
filter(languages, (str) -> false);
System.out.println("Print language whose length greater than 4:");
filter(languages, (str) -> str.length() > 4);
Predicate<String> startsWithJ = (n) -> n.startsWith("J");
Predicate<String> fourLetterLong = (n) -> n.length() == 4;
languages.stream()
.filter(startsWithJ.and(fourLetterLong))
.forEach((n) -> System.out.println("\nName, which starts with 'J' and four letter long is : " + n));
System.out.println();
List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
costBeforeTax.stream().map((cost) -> cost + .12 * cost)
.forEach(System.out::println);
double total = 0;
for (Integer cost : costBeforeTax) {
double price = cost + .12 * cost;
total = total + price;
}
System.out.println("Total : " + total);
double bill = costBeforeTax.stream().map((cost) -> cost + .12 * cost)
.reduce((sum, cost) -> sum + cost)
.get();
System.out.println("Total : " + bill);
//Get count, min, max, sum, and average for numbers
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x)
.summaryStatistics();
System.out.println("Highest prime number in List : " + stats.getMax());
System.out.println("Lowest prime number in List : " + stats.getMin());
System.out.println("Sum of all prime numbers : " + stats.getSum());
System.out.println("Average of all prime numbers : " + stats.getAverage());
}
//Even better
public static void filter(List<String> names, Predicate<String> condition) {
names.stream().filter((name) -> (condition.test(name)))
.forEach((name) -> {
System.out.println(name + " ");
});
}
}
| b4bad19be85cf50e4c5144920aa3bc265c076191 | [
"Java",
"Markdown"
] | 10 | Java | wangtaicheng/java8-tutorial | e9183a79f1221f70ae3bc4a3a955e5371b415863 | 712826917c4291542335ba6dd5e4907cb540ea17 |
refs/heads/master | <file_sep># flight_pattern_px4
Different flight pattern using PX4 Simulation.
| 39bfd315d451db0e5006fcb7b962ed79e98a8d70 | [
"Markdown"
] | 1 | Markdown | Apurv354/flight_pattern_px4 | d9459f0f12a21e304a84370f1428c7566314e2f3 | 14bf27ee63c227e7bfcc6324edd39e72712da1af |
refs/heads/master | <repo_name>davodey/flayvor-components<file_sep>/README.md
# flayvor-components
Web components for modern frameworks
| 1f2561b40a0e7d09133b53b1e6c9df2240c9f769 | [
"Markdown"
] | 1 | Markdown | davodey/flayvor-components | d9e00ce8821826a202ddffd6e6bc9657095c281f | a6e7f7fb3cca7c0a9e70ff0d3cb5b25f91149330 |
refs/heads/master | <file_sep>$(document).ready(()=>{
const OMDB_KEY="4455de9"
const OMDB_URL="https://www.omdbapi.com/?apikey="+OMDB_KEY+"&"
$('#form').on('submit',getMovieByName);
function getMovieByName(event)
{ event.preventDefault()
let pelicula=$('#search-text').val()
getMovie(pelicula)
}
getMovie=(pelicula)=>{
axios.get(OMDB_URL+'s='+pelicula)
.then((response)=>{
console.log(response.data.Search)
let movies=response.data.Search;
renderMovies(movies)
})
.catch((err)=>{
console.log(err)
})
}
renderMovies=(movies)=>{
let output='';
$.each(movies,(index,movie)=>{
output+=`<div class="col-md-3 mb-3 text-center ">
<div class="well p-3">
<img src=${movie.Poster}>
<h6 class="text-justify" >${movie.Title}</h6>
<a href="" class="btn btn-primary " onclick="getMovieById('${movie.imdbID}')">
Ver Detalle
</a>
</div>
</div>`
})
$('#movies').html(output)
}
})
<file_sep># movieapp
Es una Web App que te permite buscar peliculas y ver un pequeño resumen de la misma
| 607477e86affc1040359d6773759ecdea2430061 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | criscamih/movieapp | 441720ec2b996a37010e848f2ef207b34d787806 | 4c7d4546822201634b25def1c056d150ac45040e |
refs/heads/master | <repo_name>Xuen90/nginx-proxy<file_sep>/nginx.conf
worker_processes 1;
events {
worker_connections 1024;
accept_mutex off;
use epoll;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
server {
listen 80;
error_log stderr info;
keepalive_timeout 5;
location / {
proxy_pass http://v.atyun.org;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
proxy_set_header Host 'v.atyun.org';
proxy_redirect default;
proxy_buffering off;
}
}
} | b571dbe461fdc7d797f371e6f31c1e325f16a841 | [
"Nginx"
] | 1 | Nginx | Xuen90/nginx-proxy | 572924cb8a74279a7826d58a5189d3bd5fbc348b | f4775302a1b56123852b1b4df37d16cb00e5286a |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
public class LeaderBoardAndAchevementsController : MonoBehaviour
{
private void Start()
{
PlayGamesClientConfiguration config = new
PlayGamesClientConfiguration.Builder()
.Build();
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.Activate();
}
private void SignIn()
{
}
}
<file_sep>using UnityEngine;
using UnityEngine.Advertisements;
public class UnityAdsController : MonoBehaviour
{
[Header("Unity ads configrations")]
[SerializeField] private bool test_Mode = false;
[Space(10)]
[SerializeField] private string unity_id;
[Space(10)]
[SerializeField] private bool load_ad_OnStart = false;
[SerializeField] private string rewarded_Video_String = "Rewarded";
private void Start()
{
Advertisement.Initialize(unity_id, test_Mode);
}
public bool isUnityIntersitialReady()
{
return Advertisement.IsReady();
}
public bool isUnityRewardedReady()
{
return Advertisement.IsReady(rewarded_Video_String);
}
public void ShowUnityIntersitial()
{
if (Advertisement.IsReady())
{
Advertisement.Show();
}
}
public void ShowUnityRewarded()
{
if (Advertisement.IsReady(rewarded_Video_String))
{
Advertisement.Show(rewarded_Video_String);
}
}
private void UnityRewardedVideoResult(ShowResult result)
{
switch (result)
{
case ShowResult.Failed:
Debug.Log("Rewarded video faild __ Unity");
break;
case ShowResult.Finished:
Debug.Log("Rewarded video Finished __ Unity");
break;
case ShowResult.Skipped:
Debug.Log("Rewarded video Skipped __ Unity");
break;
}
}
}
<file_sep>using UnityEngine;
public class Admobi : MonoBehaviour
{
public static Admobi instance;
enum AdsNetworks
{
Admob,
Unity,
Mopub,
};
[Header("Game networks controller refrences")]
private UnityAdsController unityAdsController;
private AdmobControllerScript admobAdsController;
[Header("Game over ads network configration")]
[SerializeField] AdsNetworks GOAdNetwork1;
[SerializeField] AdsNetworks GOAdNetwork2;
[SerializeField] AdsNetworks GOAdNetwork3;
[Header("Level complete ads network configration")]
[SerializeField] AdsNetworks LCAdNetwork1;
[SerializeField] AdsNetworks LCAdNetwork2;
[SerializeField] AdsNetworks LCAdNetwork3;
[Header("Rewarded ads network configration")]
[SerializeField] AdsNetworks RAdNetwork1;
[SerializeField] AdsNetworks RAdNetwork2;
[SerializeField] AdsNetworks RAdNetwork3;
private void Start()
{
if (instance == null)
{
instance = this;
unityAdsController = this.GetComponent<UnityAdsController>();
admobAdsController = this.GetComponent<AdmobControllerScript>();
DontDestroyOnLoad(this.gameObject);
}
}
public void ShowGameOverAd()
{
//Network 1
if (GOAdNetwork1 == AdsNetworks.Unity)
{
if (unityAdsController.isUnityIntersitialReady())
{
unityAdsController.ShowUnityIntersitial();
}
}
else if (GOAdNetwork1 == AdsNetworks.Admob)
{
if (admobAdsController.isAdmobIntersitialReady())
{
admobAdsController.ShowInterstitial();
}
}
else if(GOAdNetwork1== AdsNetworks.Mopub)
{
}
else
{
//show local house ad
}
//Network 2
if (GOAdNetwork2 == AdsNetworks.Unity)
{
if (unityAdsController.isUnityIntersitialReady())
{
unityAdsController.ShowUnityIntersitial();
}
}
else if (GOAdNetwork2 == AdsNetworks.Admob)
{
if (admobAdsController.isAdmobIntersitialReady())
{
admobAdsController.ShowInterstitial();
}
}
else
{
//show local house ad
}
//Network 3
if (GOAdNetwork3 == AdsNetworks.Unity)
{
if (unityAdsController.isUnityIntersitialReady())
{
unityAdsController.ShowUnityIntersitial();
}
}
else if (GOAdNetwork1 == AdsNetworks.Admob)
{
if (admobAdsController.isAdmobIntersitialReady())
{
admobAdsController.ShowInterstitial();
}
}
else
{
//show local house
}
}
public void ShowLevelCompleteAd()
{
if (LCAdNetwork1 == AdsNetworks.Unity)
{
if (unityAdsController.isUnityIntersitialReady())
{
unityAdsController.ShowUnityIntersitial();
}
}
else if (LCAdNetwork1 == AdsNetworks.Admob)
{
if (admobAdsController.isAdmobIntersitialReady())
{
admobAdsController.ShowInterstitial();
}
}
else if (LCAdNetwork1 == AdsNetworks.Mopub)
{
}
else
{
//show local house ad
}
//Network 2
if (LCAdNetwork2 == AdsNetworks.Unity)
{
if (unityAdsController.isUnityIntersitialReady())
{
unityAdsController.ShowUnityIntersitial();
}
}
else if (LCAdNetwork2 == AdsNetworks.Admob)
{
if (admobAdsController.isAdmobIntersitialReady())
{
admobAdsController.ShowInterstitial();
}
}
else
{
//show local house ad
}
//Network 3
if (LCAdNetwork3 == AdsNetworks.Unity)
{
if (unityAdsController.isUnityIntersitialReady())
{
unityAdsController.ShowUnityIntersitial();
}
}
else if (LCAdNetwork3 == AdsNetworks.Admob)
{
if (admobAdsController.isAdmobIntersitialReady())
{
admobAdsController.ShowInterstitial();
}
}
else
{
//show local house
}
}
public void ShowRewardedAd()
{
if (RAdNetwork1 == AdsNetworks.Unity)
{
if (unityAdsController.isUnityRewardedReady())
{
unityAdsController.ShowUnityRewarded();
}
}
else if (RAdNetwork1 == AdsNetworks.Admob)
{
if (admobAdsController.isAdmobRewardedReady())
{
admobAdsController.ShowRewardBasedVideo();
}
}
else if (RAdNetwork1 == AdsNetworks.Mopub)
{
}
else
{
//show local house ad
}
//Network 2
if (RAdNetwork2 == AdsNetworks.Unity)
{
if (unityAdsController.isUnityRewardedReady())
{
unityAdsController.ShowUnityRewarded();
}
}
else if (RAdNetwork2 == AdsNetworks.Admob)
{
if (admobAdsController.isAdmobRewardedReady())
{
admobAdsController.ShowRewardBasedVideo();
}
}
else if (RAdNetwork2 == AdsNetworks.Mopub)
{
}
else
{
//show local house ad
}
//Network 3
if (RAdNetwork3 == AdsNetworks.Unity)
{
if (unityAdsController.isUnityRewardedReady())
{
unityAdsController.ShowUnityRewarded();
}
}
else if (RAdNetwork3 == AdsNetworks.Admob)
{
if (admobAdsController.isAdmobRewardedReady())
{
admobAdsController.ShowRewardBasedVideo();
}
}
else if (RAdNetwork3 == AdsNetworks.Mopub)
{
}
else
{
//show local house ad
}
}
public void ShowBanner()
{
admobAdsController.ShowBanner();
}
}
<file_sep>using System;
using UnityEngine;
using GoogleMobileAds.Api;
// Example script showing how to invoke the Google Mobile Ads Unity plugin.
public class AdmobControllerScript : MonoBehaviour
{
enum Banner_AdSize
{
StanderdBanner,
SmartBanner
};
[Header("Admob ids configrations")]
[SerializeField] private string admob_publisher_id = "ca-app-pub-3940256099942544~3347511713";
[SerializeField] private string admob_banner_id;
[SerializeField] private string admob_intersitial_id;
[SerializeField] private string admob_rewarded_id;
private string admob_test_banner_id = "ca-app-pub-3940256099942544/6300978111";
private string admob_test_intersitial_id= "ca-app-pub-3940256099942544/1033173712";
private string admob_test_rewarded_id= "ca-app-pub-3940256099942544/5224354917";
[Space(10)][Header("Admob ads configrations")]
[SerializeField] private bool showTestAds;
[SerializeField] private bool load_banner_Ad_OnStart = false;
[SerializeField] private bool load_intersitial_Ad_OnStart = false;
[SerializeField] private bool load_rewarded_Ad_OnStart = false;
[Space(10)][Header("Admob banner Ad configration")]
[SerializeField] AdPosition banner_Ad_position;
[SerializeField] Banner_AdSize banner_Size;
private BannerView bannerView;
private InterstitialAd interstitial;
private RewardBasedVideoAd rewardBasedVideo;
public void Start()
{
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(admob_publisher_id);
if (load_banner_Ad_OnStart)
{
RequestBanner();
}
if (load_intersitial_Ad_OnStart)
{
RequestInterstitial();
}
if (load_rewarded_Ad_OnStart)
{
RequestRewardBasedVideo();
}
}
// Returns an ad request with custom ad targeting.
private AdRequest CreateAdRequest()
{
return new AdRequest.Builder()
.AddTestDevice(AdRequest.TestDeviceSimulator)
.AddTestDevice("0123456789ABCDEF0123456789ABCDEF")
.AddKeyword("game")
.SetGender(Gender.Male)
.SetBirthday(new DateTime(1985, 1, 1))
.TagForChildDirectedTreatment(false)
.AddExtra("color_bg", "9B30FF")
.Build();
}
private void RequestBanner()
{
if (this.bannerView != null)
{
this.bannerView.Destroy();
}
// Create a 320x50 banner at the top of the screen.
if (showTestAds)
{
if (banner_Size == Banner_AdSize.SmartBanner)
{
this.bannerView = new BannerView(admob_test_banner_id, AdSize.SmartBanner, banner_Ad_position);
}
else
{
this.bannerView = new BannerView(admob_test_banner_id, AdSize.Banner, banner_Ad_position);
}
}
else
{
if (banner_Size == Banner_AdSize.SmartBanner)
{
this.bannerView = new BannerView(admob_banner_id, AdSize.SmartBanner, banner_Ad_position);
}
else
{
this.bannerView = new BannerView(admob_banner_id, AdSize.Banner, banner_Ad_position);
}
}
// Register for ad events.
this.bannerView.OnAdLoaded += this.HandleAdLoaded;
this.bannerView.OnAdFailedToLoad += this.HandleAdFailedToLoad;
this.bannerView.OnAdOpening += this.HandleAdOpened;
this.bannerView.OnAdClosed += this.HandleAdClosed;
this.bannerView.OnAdLeavingApplication += this.HandleAdLeftApplication;
// Load a banner ad.
this.bannerView.LoadAd(this.CreateAdRequest());
}
private void RequestInterstitial()
{
// Clean up interstitial ad before creating a new one.
if (this.interstitial != null)
{
this.interstitial.Destroy();
}
// Create an interstitial.
if (showTestAds)
{
this.interstitial = new InterstitialAd(admob_test_intersitial_id);
}
else
{
this.interstitial = new InterstitialAd(admob_intersitial_id);
}
// Register for ad events.
this.interstitial.OnAdLoaded += this.HandleInterstitialLoaded;
this.interstitial.OnAdFailedToLoad += this.HandleInterstitialFailedToLoad;
this.interstitial.OnAdOpening += this.HandleInterstitialOpened;
this.interstitial.OnAdClosed += this.HandleInterstitialClosed;
this.interstitial.OnAdLeavingApplication += this.HandleInterstitialLeftApplication;
// Load an interstitial ad.
this.interstitial.LoadAd(this.CreateAdRequest());
}
private void RequestRewardBasedVideo()
{
if (this.rewardBasedVideo == null)
{
this.rewardBasedVideo = RewardBasedVideoAd.Instance;
}
if (showTestAds)
{
this.rewardBasedVideo.LoadAd(this.CreateAdRequest(), admob_test_rewarded_id);
}
else
{
this.rewardBasedVideo.LoadAd(this.CreateAdRequest(), admob_rewarded_id);
}
// Get singleton reward based video ad reference.
this.rewardBasedVideo = RewardBasedVideoAd.Instance;
// RewardBasedVideoAd is a singleton, so handlers should only be registered once.
this.rewardBasedVideo.OnAdFailedToLoad += this.HandleRewardBasedVideoFailedToLoad;
this.rewardBasedVideo.OnAdRewarded += this.HandleRewardBasedVideoRewarded;
this.rewardBasedVideo.OnAdClosed += this.HandleRewardBasedVideoClosed;
this.rewardBasedVideo.OnAdLeavingApplication += this.HandleRewardBasedVideoLeftApplication;
}
public void ShowBanner()
{
this.bannerView.Show();
}
public void HideBanner()
{
this.bannerView.Hide();
}
public void ShowInterstitial()
{
if (this.interstitial.IsLoaded())
{
this.interstitial.Show();
}
else
{
RequestInterstitial();
MonoBehaviour.print("Interstitial is not ready yet");
}
}
public void ShowRewardBasedVideo()
{
if (this.rewardBasedVideo.IsLoaded())
{
this.rewardBasedVideo.Show();
}
else
{
RequestRewardBasedVideo();
MonoBehaviour.print("Reward based video ad is not ready yet");
}
}
public bool isAdmobIntersitialReady()
{
return this.interstitial.IsLoaded();
}
public bool isAdmobRewardedReady()
{
return this.rewardBasedVideo.IsLoaded();
}
#region Banner callback handlers
public void HandleAdLoaded(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLoaded event received");
}
public void HandleAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
MonoBehaviour.print("HandleFailedToReceiveAd event received with message: " + args.Message);
}
public void HandleAdOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdOpened event received");
}
public void HandleAdClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdClosed event received");
RequestBanner();
}
public void HandleAdLeftApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLeftApplication event received");
}
#endregion
#region Interstitial callback handlers
public void HandleInterstitialLoaded(object sender, EventArgs args)
{
MonoBehaviour.print("HandleInterstitialLoaded event received");
}
public void HandleInterstitialFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
MonoBehaviour.print(
"HandleInterstitialFailedToLoad event received with message: " + args.Message);
}
public void HandleInterstitialOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleInterstitialOpened event received");
}
public void HandleInterstitialClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleInterstitialClosed event received");
RequestInterstitial();
}
public void HandleInterstitialLeftApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleInterstitialLeftApplication event received");
}
#endregion
#region RewardBasedVideo callback handlers
public void HandleRewardBasedVideoLoaded(object sender, EventArgs args)
{
MonoBehaviour.print("HandleRewardBasedVideoLoaded event received");
}
public void HandleRewardBasedVideoFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
MonoBehaviour.print(
"HandleRewardBasedVideoFailedToLoad event received with message: " + args.Message);
}
public void HandleRewardBasedVideoOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleRewardBasedVideoOpened event received");
}
public void HandleRewardBasedVideoStarted(object sender, EventArgs args)
{
MonoBehaviour.print("HandleRewardBasedVideoStarted event received");
}
public void HandleRewardBasedVideoClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleRewardBasedVideoClosed event received");
RequestRewardBasedVideo();
}
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
string type = args.Type;
double amount = args.Amount;
MonoBehaviour.print(
"HandleRewardBasedVideoRewarded event received for " + amount.ToString() + " " + type);
}
public void HandleRewardBasedVideoLeftApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleRewardBasedVideoLeftApplication event received");
}
#endregion
} | 1ca5c7daa841e8eedbd86f73bc8ab6a64d8f139d | [
"C#"
] | 4 | C# | imrankhanswati/AdMobi | 97b93d5ef77f59d82255d2fa3fe1b1eecf8aebaa | b29eb7d355ef449cfd81b4dc2a47db9bd9c712ab |
refs/heads/master | <file_sep># web
save some project of web
| a5b431b5b17ab710d8f3af17d08ab31f9679d943 | [
"Markdown"
] | 1 | Markdown | guozhi97/web | 19d5e37055fca2626ec2099724dadd3540e1b8c5 | 80d8e18ee26be79d37c4e52b2cf5e16073a84363 |
refs/heads/main | <file_sep># blog
We can read, write our post
| 608206313f9148bcbd3ab0c7be17e9c683799e6b | [
"Markdown"
] | 1 | Markdown | Narendragithub/blog | 2fc35f9c68546cb89de8166835945bb22a9c8c70 | 6165e14de02d2dd937d5787d863173f58812b555 |
refs/heads/master | <file_sep>---
title: "9/6/2018 notes"
author: "<NAME>"
date: "9/6/2018"
output: html_document
runtime: shiny
---
```{r libraries}
library(dplyr)
library(ggplot2)
```
# Using python in RMD
The library reticulate enables to use python with r, you also have to direct to where it is using the *use_python* method.
```{r python_enabler}
library(reticulate)
use_python("/Users/brennandonnell/anaconda/bin/python")
```
Printing the first ten natural numbers numbers using r
```{r r_code}
x <- 1:10
print(x)
```
Printing the first ten natural numbers using python
```{python python_code}
import numpy as np
y = np.arange(1,11)
print(y)
```
# Shiny:
## What is it?
This is what you use if you can't afford tableau and/or you are on a budget.
* R package for *interactive web apps*
## 3 major road blocks
1. **User INterface (UI) aka look and feel**
+ Defines the components of the user interface
+ Page titles
+ Input options
+ Outputs
+ Defines what the user will see and interact with
2. **Server, aka brain**
+ Contains the information to build the app
+ Defines what happens in R
3. **Global/shinyapp aka enabler**
```{r shiny_example_1}
library(shiny)
# User Interface
ui_demo <- fluidPage(
# "UNH Analytics & Data Science"
#
tags$em(h2("UNH Analytics & Data Science"))
)
# Server
server_demo <- function(input, output){
}
# Enabler, creates the app.
shinyApp(ui=ui_demo, server=server_demo)
```
You can also use tags for this, see the comments.
```{r html_tags}
names(tags)
```
## Making user input
```{r shiny_example_2}
ui2 <- fluidPage(
sidebarLayout(
sidebarPanel(textInput(inputId = "n1", label = "input name")),
mainPanel(textOutput(outputId = "displaytext"))
)
)
server2 <- function(input, output) {
output$displaytext <- renderText(
print(paste("Hello", input$n1))
)
}
shinyApp(ui=ui2, server = server2)
```
## another example
make it do it for two strings together
```{r shiny_example_3}
ui3 <- fluidPage(
sidebarLayout(
sidebarPanel(textInput(inputId = "n1", label = "input first"),
textInput(inputId = "n2", label = "input second")),
mainPanel(textOutput(outputId = "displaytext"))
)
)
server3 <- function(input, output) {
output$displaytext <- renderText(
print(paste(input$n1, input$n2))
)
}
shinyApp(ui=ui3, server = server3)
```
## make a calculator
doesn't work yet
```{r shiny_example_4}
ui4 <- fluidPage(
sidebarLayout(
sidebarPanel(
numericInput(inputId = "n1", label = "First number", 0),
numericInput(inputId = "n2", label = "Second number", 0)),
mainPanel(textOutput(outputId = "calculate"))
)
)
server4 <- function(input, output) {
output$calculate <- renderText(
sum(input$n1, input$n2)
)
}
shinyApp(ui=ui4, server = server4)
```
# Moving on to the csv
```{r reading_csv, warning=FALSE, error=FALSE, message=FALSE}
library(readr)
fastfood_data <- read_csv("/Users/brennandonnell/Desktop/grad_school/R/fast_food (1).csv")
```
Doing stuff in shiny!
```{r radiobuttons}
ui_food <- fluidPage(
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
radioButtons("chain_ui", "Select Chain", choices = unique(fastfood_data$Chain),
selected = unique(fastfood_data$Chain)[1],inline = FALSE)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Text ----
h2("Scatter Plot"),
plotOutput(outputId = "scatter")
)
)
)
server_food <- function(input,output){
filtered_data <- reactive(filter(fastfood_data, Chain == input$chain_ui))
output$scatter <- renderPlot(
{
ggplot(filtered_data(), aes(x=Calories,y=Saturated_Fat))+ geom_point()+
theme_classic()+scale_x_continuous(limits = c(0, 1500)) +
scale_y_continuous(limits = c(0,35))
}
)
}
shinyApp(ui = ui_food, server = server_food)
```
#What if we want to make a server of it?
Copyt he following into a new folder.
```{r za_warudo}
library(shiny)
library(dplyr)
library(ggplot2)
library(readr)
fastfood_data <- read_csv("fast_food.csv")
```
in the previous cell, make separate .r scripts for the server, ui, and the above will be the global
---
#shinyapps.io stuff
Go to [shinyapps.io](https://www.shinyapps.io) and make an account. It's pretty nifty and will let you share your apps. You can also link it up to your GitHub account, so you should also do that.
Go to Account, and then token. Don't share your token.
Now, in RStudio, under *Tools*, select *Global Options*, and then pick *Publishing*. You'll be able to *Connect* your shinyapps.io account to this, by putting the super secret code into there.
## This is where the fun begins.
Now, open one of your global files. a little button that says *Run app* will appear From there it will do the thing. **But wait, there's more!** If you click on the *publish* icon, you can publish it to your shinyapps.io account, and then run it on that website, and other people can also run it.
**Note:** whenever you publish stuff, you don't need the enabler.
---
# For next week...
* Create multiple tabs: one with a barplot, another with a scatterplot
* get your internet to work
* make a shinyapps.io account
+ Hint: use tabsetPanel() and tabPanel() as necessary within the mainPanel.
ON to tableauprep<file_sep># r-notebooks
Class notes from my graduate classes taken in R Markdown.
**Note**: .csv files are unfortunately not included as they are not my property.
Since these are my class notes, there may be mistakes in them.
Markdown is a really wonderful thing, and I would highly recommend people give it a try.
<file_sep>---
title: "8/30/18 notes"
author: "<NAME>"
output: pdf_document
---
# NOTES
## Intro
Replication is important when writing code. Make sure it's legible and easily understandable, and that your variables make sense.
you also want to show what worked **and** what didn't.
Side note, go back and redo the code in python/r and write a report about it. You could get it published too. Go to a conference with it as opposed to a journal.
## R Markdown
What is it?
it's markdown mixed with R code. Its output is similar to HTML, but way easier to write.
Good thing about it is that you can run your R code **AND** your python code.
# THIS IS HEADING 1
## this is a second heading.
From the pop-up window, if you select **Open in browser** it opens in your browser.
## lists and asterisks
* Putting *one* asterisk around text gives you *italicized* text.
* Putting **two** asterisks around text gives you **bolded** text.
+ To give you a list, give a space between the start of the list
[link](www.rstudio.com) is how you make a link.
***
# Example: mexample.txt
## create the stuff in r markdown.
Applicants must hold a baccalaureate degree (no specific field of study is required) from an accredited college or university with a **3.0 GPA** or higher. Applicants should have demonstrated quantitative aptitude in undergraduate coursework or similar work experience in analytic field. Prior coursework may include: ***statistics, chemistry, physics, mathematics*** or other quantitative courses.
Submit an application to the [UNH Graduate School](http://gradschool.unh.edu/apply.php) with the following:
1. Prior college transcripts
2. Two letters of recommendation
3. Resume
The document was last update on: `r Sys.time()`
***
# How about actually using R code in this?
## simple.
Here's how it is done. This is called an **R Chunk**
The following function (*paste*) concatenates two strings: "AB" and "CD".
```{r}
fn <- "AB"
ln <- "CD"
print(paste(fn, ln))
x <- "Univ of"
y <- "New Hampshire"
paste(x, y)
```
Now let's say that this code didn't work, but we still want to keep it. How do we hide it? in the R chunk, put {r echo=FALSE}.
```{r echo=FALSE}
fn <- "AB"
ln <- "CD"
print(paste(fn, ln))
x <- "Univ of"
y <- "New Hampshire"
paste(x, y)
```
But now, we're still getting the output. WE don't even want that. Now try {r echo=FALSE, eval=FALSE}. With the new eval=FALSE, the code in the chunk doesn't even get executed.
```{r echo=FALSE, eval=FALSE}
fn <- "AB"
ln <- "CD"
print(paste(fn, ln))
x <- "Univ of"
y <- "New Hampshire"
paste(x, y)
```
To turn off warnings, such as from loading libraries, if you include warning=FALSE in the curly braces for the chunk, the warnings won't appear.
Lastly, to showcase the code but *not* the results, use {r results='hide'} in the chunk.
***
# question
## in R markdown...
use data(mtcars) and do some stuff
SCATTERPLOT of **MPG vs HP**
```{r warning=FALSE, results='hide', mtcars, fig.height=4}
library(ggplot2)
#plot(mtcars$mpg, mtcars$hp)
ggplot(mtcars, aes(hp, mpg)) + geom_point(aes())
```
Bar Pot of **gear**
```{r}
ggplot(mtcars, aes(gear)) + geom_bar()
```
***
# BENCHMARKING
## WHY DO WE NEED IT?
Is your code **too slow**? Does your system **Crash** whenever you run R?
Well, *try keeping your libraries up-to-date*.
system.time(command) times it.
```{r warning=FALSE}
library(readr)
```
which runs faster, read.csv() or read_csv()?
```{r warning=FALSE}
setwd("/Users/brennandonnell/Desktop/grad_school/R")
system.time(
read.csv("NH_data_072418.csv")
)
system.time(
read_csv("NH_data_072418.csv")
)
```
check out the library(microbenchmark). this'll do it a lot better.
```{r warning=FALSE, eval=FALSE}
library(microbenchmark)
microbenchmark(read.csv("NH_data_072418.csv"),
read_csv("NH_data_072418.csv"),
times = 3)
```
an important thing to know for parallel processing is *how many cores does your computer have*?
Luckily, thereis an easy way to figure it out, thanks to the benchmarkme library
```{r}
library(benchmarkme)
get_ram()
get_cpu()
```
# Code
* Which part of the code is taking the longest time to execute?
* Can you change the way you are executing the code?
+ Which is taking up the most time?
this is where the library profvis comes in.
* It allows you to benchmark *each line* of our code for...
+ d
+ d
how do you use it?
profvis({
your code here
})
```{r warning=FALSE, eval=FALSE}
library(profvis)
profvis({
library(readr)
x <- read_csv("Durham_Weather.csv")
x$below_zero_vector <- ifelse(x$TMIN < 0, 1, 0)
for (i in 1:length(x$TMIN)){
if (x$TMIN[1] < 0){
x$below_zero_loop[i] <- 1
}else{
x$below_zero_loop[i] <- 0
}
}
})
```
***
write code to make a scatterplot of tmin vs tmax using ggplot and plot. According to profvis, which is better?
```{r warning=FALSE, eval=FALSE}
profvis({
x <- read_csv("Durham_Weather.csv")
durham_weather <- filter(x, !is.na(TMAX) | !is.na(TMIN))
plot(durham_weather$TMIN, durham_weather$TMAX)
ggplot(durham_weather, aes(TMIN, TMAX)) + geom_point()
})
```
All odd occurances aside, it
what does *version* do? `r version`
it prints out the version & other stuff.
***
# Question:
* Does every year have 365 days? (no, leap year)
* Does every day have 24 hours? (no, dst)
* Does every minute have 60 seconds? (no, leap second. )
SO... what is the right day or time? what date and time is universal? what is the global standard time? [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the golden standard.
* yyyy-mm-dd
+ Example: 24 July 2018 in ISO 8601 is 2018-07-24, no need of separators (or - if needed).
* HH:MM:SS
+ Example: 9.15 PM in ISO 8601 standard is 21:15:00
```{r}
x <- Sys.Date()
```
***
# fun
Use the appropriate lubridate function to parse each of the following dates:
* d1 <- "August 29, 2018"
* d2 <- "2018-Aug-29"
* d3 <- "29-Aug-2018"
* d4 <- c("August 29 (2018)","August 30 (2018)")
* d5 <- "08/29/18"
(if you don't remember lubridate, google the following: DMY, MDY, YMD)
```{r}
library(lubridate)
d1 <- mdy("August 29, 2018")
d2 <- ymd("2018-Aug-29")
d3 <- dmy("29-Aug-2018")
d4 <- mdy(c("August 29 (2018)", "August 30 (2018)"))
d5 <- mdy("08/29/18")
```
Now try reading in durham weather again and telling the class of the variable
```{r}
y <- read.csv("Durham_Weather.csv")
typeof(y$Temp_Date)
x <- read_csv("Durham_Weather.csv")
typeof(x$Temp_Date)
typeof(x$Raw_Date)
```
SO, read.csv gives us an integer, and read_csv gives us a double. better.
now, extract and create new columns for
* day
* month (label)
* year
* weekday (label)
* yearday
(hints: In lubridate, day, month, year, wday, yday)
```{r warning=FALSE}
x1 <- read_csv("Durham_Weather.csv")
x1$Day <- day(x$Temp_Date)
x1$Month <- month(x$Temp_Date, label = TRUE)
x1$Year <- year(x$Temp_Date)
x1$Weekday <- wday(x$Temp_Date, label = TRUE)
x1$Yearday <- yday(x$Temp_Date)
```
Now try doing that with the rawdate.
```{r warning=FALSE}
x2 <- read_csv("Durham_Weather.csv")
x2$Day <- day(x$Raw_Date)
x2$Month <- month(x$Raw_Date, label = TRUE)
x2$Year <- year(x$Raw_Date)
x2$Weekday <- wday(x$Raw_Date, label = TRUE)
x2$Yearday <- yday(x$Raw_Date)
```
INterestingly enough, the date in Raw_Date switches midway through, resulting in a lot of missing data. How do we fix this?
d2$raw_date_fixed <- parse_date_time... just check the notes.
***
# Work on the following before coming back:
## checking for holidays?
* for the Durham_Weather dataset, create a column "isholiday" which equals 1 if NYSE is closed, or 0 if NYSE is open for the years 2014 & 2015
* SOme of the functions of interest to solve this problem include...
+ holidayNYSE from library(timeDate)
+ %in%
holidayNYSE takes in a year and gives back the timedates of the holidays
```{r warning=FALSE, message=FALSE}
library(timeDate)
hw <- read_csv("Durham_Weather.csv")
hw$Day <- day(hw$Temp_Date)
hw$Month_lab <- month(hw$Temp_Date, label = TRUE)
hw$Month <- month(hw$Temp_Date)
hw$Year <- year(hw$Temp_Date)
hw$Weekday <- wday(hw$Temp_Date, label = TRUE)
hw$Yearday <- yday(hw$Temp_Date)
hw$YMD <- ymd(paste(hw$Year, hw$Month, hw$Day, sep = "-"))
hw$isweekend <- ifelse(hw$Weekday %in% c("Sat", "Sun"), 1, 0)
hw$isholiday <- ifelse(hw$YMD %in% as.Date(holidayNYSE(2014:2015)), 1,
ifelse(hw$isweekend == 1, 1, 0))
```
| db3577b0044e0bcd5178ccf159f25e15da29b8aa | [
"RMarkdown",
"Markdown"
] | 3 | RMarkdown | bjn82/r-notebooks | 1744bc80f700ff30d3aae66159f12557175e0494 | 09f01c221642cedf8aad325f5d0a032a4cb46e30 |
refs/heads/master | <repo_name>TangoMan75/Stripped<file_sep>/src/scss/theme/_pre.scss
////
/// pre styling
///
/// @version 0.1.0
/// @group Theme
////
/**
* pre
*/
pre {
border: $border-style-default;
border-left: $border-style-pre;
background-color: $whisper;
border-radius: 0 $radius-sm $radius-sm 0;
}
<file_sep>/src/scss/theme/_mark.scss
////
/// Mark
///
/// @version 0.1.0
/// @group Theme
////
mark {
background-color: $glow-color;
}
<file_sep>/src/scss/layout/_pre.scss
////
/// pre layout
///
/// @version 0.1.0
/// @group Layout
/// @link https://gihub.com/TangoMan75/Stripped
////
/**
* pre layout
*/
pre {
margin: $margin-md $margin-xxl;
padding: $padding-md $padding-md $padding-md $padding-xxl;
text-align: left;
/* Lines may break between any two letters. */
word-break: break-all;
/* Allows unbreakable words to be broken. */
word-wrap: break-word;
/* Allows pre to wrap overflowing text */
white-space: pre-wrap;
}
<file_sep>/gulpfile.js/tasks/minjs.js
/**
* Minifies javascript from 'dest' folder
*
* @version 2.0.0
* @author <NAME> <<EMAIL>>
*/
/**
* Handles errors without stopping watch
*
* @param {Object} err Received error
* @url https://github.com/gulpjs/gulp/issues/259
*/
function handleError(err) {
console.log(err.toString());
this.emit('end');
}
// https://www.npmjs.com/package/gulp-uglify
// https://www.npmjs.com/package/gulp-rename
module.exports = function(gulp, plugins, config){
return function(cb){
console.log('\r\n\r\n----------> Minifying Javascript');
/**
* Source Config
* @type {Array}
*/
var arSrc = [
config.dest.js + '/*.js',
'!' + config.dest.js + '/_*.js',
'!' + config.dest.js + '/*.min.js',
];
gulp.src(arSrc)
.pipe(plugins.plumber({ errorHandler: handleError }))
.pipe(plugins.uglify())
.pipe(plugins.rename({suffix: '.min'}))
.pipe(gulp.dest(config.dest.js))
.on('end', cb)
};
};
<file_sep>/src/scss/theme/_navigation.scss
////
/// Navigation menu styling
///
/// @version 0.1.0
/// @group Theme
////
/**
* Navigation menu Styling
*/
nav > ul > li {
border: $border-style-default;
background-color: white;
box-shadow: $shadow;
&:first-child > p {
/* Place menu label inside p to display correctly */
font-weight: bold;
color: $dim-gray;
background-color: $whitesmoke;
&:hover {
background-color: $whisper;
}
& a {
font-weight: bold;
color: $primary;
}
}
& p {
color: $dim-gray;
}
& > a {
/* Menu links */
text-decoration: none;
color: $primary;
@include button($primary, white);
}
}
<file_sep>/src/scss/theme/_footer.scss
////
/// Footer styling
///
/// @version 0.1.0
/// @group Theme
////
body > footer:last-of-type,
body > div:first-of-type > footer:last-of-type {
background-color: $haiti;
color: $gray;
& > * {
/* Footer items styling */
border-left: $border-style-footer;
}
& ul {
/* List items styling in footer */
list-style: none;
}
& a {
/* Link styling in footer */
text-decoration: none;
color: white;
&:hover {
/* Hover effect on footer links */
text-decoration: underline;
}
}
}
<file_sep>/gulpfile.js/tasks/renamecss.js
/**
* Renames and moves css files
*
* @version 0.1.0
* @author <NAME> <<EMAIL>>
*/
// https://www.npmjs.com/package/gulp-rename
module.exports = function(gulp, plugins, config){
return function(cb){
console.log('\r\n\r\n----------> Renaming CSS Files');
/**
* Source Config
* @type {Array}
*/
var arSrc = [
config.src.css + '/*.css',
'!' + config.src.css + '/*.min.css',
];
gulp.src(arSrc)
.pipe(plugins.rename({ suffix: '.min' }))
.pipe(gulp.dest(config.dest.css))
.on('end', cb)
};
};
<file_sep>/src/scss/mixins/_buttons.scss
////
/// Buttons
///
/// Defines button design
///
/// @group Mixins
/// @version 0.1.1
/// @link https://github.com/TangoMan75/Stripped
////
@mixin button($color, $background) {
/* Resets buttons font-size & line-height */
font-size: $font-size-base;
line-height: $line-height-base;
color: $color;
background-color: $background;
&:hover {
background-color: darken($background, 10%);
cursor: pointer;
}
&:focus {
background-color: darken($background, 10%);
}
&:active {
background-color: darken($background, 10%);
&:hover,
&:focus {
background-color: darken($background, 17%);
}
}
&[disabled] {
opacity: 0.65;
&:hover,
&:focus {
cursor: not-allowed;
}
}
}
<file_sep>/src/scss/mixins/_panels.scss
////
/// Panels
///
/// @group Mixins
/// @version 0.1.0
/// @link https://github.com/TangoMan75/Stripped
////
// Place a section, or article, or aside containing a header or footer and it will be displayed as a panel.
@mixin panel($border-radius) {
border-radius: $border-radius;
text-align: center;
margin-bottom: $margin-sm;
/* Prevents margin collapsing and allows for scrollbar */
overflow: auto;
/* Centers panel block elements and sets margin */
& > article,
& > aside,
& > blockquote,
& > details,
& > div,
& > dl,
& > fieldset,
& > figure,
& > form,
& > h1,
& > h2,
& > h3,
& > h4,
& > h5,
& > h6,
& > img,
& > ol,
& > p,
& > section,
& > summary,
& > table,
& > ul {
margin: $margin-sm auto;
max-width: 99%;
}
& > header:first-of-type {
border-radius: $border-radius $border-radius 0 0;
/* Prevents header from collapsing when parent has display flex */
min-width: 100%;
}
& > header:first-of-type,
& > footer:last-of-type {
text-align: center;
padding: $padding-xxl;
& > * {
margin: auto;
}
}
& > header:first-of-type + footer:last-of-type {
/* Avoids double margin when a footer follows a header inside panel */
margin-top: -1px;
}
& footer:last-of-type {
border-radius: 0 0 $border-radius $border-radius;
font-size: $font-size-sm;
/* Prevents footer from collapsing when parent has display flex */
min-width: 100%;
}
}
<file_sep>/README.md
Stripped
========
Responsive Mobile-First SASS / CSS Micro Framework Without Classes
------------------------------------------------------------------
Targeting HTML elements with CSS directly is usually source of repetition and considered bad practice.
But if you often find yourself developing single page applications and **don't want to spend a lot of time on CSS design** for each one of these small projects.
And still, some styling is needed to present your work in a decent fashion **without wasting hours adding classes to your HTML for bootstrap** or typing CSS.
Then **Stripped** is for you !
Concept
-------
I've build **Stripped** why simplicity is mind.
**Stripped** layout relies on nesting and HTML semantics, so almost no scaffolding is needed exept the one emerging naturally from your HTML document.
For example: It's common practice to use a `<div>` to contain document elements (hello Boostrap users). But why would we need `<div class="container">` when we could use the `<main>` element to wrap our pages ?
Unlike Bootstrap **Stripped** allows to avoid unecessary nesting, classes definitions, and preserve HTML5 semantics in your source code.
Which should allow for fully W3C compliant HTML5, improved accessibility, lighter code and easy maintenance.
What more could you ask for !
How to use ?
------------
Just link **Stripped** CSS in the `<head>` of your document and you should see **Stripped** theme and layout applied to your page.
Link optional javascript at the end of the `<body>` of your document to use extended **Stripped** features (like animations).
How does it work ?
------------------
**Stripped** relies on the structure of your HTML to apply layout and styling.
For example, first direct `<header>` child element from `<body>` will be considered to have role `banner` and will be displayed as the main banner of the page.
All `<nav>` will be considered to have role `navigation`, `<nav>` placed in the `<header>` will be responsive.
All `<section>` will be displayed as a panel, special design will be applied to first `<header>` and last `<footer>` nested tags.
All `<article>` will be considered to have role `article` and will have special design applied to them, first `<header>` and last `<footer>` will have some special styling as well.
Last `<footer>` tag in the document will be considered to have role `contentinfo` and have special design applied to it.
If you want to dive deeper into **Stripped** structure, I've made source SASS availlable for you to customize as you need.
Features
--------
- Typographic scale.
- Automatic button mixin.
- Automatic kbd design mixin.
- Animations.
- Smooth scrolling.
- Automatic ARIA roles.
Extras
------
I diverged from **Stripped** concept a little, but I felt the need to build an optional **grid system** which adds a layer of flexibility to the framework.
**Stripped** responsive grid system takes advantage of powerful CSS3 flex-box property.
It should be intuitive to use as it kind of works like Bootsrap's one, except that you don't need to nest your HTML into a `<div class="container">`, or a `<div class="row">`. And **Stripped** doesn't add unwanted padding to create gutter between elements. Gutter is simply substracted to elements width percentage value, which lets you free to apply padding, margin and border you like.
How to use **Stripped** grid system ?
-------------------------------------
First, add `class="grid"` to parent container which will set up the necessary flex-box CSS, then add responsive `width` classes.
Example:
```html
<section class="grid">
<article class="width-sm-12 width-md-6 width-lg-3">
<p>Lorem ipsum...</p>
</article>
</section>
```
**Stripped** grid has twelve columns.
Above `<article>` will have 100% width on small screens, 50% width on medium screens, 25% width on large screens.
Separation of concerns
----------------------
**Stripped** was built with separation of concerns in mind. All layout related code on one side, and all styling related code on the other, this allows for easier maintenance and enables the possibility to develop themes on top of **Stripped** structure, without changing the scaffolding of the framework. Or you could change the layout while keeping the default design.
Limitations
-----------
Unfortunately **Stripped** concept has some limitations.
1. I've developped **Stripped** to take full advantage of latest HTML5 / CSS3 possibilities. So, I assume you're a developper and that you use a modern HTML5 compliant browser. I don't plan to work on ie8 compatibility anytime soon.
2. I cannot guarantee full cross browser consistency, so your page might look different according to how your browser renders CSS. I may try to improve on this, meanwhile try to use [reset](http://meyerweb.com/eric/tools/css/reset/reset.css) or [normalize](https://necolas.github.io/normalize.css/4.1.1/normalize.css).
3. I've intentionally setup very restrictive rules for layout which avoids **Stripped** to conflict with other CSS rules. But on the other hand, if you decide to change you HTML, your design might break. For **Stripped** to work as intended, you should **NOT** use unnecessary nesting, do **NOT** place your elements inside a `<div>` container.
4. Because **Stripped** CSS targets elements directly, and according to CSS specificity rules, all **Stripped** CSS may easilly (and should be) overridden by any other more specific rules.
Developpement
-------------
I you want to contribute and install **Stripped** developpement dependencies locally follow these steps:
### Step 1: Install Node.js
#### Install Node.js (Linux)
On linux machine install node globally with the following commands (requires curl):
```bash
$ curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
$ sudo apt-get install --assume-yes nodejs
```
#### Install Node.js (Windows)
Download and install recommended LTS version from here: [Node.js](https://nodejs.org/en)
#### Optional: Install Yarn
#### Install Yarn (Linux)
On linux machine install yarn globally with the following commands (requires curl):
```bash
$ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
$ echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
$ sudo apt-get update
$ sudo apt-get install --assume-yes yarn
```
#### Install Yarn (Windows)
Download and install latest version from here: [yarnpkg.com](https://classic.yarnpkg.com/en/docs/install/#windows-stable)
### Step 2. Install Gulp globally
Open a command console and enter following command to download and install the latest stable version:
```bash
$ npm install gulp-cli -g
# or with yarn
$ yarn global add gulp-cli
```
If you want more detailled information on intallation process, have a look at the [Getting Started](https://github.com/gulpjs/gulp/blob/master/docs/getting-started.md) chapter of the [Gulpjs](https://github.com/gulpjs) documentation on github.
Enter following command to check if *Gulp* installed correctly:
```bash
$ gulp -v
```
### Step 3. Install project dependencies
Execute the following command to download the latest stable version of required **Gulp** dependencies:
```bash
$ npm install
# or
$ yarn install
```
(Do not forget to _gitignore_ `node_modules` folder in your project root.)
How to use
----------
### Availlable commands
Enter `$ gulp watch` to start gulp listening to any change in your source directory and start working without worring about lauching tasks indiviually...
Do a `$ gulp --prod` before you commit to clean the _dist_ directory, and apply specific _production_ tasks. (Notice double dash.)
- `$ gulp clean`: Deletes all files that are not minified in the dist folder.
- `$ gulp concatcss`: Concatenates all .css files.
- `$ gulp concatjs`: Concatenates all .js files.
- `$ gulp csscomb`: Formats CSS.
- `$ gulp dump`: Dumps config and plugins variables in console.
- `$ gulp inject`: Injects minified js and css files into html.
- `$ gulp mincss`: Minifies CSS.
- `$ gulp minjs`: Minifies javascript.
- `$ gulp prefix`: Adds vendor prefixes to CSS.
- `$ gulp sasscomp`: Compiles SASS and SCSS files, and generates sourcemap.
- `$ gulp strip`: Removes console.logs from javascript.
- `$ gulp uncss`: Remove unused CSS selectors.
### Sequences
- `$ gulp`: Starts default sequence. Compiles sass, appends vendor prefixes, combs css, minifies css, injects css and js, and cleans dist directory.
- `$ gulp watch`: Starts watcher on CSS, JS, and HTML files.
- `$ gulp sass`: Compiles sass, appends vendor prefixes, combs css, minifies css, injects css, and cleans dist directory.
- `$ gulp css`: Appends vendor prefixes, combs css, minifies css, injects css, and cleans dist directory.
- `$ gulp js`: Concatenates javascript, minifies js, injects js, and cleans dist directory.
### Developpement or production settings
**TangoMan Gulp Boilerplate** makes it easy to set up specific tasks for developpement or production.
For example you don't need minification or prefixing during developping phase, while you may want to clean your _dist_ folder or to avoid making sourcemaps availlable for your final production.
Use `--prod` argument to your tasks to run Gulp with specific production settings. (Notice double dash.)
### Included plugins
**TangoMan Stripped** package.json includes the following awesome Gulp plugins:
- [del](https://www.npmjs.com/package/del)
- [gulp](https://www.npmjs.com/package/gulp)
- [gulp-autoprefixer](https://www.npmjs.com/package/gulp-autoprefixer)
- [gulp-beautify](https://www.npmjs.com/package/gulp-beautify)
- [gulp-concat](https://www.npmjs.com/package/gulp-concat)
- [gulp-csscomb](https://www.npmjs.com/package/gulp-csscomb)
- [gulp-cssnano](https://www.npmjs.com/package/gulp-cssnano)
- [gulp-inject](https://www.npmjs.com/package/gulp-inject)
- [gulp-load](https://www.npmjs.com/package/gulp-load)
- [gulp-notify](https://www.npmjs.com/package/gulp-notify)
- [gulp-plumber](https://www.npmjs.com/package/gulp-plumber)
- [gulp-rename](https://www.npmjs.com/package/gulp-rename)
- [gulp-sass](https://www.npmjs.com/package/gulp-sass)
- [gulp-sequence](https://www.npmjs.com/package/gulp-sequence)
- [gulp-sourcemaps](https://www.npmjs.com/package/gulp-sourcemaps)
- [gulp-strip](https://www.npmjs.com/package/gulp-strip)
- [gulp-uglify](https://www.npmjs.com/package/gulp-uglify)
- [gulp-uncss](https://www.npmjs.com/package/gulp-uncss)
- [gulp-util](https://www.npmjs.com/package/gulp-util)
- [require-dir](https://www.npmjs.com/package/require-dir)
License
=======
Copyrights (c) 2020 <NAME>
[![License][license-MIT]][license-url]
Distributed under the MIT license.
If you like **TangoMan Stripped** please star!
And follow me on GitHub: [TangoMan75](https://github.com/TangoMan75)
... And check my other cool projects.
[<NAME> | LinkedIn](https://www.linkedin.com/in/morinmatthias)
[license-MIT]: https://img.shields.io/badge/Licence-MIT-green.svg
[license-url]: LICENSE
<file_sep>/gulpfile.js/tasks/csscomb.js
/**
* Formats all CSS from both 'src' and 'dest' folders
*
* @version 1.1.0
* @author <NAME> <<EMAIL>>
*/
// https://www.npmjs.com/package/gulp-csscomb
// http://csscomb.com/config
module.exports = function(gulp, plugins, config){
return function(cb){
// gulp-csscomb is so bad! You need to have this json inside a .csscomb.json file present in the same folder as the source file(s), or in the project root folder.
// Passing arguments directly as a parameter is NOT POSSIBLE!!!
ojbSetting = {
"remove-empty-rulesets": true,
"always-semicolon": true,
"color-case": "upper",
"block-indent": "\t",
"color-shorthand": true,
"element-case": "lower",
"eof-newline": true,
"leading-zero": false,
"quotes": "double",
"space-before-colon": "",
"space-after-colon": " ",
"space-before-combinator": " ",
"space-after-combinator": " ",
"space-between-declarations": "\n",
"space-before-opening-brace": " ",
"space-after-opening-brace": "\n",
"space-after-selector-delimiter": "\n",
"space-before-selector-delimiter": "",
"space-before-closing-brace": "\n",
"strip-spaces": false,
"unitless-zero": true,
"vendor-prefix-align": true
};
console.log('\r\n\r\n----------> Combing CSS');
gulp.src(config.src.css + '/*.css')
.pipe(plugins.csscomb(ojbSetting))
.pipe(gulp.dest(config.src.css))
.pipe(gulp.dest(config.dest.css))
.on('end', cb)
};
};
<file_sep>/src/scss/theme/_h.scss
////
/// h styling
///
/// @version 0.1.0
/// @group Theme
////
h5, h6 {
color: $grey;
}
<file_sep>/gulpfile.js/index.js
/**
* TangoMan Gulp Boilerplate
* =========================
*
* Set up your front-end Gulp workflow in minutes
* ----------------------------------------------
*
* @version 1.0.0
* @licence MIT
* @author <NAME> <<EMAIL>>
*/
/**************************************************
* Requires
**************************************************/
// https://www.npmjs.com/package/gulp
var gulp = require('gulp'); // The streaming build system
// Automatically load any gulp plugins in your package.json
// https://www.npmjs.com/package/gulp-load-plugins
// Which is way more efficient than https://www.npmjs.com/package/gulp-require-dir method
var plugins = require('gulp-load-plugins')();
// Loads gulpfile configuration
config = require('./config.json');
/**************************************************
* getTask
**************************************************/
/**
* Returns specified task from task folder
*
* This is a function I found from
* http://macr.ae/article/splitting-gulpfile-multiple-files.html
*
* @param {String} task Task name
* @return {Object} Task as a module
*/
function getTask(task){
/**
* getTask Configuration
*
* @type {String} Tasks source folder
*/
var tasksDirectory = './tasks/';
return require(tasksDirectory + task)(gulp, plugins, config);
};
/**************************************************
* Individual tasks
* 'command' -> 'file'
**************************************************/
gulp.task('clean', getTask('clean'));
gulp.task('concatjs', getTask('concatjs'));
gulp.task('csscomb', getTask('csscomb'));
gulp.task('dump', getTask('dump'));
gulp.task('inject', getTask('inject'));
gulp.task('mincss', getTask('mincss'));
gulp.task('minjs', getTask('minjs'));
gulp.task('prefix', getTask('prefix'));
gulp.task('renamecss', getTask('renamecss'));
gulp.task('sasscomp', getTask('sasscomp'));
gulp.task('strip', getTask('strip'));
gulp.task('uncss', getTask('uncss'));
gulp.task('watch', getTask('watch'));
/**************************************************
* CSS task sequences
**************************************************/
var cssDev = function(cb){
plugins.sequence('csscomb', config.inject?'inject':'', cb);
};
var cssProd = function(cb){
plugins.sequence('csscomb', 'prefix', 'mincss', config.inject?'inject':'', config.clean?'clean':'', cb);
};
gulp.task('css', plugins.util.env.prod ? cssProd : cssDev);
/**************************************************
* SASS task sequences
**************************************************/
var sassDev = function(cb){
plugins.sequence('sasscomp', 'csscomb', config.inject?'inject':'', cb);
};
var sassProd = function(cb){
plugins.sequence('sasscomp', 'csscomb', 'prefix', 'mincss', config.inject?'inject':'', config.clean?'clean':'', cb);
};
gulp.task('sass', plugins.util.env.prod ? sassProd : sassDev);
/**************************************************
* Javascript task sequences
**************************************************/
var jsDev = function(cb){
plugins.sequence('concatjs', config.inject?'inject':'', cb);
};
var jsProd = function(cb){
plugins.sequence('concatjs', 'strip', 'minjs', config.inject?'inject':'', config.clean?'clean':'', cb);
};
gulp.task('js', plugins.util.env.prod ? jsProd : jsDev);
/**************************************************
* Default Task
**************************************************/
var defaultDev = function(cb){
plugins.sequence(['sasscomp', 'concatjs'], 'csscomb', config.inject?'inject':'', cb);
};
var defaultProd = function(cb){
plugins.sequence(['sasscomp', 'concatjs'], 'csscomb', ['prefix', 'strip'], ['mincss', 'minjs'], config.inject?'inject':'', config.clean?'clean':'', cb);
};
gulp.task('default', plugins.util.env.prod ? defaultProd : defaultDev);
<file_sep>/src/scss/layout/_code.scss
////
/// code layout
///
/// @version 0.1.0
/// @group Layout
/// @link https://gihub.com/TangoMan75/Stripped
////
/**
* Code layout
*/
code {
padding: $padding-xxs $padding-xs;
}
/// Code contained inside pre
pre code {
padding: 0;
font-size: inherit;
color: inherit;
/* Whitespace is preserved by the browser. Text will wrap when necessary, and on line breaks. */
white-space: pre-wrap;
background-color: transparent;
border-radius: 0;
}
<file_sep>/gulpfile.js/tasks/clean.js
/**
* Deletes all css/js files that are not minified in the dist folder
*
* @version 1.0.1
* @author <NAME> <<EMAIL>>
* @note Will run synchronouly since del is not a gulp plugin
*/
module.exports = function(gulp, plugins, config){
return function(cb){
console.log('\r\n\r\n----------> Cleaning');
// Delete files and folders
// https://www.npmjs.com/package/del
var del = require('del');
// Not automatically loaded by "gulp-load-plugins" since not a Gulp plugin
/**
* Del Options
*
* Deletes all files that are not minified
* @type {Array}
*/
var arTarget = [
config.dest.css + '/*.*',
'!' + config.dest.css + '/*.min.css',
config.dest.js + '/*.*',
'!' + config.dest.js + '/*.min.js',
];
if (config.clean) {
console.log('----------> Removing all non-minified ".css" & ".js" files in "dest" folder');
del(arTarget);
} else {
console.log('----------> Config setting defined on "false"');
}
cb();
};
};
<file_sep>/src/html5_Test_Page.md
html5 Test Page
===============
Missing tags
------------
- input[file]
- input[keygen]
- <aside>
- <details>
- <summary>
- <div>
- <span>
Typo
----
for for
Removed unecessary div
----------------------
I know it's common practice to use a <div> to contain document (hello Boostrap users).
We don't really need it here though, so I removed it to avoid one level of unnecessary nesting.
Table
-----
html code should appear in the same order which elements are rendered by browser in documents.
So I moved the <tfoot> section after the <tbody> section in <table>.
<file_sep>/src/scss/theme/_hr.scss
////
/// hr styling
///
/// @version 0.1.0
/// @group Theme
////
hr {
border-style: none;
border-bottom: $border-style-hr;
}
<file_sep>/TODO.md
TODO
====
- Remove Gulp
- Use Webpack
<file_sep>/src/scss/theme/_blockquote.scss
////
/// Blockquote styling
///
/// @version 0.1.0
/// @group Theme
////
blockquote {
&::before,
&::after {
color: $primary;
font-size: $font-size-xxl;
font-weight: bold;
}
&::before {
content: "“";
float: left;
}
&::after {
content: "”";
float: right;
clear: both;
}
}
<file_sep>/src/scss/mixins/_padding-scale.scss
////
/// Padding scale
///
/// Sets global padding values
///
/// @group Mixins
/// @version 0.1.0
/// @link https://github.com/TangoMan75/Stripped
////
@mixin padding-scale($padding-base, $scale) {
$padding-md: $padding-base !global;
$padding-sm: $padding-md / $scale !global;
$padding-xs: $padding-sm / $scale !global;
$padding-xxs: $padding-xs / $scale !global;
$padding-lg: $padding-md * $scale !global;
$padding-xl: $padding-lg * $scale !global;
$padding-xxl: $padding-xl * $scale !global;
}
<file_sep>/gulpfile.js/tasks/mincss.js
/**
* Minifies CSS with cssnano
*
* @version 2.0.0
* @author <NAME> <<EMAIL>>
*/
// https://www.npmjs.com/package/gulp-cssnano
// https://www.npmjs.com/package/gulp-rename
module.exports = function(gulp, plugins, config){
return function(cb){
console.log('\r\n\r\n----------> Minifying CSS');
/**
* Source Config
* @type {Array}
*/
var arSrc = [
config.dest.css + '/*.css',
'!' + config.dest.css + '/*.min.css',
];
gulp.src(arSrc)
.pipe(plugins.rename({ suffix: '.min' }))
.pipe(plugins.cssnano())
.pipe(gulp.dest(config.dest.css))
.on('end', cb)
};
};
<file_sep>/src/scss/theme/_lists.scss
////
/// Lists styling
///
/// @version 0.1.0
/// @group Theme
////
dl > dt {
color: $primary;
font-weight: bold;
& > dd {
font-style: italic;
}
}
ol {
list-style-type: decimal-leading-zero;
}
ul {
list-style-type: circle;
}
<file_sep>/gulpfile.js/tasks/sassdoc.js
/**
* Generates SASS documentation
*
* @version 1.0.0
* @author <NAME> <<EMAIL>>
* @note Will run synchronouly since sassdoc is not a gulp plugin
*/
// https://www.npmjs.com/package/sassdoc
var sassdoc = require('sassdoc'); // A documentation tool for sass
module.exports = function(gulp, plugins, config){
return function(cb){
console.log('\r\n\r\n----------> Creating SASS documentation');
/**
* SassDoc Options
* @type {Object}
*/
var objDestination = {
dest: config.dest.doc + '/sass/',
};
/**
* SassDoc Source Config
*
* @type {Array}
*/
var arSrc = [
config.src.scss + '/**/*.scss',
];
gulp.src(arSrc)
.pipe(sassdoc(objDestination))
.resume()
cb();
};
};
<file_sep>/gulpfile.js/tasks/uncss.js
/**
* Remove unused CSS selectors
*
* This task is probably useless when you work with a twig template
*
* @version 1.0.0 beta
* @author <NAME> <<EMAIL>>
*/
// https://www.npmjs.com/package/gulp-uncss
module.exports = function(gulp, plugins, config){
return function(cb){
console.log('\r\n\r\n----------> Removing unused CSS');
/**
* uncss Options
* @type {Object}
*/
var objOption = {
html: [config.dest.index]
}
gulp.src(config.src.css + '/**/*.css')
.pipe(plugins.uncss(objOption))
.pipe(gulp.dest(config.dest.css))
.on('end', cb)
};
};
<file_sep>/gulpfile.js/tasks/prefix.js
/**
* Adds vendor prefixes to CSS
*
* @note Attention: Autoprefixer removes embedded sourcemaps!
* @version 1.0.1
* @author <NAME> <<EMAIL>>
*/
/**
* Handles errors without stopping watch
*
* @param {Object} err Received error
* @url https://github.com/gulpjs/gulp/issues/259
*/
function handleError(err) {
console.log(err.toString());
this.emit('end');
}
// https://www.npmjs.com/package/gulp-autoprefixer
// https://www.npmjs.com/package/gulp-plumber
module.exports = function(gulp, plugins, config){
return function(cb){
console.log('\r\n\r\n----------> Prefixing CSS');
/**
* Autoprefixer Config
* @type {Object}
* @url https://github.com/postcss/autoprefixer#options
* @url https://github.com/ai/browserslist#queries
*/
var objOptions = {
browsers: [
'> 1%',
'last 2 versions',
'Android 2.3',
'Android >= 4',
'Chrome >= 20',
'Firefox >= 24',
'Explorer >= 8',
'iOS >= 6',
'Opera >= 12',
'Safari >= 6',
],
cascade: true,
add: true,
remove: true,
supports: true,
flexbox: true,
grid: true,
};
gulp.src(config.src.css + '/*.css')
.pipe(plugins.plumber({ errorHandler: handleError }))
.pipe(plugins.autoprefixer(objOptions))
.pipe(gulp.dest(config.src.css))
.pipe(gulp.dest(config.dest.css))
.on('end', cb);
};
};
<file_sep>/src/scss/variables/_typography.scss
////
/// Typography
/// Setting default typography variables for mobiles
///
/// @group Variables
/// @version 0.2.0
/// @link https://github.com/TangoMan75/Stripped
////
$sans-serif: "Helvetica Neue", Helvetica, Arial, sans-serif;
$serif: Georgia, "Times New Roman", Times, serif;
$monospace: Menlo, Monaco, Consolas, "Courier New", monospace;
$noto: "Noto Sans", sans-serif;
$roboto: Roboto, sans-serif;
$ubuntu: Ubuntu, sans-serif;
$font-weight-base: 400;
$line-height-base: 160%;
$font-size-base: 1em;
@include type-scale($font-size-base, $major-second);
<file_sep>/src/scss/theme/_buttons.scss
////
/// Buttons styling
///
/// @version 0.1.0
/// @group Theme
////
/**
* Buttons
*/
input[type='button'],
input[type='submit'],
input[type='reset'],
button[type='button'],
button[type='submit'],
button[type='reset'] {
border-radius : $radius-md;
}
input[type='button'],
input[type='submit'],
button {
@include button(white, $primary);
}
input[type='reset'],
button[type='reset'] {
@include button(white, $danger);
}
<file_sep>/src/scss/variables/_colors.scss
////
/// Colors
///
/// Add here your color palettes, DO NOT CHANGE color values directly !
/// If you want to change some element's color go in the styling sections.
///
/// @group Variables
/// @version 0.2.0
/// @link https://github.com/TangoMan75/Stripped
/// @link https://www.htmlcsscolor.com
////
// Bootstrap 3 Colors
//--------------------------------------------------
$primary: #337ab7 !default; // Curious Blue
$success: #5cb85c !default; // Fern
$info: #5bc0de !default; // Malibu
$warning: #f0ad4e !default; // Casablanca
$danger: #d9534f !default; // Valencia
$btn-active: #286090 !default; // Endeavour
$btn-default: #e6e6e6 !default; // Whisper
// Bootstrap 4 Colors
//--------------------------------------------------
$primary: #007bff !default; // Dodger Blue
$secondary: #6c757d !default; // Raven
$success: #28a745 !default; // Chateau Green
$info: #17a2b8 !default; // Pelorous
$warning: #ffc107 !default; // Amber
$danger: #dc3545 !default; // Amaranth
$light: #f8f9fa !default; // Alice Blue
$dark: #343a40 !default; // Baltic Sea
/// Social media brand colors
//--------------------------------------------------
$bitbucket: #0052cc !default; // rgb(0, 82, 204);
$codepen: #47cf73 !default; // rgb(71, 207, 115);
$discord: #7289da !default; // rgb(114, 137, 218);
$dribble: #ea4c89 !default; // rgb(234, 76, 137);
$dropbox: #007ee5 !default; // rgb(0, 126, 229);
$facebook: #3b5998 !default; // rgb(59, 89, 152);
$gitlab: #fa7035 !default; // rgb(250, 112, 53);
$google: #4285f4 !default; // rgb(66, 133, 244);
$instagram: #e95950 !default; // rgb(233, 89, 80);
$linkedin: #0077b5 !default; // rgb(0, 119, 181);
$openclassrooms: #7451eb !default; // rgb(116, 81, 235);
$pocket: #ef4056 !default; // rgb(239, 64, 86);
$reddit: #ff4500 !default; // rgb(255, 69, 0);
$rss: #ff6600 !default; // rgb(255, 102, 0);
$skype: #00aff0 !default; // rgb(0, 175, 240);
$slack: #400d40 !default; // rgb(64, 13, 64);
$snapchat: #fffc00 !default; // rgb(255, 252, 0);
$telegram: #0088cc !default; // rgb(0, 136, 204);
$twitter: #1da1f2 !default; // rgb(29, 161, 242);
$udemy: #ec5252 !default; // rgb(236, 82, 82);
$vk: #45668e !default; // rgb(69, 102, 142);
$whatsapp: #4dc247 !default; // rgb(77, 194, 71);
$youtube: #ff0000 !default; // rgb(255, 0, 0);
/// Bright colors
//--------------------------------------------------
$bright-green: #3fb911 !default; // Kelly Green
$green: #94c20d !default; // Citrus
$yellow-green: #a2a429 !default; // Lucky
$yellow: #d9b125 !default; // Gold Tips
$orange: #f17d3e !default; // Pizazz
$red: #d8624c !default; // Flamingo
$blue: #1081c1 !default; // Bondi Blue
$pink: #ff69b4 !default; // Hot Pink
$light-pink: #f9f2f4 !default; // Lavender Blush
$dark-pink: #c7254e !default; // Old Rose
$purple: #604688 !default; // Daisy Bush
/// Dark colors
//--------------------------------------------------
$choco: #663606 !default; // Baker's Choco
$barossa: #553344 !default; // Barossa
$haiti: #2a2730 !default; // Haiti
// Gray
//--------------------------------------------------
$black: #000000 !default; // Black
$black: #111111 !default; // Black
$nero: #222222 !default; // lighten(#000, 13.5%); // Nero
$night-rider: #333333 !default; // lighten(#000, 20%); // Night Rider
$charcoal: #444444 !default; // Charcoal
$matterhorn: #555555 !default; // lighten(#000, 33.5%); // Matterhorn
$dim-gray: #666666 !default; // lighten(#000, 40%); // Dim Gray
$grey: #777777 !default; // lighten(#000, 46.7%); // Grey
$grey: #888888 !default; // Grey
$nobel: #999999 !default; // lighten(#000, 61%); // Nobel
$nobel: #9c9c9c !default; // lighten(#000, 61%); // Nobel
$dark-gray: #aaaaaa !default; // Dark Gray
$silver: #bbbbbb !default; // Silver
$very-light-grey: #cccccc !default; // lighten(#000, 80%); // Very Light Grey
$gainsboro: #dddddd !default; // Gainsboro
$whisper: #eeeeee !default; // lighten(#000, 93.5%); // Whisper
$whisper: #e6e6e6 !default; // Whisper
$whitesmoke: #f5f5f5 !default; // lighten(#000, 96%); // White Smoke
$white: #ffffff !default; // White
// TangoMan Gray
//--------------------------------------------------
$default: #555 !default; // Matterhorn
$gray-darker: #333 !default; // Night Rider
$gray-dark: #555 !default; // Matterhorn
$gray: #777 !default; // Grey
$gray-light: #ddd !default; // Gainsboro
$gray-lighter: #eee !default; // Whisper
/// Bootstrap Gray
//--------------------------------------------------
$gray-darker: #222 !default; // Nero
$gray-dark: #333 !default; // Night Rider
$gray: #555 !default; // Matterhorn
$gray-light: #777 !default; // Grey
$gray-lighter: #eee !default; // Whisper
/// Input colors
//--------------------------------------------------
$glow-color: rgba(102, 175, 233, 0.6); // #66a5e9 // Cornflower Blue
<file_sep>/gulpfile.js/tasks/watch.js
/**
* Starts watcher on CSS, JS, IMG, and HTML files
*
* @version 2.0.0
* @author <NAME> <<EMAIL>>
*/
// https://www.npmjs.com/package/gulp-watch
module.exports = function(gulp, plugins, config){
return function(){
console.log('\r\n\r\n----------> Watching');
// Changes in the src directory
gulp.watch(config.src.js + '/**/*.js', ['js']);
gulp.watch(config.src.scss + '/**/*.{sass,scss}', ['sass']);
gulp.watch(config.src.index, ['inject']);
};
};
<file_sep>/src/scss/mixins/_kbd.scss
////
/// kbd
///
/// Defines kbd style
///
/// @group Mixins
/// @version 0.1.0
/// @link https://github.com/TangoMan75/Stripped
////
@mixin kbd($color, $background) {
/* Resets buttons font-size & line-height */
font-size: $font-size-xxs;
line-height: $line-height-base;
padding: 2px 8px 4px 4px;
color: $color;
background: linear-gradient(to top left, lighten($background, 10%), $background);
border-radius: $radius-sm;
border-top: 2px solid lighten($background, 25%);
border-left: 3px solid lighten($background, 10%);
border-bottom: 5px solid darken($background, 8%);
border-right: 4px solid darken($background, 3%);
box-shadow: $shadow-kbd
}
<file_sep>/gulpfile.js/tasks/sasscomp.js
/**
* Compiles SASS and SCSS files to both 'src' and 'dest' folders, and generates sourcemap
*
* Use `gulp sass --prod` to disable sourcemaps
*
* @version 2.1.0
* @author <NAME> <<EMAIL>>
*/
/**
* Handles errors without stopping watch
*
* @param {Object} err Received error
* @url https://github.com/gulpjs/gulp/issues/259
*/
function handleError(err) {
console.log(err.toString());
this.emit('end');
}
/**
* @requires The following modules
* https://www.npmjs.com/package/gulp-plumber
* https://www.npmjs.com/package/gulp-sass
* https://www.npmjs.com/package/gulp-sourcemaps
* https://www.npmjs.com/package/gulp-util
*/
module.exports = function(gulp, plugins, config){
return function(cb){
console.log('\r\n\r\n----------> Compiling SASS');
/**
* Sass Options
* @type {Object}
*/
var objOptions = {
// outputStyle: 'compressed',
outputStyle: 'expanded',
};
if (plugins.util.env.prod) {
console.log('----------> Production Mode');
gulp.src(config.src.scss + '/**/*.{sass,scss}')
.pipe(plugins.plumber({ errorHandler: handleError }))
.pipe(plugins.sass(objOptions))
.pipe(gulp.dest(config.src.css))
.pipe(gulp.dest(config.dest.css))
.on('end', cb);
} else {
console.log('----------> Dev Mode');
gulp.src(config.src.scss + '/**/*.{sass,scss}')
.pipe(plugins.sourcemaps.init('debug'))
.pipe(plugins.plumber({ errorHandler: handleError }))
.pipe(plugins.sass(objOptions))
.pipe(gulp.dest(config.src.css))
.pipe(plugins.sourcemaps.write())
.pipe(gulp.dest(config.src.css))
.pipe(gulp.dest(config.dest.css))
.on('end', cb);
}
};
};
<file_sep>/src/scss/mixins/_radius-scale.scss
////
/// Radius scale
///
/// Sets global radiuses values
///
/// @group Mixins
/// @version 0.1.0
/// @link https://github.com/TangoMan75/Stripped
////
@mixin radius-scale($radius-base, $scale) {
$radius-xxl: $radius-base !global;
$radius-xl: $radius-xxl / $scale !global;
$radius-lg: $radius-xl / $scale !global;
$radius-md: $radius-lg / $scale !global;
$radius-sm: $radius-md / $scale !global;
$radius-xs: $radius-sm / $scale !global;
$radius-xxs: $radius-xs / $scale !global;
}
| aee67d836de36e426649dc7e9afdb7f9ff78ebcb | [
"Markdown",
"SCSS",
"JavaScript"
] | 32 | Markdown | TangoMan75/Stripped | e642c5e05148c7adee078172a13aecb63cd51ee6 | 6f70ba827f3ed9ea1003bf4a810608cb340ac93b |
refs/heads/master | <file_sep>#tag IOSView
Begin iosView ShowDetailView
BackButtonTitle = ""
Compatibility = ""
LargeTitleMode = "2"
Left = 0
NavigationBarVisible= True
TabIcon = ""
TabTitle = ""
Title = "Show Details"
Top = 0
Begin iOSTextField LocationField
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = LocationField, 1, <Parent>, 1, False, +1.00, 4, 1, *kStdGapCtlToViewH, , True
AutoLayout = LocationField, 2, <Parent>, 2, False, +1.00, 4, 1, -*kStdGapCtlToViewH, , True
AutoLayout = LocationField, 3, ShowNameField, 4, False, +1.00, 4, 1, *kStdControlGapV, , True
AutoLayout = LocationField, 8, , 0, True, +1.00, 4, 1, 31, , True
Enabled = True
Height = 31.0
KeyboardType = "0"
Left = 20
LockedInPosition= False
Password = <PASSWORD>
PlaceHolder = "Show Location"
Scope = 2
Text = ""
TextAlignment = "0"
TextColor = &c00000000
TextFont = ""
TextSize = 0
Top = 178
Visible = True
Width = 280.0
End
Begin iOSDatePicker ShowDatePicker
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = ShowDatePicker, 1, <Parent>, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = ShowDatePicker, 2, <Parent>, 2, False, +1.00, 4, 1, -0, , True
AutoLayout = ShowDatePicker, 3, LocationField, 4, False, +1.00, 4, 1, *kStdControlGapV, , True
AutoLayout = ShowDatePicker, 8, , 0, True, +1.00, 4, 1, 162, , True
CountDownDuration= 0.0
Enabled = True
Height = 162.0
Left = 0
LockedInPosition= False
MinuteInterval = 0
Mode = "2"
Scope = 2
Top = 217
Visible = True
Width = 320.0
End
Begin iOSTextField ShowNameField
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = ShowNameField, 1, <Parent>, 1, False, +1.00, 4, 1, *kStdGapCtlToViewH, , True
AutoLayout = ShowNameField, 2, <Parent>, 2, False, +1.00, 4, 1, -*kStdGapCtlToViewH, , True
AutoLayout = ShowNameField, 8, , 0, True, +1.00, 4, 1, 31, , True
AutoLayout = ShowNameField, 3, Separator1, 4, False, +1.00, 4, 1, *kStdControlGapV, , True
Enabled = True
Height = 31.0
KeyboardType = "0"
Left = 20
LockedInPosition= False
Password = <PASSWORD>
PlaceHolder = "Show Name"
Scope = 2
Text = ""
TextAlignment = "0"
TextColor = &c00000000
TextFont = ""
TextSize = 0
Top = 139
Visible = True
Width = 280.0
End
Begin iOSButton SaveButton
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = SaveButton, 8, , 0, False, +1.00, 4, 1, 30, , True
AutoLayout = SaveButton, 1, <Parent>, 1, False, +1.00, 4, 1, *kStdGapCtlToViewH, , True
AutoLayout = SaveButton, 3, TopLayoutGuide, 4, False, +1.00, 4, 1, *kStdControlGapV, , True
AutoLayout = SaveButton, 7, , 0, False, +1.00, 4, 1, 100, , True
Caption = "Save"
Enabled = True
Height = 30.0
Left = 20
LockedInPosition= False
Scope = 0
TextColor = &c007AFF00
TextFont = ""
TextSize = 0
Top = 73
Visible = True
Width = 100.0
End
Begin iOSButton CancelButton
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = CancelButton, 8, , 0, False, +1.00, 4, 1, 30, , True
AutoLayout = CancelButton, 2, <Parent>, 2, False, +1.00, 4, 1, -*kStdGapCtlToViewH, , True
AutoLayout = CancelButton, 3, TopLayoutGuide, 4, False, +1.00, 4, 1, *kStdControlGapV, , True
AutoLayout = CancelButton, 7, , 0, False, +1.00, 4, 1, 100, , True
Caption = "Cancel"
Enabled = True
Height = 30.0
Left = 200
LockedInPosition= False
Scope = 0
TextColor = &c007AFF00
TextFont = ""
TextSize = 0
Top = 73
Visible = True
Width = 100.0
End
Begin iOSSeparator Separator1
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = Separator1, 8, , 0, True, +1.00, 4, 1, 20, , True
AutoLayout = Separator1, 1, <Parent>, 1, False, +1.00, 4, 1, *kStdGapCtlToViewH, , True
AutoLayout = Separator1, 2, <Parent>, 2, False, +1.00, 4, 1, -*kStdGapCtlToViewH, , True
AutoLayout = Separator1, 3, SaveButton, 4, False, +1.00, 4, 1, *kStdControlGapV, , True
Height = 20.0
Left = 20
LockedInPosition= False
Scope = 0
Top = 111
Visible = True
Width = 280.0
End
End
#tag EndIOSView
#tag WindowCode
#tag EndWindowCode
#tag Events SaveButton
#tag Event
Sub Action()
Try
// Add the show itself
Dim showSQL As Text = "INSERT INTO Show (Name, Location, Date) VALUES (?1, ?2, ?3);"
App.DB.SQLExecute(showSQL, ShowNameField.Text, LocationField.Text, ShowDatePicker.DefaultDate.ToText)
Dim showID As Integer = App.DB.LastRowID
// Add initial score data
Dim scoreSQL As Text = "INSERT INTO Score (ShowID, DrumMajorScore, ColorGuardScore, VisualScore, PercussionScore, MusicScore, GeneralEffectScore, OverallScore) " + _
"VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8);"
App.DB.SQLExecute(scoreSQL, showID, 3, 3, 3, 3, 3, 3, 3)
Self.CloseModal
Catch e As iOSSQLiteException
// Yikes!
Break
End Try
End Sub
#tag EndEvent
#tag EndEvents
#tag Events CancelButton
#tag Event
Sub Action()
Self.CloseModal
End Sub
#tag EndEvent
#tag EndEvents
#tag ViewBehavior
#tag ViewProperty
Name="Index"
Visible=true
Group="ID"
InitialValue="-2147483648"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="Name"
Visible=true
Group="ID"
Type="String"
#tag EndViewProperty
#tag ViewProperty
Name="Super"
Visible=true
Group="ID"
Type="String"
#tag EndViewProperty
#tag ViewProperty
Name="Left"
Visible=true
Group="Position"
InitialValue="0"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="Top"
Visible=true
Group="Position"
InitialValue="0"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="BackButtonTitle"
Group="Behavior"
Type="Text"
EditorType="MultiLineEditor"
#tag EndViewProperty
#tag ViewProperty
Name="NavigationBarVisible"
Group="Behavior"
Type="Boolean"
#tag EndViewProperty
#tag ViewProperty
Name="TabIcon"
Group="Behavior"
Type="iOSImage"
#tag EndViewProperty
#tag ViewProperty
Name="TabTitle"
Group="Behavior"
Type="Text"
#tag EndViewProperty
#tag ViewProperty
Name="Title"
Group="Behavior"
Type="Text"
EditorType="MultiLineEditor"
#tag EndViewProperty
#tag ViewProperty
Name="LargeTitleMode"
Visible=true
Group="Behavior"
InitialValue="2"
Type="LargeTitleDisplayModes"
EditorType="Enum"
#tag EnumValues
"0 - Automatic"
"1 - Always"
"2 - Never"
#tag EndEnumValues
#tag EndViewProperty
#tag EndViewBehavior
<file_sep>#tag Class
Protected Class App
Inherits IOSApplication
#tag CompatibilityFlags = TargetIOS
#tag Event
Function Open(launchOptionsHandle as Ptr) As Boolean
// Initialize SQLite database in the Documents folder
Dim dbFile As FolderItem = SpecialFolder.Documents.Child("MarchingBandScore.sqlite")
DB = New iOSSQLiteDatabase
DB.DatabaseFile = dbFile
If Not dbFile.Exists Then
// Create the database and the tables
If DB.CreateDatabaseFile Then
Try
DB.SQLExecute(kShowTable)
DB.SQLExecute(kScoreTable)
Catch e As iOSSQLiteException
// Yikes!
// This would be really bad (low storage?) so may want
// to show an error view.
End Try
End If
Else
// Connect to the database
If DB.Connect Then
// All good!
End If
End If
End Function
#tag EndEvent
#tag Property, Flags = &h0
DB As iOSSQLiteDatabase
#tag EndProperty
#tag Constant, Name = kScoreTable, Type = Text, Dynamic = False, Default = \"CREATE TABLE [Score] (\n [ID] INTEGER NOT NULL\x2C\n [ShowID] INTEGER\x2C\n [DrumMajorScore] INTEGER\x2C\n [ColorGuardScore] INTEGER\x2C\n [VisualScore] INTEGER\x2C\n [PercussionScore] INTEGER\x2C\n [MusicScore] INTEGER\x2C\n [GeneralEffectScore] INTEGER\x2C\n [OverallScore] INTEGER\x2C \n PRIMARY KEY ([ID])\n);", Scope = Public
#tag EndConstant
#tag Constant, Name = kShowTable, Type = Text, Dynamic = False, Default = \"CREATE TABLE [Show] (\n [ID] INTEGER NOT NULL\x2C\n [Name] TEXT\x2C\n [Location] TEXT\x2C\n [Date] TEXT\x2C \n PRIMARY KEY ([ID])\n);", Scope = Public
#tag EndConstant
#tag ViewBehavior
#tag EndViewBehavior
End Class
#tag EndClass
<file_sep>#tag IOSView
Begin iosView ShowsView
BackButtonTitle = ""
Compatibility = ""
LargeTitleMode = "1"
Left = 0
NavigationBarVisible= True
TabIcon = ""
TabTitle = ""
Title = "Shows"
Top = 0
Begin iOSToolButton AddShowButton
Caption = "Untitled"
Enabled = True
Height = 22
Image = "0"
Image = "0"
Left = 8
LockedInPosition= False
Scope = 2
Top = 32
Type = "4"
Width = 22.0
End
Begin iOSTable ShowsTable
AccessibilityHint= ""
AccessibilityLabel= ""
AllowRefresh = False
AutoLayout = ShowsTable, 1, <Parent>, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = ShowsTable, 2, <Parent>, 2, False, +1.00, 4, 1, -0, , True
AutoLayout = ShowsTable, 3, TopLayoutGuide, 3, False, +1.00, 4, 1, 0, , True
AutoLayout = ShowsTable, 4, BottomLayoutGuide, 4, False, +1.00, 4, 1, 0, , True
EditingEnabled = False
EstimatedRowHeight= -1
Format = "0"
Height = 415.0
Left = 0
LockedInPosition= False
Scope = 2
SectionCount = 0
Top = 65
Visible = True
Width = 320.0
End
End
#tag EndIOSView
#tag WindowCode
#tag Event
Sub Activate()
ShowDataSource.Load
ShowsTable.ReloadData
End Sub
#tag EndEvent
#tag Event
Sub Open()
ShowDataSource = New ShowData
ShowDataSource.Load
ShowsTable.DataSource = ShowDataSource
End Sub
#tag EndEvent
#tag Event
Sub ToolbarPressed(button As iOSToolButton)
Select Case button
Case AddShowButton
Dim v As New ShowDetailView
Self.ShowModal(v)
End Select
End Sub
#tag EndEvent
#tag Method, Flags = &h21
Private Sub LoadShows()
End Sub
#tag EndMethod
#tag Property, Flags = &h0
ShowDataSource As ShowData
#tag EndProperty
#tag EndWindowCode
#tag Events ShowsTable
#tag Event
Sub Action(section As Integer, row As Integer)
// Show scores for this show
Dim v As New ScoresView
v.ShowID = Me.RowData(section, row).Tag
v.Load
Self.PushTo(v)
End Sub
#tag EndEvent
#tag EndEvents
#tag ViewBehavior
#tag ViewProperty
Name="Index"
Visible=true
Group="ID"
InitialValue="-2147483648"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="Name"
Visible=true
Group="ID"
Type="String"
#tag EndViewProperty
#tag ViewProperty
Name="Super"
Visible=true
Group="ID"
Type="String"
#tag EndViewProperty
#tag ViewProperty
Name="Left"
Visible=true
Group="Position"
InitialValue="0"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="Top"
Visible=true
Group="Position"
InitialValue="0"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="BackButtonTitle"
Group="Behavior"
Type="Text"
EditorType="MultiLineEditor"
#tag EndViewProperty
#tag ViewProperty
Name="NavigationBarVisible"
Group="Behavior"
Type="Boolean"
#tag EndViewProperty
#tag ViewProperty
Name="TabIcon"
Group="Behavior"
Type="iOSImage"
#tag EndViewProperty
#tag ViewProperty
Name="TabTitle"
Group="Behavior"
Type="Text"
#tag EndViewProperty
#tag ViewProperty
Name="Title"
Group="Behavior"
Type="Text"
EditorType="MultiLineEditor"
#tag EndViewProperty
#tag ViewProperty
Name="LargeTitleMode"
Visible=true
Group="Behavior"
InitialValue="2"
Type="LargeTitleDisplayModes"
EditorType="Enum"
#tag EnumValues
"0 - Automatic"
"1 - Always"
"2 - Never"
#tag EndEnumValues
#tag EndViewProperty
#tag EndViewBehavior
<file_sep>#tag Module
Protected Module Extensions
#tag Method, Flags = &h0
Sub CloseModal(Extends v As iOSView)
// Close the Modal view to return to the calling view
Declare Sub dismissViewController Lib "UIKit" _
Selector "dismissViewControllerAnimated:completion:" _
(parentView As Ptr, animated As Boolean, completion As Ptr)
dismissViewController(v.Handle, True, Nil)
End Sub
#tag EndMethod
#tag Method, Flags = &h0
Sub ShowModal(Extends v As iOSView, mv As iOSView)
// Display the View mv modally
Declare Sub presentViewController Lib "UIKit" _
Selector "presentViewController:animated:completion:" _
(parentView As Ptr, viewControllerToPresent As Ptr, animated As Boolean, completion As Ptr)
presentViewController(v.Handle, mv.Handle, True, Nil)
End Sub
#tag EndMethod
#tag ViewBehavior
#tag ViewProperty
Name="Name"
Visible=true
Group="ID"
Type="String"
#tag EndViewProperty
#tag ViewProperty
Name="Index"
Visible=true
Group="ID"
InitialValue="-2147483648"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="Super"
Visible=true
Group="ID"
Type="String"
#tag EndViewProperty
#tag ViewProperty
Name="Left"
Visible=true
Group="Position"
InitialValue="0"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="Top"
Visible=true
Group="Position"
InitialValue="0"
Type="Integer"
#tag EndViewProperty
#tag EndViewBehavior
End Module
#tag EndModule
<file_sep>#tag Class
Protected Class ShowData
Implements iOSTableDataSource
#tag Method, Flags = &h0
Sub Load()
ReDim Shows(-1)
Dim sql As Text = "SELECT * FROM Show;"
Dim results As iOSSQLiteRecordSet
results = App.DB.SQLSelect(sql)
While Not results.EOF
Dim s As New Show
s.ID = results.Field("ID").IntegerValue
s.Name = results.Field("Name").TextValue
s.Location = results.Field("Location").TextValue
s.Date = results.Field("Date").TextValue
Shows.Append(s)
results.MoveNext
Wend
results.Close
End Sub
#tag EndMethod
#tag Method, Flags = &h0
Function RowCount(table as iOSTable, section As Integer) As Integer
// Part of the iOSTableDataSource interface.
Return Shows.Ubound + 1
End Function
#tag EndMethod
#tag Method, Flags = &h0
Function RowData(table as iOSTable, section As Integer, row As Integer) As iOSTableCellData
// Part of the iOSTableDataSource interface.
// Create the cell to display
Dim cell As iOSTableCellData = table.CreateCell
cell.Text = Shows(row).Location + " (" + Shows(row).Date + ")"
cell.DetailText = Shows(row).Name
cell.Tag = Shows(row).ID
Return cell
End Function
#tag EndMethod
#tag Method, Flags = &h0
Function SectionCount(table as iOSTable) As Integer
// Part of the iOSTableDataSource interface.
Return 1
End Function
#tag EndMethod
#tag Method, Flags = &h0
Function SectionTitle(table as iOSTable, section As Integer) As Text
// Part of the iOSTableDataSource interface.
Return ""
End Function
#tag EndMethod
#tag Property, Flags = &h21
Private Shows() As Show
#tag EndProperty
#tag ViewBehavior
#tag ViewProperty
Name="Name"
Visible=true
Group="ID"
Type="String"
#tag EndViewProperty
#tag ViewProperty
Name="Index"
Visible=true
Group="ID"
InitialValue="-2147483648"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="Super"
Visible=true
Group="ID"
Type="String"
#tag EndViewProperty
#tag ViewProperty
Name="Left"
Visible=true
Group="Position"
InitialValue="0"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="Top"
Visible=true
Group="Position"
InitialValue="0"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="Shows()"
Group="Behavior"
Type="Integer"
#tag EndViewProperty
#tag EndViewBehavior
End Class
#tag EndClass
<file_sep># MarchingBandScoreKeeper
Track scores for marching band shows
<file_sep>#tag IOSView
Begin iosView ScoresView
BackButtonTitle = ""
Compatibility = ""
LargeTitleMode = "0"
Left = 0
NavigationBarVisible= True
TabIcon = ""
TabTitle = ""
Title = "Scores"
Top = 0
Begin iOSSegmentedControl DrumMajorStarRating
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = DrumMajorStarRating, 8, , 0, True, +1.00, 4, 1, 29, , True
AutoLayout = DrumMajorStarRating, 2, <Parent>, 2, False, +1.00, 4, 1, -*kStdGapCtlToViewH, , True
AutoLayout = DrumMajorStarRating, 3, DrumMajorLabel, 3, False, +1.00, 4, 1, 0, , True
AutoLayout = DrumMajorStarRating, 7, <Parent>, 7, False, +0.40, 4, 1, 0, , True
Caption = ""
Enabled = True
Height = 29.0
Left = 172
LockedInPosition= False
Scope = 2
Segments = "1\n\nFalse\r2\n\nFalse\r3\n\nFalse\r4\n\nFalse\r5\n\nFalse"
Top = 73
Value = -1
Visible = True
Width = 128.0
End
Begin iOSLabel DrumMajorLabel
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = DrumMajorLabel, 8, , 0, False, +1.00, 4, 1, 30, , True
AutoLayout = DrumMajorLabel, 1, <Parent>, 1, False, +1.00, 4, 1, *kStdGapCtlToViewH, , True
AutoLayout = DrumMajorLabel, 3, TopLayoutGuide, 4, False, +1.00, 4, 1, *kStdControlGapV, , True
AutoLayout = DrumMajorLabel, 7, <Parent>, 7, False, +0.40, 4, 1, 0, , True
Enabled = True
Height = 30.0
Left = 20
LineBreakMode = "0"
LockedInPosition= False
Scope = 2
Text = "Drum Major"
TextAlignment = "0"
TextColor = &c00000000
TextFont = ""
TextSize = 0
Top = 73
Visible = True
Width = 128.0
End
Begin iOSSegmentedControl ColorGuardStarRating
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = ColorGuardStarRating, 8, , 0, True, +1.00, 4, 1, 29, , True
AutoLayout = ColorGuardStarRating, 1, DrumMajorStarRating, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = ColorGuardStarRating, 3, DrumMajorStarRating, 4, False, +1.00, 4, 1, *kStdControlGapV, , True
AutoLayout = ColorGuardStarRating, 7, DrumMajorStarRating, 7, False, +1.00, 4, 1, 0, , True
Caption = ""
Enabled = True
Height = 29.0
Left = 172
LockedInPosition= False
Scope = 2
Segments = "1\n\nFalse\r2\n\nFalse\r3\n\nFalse\r4\n\nFalse\r5\n\nFalse"
Top = 110
Value = -1
Visible = True
Width = 128.0
End
Begin iOSSegmentedControl VisualStarRating
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = VisualStarRating, 8, , 0, True, +1.00, 4, 1, 29, , True
AutoLayout = VisualStarRating, 1, ColorGuardStarRating, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = VisualStarRating, 3, ColorGuardStarRating, 4, False, +1.00, 4, 1, *kStdControlGapV, , True
AutoLayout = VisualStarRating, 7, DrumMajorStarRating, 7, False, +1.00, 4, 1, 0, , True
Caption = ""
Enabled = True
Height = 29.0
Left = 172
LockedInPosition= False
Scope = 2
Segments = "1\n\nFalse\r2\n\nFalse\r3\n\nFalse\r4\n\nFalse\r5\n\nFalse"
Top = 147
Value = -1
Visible = True
Width = 128.0
End
Begin iOSSegmentedControl PercussionStarRating
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = PercussionStarRating, 8, , 0, True, +1.00, 4, 1, 29, , True
AutoLayout = PercussionStarRating, 1, VisualStarRating, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = PercussionStarRating, 3, VisualStarRating, 4, False, +1.00, 4, 1, *kStdControlGapV, , True
AutoLayout = PercussionStarRating, 7, DrumMajorStarRating, 7, False, +1.00, 4, 1, 0, , True
Caption = ""
Enabled = True
Height = 29.0
Left = 172
LockedInPosition= False
Scope = 2
Segments = "1\n\nFalse\r2\n\nFalse\r3\n\nFalse\r4\n\nFalse\r5\n\nFalse"
Top = 184
Value = -1
Visible = True
Width = 128.0
End
Begin iOSSegmentedControl MusicStarRating
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = MusicStarRating, 8, , 0, True, +1.00, 4, 1, 29, , True
AutoLayout = MusicStarRating, 1, PercussionStarRating, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = MusicStarRating, 3, PercussionStarRating, 4, False, +1.00, 4, 1, *kStdControlGapV, , True
AutoLayout = MusicStarRating, 7, DrumMajorStarRating, 7, False, +1.00, 4, 1, 0, , True
Caption = ""
Enabled = True
Height = 29.0
Left = 172
LockedInPosition= False
Scope = 2
Segments = "1\n\nFalse\r2\n\nFalse\r3\n\nFalse\r4\n\nFalse\r5\n\nFalse"
Top = 221
Value = -1
Visible = True
Width = 128.0
End
Begin iOSSegmentedControl GeneralEffectStarRating
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = GeneralEffectStarRating, 8, , 0, True, +1.00, 4, 1, 29, , True
AutoLayout = GeneralEffectStarRating, 1, MusicStarRating, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = GeneralEffectStarRating, 3, MusicStarRating, 4, False, +1.00, 4, 1, *kStdControlGapV, , True
AutoLayout = GeneralEffectStarRating, 7, DrumMajorStarRating, 7, False, +1.00, 4, 1, 0, , True
Caption = ""
Enabled = True
Height = 29.0
Left = 172
LockedInPosition= False
Scope = 2
Segments = "1\n\nFalse\r2\n\nFalse\r3\n\nFalse\r4\n\nFalse\r5\n\nFalse"
Top = 258
Value = -1
Visible = True
Width = 128.0
End
Begin iOSSegmentedControl OverallStarRating
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = OverallStarRating, 8, , 0, True, +1.00, 4, 1, 29, , True
AutoLayout = OverallStarRating, 1, GeneralEffectStarRating, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = OverallStarRating, 3, GeneralEffectStarRating, 4, False, +1.00, 4, 1, *kStdControlGapV, , True
AutoLayout = OverallStarRating, 7, DrumMajorStarRating, 7, False, +1.00, 4, 1, 0, , True
Caption = ""
Enabled = True
Height = 29.0
Left = 172
LockedInPosition= False
Scope = 2
Segments = "1\n\nFalse\r2\n\nFalse\r3\n\nFalse\r4\n\nFalse\r5\n\nFalse"
Top = 295
Value = -1
Visible = True
Width = 128.0
End
Begin iOSLabel ColorGuardLabel
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = ColorGuardLabel, 11, ColorGuardStarRating, 11, False, +1.00, 4, 1, 0, , True
AutoLayout = ColorGuardLabel, 8, , 0, False, +1.00, 4, 1, 30, , True
AutoLayout = ColorGuardLabel, 1, DrumMajorLabel, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = ColorGuardLabel, 7, DrumMajorLabel, 7, False, +1.00, 4, 1, 0, , True
Enabled = True
Height = 30.0
Left = 20
LineBreakMode = "0"
LockedInPosition= False
Scope = 2
Text = "Color Guard"
TextAlignment = "0"
TextColor = &c00000000
TextFont = ""
TextSize = 0
Top = 109
Visible = True
Width = 128.0
End
Begin iOSLabel VisualLabel
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = VisualLabel, 1, ColorGuardLabel, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = VisualLabel, 7, , 0, False, +1.00, 4, 1, 128, , True
AutoLayout = VisualLabel, 11, VisualStarRating, 11, False, +1.00, 4, 1, 0, , True
AutoLayout = VisualLabel, 8, , 0, False, +1.00, 4, 1, 30, , True
Enabled = True
Height = 30.0
Left = 20
LineBreakMode = "0"
LockedInPosition= False
Scope = 2
Text = "Visual"
TextAlignment = "0"
TextColor = &c00000000
TextFont = ""
TextSize = 0
Top = 146
Visible = True
Width = 128.0
End
Begin iOSLabel PercussionLabel
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = PercussionLabel, 11, PercussionStarRating, 11, False, +1.00, 4, 1, 0, , True
AutoLayout = PercussionLabel, 8, , 0, False, +1.00, 4, 1, 30, , True
AutoLayout = PercussionLabel, 1, VisualLabel, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = PercussionLabel, 7, DrumMajorLabel, 7, False, +1.00, 4, 1, 0, , True
Enabled = True
Height = 30.0
Left = 20
LineBreakMode = "0"
LockedInPosition= False
Scope = 2
Text = "Percussion"
TextAlignment = "0"
TextColor = &c00000000
TextFont = ""
TextSize = 0
Top = 183
Visible = True
Width = 128.0
End
Begin iOSLabel MusicLabel
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = MusicLabel, 1, PercussionLabel, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = MusicLabel, 7, , 0, False, +1.00, 4, 1, 128, , True
AutoLayout = MusicLabel, 11, MusicStarRating, 11, False, +1.00, 4, 1, 0, , True
AutoLayout = MusicLabel, 8, , 0, False, +1.00, 4, 1, 30, , True
Enabled = True
Height = 30.0
Left = 20
LineBreakMode = "0"
LockedInPosition= False
Scope = 2
Text = "Music"
TextAlignment = "0"
TextColor = &c00000000
TextFont = ""
TextSize = 0
Top = 220
Visible = True
Width = 128.0
End
Begin iOSLabel GeneralEffectLabel
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = GeneralEffectLabel, 11, GeneralEffectStarRating, 11, False, +1.00, 4, 1, 0, , True
AutoLayout = GeneralEffectLabel, 8, , 0, False, +1.00, 4, 1, 30, , True
AutoLayout = GeneralEffectLabel, 1, MusicLabel, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = GeneralEffectLabel, 7, DrumMajorLabel, 7, False, +1.00, 4, 1, 0, , True
Enabled = True
Height = 30.0
Left = 20
LineBreakMode = "0"
LockedInPosition= False
Scope = 2
Text = "General Effect"
TextAlignment = "0"
TextColor = &c00000000
TextFont = ""
TextSize = 0
Top = 257
Visible = True
Width = 128.0
End
Begin iOSLabel OverallEffectLabel
AccessibilityHint= ""
AccessibilityLabel= ""
AutoLayout = OverallEffectLabel, 11, OverallStarRating, 11, False, +1.00, 4, 1, 0, , True
AutoLayout = OverallEffectLabel, 8, , 0, False, +1.00, 4, 1, 30, , True
AutoLayout = OverallEffectLabel, 1, GeneralEffectLabel, 1, False, +1.00, 4, 1, 0, , True
AutoLayout = OverallEffectLabel, 7, DrumMajorLabel, 7, False, +1.00, 4, 1, 0, , True
Enabled = True
Height = 30.0
Left = 20
LineBreakMode = "0"
LockedInPosition= False
Scope = 2
Text = "Overall"
TextAlignment = "0"
TextColor = &c00000000
TextFont = ""
TextSize = 0
Top = 294
Visible = True
Width = 128.0
End
End
#tag EndIOSView
#tag WindowCode
#tag Event
Sub Open()
End Sub
#tag EndEvent
#tag Method, Flags = &h0
Sub Load()
Dim scoreSQL As Text = "SELECT * FROM Score WHERE ShowID = ?1"
Dim results As iOSSQLiteRecordSet
Try
results = App.DB.SQLSelect(scoreSQL, ShowID)
If Not results.EOF Then
Dim dmScore As Integer = results.Field("DrumMajorScore").IntegerValue - 1
DrumMajorStarRating.Item(dmScore).Selected = True
Dim cgScore As Integer = results.Field("ColorGuardScore").IntegerValue - 1
ColorGuardStarRating.Item(cgScore).Selected = True
Dim vScore As Integer = results.Field("VisualScore").IntegerValue - 1
VisualStarRating.Item(vScore).Selected = True
Dim pScore As Integer = results.Field("PercussionScore").IntegerValue - 1
PercussionStarRating.Item(pScore).Selected = True
Dim mScore As Integer = results.Field("MusicScore").IntegerValue - 1
MusicStarRating.Item(mScore).Selected = True
Dim geScore As Integer = results.Field("GeneralEffectScore").IntegerValue - 1
GeneralEffectStarRating.Item(geScore).Selected = True
Dim oScore As Integer = results.Field("OverallScore").IntegerValue - 1
OverallStarRating.Item(oScore).Selected = True
End If
End Try
End Sub
#tag EndMethod
#tag Method, Flags = &h21
Private Sub Update(col As Text, value As Integer)
Dim updateSQL As Text = "UPDATE Score SET " + col + "=?1 WHERE ShowID = ?2"
Try
App.DB.SQLExecute(updateSQL, value, ShowID)
Catch e As iOSSQLiteException
// Yikes!
End Try
End Sub
#tag EndMethod
#tag Property, Flags = &h0
ShowID As Integer
#tag EndProperty
#tag EndWindowCode
#tag Events DrumMajorStarRating
#tag Event
Sub ValueChanged()
Update("DrumMajorScore", Me.Value + 1)
End Sub
#tag EndEvent
#tag EndEvents
#tag Events ColorGuardStarRating
#tag Event
Sub ValueChanged()
Update("ColorGuardScore", Me.Value + 1)
End Sub
#tag EndEvent
#tag EndEvents
#tag Events VisualStarRating
#tag Event
Sub ValueChanged()
Update("VisualScore", Me.Value + 1)
End Sub
#tag EndEvent
#tag EndEvents
#tag Events PercussionStarRating
#tag Event
Sub ValueChanged()
Update("PercussionScore", Me.Value + 1)
End Sub
#tag EndEvent
#tag EndEvents
#tag Events MusicStarRating
#tag Event
Sub ValueChanged()
Update("MusicScore", Me.Value + 1)
End Sub
#tag EndEvent
#tag EndEvents
#tag Events GeneralEffectStarRating
#tag Event
Sub ValueChanged()
Update("GeneralEffectScore", Me.Value + 1)
End Sub
#tag EndEvent
#tag EndEvents
#tag Events OverallStarRating
#tag Event
Sub ValueChanged()
Update("OverallScore", Me.Value + 1)
End Sub
#tag EndEvent
#tag EndEvents
#tag ViewBehavior
#tag ViewProperty
Name="Index"
Visible=true
Group="ID"
InitialValue="-2147483648"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="Name"
Visible=true
Group="ID"
Type="String"
#tag EndViewProperty
#tag ViewProperty
Name="Super"
Visible=true
Group="ID"
Type="String"
#tag EndViewProperty
#tag ViewProperty
Name="Left"
Visible=true
Group="Position"
InitialValue="0"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="Top"
Visible=true
Group="Position"
InitialValue="0"
Type="Integer"
#tag EndViewProperty
#tag ViewProperty
Name="BackButtonTitle"
Group="Behavior"
Type="Text"
EditorType="MultiLineEditor"
#tag EndViewProperty
#tag ViewProperty
Name="NavigationBarVisible"
Group="Behavior"
Type="Boolean"
#tag EndViewProperty
#tag ViewProperty
Name="TabIcon"
Group="Behavior"
Type="iOSImage"
#tag EndViewProperty
#tag ViewProperty
Name="TabTitle"
Group="Behavior"
Type="Text"
#tag EndViewProperty
#tag ViewProperty
Name="Title"
Group="Behavior"
Type="Text"
EditorType="MultiLineEditor"
#tag EndViewProperty
#tag ViewProperty
Name="LargeTitleMode"
Visible=true
Group="Behavior"
InitialValue="2"
Type="LargeTitleDisplayModes"
EditorType="Enum"
#tag EnumValues
"0 - Automatic"
"1 - Always"
"2 - Never"
#tag EndEnumValues
#tag EndViewProperty
#tag EndViewBehavior
| da5fec98fc58c76eecb55eda94777d7ad4a9d725 | [
"Markdown",
"Xojo"
] | 7 | Markdown | paullefebvre/MarchingBandScoreKeeper | 6197ee71f8e5fe65aa0c1a6e67e785fb1f4ca911 | 93d3c3a7c85ee6cc3d16513bf5380a4f76beae32 |
refs/heads/main | <repo_name>Reneuwumuhire/signal-clone-native<file_sep>/README.md
# signal-clone-native
this is just a simple signal clone... learn React Native.
<file_sep>/firebase.js
import * as firebase from "firebase"
import "firebase/auth";
//import "firebase/database";
import "firebase/firestore";
//import "firebase/functions";
//import "firebase/storage";
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "signal-clone-33d14.firebaseapp.com",
projectId: "signal-clone-33d14",
storageBucket: "signal-clone-33d14.appspot.com",
messagingSenderId: "44800056977",
appId: "1:44800056977:web:3cf3d4455e5adb400ea930"
};
let app;
if (firebase.apps.length === 0) {
app = firebase.initializeApp(firebaseConfig);
} else {
app = firebase.app();
}
const db = app.firestore();
const auth = firebase.auth();
export { db, auth }; | 7b5009fd1c7fc1aa7da6dd3fa5d4181d6dec68af | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Reneuwumuhire/signal-clone-native | 2c48a5239b7839e1a9dc129eccc92da389e5e1e6 | 035c662bc08ee6baf1916c8c7b62334782b4844c |
refs/heads/master | <file_sep># Balance exporter for Selectel service
The selectel balance exporter allows exporting balance for each service in [selectel](https://selectel.ru) to [prometheus](https://prometheus.io)
## How it works
Exporter request balance every hour (by default) and store it value in memory.
When prometheus request metrics, exporter send balance value from memory.
## Configuration
You must set environment variable:
* `SELECTEL_API_KEY` - your api key. Api key can be generated at page https://my.selectel.ru/profile/apikeys
## Command-line flags
* `listen-address` - The address to listen on for HTTP requests. (Default: `0.0.0.0:9600`)
* `interval` - Interval (in seconds) for balance requests. (Default: `3600`)
* `retry-interval` - Interval (in seconds) for load balance when errors. (Default: `10`)
* `retry-limit` - Count of tries when error. (Default: `10`)
## Metrics example
```
# HELP balance_selectel Balance for service in selectel account
# TYPE balance_selectel gauge
balance_selectel{service="primary"} 10000.54
balance_selectel{service="storage"} 20000.52
balance_selectel{service="vmware"} 0
balance_selectel{service="vpc"} 300000.47
```
## Running with docker
```sh
docker run \
-e SELECTEL_API_KEY=<your-key> \
-p 9600:9600 \
--restart=unless-stopped \
--name selectel-balance-exporter \
-d \
xxxcoltxxx/selectel-balance-exporter
```
## Running with docker-compose
Create configuration file. For example, file named `docker-compose.yaml`:
```yaml
version: "3"
services:
selectel-balance-exporter:
image: xxxcoltxxx/selectel-balance-exporter
restart: unless-stopped
environment:
SELECTEL_API_KEY: <your-key>
ports:
- 9600:9600
```
Run exporter:
```sh
docker-compose up -d
```
Show service logs:
```sh
docker-compose logs -f selectel-balance-exporter
```
## Running with systemctl
Set variables you need:
```sh
SELECTEL_EXPORTER_VERSION=0.2.0
SELECTEL_EXPORTER_PLATFORM=linux
SELECTEL_EXPORTER_ARCH=amd64
SELECTEL_API_KEY=<your-key>
```
Download release:
```sh
wget https://github.com/xxxcoltxxx/selectel-balance-exporter/releases/download/v${SELECTEL_EXPORTER_VERSION}/selectel-balance-exporter_${SELECTEL_EXPORTER_VERSION}_${SELECTEL_EXPORTER_PLATFORM}_${SELECTEL_EXPORTER_ARCH}.tar.gz
tar xvzf selectel-balance-exporter_${SELECTEL_EXPORTER_VERSION}_${SELECTEL_EXPORTER_PLATFORM}_${SELECTEL_EXPORTER_ARCH}.tar.gz
mv ./selectel-balance-exporter /usr/local/bin/selectel-balance-exporter
```
Add service to systemctl. For example, file named `/etc/systemd/system/selectel_balance_exporter.service`:
```sh
[Unit]
Description=Selectel Balance Exporter
Wants=network-online.target
After=network-online.target
[Service]
Environment="SELECTEL_API_KEY=${SELECTEL_API_KEY}"
Type=simple
ExecStart=/usr/local/bin/selectel-balance-exporter
[Install]
WantedBy=multi-user.target
```
Reload systemctl configuration and restart service
```sh
systemctl daemon-reload
systemctl restart selectel_balance_exporter
```
Show service status:
```sh
systemctl status selectel_balance_exporter
```
Show service logs:
```sh
journalctl -fu selectel_balance_exporter
```
<file_sep>package main
import (
"context"
"errors"
"flag"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/version"
"log"
"net/http"
"os"
"os/signal"
"selectel_balance_exporter/balance_retrievers"
"sync"
"syscall"
"time"
)
var addr = flag.String("listen-address", ":9600", "The address to listen on for HTTP requests.")
var interval = flag.Int("interval", 3600, "Interval (in seconds) for request balance.")
var retryInterval = flag.Int("retry-interval", 10, "Interval (in seconds) for load balance when errors.")
var retryLimit = flag.Int("retry-limit", 10, "Count of tries when error.")
var (
retrievers []balance_retrievers.BalanceRetriever
balanceGauge *prometheus.GaugeVec
mutex sync.RWMutex
hasError = false
retryCount = 0
)
func init() {
balanceGauge = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Subsystem: "balance",
Name: "selectel",
Help: "Balance for service in selectel account",
},
[]string{"service"},
)
prometheus.MustRegister(balanceGauge)
flag.Parse()
}
func main() {
log.Println("Starting Selectel balance exporter", version.Info())
log.Println("Build context", version.BuildContext())
config, err := readConfig()
if err != nil {
log.Fatalln(err)
}
registerRetriever(balance_retrievers.NewSelectelRetriever(config))
if err := loadBalance(); err != nil {
log.Fatalln(err)
}
go startBalanceUpdater()
srv := &http.Server{
Addr: *addr,
WriteTimeout: time.Second * 2,
ReadTimeout: time.Second * 2,
IdleTimeout: time.Second * 60,
Handler: nil,
}
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/index.html")
})
go func() {
log.Fatalln(srv.ListenAndServe())
}()
log.Printf("Selectel balance exporter has been started at address %s\n", *addr)
log.Printf("Exporter will update balance every %d seconds\n", *interval)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, syscall.SIGTERM)
<-c
log.Println("Selectel balance exporter shutdown")
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalln(err)
}
os.Exit(0)
}
func readConfig() (balance_retrievers.SelectelConfig, error) {
var config balance_retrievers.SelectelConfig
if apiKey, ok := os.LookupEnv("SELECTEL_API_KEY"); ok {
config.ApiKey = apiKey
} else {
return balance_retrievers.SelectelConfig{}, errors.New("environment \"SELECTEL_API_KEY\" is not set")
}
return config, nil
}
func registerRetriever(fetcher balance_retrievers.BalanceRetriever) {
mutex.Lock()
retrievers = append(retrievers, fetcher)
mutex.Unlock()
}
func startBalanceUpdater() {
for {
if hasError {
log.Printf("Request will retry after %d seconds\n", *retryInterval)
time.Sleep(time.Second * time.Duration(*retryInterval))
} else {
time.Sleep(time.Second * time.Duration(*interval))
}
if err := loadBalance(); err != nil {
log.Println(err.Error())
hasError = true
retryCount++
if retryCount >= *retryLimit {
log.Printf("Retry limit %d has been exceeded\n", *retryLimit)
hasError = false
retryCount = 0
}
} else {
hasError = false
retryCount = 0
}
}
}
func loadBalance() error {
for _, f := range retrievers {
if results, err := f.GetBalance(); err != nil {
return err
} else {
for _, b := range results {
balanceGauge.With(prometheus.Labels{"service": b.Name}).Set(b.Balance)
}
}
}
return nil
}
<file_sep>package balance_retrievers
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
const selectelUrl = "https://my.selectel.ru/api/v3/billing/balance"
type SelectelConfig struct {
ApiKey string
}
type SelectelBalanceRetriever struct {
config SelectelConfig
}
type BalanceResponse struct {
Data struct {
Primary selectelBalance `json:"primary"`
Storage selectelBalance `json:"storage"`
Vmware selectelBalance `json:"vmware"`
Vpc selectelBalance `json:"vpc"`
} `json:"data"`
}
type selectelBalance struct {
Balance float64 `json:"main"`
}
func NewSelectelRetriever(config SelectelConfig) BalanceRetriever {
return SelectelBalanceRetriever{
config: config,
}
}
func (bf SelectelBalanceRetriever) GetName() string {
return "selectel"
}
func (bf SelectelBalanceRetriever) GetBalance() ([]ServiceBalance, error) {
body, err := bf.loadBody()
if err != nil {
return []ServiceBalance{}, errors.New(fmt.Sprintf("Error fetching balance: %s", err.Error()))
}
balanceResponse := BalanceResponse{}
if err := json.Unmarshal(body, &balanceResponse); err != nil {
return []ServiceBalance{}, errors.New(fmt.Sprintf("Response parse error: %s", err.Error()))
}
return []ServiceBalance{
{Name: "primary", Balance: balanceResponse.Data.Primary.Balance / 100},
{Name: "storage", Balance: balanceResponse.Data.Storage.Balance / 100},
{Name: "vmware", Balance: balanceResponse.Data.Vmware.Balance / 100},
{Name: "vpc", Balance: balanceResponse.Data.Vpc.Balance / 100},
}, nil
}
func (bf SelectelBalanceRetriever) loadBody() ([]byte, error) {
client := http.Client{
Timeout: time.Second * 2,
}
req, err := http.NewRequest(http.MethodGet, selectelUrl, nil)
if err != nil {
return []byte{}, errors.New(fmt.Sprintf("Cannot create request: %s", err.Error()))
}
req.Header.Add("X-token", bf.config.ApiKey)
res, err := client.Do(req)
if err != nil {
return []byte{}, errors.New(fmt.Sprintf("Request error: %s", err.Error()))
}
defer func() {
err := res.Body.Close()
if err != nil {
log.Println(fmt.Sprintf("Cannot close response body: %s", err.Error()))
}
}()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return []byte{}, errors.New(fmt.Sprintf("Cannot read response body: %s", err.Error()))
}
return body, nil
}
<file_sep>module selectel_balance_exporter
go 1.16
require (
github.com/gogo/protobuf v1.1.1 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/prometheus/client_golang v1.11.0
github.com/prometheus/common v0.28.0
golang.org/x/sys v0.0.0-20210608053332-aa57babbf139 // indirect
)
<file_sep>package balance_retrievers
type BalanceRetriever interface {
GetName() string
GetBalance() (balances []ServiceBalance, err error)
}
type ServiceBalance struct {
Name string
Balance float64
}
| 19127cd178c5fd2ba1c738c4b9c3f7c6904d1c7e | [
"Go Module",
"Markdown",
"Go"
] | 5 | Go Module | Vetrinus/selectel-balance-exporter | 5b5bfeb333cb00c5245d9ff2a23bb31f4b33b620 | ef81deb5b8364b03faef2d185b39118a0e63a82b |
refs/heads/master | <repo_name>uml-ubicomp-2017/assignment-5-idea-challenge-smart-showered<file_sep>/README.md
# assignment-5-idea-challenge-smart-showered
assignment-5-idea-challenge-smart-showered created by GitHub Classroom
MindMap-Water waste in the shower:http://www.xmind.net/m/X2uj
Team members:
<NAME>, Student ID:01607330, Email:<EMAIL>
<NAME>, Student ID:01608899, Email:<EMAIL>
<NAME>, Student ID:01607479, Email:<EMAIL>
3/2/2017 Upload Fianl Idea plan draft.
3/7/2017 Upload Analysis of paper - Mind Map http://www.xmind.net/m/mJGY, and paper.
3/18/2017 Upload a summary about interview 5 people.
| 2aa542c7394750ea7b541ea976392e5fd32db121 | [
"Markdown"
] | 1 | Markdown | uml-ubicomp-2017/assignment-5-idea-challenge-smart-showered | ac52741922f5ad1e25454395bb6c4887646fa6cc | e652ea362833ad1d11e4cea36c7a1d697f285847 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Graphics
{
class Bresenham
{
public List<int> Xpoints = new List<int>();
public List<int> Ypoints = new List<int>();
public List<int> Ppoints = new List<int>();
public Bresenham()
{
}
void swap(ref int x0,ref int y0,ref int xEnd,ref int yEnd)
{
int temp0, temp1;
temp0 = x0;
x0 = y0;
y0 = temp0;
temp1 = xEnd;
xEnd = yEnd;
yEnd = temp1;
}
public void Bresline(int x0, int y0, int xEnd, int yEnd)
{
int xf = 0, yf = 0;
int pstart=0;
float slope = (float)(yEnd - y0) / (float)(xEnd - x0);
Console.WriteLine("Slope="+(yEnd - y0)+ "/" + (xEnd - x0) + " ----> "+"Slope=" +slope.ToString("0.00")+"\n");
if(x0<xEnd && (slope>=0 &&slope<=1))
{
if (slope==0)
{
Console.WriteLine("Line is horizontal");
}
xf = x0;
yf = y0;
int dx = Math.Abs(xEnd - x0);
int dy = Math.Abs(yEnd - y0);
int p0 = 2 * dy - dx;
pstart = p0;
// Ppoints.Add(p0);
Console.WriteLine("Line lies in First octant\n");
Console.WriteLine("Δx=" + dx+ "\nΔy=" + dy+ "\n2Δy=" + 2*dy+ "\n2Δy-2Δx="+2*(dy-dx)+"\nP0="+(2*dy-dx)+"\n");
while (x0 < xEnd)
{
x0++;
if (p0 < 0)
{
p0 += 2 * dy;
}
else
{
y0++;
p0 += 2 * (dy - dx);
}
Xpoints.Add(x0);
Ypoints.Add(y0);
Ppoints.Add(p0);
}
}
else if (y0<yEnd&&slope>1)
{
swap(ref x0, ref y0, ref xEnd, ref yEnd);
xf = x0;
yf = y0;
int dx = Math.Abs(xEnd - x0);
int dy = Math.Abs(yEnd - y0);
int p0 = 2 * dy - dx;
pstart = p0;
// Ppoints.Add(p0);
Console.WriteLine("Line lies in Second octant\n");
Console.WriteLine("Δx=" + dx + "\nΔy=" + dy + "\n2Δy=" + 2 * dy + "\n2Δy-2Δx=" + 2 * (dy - dx) + "\nP0=" + p0 + "\n");
while (x0 < xEnd)
{
x0++;
if (p0 < 0)
{
p0 += 2*dy;
}
else
{
y0++;
p0 += 2 * (dy - dx);
}
Xpoints.Add(x0);
Ypoints.Add(y0);
Ppoints.Add(p0);
}
}
else if (y0 < yEnd && slope < -1)
{
swap(ref x0, ref y0, ref xEnd, ref yEnd);
xf = x0;
yf = y0;
int dx = Math.Abs(xEnd - x0);
int dy = Math.Abs(yEnd - y0);
int p0 = 2 * dy - dx;
pstart = p0;
// Ppoints.Add(p0);
Console.WriteLine("Line lies in Third octant\n");
Console.WriteLine("Δx=" + dx + "\nΔy=" + dy + "\n2Δy=" + 2 * dy + "\n2Δy-2Δx=" + 2 * (dy - dx) + "\nP0=" + p0 + "\n");
while (x0 < xEnd)
{
x0++;
if (p0 < 0)
{
p0 += 2 * dy;
}
else
{
y0--;
p0 += 2 * (dy - dx);
}
Xpoints.Add(x0);
Ypoints.Add(y0);
Ppoints.Add(p0);
}
}
else if (x0 > xEnd && (slope >=-1&&slope<=0))
{
xf = x0;
yf = y0;
int dx = Math.Abs(xEnd - x0);
int dy = Math.Abs(yEnd - y0);
int p0 = 2 * dy - dx;
pstart = p0;
// Ppoints.Add(p0);
Console.WriteLine("Line lies in Fourth octant\n");
Console.WriteLine("Δx=" + dx + "\nΔy=" + dy + "\n2Δy=" + 2 * dy + "\n2Δy-2Δx=" + 2 * (dy - dx) + "\nP0=" + p0 + "\n");
while (x0 > xEnd)
{
x0--;
if (p0 < 0)
{
p0 += 2 * dy;
}
else
{
y0++;
p0 += 2 * (dy - dx);
}
Xpoints.Add(x0);
Ypoints.Add(y0);
Ppoints.Add(p0);
}
}
else if (x0 > xEnd && (slope > 0 && slope <= 1))
{
xf = x0;
yf = y0;
int dx = Math.Abs(xEnd - x0);
int dy = Math.Abs(yEnd - y0);
int p0 = 2 * dy - dx;
pstart = p0;
// Ppoints.Add(p0);
Console.WriteLine("Line lies in Fifth octant\n");
Console.WriteLine("Δx=" + dx + "\nΔy=" + dy + "\n2Δy=" + 2 * dy + "\n2Δy-2Δx=" + 2 * (dy - dx) + "\nP0=" + p0 + "\n");
while (x0 > xEnd)
{
x0--;
if (p0 < 0)
{
p0 += 2 * dy;
}
else
{
y0--;
p0 += 2 * (dy - dx);
}
Xpoints.Add(x0);
Ypoints.Add(y0);
Ppoints.Add(p0);
}
}
else if (y0 > yEnd && slope > 1)
{
swap(ref x0, ref y0, ref xEnd, ref yEnd);
xf = x0;
yf = y0;
int dx = Math.Abs(xEnd - x0);
int dy = Math.Abs(yEnd - y0);
int p0 = 2 * dy - dx;
pstart = p0;
// Ppoints.Add(p0);
Console.WriteLine("Line lies in Sixth octant\n");
Console.WriteLine("Δx=" + dx + "\nΔy=" + dy + "\n2Δy=" + 2 * dy + "\n2Δy-2Δx=" + 2 * (dy - dx) + "\nP0=" + p0 + "\n");
while (x0 > xEnd)
{
x0--;
if (p0 < 0)
{
p0 += 2 * dy;
}
else
{
y0--;
p0 += 2 * (dy - dx);
}
Xpoints.Add(x0);
Ypoints.Add(y0);
Ppoints.Add(p0);
}
}
else if (y0 > yEnd && slope < -1)
{
swap(ref x0, ref y0, ref xEnd, ref yEnd);
xf = x0;
yf = y0;
int dx = Math.Abs(xEnd - x0);
int dy = Math.Abs(yEnd - y0);
int p0 = 2 * dy - dx;
pstart = p0;
// Ppoints.Add(p0);
Console.WriteLine("Line lies in Seventh octant\n");
Console.WriteLine("Δx=" + dx + "\nΔy=" + dy + "\n2Δy=" + 2 * dy + "\n2Δy-2Δx=" + 2 * (dy - dx) + "\nP0=" + p0 + "\n");
while (x0 > xEnd)
{
x0--;
if (p0 < 0)
{
p0 += 2 * dy;
}
else
{
y0++;
p0 += 2 * (dy - dx);
}
Xpoints.Add(x0);
Ypoints.Add(y0);
Ppoints.Add(p0);
}
}
else if (x0 < xEnd && (slope <= 0 && slope >= -1))
{
if (slope == 0)
{
Console.WriteLine("Line is horizontal");
}
xf = x0;
yf = y0;
int dx = Math.Abs(xEnd - x0);
int dy = Math.Abs(yEnd - y0);
int p0 = 2 * dy - dx;
pstart = p0;
// Ppoints.Add(p0);
Console.WriteLine("Line lies in Eighth octant\n");
Console.WriteLine("Δx=" + dx + "\nΔy=" + dy + "\n2Δy=" + 2 * dy + "\n2Δy-2Δx=" + 2 * (dy - dx) + "\nP0=" + (2 * dy - dx) + "\n");
while (x0 < xEnd)
{
x0++;
if (p0 < 0)
{
p0 += 2 * dy;
}
else
{
y0--;
p0 += 2 * (dy - dx);
}
Xpoints.Add(x0);
Ypoints.Add(y0);
Ppoints.Add(p0);
}
}
Console.WriteLine("k" + "\t" + "Pk" + "\t" +"(Xk,Yk)");
Console.WriteLine("--" + "\t" + "--" + "\t" + "-------");
Console.WriteLine(0 + "\t" + pstart + "\t" + "(" + xf + "," + yf + ")" + "\t");
for (int i = 0; i < Xpoints.Count;i++)
{
Console.WriteLine(i+1 + "\t" + Ppoints[i] + "\t" + "(" + Xpoints[i] + "," + Ypoints[i] + ")" + "\t");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Threading;
namespace Graphics
{
class Program
{
public static void Main(string[] args)
{
int choice;
Console.WriteLine("Choose the algorithm from the list below\n1-DDA\n2-Bresenham\n3-Circle\n\n(1,2,3)?");
choice = int.Parse(Console.ReadLine());
if (choice == 1)
{
Console.WriteLine("\n\t** DDA algoritm **\nfollow the on-screen instructions to continue");
DDA dDA = new DDA();
int x0, y0, x1, y1;
Console.WriteLine("\nenter the start x point ");
x0 = int.Parse(Console.ReadLine());
Console.WriteLine("enter the start y point ");
y0 = int.Parse(Console.ReadLine());
Console.WriteLine("enter the end x point ");
x1 = int.Parse(Console.ReadLine());
Console.WriteLine("enter the end y point ");
y1 = int.Parse(Console.ReadLine());
Console.WriteLine("\n(X0,Y0)=("+x0+","+y0+")\t\t"+"(X1,Y1)=("+x1+","+y1+")\n");
dDA.DDAline(x0, y0, x1, y1);
}
if (choice == 2)
{
Console.WriteLine("\n\t** Bresenham algoritm **\nfollow the on-screen instructions to continue");
Bresenham bresenHam = new Bresenham();
int x0, y0, x1, y1;
Console.WriteLine("\nenter the start x point ");
x0 = int.Parse(Console.ReadLine());
Console.WriteLine("enter the start y point ");
y0 = int.Parse(Console.ReadLine());
Console.WriteLine("enter the end x point ");
x1 = int.Parse(Console.ReadLine());
Console.WriteLine("enter the end y point ");
y1 = int.Parse(Console.ReadLine());
Console.WriteLine("\n(X0,Y0)=(" + x0 + "," + y0 + ")\t\t" + "(X1,Y1)=("+ x1+","+ y1+")\n");
bresenHam.Bresline(x0, y0, x1, y1);
/*for (int i = 0; i < bresenHam.Xpoints.Count; i++)
{
Console.WriteLine(bresenHam.Xpoints[i] + "\t" + bresenHam.Ypoints[i]);
}*/
}
if (choice == 3)
{
Circle circle = new Circle();
circle.CirclePoints(10);
for (int i = 0; i < circle.Xpoints.Count; i++)
{
Console.WriteLine(circle.Xpoints[i] + "\t" + circle.Ypoints[i]);
}
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Graphics
{
class DDA
{
public List<int> Xpoints = new List<int>();
public List<int> Ypoints = new List<int>();
public List<float> UnroundedPoints = new List<float>();
public DDA()
{
}
public void DDAline(int x0, int y0, int xEnd, int yEnd)
{
int dx = xEnd - x0;
int dy = yEnd - y0;
int steps, xf, yf;
float slope = (float)dy / (float)dx;
Console.WriteLine("Slope="+slope.ToString("0.000")+" in decimal");
Console.WriteLine("Slope="+dy+"/"+dx+" in division form\n");
float x = x0, y = y0;
if (Math.Abs(dx) > Math.Abs(dy))
{
steps = Math.Abs(dx);
}
else
{
steps = Math.Abs(dy);
}
if (slope > 1)
{
if (xEnd > x0 || yEnd > y0)
{
Console.WriteLine("Slope is greater than one line processed from left to right\nSo, Y will be increased and calculate X\n");
}
else
{
Console.WriteLine("Slope is greater than one line processed from right to left\nSo, Y will be decreased and calculate X\n");
}
for (int i = 0; i < steps; i++)
{
y0 = y0 + (xEnd > x0 || yEnd > y0 ? 1 : -1);
Ypoints.Add(y0);
x = x + (xEnd > x0 || yEnd > y0 ? (1 / slope) : (-1 / slope));
UnroundedPoints.Add(x);
xf = (int)Math.Round(x);
Xpoints.Add(xf);
}
for (int i = 0; i < Xpoints.Count; i++)
{
Console.WriteLine("(" + Xpoints[i] + "," + Ypoints[i] + ")" + "\t\t" + "Point in unrounded shape (" + UnroundedPoints[i].ToString("0.00") + "," + Ypoints[i] + ")");
}
}
else if(slope <=1)
{
if((xEnd > x0 || yEnd > y0) && (slope>0 && slope<1))
{
Console.WriteLine("Slope is less than one line processed from left to right\nSo, X will be increased and calculate Y\n");
}
else
{
Console.WriteLine("Slope is less than one line processed from right to left\nSo, X will be decreased and calculate Y\n");
}
for (int i = 0; i < steps; i++)
{
if((xEnd > x0 || yEnd > y0) && (slope>0 && slope<1))
{
x0 = x0 + 1;
Xpoints.Add(x0);
}
else if (xEnd < x0 || yEnd < y0)
{
x0 = x0 - 1;
Xpoints.Add(x0);
}
if ((xEnd > x0 || yEnd > y0) && (slope > 0 && slope < 1))
{
y = y + slope;
UnroundedPoints.Add(y);
yf = (int)Math.Round(y);
Ypoints.Add(yf);
}
else if (xEnd < x0 || yEnd < y0)
{
y = y - slope ;
UnroundedPoints.Add(y);
yf = (int)Math.Round(y);
Ypoints.Add(yf);
}
}
for (int i = 0; i < Xpoints.Count; i++)
{
Console.WriteLine("(" + Xpoints[i] + "," + Ypoints[i] + ")" + "\t\t" + "Point in unrounded shape (" + Xpoints[i] + "," + UnroundedPoints[i].ToString("0.00") + ")");
}
}
else
{
Console.WriteLine("Error! invalid points no line can be drawn\n");
}
}
}
}
<file_sep># Graphics Course
<ul>
<h2>Using C#</h2>
<li>Get points of line to draw it by using DDA Algorithm</li>
<li>Get points of line to draw it by using Bresenham</li>
<li>Get points of Circle to draw it by using Midpoint Circle Algorithm </li>
</ul>
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Graphics
{
class Circle
{
public List<int> Xpoints = new List<int>();
public List<int> Ypoints = new List<int>();
public Circle()
{
}
public void CirclePoints(int r)
{
int x = 0;
int y = r;
int p0 = 1 - r;
while (x < y)
{
if (p0 < 0)
{
p0 += 2 * x + 3;
}
else
{
p0 += 2 * (x - y) + 5;
y--;
}
x++;
Xpoints.Add(x);
Ypoints.Add(y);
}
}
}
}
| d394b55fa8956321aa22b176ab8784e6f29c656f | [
"C#",
"Markdown"
] | 5 | C# | Abanoub98/Graphics-packages | 8f2bcd5a861416ac6904986f89040b724dbe4d84 | 72324410b3cb6efa9d61412dde65027fd3519c1a |
refs/heads/master | <file_sep>package :ruby do
description 'Ruby'
version '1.9.3'
source "ftp://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p194.tar.gz"
requires :ruby_dependencies
verify do
has_executable "/usr/local/bin/ruby"
end
end
package :ruby_dependencies do
apt %{zlib1g-dev libssl-dev libreadline-dev libyaml-dev libcurl4-openssl-dev curl}
requires :build_essential
end
<file_sep>%w(build_essential bundler deploy_user git libxml passenger postgresql mysql ruby).each do |lib|
require "reverb/stack/#{lib}"
end
<file_sep>REVERB Sprinkle Stack
=====================
A collection of sprinkle packages for provisioning servers.
## Usage
When running sprinkle from the project root set the `APP_ROOT`, which allows
add_deploy_ssh_keys to find an authorized_keys file in config/authorized_keys by
convention.
sprinkle -c -s config/install.rb APP_ROOT=`pwd`
<file_sep>package :bundler do
description "Bundler"
requires :ruby
gem "bundler"
verify do
has_gem "bundler"
end
end
<file_sep>package :postgres_client, :provides => :database do
description 'PostgreSQL Client'
apt %w(postgresql-client libpq-dev)
verify do
has_apt 'postgresql-client'
end
end
package :postgres_server do
apt %w(postgresql)
requires :postgres_client
verify do
has_apt "postgresql"
end
end
<file_sep>package :passenger do
description "Phusion Passenger with nginx"
requires :ruby
gem "passenger" do
post :install, "sudo passenger-install-nginx-module --auto --auto-download --prefix=/usr/local/nginx"
end
verify do
has_gem "passenger"
end
end
package :nginx_passenger do
description "Configure nginx installed through passenger"
requires :passenger
push_text File.read(File.join(File.dirname(__FILE__),'nginx','usr','local','nginx','conf','nginx.conf')), "/usr/local/nginx/conf/nginx.conf", :sudo => true do
post :install, "sudo mkdir -p /usr/local/nginx/conf/sites-enabled"
end
push_text File.read(File.join(File.dirname(__FILE__),'nginx','etc','init.d','nginx')), "/etc/init.d/nginx", :sudo => true do
post :install, "sudo chmod +x /etc/init.d/nginx"
post :install, "sudo /usr/sbin/update-rc.d -f nginx defaults"
post :install, "sudo /etc/init.d/nginx start"
end
verify do
has_executable "/usr/local/nginx/sbin/nginx"
has_file "/etc/init.d/nginx"
has_file "/usr/local/nginx/conf/nginx.conf"
has_directory "/usr/local/nginx/conf/sites-enabled"
end
end
<file_sep>package :libxml do
description "LibXML Dependencies for Nokogiri"
apt %w{libxml2 libxml2-dev libxslt1-dev}
verify do
has_apt "libxml2"
has_apt "libxml2-dev"
has_apt "libxslt1-dev"
end
end
<file_sep>Gem::Specification.new do |s|
s.name = "reverb-sprinkle-stack"
s.version = "1.0.1"
s.platform = Gem::Platform::RUBY
s.homepage = "http://github.com/reverbhq/reverb-sprinkle-stack"
s.authors = ["<NAME>", "REVERB"]
s.email = ["<EMAIL>"]
s.description = "A collection of Sprinkle packages"
s.summary = "A collection of Sprinkle packages"
s.files = `git ls-files`.split("\n").sort
s.require_paths = ["lib"]
s.add_dependency("sprinkle")
end
<file_sep>package :deploy_user do
description 'Create deploy user'
requires :create_deploy_user, :add_deploy_ssh_keys, :set_permissions
end
package :create_deploy_user do
description "Create the deploy user"
runner "useradd --create-home --shell /bin/bash --user-group --groups users,sudo deploy"
verify do
has_directory "/home/deploy"
end
end
package :add_deploy_ssh_keys do
description "Add deployer public key to authorized ones"
requires :create_deploy_user
local_keys_file = "#{ENV['APP_ROOT']}/config/authorized_keys"
keys = File.read(local_keys_file)
authorized_keys_file = "/home/deploy/.ssh/authorized_keys"
push_text keys, authorized_keys_file, :sudo => true do
pre :install, "mkdir -p /home/deploy/.ssh"
# make it overwrite so can update keys via sprinkle, NOTE there is no verify
pre :install, 'rm -f /home/deploy/.ssh/authorized_keys'
end
end
package :set_permissions do
description "Set correct permissons and ownership"
requires :add_deploy_ssh_keys
runner "chmod 0700 /home/deploy/.ssh"
runner "chown -R deploy:deploy /home/deploy/.ssh"
runner "chmod 0600 /home/deploy/.ssh/authorized_keys"
end
<file_sep>package :mysql_client, :provides => :database do
description 'MySQL Client'
apt %w(mysql-client libmysqlclient-dev libmysql-ruby)
verify do
has_apt 'mysql-client'
end
end
package :mysql_server do
description 'MySQL Server'
apt %w(mysql-server)
requires :mysql_client
verify do
has_apt "mysql-server"
end
end
| 4038bf353b1914b96af5d41731f84d949edd6e50 | [
"Markdown",
"Ruby"
] | 10 | Markdown | reverbhq/reverb-sprinkle-stack | cd9ef0b6d22050dbec8c2f7b7cfdc1260c23ab67 | 7bba699ba682743a283f9db881e37c4e6f5b44ea |
refs/heads/master | <repo_name>wangxianbiao/LearningNote<file_sep>/README.md
# hello-world
list
| 54437045fde4b12327019a086cb13f3b50a01f45 | [
"Markdown"
] | 1 | Markdown | wangxianbiao/LearningNote | 7a2b296178944c28c7bffe73e07842a36d9f3f49 | 17065993276f7bb1bbe4c51c61bffde686af71bb |
refs/heads/master | <file_sep>### What i learn:
# 20 May 2021
- Routing
- Component Management
- Props Children
- Render Listing Data
# 24 May 2021
- Getting use input and Handling submision form
- Firebase setup for react
- Sending Http request to Firebase in React
- Navigate Programmaticly
- Fetch data from firebase
- useEffect<file_sep>import React from "react";
import { useHistory } from 'react-router-dom'
import Navbar from "../../component/layouts/Navbar";
import NewMeetUpForm from "../../component/NewMeetupForm";
import "./style.css";
function NewMeetUpPage() {
const history = useHistory();
const newMeetupHandler = (meetupData) => {
fetch(
"https://react-meetup-ac217-default-rtdb.firebaseio.com/meetups.json",
{
method: 'POST',
body: JSON.stringify(meetupData),
headers : {
'Content-Type': 'application/json'
}
}
).then(() => {
history.replace('/')
});
};
return (
<div>
<Navbar />
<div className="container custom-container">
<header className="text-center">
<h1>All Meet Up</h1>
</header>
<section>
<NewMeetUpForm newMeetup={newMeetupHandler} />
</section>
</div>
</div>
);
}
export default NewMeetUpPage;
<file_sep>import { Route, Switch } from "react-router-dom";
// Pages
import AllMeetUpsPage from "./pages/AllMeetUps/";
import NewMeetupPage from "./pages/NewMeetUp/";
import FavoritePage from "./pages/Favorites/";
function App() {
return (
<div className="App">
<Switch>
<Route path="/" exact>
<AllMeetUpsPage />
</Route>
<Route path="/new-meet-up">
<NewMeetupPage />
</Route>
<Route path="/favorites">
<FavoritePage />
</Route>
</Switch>
</div>
);
}
export default App;
<file_sep>import React from 'react'
import Navbar from '../../component/layouts/Navbar';
function FavoritesPage() {
return (
<div>
<Navbar />
<h1>Favorites Page</h1>
</div>
)
}
export default FavoritesPage
<file_sep>import React from "react";
import MeetupItem from "./MeetupItem";
function MeetupList(props) {
return (
<>
{props.data.map((x) => (
<MeetupItem
key={x.id}
id={x.id}
image={x.image}
title={x.title}
description={x.description}
/>
))}
</>
);
}
export default MeetupList;
<file_sep>import { React, useState } from "react";
import Card from "../card";
import { Link } from "react-router-dom";
import FavoriteIcon from "@material-ui/icons/Favorite";
import QuestionAnswerIcon from '@material-ui/icons/QuestionAnswerOutlined';
import ShareIcon from '@material-ui/icons/Share';
function MeetupItem(props) {
const [like, setLike] = useState(false);
const Like = () => {
!like ? setLike(true) : setLike(false)
}
return (
<Card class="card custom-card">
<img src={props.image} class="card-img-top" alt="..." />
<div class="card-body">
<h5 class="card-title">{props.title}</h5>
<p class="card-text">{props.description}</p>
<Link to="#" className="btn" onClick={Like}>
{ like ?
<FavoriteIcon style={{ color: "#f9226a" }} />
:
<FavoriteIcon />
}
{ like ? " You and " : null}
200
</Link>
<Link to="#" className="btn">
<QuestionAnswerIcon titleAccess="Comment" />
</Link>
<Link to="#" className="btn">
<ShareIcon titleAccess="Share" />
</Link>
</div>
</Card>
);
}
export default MeetupItem;
| b4ce2eaa77ab29b614b3f2675c4f86d3985fa5b0 | [
"Markdown",
"JavaScript"
] | 6 | Markdown | fillahfirdausyah/react-meetup | fe91d96a0babd5f12714316fc6f8ce44ec0e33c9 | 2e91fc8daad5ee61bcf41b48cbde855407cb63c2 |
refs/heads/main | <repo_name>hossain1652/Barbar-shop<file_sep>/README.md
# Barbar-shop
| e6fa4238faea9aceaa2d39753efa43684365361c | [
"Markdown"
] | 1 | Markdown | hossain1652/Barbar-shop | 0ed16241cc4ded76a693d8ca0044bb7cdf3a4506 | 64cf67a39ae9227f3b9e88b3e5c18176b48499bf |
refs/heads/master | <repo_name>MKProject-code/symfony-promo-code-generator<file_sep>/src/Form/PromoCodeType.php
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\LessThanOrEqual;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Positive;
class PromoCodeType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('length', IntegerType::class, [
'mapped' => false,
'constraints' => array(
new NotBlank(array(
'message' => 'Please enter a value.'
)),
new LessThanOrEqual(array(
'value' => 20,
'message' => 'Please use a number less than or equal to 20.'
)),
new Positive(array(
'message' => 'Please use only positive numbers.'
))
)
])
->add('amount', IntegerType::class, [
'mapped' => false,
'constraints' => array(
new NotBlank(array(
'message' => 'Please enter a value.'
)),
new LessThanOrEqual(array(
'value' => 1000,
'message' => 'Please use a number less than or equal to 1000.'
)),
new Positive(array(
'message' => 'Please use only positive numbers.'
))
)
])
->add('type', ChoiceType::class, [
'choices' => [
'Alphanumeric' => true,
'Only numbers' => false,
],
'mapped' => false
])
->add('generate', SubmitType::class);
}
}
<file_sep>/templates/code/index.html.twig
{% extends 'base.html.twig' %}
{% block title %}Promotion codes generator{% endblock %}
{% block body %}
{{ form(form) }}
<br/>
{% for code in promoCodes %}
<b>{{ code }}</b><br/><br/>
{% endfor %}
{% endblock %}
<file_sep>/README.md
# Description
This is a simple promotional code generator written in PHP - Symfony framework.
You can generate code from WEB page or console command.
The generated codes save to database.
# Run server
`symfony server:start`
# Test
#### Windows
`php bin\phpunit`
#### Linux
`./bin/phpunit`
# Promo codes generator
### From browser
`https://127.0.0.1:8000/code`
### From console
#### Windows
`php bin\console generate-promo-codes [-a|--alphanumeric] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command> <length> <amount>`
#### Linux
`./bin/console generate-promo-codes [-a|--alphanumeric] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command> <length> <amount>`
```
Description:
Generate promo codes and save them to file
Usage:
generate-promo-codes [options] [--] <length> <amount>
Arguments:
length length of one code
amount amount of code to generate
Options:
-a, --alphanumeric Generate alphanumeric codes
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
-e, --env=ENV The Environment name. [default: "dev"]
--no-debug Switches off debug mode.
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
```
<file_sep>/src/Controller/PromoCodeController.php
<?php
namespace App\Controller;
use App\Entity\PromoCode;
use App\Form\PromoCodeType;
use App\Repository\PromoCodeRepository;
use App\Service\PromoCodeGenerator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class PromoCodeController extends AbstractController
{
/**
* @var PromoCodeGenerator
*/
private $promoCodeGenerator;
/**
* @var PromoCodeRepository
*/
private $promoCodeRepository;
/**
* PromoCodeController constructor.
* @param PromoCodeGenerator $promoCodeGenerator
*/
public function __construct(PromoCodeGenerator $promoCodeGenerator, PromoCodeRepository $promoCodeRepository)
{
$this->promoCodeGenerator = $promoCodeGenerator;
$this->promoCodeRepository = $promoCodeRepository;
}
/**
* @Route("/code", name="code")
* @param Request $request
* @return Response
*/
public function index(Request $request): Response
{
$promoCode = new PromoCode();
$form = $this->createForm(PromoCodeType::class, $promoCode);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$length = $form->get('length')->getData();
$amount = $form->get('amount')->getData();
$alphanumeric = $form->get('type')->getData();
$promoCodesArray = $this->promoCodeGenerator->generateRandomCodes($alphanumeric, $length, $amount);
$promoCodeEntities = [];
foreach($promoCodesArray as $code) {
$promoCodeEntity = new PromoCode();
$promoCodeEntity->setCode($code);
$promoCodeEntities[] = $promoCodeEntity;
}
$this->promoCodeRepository->save($promoCodeEntities);
return $this->render('code/index.html.twig', [
'form' => $form->createView(),
'promoCodes' => $promoCodesArray,
]);
}
return $this->render('code/index.html.twig', [
'form' => $form->createView(),
'promoCodes' => [],
]);
}
}
<file_sep>/src/Service/PromoCodeGenerator.php
<?php
namespace App\Service;
class PromoCodeGenerator
{
/**
* @param bool $alphanumeric
* @param int $length
* @param int $amount
* @return array
*/
public function generateRandomCodes(bool $alphanumeric = true, int $length = 10, int $amount = 1): array
{
$codes = [];
for ($i1 = 0; $i1 < $amount; $i1++) {
$characters = $alphanumeric ? '0123456789ABCDEFGHILKMNOPQRSTUVWXYZ' : '0123456789';
$charactersMaxIndex = strlen($characters) - 1;
$randomString = '';
for ($i2 = 0; $i2 < $length; $i2++) {
$randomString .= $characters[mt_rand(0, $charactersMaxIndex)];
}
$codes[] = $randomString;
}
return $codes;
}
}<file_sep>/src/Command/GeneratePromoCodeCommand.php
<?php
namespace App\Command;
use App\Repository\PromoCodeRepository;
use App\Service\PromoCodeGenerator;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
class GeneratePromoCodeCommand extends Command
{
protected static $defaultName = 'generate-promo-codes';
/**
* @var PromoCodeRepository
*/
private $promoCodeRepository;
/**
* @var PromoCodeGenerator
*/
private $promoCodeGenerator;
/**
* GeneratePromoCodeCommand constructor.
* @param PromoCodeRepository $promoCodeRepository
* @param PromoCodeGenerator $promoCodeGenerator
*/
public function __construct(PromoCodeRepository $promoCodeRepository, PromoCodeGenerator $promoCodeGenerator)
{
$this->promoCodeRepository = $promoCodeRepository;
$this->promoCodeGenerator = $promoCodeGenerator;
parent::__construct();
}
protected function configure(): void
{
$this
->setDescription('Generate promo codes and save them to file')
->addArgument('length', InputArgument::REQUIRED, 'length of one code')
->addArgument('amount', InputArgument::REQUIRED, 'amount of code to generate')
->addOption('alphanumeric', 'a', InputOption::VALUE_NONE, 'Generate alphanumeric codes');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$length = $input->getArgument('length');
if (!is_numeric($length) || $length <= 0) {
$io->error('Argument "length" must be a positive number!');
return 0;
}
$amount = $input->getArgument('amount');
if (!is_numeric($amount) || $length <= 0) {
$io->error('Argument "amount" must be a positive number!');
return 0;
}
$alphanumeric = $input->getOption('alphanumeric');
$promoCodesArray = $this->promoCodeGenerator->generateRandomCodes($alphanumeric, $length, $amount);
$promoCodeEntities = [];
foreach($promoCodesArray as $code) {
$promoCodeEntity = new PromoCode();
$promoCodeEntity->setCode($code);
$promoCodeEntities[] = $promoCodeEntity;
}
$this->promoCodeRepository->save($promoCodeEntities);
$io->success(sprintf('Successfully generated %d %s promo codes of length %d.', $amount, $alphanumeric ? 'alphanumeric' : 'numeric', $length));
return 0;
}
}
<file_sep>/src/Repository/PromoCodeRepository.php
<?php
namespace App\Repository;
use App\Entity\PromoCode;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method PromoCode|null find($id, $lockMode = null, $lockVersion = null)
* @method PromoCode|null findOneBy(array $criteria, array $orderBy = null)
* @method PromoCode[] findAll()
* @method PromoCode[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class PromoCodeRepository extends ServiceEntityRepository
{
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* PromoCodeRepository constructor.
* @param ManagerRegistry $registry
* @param EntityManagerInterface $entityManager
*/
public function __construct(ManagerRegistry $registry, EntityManagerInterface $entityManager)
{
parent::__construct($registry, PromoCode::class);
$this->entityManager = $entityManager;
}
/**
* @param array $promoCodes
*/
public function save(array $promoCodes): void
{
foreach($promoCodes as $promoCode) {
$this->entityManager->persist($promoCode);
}
$this->entityManager->flush();
}
}
<file_sep>/tests/Service/PromoCodeGeneratorTest.php
<?php
namespace App\Tests\Service;
use App\Service\PromoCodeGenerator;
use PHPUnit\Framework\TestCase;
class PromoCodeGeneratorTest extends TestCase
{
public function testGenerateRandomCodes(): void
{
$promoCodeGenerator = new PromoCodeGenerator();
$result = $promoCodeGenerator->generateRandomCodes(true, 40, 32);
self::assertIsArray($result);
self::assertContainsOnly('string', $result);
self::assertCount(32, $result);
foreach ($result as $code) {
self::assertEquals(40, strlen($code));
self::assertTrue(ctype_alnum($code));
}
$result = $promoCodeGenerator->generateRandomCodes(false, 55, 25);
self::assertIsArray($result);
self::assertContainsOnly('string', $result);
self::assertCount(25, $result);
foreach ($result as $code) {
self::assertEquals(55, strlen($code));
self::assertTrue(ctype_digit($code));
}
}
}
| 25b1c47da7e43027f7ca50f592e75de3e90e0b26 | [
"Twig",
"Markdown",
"PHP"
] | 8 | Twig | MKProject-code/symfony-promo-code-generator | 29179c0aa9ca2b0bd1f08733a9e2f0cae1476429 | ae38260a38f17c0e4a3f6fba9853564bfd09cc7e |
refs/heads/master | <file_sep>{% if template contains 'thankyou' %}
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = {{ integration['google_conversion_id'] }};
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "{{ integration['google_conversion_label'] }}";
var google_remarketing_only = false;
var google_conversion_value = "{{ cart.subtotal_price }}";
var google_conversion_currency = "{{ shop.currency_code }}";
/* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/{{ integration['google_conversion_id'] }}/?label={{ integration['google_conversion_label'] }}¤cy_code={{ shop.currency_code }}&value={{ cart.subtotal_price }}&guid=ON&script=0"/>
</div>
</noscript>
{% endif %}
| bf39d825a97f312def4d226a7b5bb06615b2c862 | [
"Liquid"
] | 1 | Liquid | versacommerce/google-conversion-tracking-integration | dad1c32b3c36133bea895d5e05b4d0e373845b39 | 1b3c61ba64d0fd5a5e919eaea861d2b47d953fc5 |
refs/heads/master | <repo_name>MIKNOTAURO/djangocon-2016-demo<file_sep>/fabfile/test.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from fabric.api import task
from .utils import docker_exec, build_venv
__all__ = ('run_all', 'es', 'failed', 'force_db', 'no_es', 'tdd')
def run_tests(name="live", flags='', args=''):
with build_venv(name):
docker_exec("py.test %s src/olympia %s" % (flags, args))
@task
def tdd(name="live", args=''):
"""to run the entire test suite, but stop on the first error"""
run_tests(name, "-x --pdb", args)
@task
def run_all(name="live", args=''):
"""to run the entire test suite"""
run_tests(name, args=args)
@task
def es(name="live", args=''):
"""to run the ES tests"""
run_tests(name, "-m es_tests", args)
@task
def failed(name="live", args=''):
"""to rerun the failed tests from the previous run"""
run_tests(name, "--lf", args)
@task
def force_db(name="live", args=''):
"""to run the entire test suite with a new database"""
run_tests(name, "--create-db", args)
@task
def no_es(name="live", args=''):
"""to run all but the ES tests"""
run_tests(name, "-m 'no es_tests'", args)
<file_sep>/wsgi/stub.ini
[uwsgi]
plugins = logfile,http,python
master = true
uid = olympia
gid = olympia
http = :1999
processes = 1
wsgi-file = /code/wsgi/stub.py
procname = uwsgi stub
logto = /code/deploy/logs/uwsgi-stub.log
<file_sep>/wsgi/uwsgi_status.ini
[uwsgi]
plugins = logfile,http,python
master = true
uid = olympia
gid = olympia
http = :9999
processes = 1
wsgi-file = /code/wsgi/uwsgi_status.py
procname = uwsgi status
logto = /code/deploy/logs/uwsgi-status.log
<file_sep>/fabfile/__init__.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from distutils.spawn import find_executable
from glob import glob
import socket
import time
import os
import re
from fabric.api import abort, cd, env, hide, lcd, local, task, settings, quiet
from .build_port_convert import build_to_port, base26_encode
from .utils import docker_exec, build_venv, dealias_build
# from . import test # noqa
ROOT_DIR = os.path.dirname(os.path.dirname(__file__))
NUM_ADDONS = NUM_THEMES = 10
env.docker_shell_env = {
'NPM_CONFIG_PREFIX': '/code/deploy/deps/',
'PIP_CACHE_DIR': '/code/deploy/deps/cache/',
'LANG': 'en_US.UTF-8',
'LC_ALL': 'en_US.UTF-8',
}
@task
def init():
"""to initialize a docker image"""
build_wheels()
docker_exec("mkdir -p /code/deploy/assets/{static,media}")
create_build("a")
create_build("b")
docker_exec(
"ln -sfvn a /code/deploy/builds/_live",
"ln -sfvn b /code/deploy/builds/_stage")
initialize_db()
populate_data()
activate("a")
activate("b")
nginx_reload()
@task
def build_wheels():
"""Build the wheels for all dependencies"""
tmp_dir = docker_exec("mktemp -d", capture=True)
with cd(tmp_dir):
docker_exec(
"cp /code/addons-server/requirements/*.txt .",
"cp /code/src/requirements/hadjango.txt .",
"mkdir -p /code/deploy/deps/wheelhouse",
r"perl -pi -e 's/^ .+$//g;s/ \\//g;s/setuptools==23\.0\.0/setuptools==25\.1\.1/g;' *.txt",
"pip wheel -f /code/deploy/deps/wheelhouse --wheel-dir=/code/deploy/deps/wheelhouse --no-deps -r dev.txt",
"pip wheel -f /code/deploy/deps/wheelhouse --wheel-dir=/code/deploy/deps/wheelhouse --no-deps -r docs.txt",
"pip wheel -f /code/deploy/deps/wheelhouse --wheel-dir=/code/deploy/deps/wheelhouse --no-deps -r hadjango.txt",
("pip wheel -f /code/deploy/deps/wheelhouse --wheel-dir=/code/deploy/deps/wheelhouse --no-deps -r"
" <(perl -pe 's/^\-e //g;' prod_without_hash.txt)"))
@task
def create_build(name):
"""Creates a new build of the Mozilla addons-server"""
symlink_static_dirs(name)
copy_src(name)
git_init(name)
with build_venv(name):
npm_install(name)
pip_install(name)
build_assets(name)
port = build_to_port(name)
docker_exec(
'echo "upstream web { server web:%d; }" > live.conf' % port,
'echo "upstream webstage { server web:%d; }" > stage.conf' % port,
'date +%FT%T > .DEPLOY_TAG')
docker_exec("ln -svfn /code/conf/uwsgi/vassal.skel vassal.ini")
def symlink_static_dirs(name):
"""
Creates symlinks for the static and media directories of build ``name`` so
that nginx static serving works correctly.
The directory './deploy/assets/static/%(name)s' will be created, along with
the following symlink
- ./deploy/builds/%(name)s/assets/static -> ./deploy/assets/static/%(name)s
"""
build_dir = "/code/deploy/builds/%s" % name
static_dir = "/code/deploy/assets/static/%s" % name
link_dir = "%s/assets/static" % build_dir
docker_exec(
"mkdir -p %s" % static_dir,
"mkdir -p %s/assets" % build_dir,
"ln -sfvn /code/deploy/assets/media %s/assets/media" % build_dir,
"[ -L %(link_dir)s ] || ln -s %(static_dir)s %(link_dir)s" % {
'link_dir': link_dir,
'static_dir': static_dir,
})
for d in glob("%s/deploy/assets/static/*" % ROOT_DIR):
link_dir = "/code/deploy/assets/static/%s/%s" % (os.path.basename(d), name)
docker_exec("[ -L %(link_dir)s ] || ln -s %(static_dir)s %(link_dir)s" % {
'link_dir': link_dir,
'static_dir': static_dir,
})
def copy_src(name):
build_dir = "/code/deploy/builds/%s" % name
docker_exec(
"git ls-files"
" | perl -pne 's/\"//g; s/e\\\\314\\\\201/é/g;'" # Fix jétpack.xpi path
" | rsync -a --info=progress2 --files-from=- . %s" % build_dir)
docker_exec("cp /code/src/local_settings.py %s" % build_dir)
with build_venv(name):
docker_exec("cp -R /code/src/hadjango .")
docker_exec("cp /code/src/requirements/*.txt requirements")
docker_exec("cp /code/fabfile/build_port_convert.py hadjango")
docker_exec(
r"perl -pi -e "
r"'s/^ .+$//g;s/ \\//g;"
r"s/setuptools==23\.0\.0/setuptools==25\.1\.1/g;' "
"requirements/*.txt")
def git_init(name):
"""Create fake git repo so that jingo minify can cache bust images"""
if not os.path.exists("%s/deploy/builds/%s/.git" % (ROOT_DIR, name)):
with build_venv(name):
docker_exec(
'git init',
'cat /dev/urandom | head -c256 > .random',
'git add .random',
'git commit -m "Initial commit"')
def pip_install(name):
build_wheels()
args = "-f /code/deploy/deps/wheelhouse --no-index --no-deps"
with build_venv(name):
olympia_egg_link = (
"/code/deploy/builds/%s/lib/python2.7/site-packages/olympia.egg-link" % name)
docker_exec((
'[ -f %(egg_link)s ]'
' || pip install %(args)s -e .') % {'egg_link': olympia_egg_link, 'args': args})
docker_exec(
"pip install %s -r requirements/dev.txt" % args,
"pip install %s -r requirements/docs.txt" % args,
"pip install %s -r requirements/prod_without_hash.txt" % args,
"pip install %s -r requirements/hadjango.txt" % args)
def npm_install(name="_live"):
if os.path.exists(os.path.join(ROOT_DIR, 'deploy', 'builds', name, 'node_modules')):
return
with build_venv(name):
# npm install has a bug when run inside docker on a mounted volume
# (see <https://github.com/npm/npm/issues/9863>). So we run npm
# install in a temp directory, then move it back.
tmp_dir = docker_exec("mktemp -d", capture=True)
docker_exec("cp package.json %s" % tmp_dir)
with cd(tmp_dir):
docker_exec("npm install")
docker_exec("mv %s/node_modules ." % tmp_dir)
def initialize_db():
"""to create a new database"""
with build_venv("_live"):
docker_exec(
"python manage.py reset_db",
"python manage.py syncdb --noinput",
"python manage.py loaddata initial.json",
"python manage.py import_prod_versions",
"schematic --fake src/olympia/migrations/",
"python manage.py createsuperuser",
"python manage.py loaddata zadmin/users")
def populate_data():
"""to populate a new database"""
with build_venv("_live"):
docker_exec(
# reindex --wipe will force the ES mapping to be re-installed. Useful to
# make sure the mapping is correct before adding a bunch of add-ons.
"python manage.py reindex --wipe --force --noinput",
"python manage.py generate_addons --app firefox %s" % NUM_ADDONS,
"python manage.py generate_addons --app thunderbird %s" % NUM_ADDONS,
"python manage.py generate_addons --app android %s" % NUM_ADDONS,
"python manage.py generate_addons --app seamonkey %s" % NUM_ADDONS,
"python manage.py generate_themes %s" % NUM_THEMES,
# Now that addons have been generated, reindex.
"python manage.py reindex --force --noinput",
# Also update category counts (denormalized field)
"python manage.py cron category_totals")
def build_assets(name):
with build_venv(name):
docker_exec(
"python manage.py compress_assets",
"python manage.py collectstatic --noinput")
@task
def swap_live(name=None):
"""Swap the specified build (default: _stage) with _live"""
if name is None:
name = dealias_build("_stage")
live = dealias_build("_live")
with cd("/code/deploy/builds"):
docker_exec(
"ln -snvf %s _stage" % live,
"ln -snvf %s _live" % name)
nginx_reload()
@task
def stage(name):
"""Stage the designated build"""
live = dealias_build("_live")
stage = dealias_build("_stage")
if name == live:
abort("Cannot stage the live build; use 'fab swap_live' instead")
if name == stage:
abort("Build %s is already staged" % name)
if not os.path.islink("%s/deploy/builds/%s/zerg.ini" % (ROOT_DIR, name)):
activate(name)
time.sleep(10)
warmup(name)
with cd("/code/deploy/builds"):
docker_exec("ln -snvf %s _stage" % name)
@task
def activate(name):
"""Start uWSGI zerg instances for a build"""
with build_venv(name):
if not os.path.islink("%s/deploy/builds/%s/vassal.ini" % (ROOT_DIR, name)):
docker_exec("ln -svfn /code/conf/uwsgi/vassal.skel vassal.ini")
time.sleep(3)
docker_exec("ln -svfn /code/conf/uwsgi/zerg.skel zerg.ini")
# Wait for the emperor to poll again
time.sleep(3)
@task
def deactivate(name):
"""Stop uWSGI zerg instance for a build"""
if not os.path.islink("%s/deploy/builds/%s/zerg.ini" % (ROOT_DIR, name)):
return
with build_venv(name):
docker_exec("rm -f zerg.ini")
time.sleep(3)
@task
def stop(name):
"""Stop all uwsgi vassals and zergs for a build"""
deactivate(name)
if not os.path.islink("%s/deploy/builds/%s/vassal.ini" % (ROOT_DIR, name)):
return
with build_venv(name):
docker_exec("rm -f vassal.ini")
time.sleep(3)
@task
def warmup(name="_stage"):
"""Warm up a build, to be used before swapping to live"""
with build_venv(name):
docker_exec("python manage.py warmup")
@task
def nginx_reload():
"""Reload nginx config"""
docker_exec("nginx -s reload", server="nginx")
@task
def ip():
"""The ip where the addons site can be accessed"""
docker_host = os.environ.get("DOCKER_HOST") or ""
if not docker_host:
with quiet():
docker_env = local("docker-machine env addons", capture=True)
if docker_env:
match = re.search(r'DOCKER_HOST="(tcp://[^"]+?)"', docker_env)
if match:
docker_host = match.group(1)
match = re.search(r'tcp://([^:]+):', docker_host)
if match:
print(match.group(1))
else:
try:
# host used by dlite
_, _, ips = socket.gethostbyname_ex("local.docker")
except:
abort("Could not determine docker-machine host; perhaps localhost?")
else:
print(ips[0])
@task
def find_free_build():
"""Find what the next free build directory name is."""
current_builds = set([os.path.basename(p) for p in glob("%s/deploy/builds/[a-z]*" % ROOT_DIR)])
i = 0
while True:
build = base26_encode(i)
if build not in current_builds:
print(build)
return
i += 1
@task
def rm(name):
"""Delete a build"""
live_name = dealias_build("_live")
stage_name = dealias_build("_stage")
if name in (live_name, stage_name):
abort("Cannot delete the current live or stage build")
stop(name)
docker_exec("rm -rf /code/deploy/builds/%s" % name)
@task
def djshell(name="_live"):
"""Connect to a running addons-server django shell"""
with build_venv(name):
docker_exec("python manage.py shell")
@task
def shell(server='web'):
"""Connect to a running addons-server docker shell"""
cwd = '/code' if server == 'web' else '/'
with cd(cwd):
docker_exec("bash", root=True, server=server)
@task
def make_incremental_build(name, basis="live"):
"""
Archive a build, hard-linking unchanged files from the "basis" build (default live)
This can significantly reduce the disk space used by multiple builds.
On mac, requires ``brew install coreutils``
"""
cp_bin = find_executable('gcp')
if find_executable('gcp'):
cp_bin = "gcp"
else:
cp_bin = "cp"
live_name = dealias_build("_live")
stage_name = dealias_build("_stage")
if name in (live_name, stage_name):
abort("Cannot turn the live or stage build into an incremental build")
basis = dealias_build(basis)
stop(name)
with lcd("%s/deploy/builds" % ROOT_DIR):
local("mv %(name)s %(name)s~" % {'name': name})
with settings(hide("stderr"), warn_only=True):
cp_ret = local("%(cp_bin)s -al %(basis)s %(name)s" % {
'basis': basis,
'name': name,
'cp_bin': cp_bin,
})
if not cp_ret.succeeded:
local("mv %(name)s~ %(name)s" % {'name': name})
abort("Local cp bin does not support -l flag (on mac: brew install coreutils)")
local("rsync -acH --delete %(name)s~/ %(name)s" % {'name': name})
local("rm -rf %(name)s~" % {'name': name})
<file_sep>/src/hadjango/uwsgi/bootstrap.py
"""
A script which preloads most modules in Django.
This file is executed via execfile() from other files in this directory.
It is assumed that the original file which is executing this file has set
os.environ['DJANGO_SETTINGS_MODULE'] prior to calling execfile().
"""
import os
from importlib import import_module
os.environ["CELERY_LOADER"] = "django"
def run_mgmt_validate():
import django.core.management
utility = django.core.management.ManagementUtility()
command = utility.fetch_command('runserver')
command.validate(display_num_errors=True)
def load_templatetags():
import_module('django.template.base').get_templatetags_modules()
def load_admin():
import_module('django.contrib.admin').autodiscover()
def load_i18n(lang_code):
import_module('django.utils.translation').activate(lang_code)
def load_urls():
import_module('django.core.urlresolvers').resolve('/')
def setup():
import django
django.setup()
from django.conf import settings
load_templatetags()
if 'django.contrib.admin' in settings.INSTALLED_APPS:
load_admin()
load_i18n(settings.LANGUAGE_CODE)
load_urls()
run_mgmt_validate()
setup()
<file_sep>/docker/README.md
These are files that are either copied into docker containers, or are
executed as the entry points in `docker-compose.yml`.
<file_sep>/fabfile/README.md
Defines all of the commands available to fabric (run `fab --list` from the root
of the repository to see a full list).
All tasks are defined in `fabfile/__init__.py`.
<file_sep>/wsgi/README.md
Contains the uwsgi configuration files (`*.ini`) and wsgi files `*.py` for
simple wsgi applications that start on load.
<dl>
<dt>stub.ini / stub.py</dt>
<dd>
A “hello world” wsgi application that is the initial upstream for
nginx before `fab init` has been run.
</dd>
<dt>uwsgi_status.ini / uwsgi_status.py</dt>
<dd>
A very simple app, bound on port `:9999`, that merges the output of
the various uwsgi stat sockets at `/var/run/uwsgi/*.stats` and combines
that with information pulled from the process table (see
`src/hadjango/uwsgi/wsgi.py`), outputing the result as json.
This script returns the data that powers the uwsgi dashboard
(at http://live.addons/uwsgi/).
</dd>
</dl>
<file_sep>/wsgi/stub.py
#!/usr/bin/env python
"""
A very simple wsgi application, used for the initial upstream before the
environments have been initialized.
"""
html = """<!DOCTYPE html>
<html>
<head>
<title>High Availability Django Demo</title>
<style type="text/css">
html {
font-family: -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", Helvetica, sans-serif;
}
body {
font-size: 18px;
background: #fff;
margin: 3em 5em;
}
pre {
display: inline-block;
padding: 1em;
}
pre, code {
font-family: SFMono, Consolas, Menlo, Monaco, monospace;
background: #eaeaea;
}
h1 {
font-size: 1.5em;
color: #333;
margin-bottom: 2em;
}
</style>
</head>
<body>
<h1>Welcome to the High Availability Django Demo!</h1>
<p>To continue, run:</p>
<pre><code>fab init</code></pre>
<p>from the root of the checked out repository.
</body>
</html>"""
def application(environ, start_response):
status = '200 OK'
headers = [
('Content-Type', 'text/html'),
('Content-Length', str(len(html))),
]
start_response(status, headers)
return [html]
<file_sep>/fabfile/utils.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from contextlib import contextmanager
import os
import re
import six
from fabric.api import env, local
from fabric.context_managers import cd, path, quiet
from fabric.state import win32
ROOT_DIR = os.path.dirname(os.path.dirname(__file__))
IN_DOCKER = os.path.exists('/addons-server-centos7-container')
if IN_DOCKER:
DOCKER_NAME = ""
else:
COMPOSE_PROJECT_NAME = os.path.basename(ROOT_DIR.replace('-', '').replace('_', ''))
DOCKER_NAME = "%s_%%(server)s_1" % COMPOSE_PROJECT_NAME
def docker_exec(*cmd, **kwargs):
server = kwargs.pop('server', 'web')
root = kwargs.pop('root', False if server == 'web' else True)
default_cwd = "addons-server" if server == "web" else "/"
cwd = env['cwd'] if env['cwd'] else default_cwd
if not cmd[0].startswith('cd '):
cmd = ("cd %s" % cwd, ) + cmd
cmd = " && ".join(cmd)
if server == "web":
cmd = _prefix_env_vars(cmd)
cmd = cmd.replace("'", "'\"'\"'")
if root:
full_cmd = "bash -c '%s'" % cmd
else:
full_cmd = """su olympia -c 'bash -c '"'"'%s'"'"''""" % cmd.replace("'", "'\"'\"'")
if not IN_DOCKER:
container_name = DOCKER_NAME % {'server': server}
full_cmd = "docker exec -t -i %s %s" % (container_name, full_cmd)
if (six.PY2 and isinstance(full_cmd, unicode)):
full_cmd = full_cmd.encode('utf-8')
return local(full_cmd, **kwargs)
@contextmanager
def build_venv(name):
old_build_name = env.get('build_name')
env['build_name'] = name
build_dir = "/code/deploy/builds/%s" % name
with cd("%s" % build_dir):
docker_exec("[ -f bin/pip ] || virtualenv . --never-download")
with path(os.path.join(build_dir, 'bin'), behavior='prepend'):
yield
env['build_name'] = old_build_name
_find_unsafe = re.compile(r'[a-zA-Z0-9_^@%+=:,./-]').search
def quote(s):
"""Return a shell-escaped version of the string *s*."""
if not s:
return "''"
if _find_unsafe(s) is None:
return s
# use single quotes, and put single quotes into double quotes
# the string $'b is then quoted as '$'"'"'b'
return "'" + s.replace("'", "'\"'\"'") + "'"
def _shell_escape(string):
"""
Escape double quotes, backticks and dollar signs in given ``string``.
For example::
>>> _shell_escape('abc$')
'abc\\\\$'
>>> _shell_escape('"')
'\\\\"'
"""
for char in ('"', '$', '`'):
string = string.replace(char, '\%s' % char)
return string
def _prefix_env_vars(command, local=False):
"""
Prefixes ``command`` with any shell environment vars, e.g. ``PATH=foo ``.
Currently, this only applies the PATH updating implemented in
`~fabric.context_managers.path` and environment variables from
`~fabric.context_managers.shell_env`.
Will switch to using Windows style 'SET' commands when invoked by
``local()`` and on a Windows localhost.
"""
env_vars = {}
# path(): local shell env var update, appending/prepending/replacing $PATH
path = env.path
if path:
if env.path_behavior == 'append':
path = '$PATH:\"%s\"' % path
elif env.path_behavior == 'prepend':
path = '\"%s\":$PATH' % path
elif env.path_behavior == 'replace':
path = '\"%s\"' % path
env_vars['PATH'] = path
# shell_env()
env_vars.update(env.get('docker_shell_env'))
if env_vars:
set_cmd, exp_cmd = '', ''
if win32 and local:
set_cmd = 'SET '
else:
exp_cmd = 'export '
exports = ' '.join(
'%s%s="%s"' % (set_cmd, k, v if k == 'PATH' else _shell_escape(v))
for k, v in env_vars.iteritems()
)
shell_env_str = '%s%s && ' % (exp_cmd, exports)
else:
shell_env_str = ''
return "%s%s" % (shell_env_str, command)
def dealias_build(name):
if name in ("live", "stage"):
name = "_%s" % name
path = "%s/deploy/builds/%s" % (ROOT_DIR, name)
with quiet():
return os.path.basename(
docker_exec("cd %s && pwd -P" % path, capture=True))
<file_sep>/src/hadjango/management/commands/warmup.py
import random
from django.conf import settings
from django.core.management.base import BaseCommand
import requests
from requests_futures.sessions import FuturesSession
from hadjango.build_port_convert import build_to_port
class Command(BaseCommand):
"""
Command that primes processes/cache for a given build
"""
help = 'Warms up processes/cache for a given host/port'
def add_arguments(self, parser):
parser.add_argument('--build', '-b', dest='build',
default=settings.BUILD_NAME, help='Build to warm up: (a|b|c|...)')
parser.add_argument('--concurrents', '-c', dest='concurrents',
default='6', help='Number of concurrent requests to make')
def handle(self, **options):
server = "web"
build = options['build']
port = build_to_port(build)
max_workers = int(options['concurrents'])
session = FuturesSession(max_workers=max_workers)
futures = []
random_version = random.randint(0, 65535)
for i in range(0, max_workers):
version = '' if i == 0 else '?v=%d%d' % (i, random_version)
futures.append(session.get('http://%(server)s:%(port)d/en-US/firefox/%(version)s' % {
'server': server,
'port': port,
'version': version,
}))
for i, future in enumerate(futures):
# wait for the response to complete
try:
response = future.result()
except requests.ConnectionError:
status = 'XXX'
time = 0
else:
status = response.status_code
time = int(round(response.elapsed.total_seconds() * 1000.0))
self.stdout.write("%(server)s: (%(status)s) %(time)6d ms: worker %(i)s\n" % {
'server': server,
'status': status,
'time': time,
'i': i + 1,
})
self.stdout.write("Successfully warmed up.")
<file_sep>/README.md
# Django UWSGI deploy demo
This repository demonstrates the principles behind the talk “High-Availability
Django” given by <NAME> of _The Atlantic_ at the 2016 Djangocon.
In order to simulate the deployment of a large-ish Django project, it uses the
source for [addons.mozilla.org](https://addons.mozilla.org/), [found
here](https://github.com/mozilla/addons-server).
## Running
In order to run this demo VM, Docker, Fabric, and VirtualBox must be
installed. Once installed, the VM can be provisioned by running (from the
root of the checked out repository):
```shell
git submodule init
git submodule update
# Skip the next two steps if you don't want docker-machine
docker-machine create --driver virtualbox addons
eval $(docker-machine env addons)
docker-compose up -d
fab init
```
During the `fab init` step you will be prompted once when the database is initialized,
and then again to create the superuser.
Using `docker-machine` is not required unless you are using the older Docker Toolbox
on Mac (or you have installed it with `brew install docker`). Keep in mind however
that by default, running `docker-compose up` without using a docker-machine VM will
bind to port 80 on your localhost, which means it will need to be unused, so
you may wish to use `docker-machine` even if you don't need to.
Alternatively, if you are using Docker for Mac, you can use
[https://github.com/nlf/dlite](https://github.com/nlf/dlite) to have docker use a
separate bridged network (and thus separate ips for its containers).
Grab the ip address using the command `fab ip` (unless you are not using `docker-machine`
or `dlite`, in which case it will be `127.0.0.1`), and then add to your `/etc/hosts` files:
```
192.168.64.7 live.addons stage.addons
```
Replacing `192.168.64.7` with the ip address for docker.
After running `fab init`, you should be able to visit http://live.addons/ and http://stage.addons/
to see the two initial builds (note that there may be a delay while the code initializes).
You can view a live-updating uwsgi status dashboard at http://live.addons/uwsgi/
## Creating new builds
Builds are stored in folders, as part of the sequence {a, b, c, ..., z, aa, ab, ...}
In many scenarios, builds will cycle between a, b, and c, and the unused build
(the one linked neither to live or stage) can be removed or archived after each build.
To find the next unused build folder, run `fab find_free_build`.
Then, to create the build, run, e.g. `fab create_build:z` where “z” should be
whatever build name was returned from `find_free_build`.
## Staging and deploying builds
To set a build as active (which will create a wsgi configuration that
spawns vassal in uWSGI emperor mode), run `fab activate:z`.
To then stage this build, run `fab stage:z` (again, the string after the “:”
being the build name), which will unlink the current stage build and link the
specified build to stage.
To “warm up” a build by hitting it with concurrent requests, use the command
`fab warmup:z` (the build name is optional and defaults to the stage build).
To swap the stage and live builds, run `fab swap_live`. By default, this will
swap live with the stage build, but it is possible to specify a different
build by, e.g. `fab swap_live:z`.
To spin down an old build (it cannot be the current live or stage builds), run
`fab deactivate:z`.
## `fab init` and `fab create_build`
(Note: This repository's directory will be mounted as `/code` within the docker container,
so when you see paths like `/code/deploy/...` below, keep in mind that this refers also
to `./deploy/...` within this repository.)
Running `fab init` executes a number of steps to get a stage and live build up and running:
- Builds all of the requirements into wheels, output to /code/deploy/deps/wheelhouse, which
then allows for faster `pip install` when creating new addons-server builds
- Creates two builds, “a” and “b”, in directories `/code/deploy/builds/{a,b}`
(`fab create_build:a` and `fab create_build:b`). The `create_build` command
does the following:
- Creates symlinks for the static and media directories of the build so
that nginx static serving works correctly.
<sup>*Note*: All static assets (static files and user-uploaded media) live
outside of the `builds` directory, in `/code/deploy/assets`. This is
to allow for the common use case where static files and user media use
a distinct mount or partition from the rest of the code. In order to
keep all static file urls distinct (beyond whatever staticfile cache busting
is used), the static files for all builds are kept in separate directories,
e.g. `/code/deploy/assets/static/a`.</sup>
- Uses `rsync` to copy the source in the `addons-server` submodule to the
build directory, and copies the contents of `/code/src` on top of that.
- From the build directory, runs `git init` and commits a randomly generated
file. Mozilla’s addons-server uses the git commit hash to cache-bust minified
assets, so this ensures that this step won’t fail and that the hash will be
unique for each build.
- Runs `npm install` as well as `pip install` with the requirements files, using
the `--no-index` flag and our wheeldir of `code/deploy/deps/wheelhouse` to
keep this speedy.
- Runs `manage.py collectstatic` and `manage.py compress_assets` (the latter being a
jingo-minify management command specific to the mozilla addons-server project)
from the build’s virtualenv.
- Determines what port number corresponds to the current build name, and creates
`/code/deploy/builds/a/live.conf` and `/code/deploy/builds/a/stage.conf`, which
are nginx configuration files that specify the upstream. This will only come
into play if the build gets designated as the stage or live build (since nginx
includes `/code/deploy/builds/_live/live.conf` and `/code/deploy/builds/_stage/stage.conf`).
- Creates symlinks to the uwsgi skeleton file `/code/conf/uwsgi/vassal.skel` at
`/code/deploy/builds/{a,b}/vassal.ini`. This step causes the uWSGI emperor to spawn
a vassal that will manage the zerg instances. At this point the application on the
``web`` container will be listening on ports `2000` and `2010` (for the a and b builds,
respectively), but because there are no zerg instances attached to the vassal
http requests will not yet route.
- After the builds “a” and “b” are created and linked, respectively, to
`/code/deploy/builds/_live` and `/code/deploy/builds/_stage`,
`fab init` initiates the database and populates it with sample test data,
executed using the manage.py in the `_live` (read “a”) build’s virtualenv.
- It then symlinks to the uwsgi skeleton file `/code/conf/uwsgi/zerg.skel` from
`/code/deploy/builds/{a,b}/zerg.ini`. This “activates” (`fab activate:a`) the
build, spawning zerg instances that attach to the vassal.
- Lastly, `nginx -s reload` is run on the nginx container, updating the upstreams.
## Troubleshooting
* Problem: You encounter the error “Error response from daemon: client is newer than server (client API version: 1.24, server API version: 1.22)”
* Solution: `export DOCKER_API_VERSION=1.22`
<file_sep>/wsgi/uwsgi_status.py
#!/usr/bin/env python
import sys
import re
import errno
import glob
import socket
import json
import logging
import psutil
logging.basicConfig()
logger = logging.getLogger()
re_procname = re.compile(r"(?i)"
r"uwsgi (?P<type>(?:worker|master))"
r"(?: (?P<worker_num>\d+))? "
r"<(?P<build>[^\.]+)>"
r"(?: \[(?P<deploy_tag>[^\]]+)\])?")
class UwsgiProcess(object):
def __init__(self, pinfo):
self.pid = pinfo['pid']
self.status = pinfo['status']
self.name = pinfo['cmdline'][0]
self.create_time = pinfo['create_time']
m = re_procname.match(self.name)
if not m:
raise Exception("Bad uwsgi process name")
matches = m.groupdict()
self.is_master = matches['type'] == 'master'
if self.is_master:
self.workers = []
else:
self.worker_num = int(matches['worker_num'])
self.ppid = pinfo['ppid']
self.deploy_tag = matches['deploy_tag']
self.build = matches['build']
def get_uwsgi_procs():
procs = {}
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(
attrs=['pid', 'ppid', 'name', 'cmdline', 'create_time', 'status'])
except psutil.NoSuchProcess:
pass
else:
if not len(pinfo['cmdline']):
continue
if pinfo['cmdline'][0].startswith('u') and pinfo['ppid'] != 1:
if re_procname.match(pinfo['cmdline'][0]):
procs[pinfo['pid']] = UwsgiProcess(pinfo)
stat_sock_files = glob.glob('/var/run/uwsgi/*.stats')
for stat_sock_file in stat_sock_files:
js = ''
try:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(stat_sock_file)
while True:
d = s.recv(4096)
if len(d) < 1:
break
js += d.decode('utf-8')
except IOError as e:
if e.errno == errno.ECONNREFUSED:
logger.error("Connection refused to socket %s" % stat_sock_file)
elif e.errno != errno.EINTR:
raise
continue
except:
raise Exception("Unable to get uwsgi statistics for socket %s"
% stat_sock_file)
raw_stats = json.loads(js)
if raw_stats['pid'] not in procs:
continue
workers = raw_stats.pop('workers')
master_proc = procs[raw_stats['pid']]
master_proc.status = 'active'
master_proc.__dict__.update(raw_stats)
for worker in workers:
pid = worker['pid']
if pid in procs:
uwsgi_worker = procs.pop(pid)
uwsgi_worker.__dict__.update(worker)
master_proc.workers.append(uwsgi_worker.__dict__)
master_proc.deploy_tag = uwsgi_worker.deploy_tag
for pid in reversed(sorted(procs.keys())):
proc = procs[pid]
if not proc.is_master and proc.ppid in procs:
procs[proc.ppid].workers.append(procs.pop(pid).__dict__)
build_data = {}
for pid in reversed(sorted(procs.keys())):
proc = procs[pid]
build = proc.build
if build not in build_data:
build_data[build] = []
build_data[build].append(proc.__dict__)
data = []
for build in sorted(build_data.keys()):
data.append({
"name": build,
"processes": build_data[build],
})
return {
"configs": data
}
def application(environ, start_response):
status = '200 OK'
output = json.dumps(get_uwsgi_procs())
headers = [
('Content-Type', 'application/json'),
('Content-Length', str(len(output)))
]
start_response(status, headers)
return [output]
if __name__ == '__main__':
sys.stdout.write(json.dumps(get_uwsgi_procs()))
<file_sep>/fabfile/build_port_convert.py
#!/usr/bin/env python
"""Convert a build name (e.g. 'a', 'b', etc.) to a port number, or vice-versa"""
from __future__ import print_function
import os
import sys
START_PORT = 2000
PORT_INCREMENT = 10
MAX_PORT = 65535
MAX_PORT_NUMS = (MAX_PORT - START_PORT) // PORT_INCREMENT
NUM_TO_CHAR = dict([((i), chr(i + ord('a'))) for i in range(0, 26)])
CHAR_TO_NUM = dict(map(reversed, NUM_TO_CHAR.items()))
def base26_decode(string):
num = 0
i = 0
while i < len(string):
char = string[i]
offset = 0
if i == 0:
offset = 1
power = len(string) - i - 1
num += (26 ** power) * (CHAR_TO_NUM[char] + offset)
if offset:
while power > 1:
power -= 1
num += 26 ** power
i += 1
return num - 1
def base26_encode(num):
string = ''
num += 1
while num:
num, val = divmod((num - 1), 26)
string = "%s%s" % (NUM_TO_CHAR[val], string)
return string
def port_to_build(port):
if port < START_PORT:
usage("Port number must be greater than or equal to %d" % START_PORT)
if port > MAX_PORT:
usage("Port number must be less than %d" % MAX_PORT)
num, index = divmod((port - START_PORT), PORT_INCREMENT)
return (base26_encode(num), index)
def build_to_port(name):
if name[-1].isdigit():
index = int(name[-1])
name = name[:-1]
else:
index = 0
num = base26_decode(name)
port = START_PORT + (num * PORT_INCREMENT) + index
return port
USAGE = """%(error)s
Usage: %(script_name)s [port|build_name [index]]
build_name A string composed of lowercase letters, as part of the sequence
a, b, c, ..., z, aa, ab, ac, ..., zz, aaa, ..., %(max_build_name)s
index Optional (defaults to 0), an integer between 0 and %(max_index)s
which is added to the port number for the build_name
port An integer, greater than %(start)s, which is converted into a
build_name and index.
""".strip()
def usage(error=""):
if error:
error = "ERROR: %s\n" % error
script_name = os.path.basename(sys.argv[0])
print(USAGE % {
"script_name": script_name,
"max_build_name": base26_encode(MAX_PORT_NUMS),
"max_index": PORT_INCREMENT,
"start": START_PORT,
"error": error,
})
sys.exit(1)
if __name__ == '__main__':
if len(sys.argv) != 2:
usage()
arg = sys.argv[-1]
if arg.isdigit():
print("%s %d" % port_to_build(int(arg)))
elif len(arg) > 3:
usage()
else:
print(build_to_port(arg))
<file_sep>/src/hadjango/uwsgi/wsgi.py
import re
import os
import sys
import site
import uwsgi
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
sys.path.insert(0, project_root)
site.addsitedir(os.path.join(
project_root,
"lib",
"python" + sys.version[0:3],
"site-packages"))
def get_site_name():
settings_module = os.environ.get('DJANGO_SETTINGS_MODULE') or ''
matches = re.match(r'settings\.(\w+)\.live', settings_module)
if matches:
site_name = matches.group(1)
else:
site_name = 'unknown'
return site_name
site_name = get_site_name()
def set_uwsgi_proc_name():
build_dir = os.path.basename(project_root)
try:
deploy_tag = open(os.path.join(project_root, '.DEPLOY_TAG')).read().strip()
except IOError:
deploy_tag = '?'
os.environ['DEPLOY_TAG'] = deploy_tag
uwsgi.setprocname("uwsgi worker %(worker_id)d <%(build)s> [%(tag)s]" % {
'worker_id': uwsgi.worker_id(),
'build': build_dir,
'tag': deploy_tag,
})
set_uwsgi_proc_name()
execfile(os.path.join(os.path.dirname(__file__), 'bootstrap.py'))
_application = None
def application(environ, start_response):
global _application
uwsgi.set_logvar('worker_id', str(uwsgi.worker_id()))
if not os.environ.get('DJANGO_SETTINGS_MODULE'):
os.environ['DJANGO_SETTINGS_MODULE'] = environ.get('DJANGO_SETTINGS_MODULE', 'settings')
if _application is None:
try:
from django.core.wsgi import get_wsgi_application
except ImportError:
import django.core.handlers.wsgi
_application = django.core.handlers.wsgi.WSGIHandler()
else:
_application = get_wsgi_application()
return _application(environ, start_response)
<file_sep>/docker-compose.yml
version: '2'
services:
web:
# build: .
image: hadjango/djangocon-2016-demo
entrypoint: ./docker/start-docker.sh
command: supervisord -n -c /code/docker/supervisor.conf
privileged: true
expose:
- "1999"
- "2000"
- "2010"
- "2020"
- "2030"
- "2040"
- "2050"
- "2060"
- "2070"
- "2080"
- "2090"
- "2100"
- "2110"
- "2120"
- "2130"
- "2140"
- "2150"
- "2160"
- "2170"
- "2180"
- "2190"
- "2200"
- "2210"
- "2220"
- "2230"
- "2240"
- "2250"
- "9999"
volumes:
- .:/code
links:
- memcached
- mysqld
- elasticsearch
- redis
environment:
- PYTHONUNBUFFERED=1
- RECURSION_LIMIT=10000
- TERM=xterm-256color
nginx:
# build: ./nginx
image: hadjango/addons-nginx
entrypoint: /code/docker/start-nginx.sh
command: nginx -g 'daemon off;'
ports:
- "80"
ports:
- "80:80"
volumes:
- .:/code
links:
- web:web
memcached:
image: memcached:1.4
mysqld:
image: mysql:5.6
environment:
- MYSQL_ALLOW_EMPTY_PASSWORD=yes
- MYSQL_DATABASE=olympia
elasticsearch:
image: elasticsearch:1.6
redis:
image: redis:2.8
<file_sep>/docker/start-nginx.sh
#!/bin/bash
# If running within docker-machine, the current directory will be a mounted
# volume, owned by the user running Docker on the host machine.
#
# In that case, we don't want to trample all over the contents of this
# directory with files owned by root. So we create a new user with the same
# UID, and drop privileges before running any commands.
#
# If we are not running in docker-machine, we create a user with uid 1000
# and execute commands as that user.
# Get the numeric user ID of the current directory.
uid=$(ls -nd /code | awk '{ print $3 }')
gid=$(ls -nd /code | awk '{ print $4 }')
# If the current working directory is owned by root, that means we're running
# with plain-old docker, not docker-machine.
if [ "$uid" == "0" ]; then
uid=1000
gid=1000
fi
group_name=$(getent group $gid)
groupadd -g 1000 olympia 2>&1 2>/dev/null
# Create an `olympia` user with that ID, and the current directory
# as its home directory.
if [ -z "$group_name" ]; then
useradd -Md $(pwd) -u $uid -g $gid -G olympia olympia 2>&1 2>/dev/null
else
useradd -Md $(pwd) -u $uid -g $gid olympia 2>&1 2>/dev/null
fi
if [ ! -L /code/deploy/builds/_live ]; then
mkdir -p /code/deploy/tmp/live
mkdir -p /code/deploy/tmp/stage
echo "upstream web { server web:1999; }" > /code/deploy/tmp/live/live.conf;
echo "upstream webstage { server web:1999; }" > /code/deploy/tmp/stage/stage.conf;
ln -sfvn /code/deploy/tmp/live /code/deploy/builds/_live
ln -sfvn /code/deploy/tmp/stage /code/deploy/builds/_stage
fi
chown -R $uid:$gid /code/deploy/tmp
chown $uid:$gid /code/deploy/builds/*
exec su root -c 'exec "$@"' sh -- "$@"
<file_sep>/src/local_settings.py
import os
from olympia.lib.settings_base import INSTALLED_APPS
INSTALLED_APPS = ('hadjango', ) + INSTALLED_APPS + ('olympia.landfill', )
BROKER_URL = 'amqp://olympia:olympia@rabbitmq/olympia'
CELERY_RESULT_BACKEND = 'redis://redis:6379/1'
REDIS_LOCATION = 'redis://redis:6379/0?socket_timeout=0.5'
ES_HOSTS = ['elasticsearch:9200']
ES_URLS = ['http://%s' % h for h in ES_HOSTS]
SITE_DIR = 'http://olympia.dev'
CACHES = {
'default': {
'BACKEND': 'caching.backends.memcached.MemcachedCache',
'LOCATION': 'memcached:11211',
}
}
ROOT = os.path.realpath(os.path.dirname(__file__))
BUILD_NAME = os.path.basename(ROOT)
STATIC_ROOT = os.path.join(ROOT, "assets", "static")
MEDIA_ROOT = os.path.join(ROOT, "assets", "media")
STATIC_URL = "/static/%s/" % BUILD_NAME
CELERY_ALWAYS_EAGER = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'olympia',
'USER': 'root',
'PASSWORD': '',
'HOST': 'mysqld',
'PORT': '',
'OPTIONS': {'sql_mode': 'STRICT_ALL_TABLES'},
'TEST_CHARSET': 'utf8',
'TEST_COLLATION': 'utf8_general_ci',
# Run all views in a transaction unless they are decorated not to.
'ATOMIC_REQUESTS': True,
# Pool our database connections up for 300 seconds
'CONN_MAX_AGE': 300,
},
}
# A database to be used by the services scripts, which does not use Django.
# The settings can be copied from DATABASES, but since its not a full Django
# database connection, only some values are supported.
SERVICES_DATABASE = {
'NAME': DATABASES['default']['NAME'],
'USER': DATABASES['default']['USER'],
'PASSWORD': DATABASES['default']['PASSWORD'],
'HOST': DATABASES['default']['HOST'],
'PORT': DATABASES['default']['PORT'],
}
<file_sep>/.gitconfig
[user]
email = <EMAIL>
name = Nobody
<file_sep>/docker/start-docker.sh
#!/bin/sh
# If running within docker-machine, the current directory will be a mounted
# volume, owned by the user running Docker on the host machine.
#
# In that case, we don't want to trample all over the contents of this
# directory with files owned by root. So we create a new user with the same
# UID, and drop privileges before running any commands.
#
# If we are not running in docker-machine, we create a user with uid 1000
# and execute commands as that user.
# Get the numeric user ID of the current directory.
uid=$(ls -nd . | awk '{ print $3 }')
gid=$(ls -nd . | awk '{ print $4 }')
# If the current working directory is owned by root, that means we're running
# with plain-old docker, not docker-machine.
if [ "$uid" == "0" ]; then
uid=1000
gid=1000
fi
group_name=$(getent group $gid)
groupadd -g 1000 olympia
# Create an `olympia` user with that ID, and the current directory
# as its home directory.
if [ -z "$group_name" ]; then
useradd -Md $(pwd) -u $uid -g $gid -G olympia olympia
else
useradd -Md $(pwd) -u $uid -g $gid olympia
fi
if [ ! -d /deps ]; then
mkdir /deps
chown $uid:$gid /deps
fi
mkdir -p /var/run/supervisor
chown $uid:$gid /var/run/supervisor
chown $uid:$gid /var/run/uwsgi
# Switch to that user and execute our actual command.
exec su root -c 'exec "$@"' sh -- "$@"
| 7b9916786e42eeb329ab8b1248450fff9db15270 | [
"Shell",
"INI",
"Markdown",
"Git Config",
"YAML",
"Python"
] | 20 | Shell | MIKNOTAURO/djangocon-2016-demo | 3b7de543ee2d48c3ecdb93d18a177c0dea51273f | f84cd6d404c3e1b39f7aecb048042e0664ace7d7 |
refs/heads/master | <file_sep><h1>List#skuinput</h1>
<p>Find me in app/views/list/skuinput.html.erb</p>
<%= form_for(:sku_input, :url => {:action => 'list'} ) do |f|%>
<%= f.text_area(:lista_produtos) %>
<br>
<%= submit_tag("Enviar lista") %>
<% end %>
<file_sep>This is an app to create email newsletters<file_sep>class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.decimal "price", :precision => 10, :scale => 2
t.decimal "special_price", :precision => 10, :scale => 2
t.string "url"
t.string "image_url"
t.string "sprite_url"
t.string "brand"
t.string "product_name"
t.decimal "sales_1M", :precision => 20, :scale => 2
t.decimal "sales_3M", :precision => 20, :scale => 2
t.decimal "sales_6M", :precision => 20, :scale => 2
t.string "department"
t.string "sector"
t.string "family"
t.string "sub_family"
t.timestamps
end
add_index("products", "brand")
add_index("products", "department")
add_index("products", "sector")
add_index("products", "family")
add_index("products", "sub_family")
end
end
<file_sep>class ListController < ApplicationController
def skuinput
if params[:sku_input].class != NilClass
lista2 = params[:sku_input]
lista3 = params[:sku_input][:lista_produtos].split("\r\n")
query_string = "id IN (1"
lista3.each do |t|
query_string = "#{query_string}, #{t.to_s}"
end
query_string = "#{query_string})"
end
end
end
<file_sep>class ProjectItem < ActiveRecord::Base
attr_accessible :id, :classe, :product_id, :banner_id, :header_id, :project_id, :position, :created_at, :updated_at
belongs_to :banner
belongs_to :product
belongs_to :project
end
<file_sep>development:
adapter: mysql
encoding: utf8
database: crm_development
pool: 5
username: rubystack
password: <PASSWORD>
host: localhost
port: 3306
test:
adapter: mysql
database: crm_test
username: rubystack
password: <PASSWORD>
port: 3306
production:
adapter: mysql
database: crm_production
username: rubystack
password: <PASSWORD>
port: 3306<file_sep><script type="text/javascript">
$(document).ready(function() {
$(".sortable").sortable({
connectWith: '.sortable',
opacity: 0.4,
tolerance: 'pointer',
placeholder: 'place_holder',
helper: function(event, el) {
var myclone = el.clone();
$('body').append(myclone);
return myclone;
},
}).disableSelection();
});
</script>
<div style="width:1500px;">
<h1>Escolha os banners de categorias</h1>
<%= form_for(:shop_select, :url => {:action => 'shopselect'} ) do |f|%>
<%= submit_tag("Done!") %>
<% end %>
<div class='wrapper'>
<%= paginate @faixas %>
<ul id="faqs" class="sortable" style="min-height: 200px; width: 700px; list-style:none; float:left;">
<% @faixas.each do |t| %>
<li id="faq_bannerx<%= t.id %>" class="faq" style="margin-right:0px; float:left;">
<span class="handle">[drag]</span>
<div class = "banner">
<img class="image_banner" width="680" src="<%= t.banner_url.force_encoding('UTF-8') %>">
</div>
</li>
<% end %>
</ul>
<ul id="faqs2" class="sortable" data-update-url="http://localhost:3500/view/sort" style="border: 1px solid black; width: 700px; min-height: 600px; float:left; list-style:none;">
<% @projects.each do |t| %>
<% if t.classe == 'banner' %>
<li id="faq_bannerx<%= t.banner_id %>" class="faq" style="margin-right:0px; float:left;">
<span class="handle">[drag]</span>
<div class = "banner">
<img class="image_banner" width="680" src="<%= t.banner_url %>">
</div>
</li>
<% end %>
<% if t.classe == 'produto' %>
<li id="faq_produtox<%= t.product_id %>" class="faq" style="width:226px; float:left; margin-left:auto;margin-right:auto; text-align:center">
<div class="handle">[drag]</div>
<div class = "produto">
<% if not t.special_price.nil? %>
<!-- se tiver special price, retornar formato % -->
<div class="product-discount">
<%= (number_with_precision(100*(t.special_price.to_f / t.price.to_f - 1), :precision => 0)) %> %
</div>
<% else %>
<div style="height: 15px;"></div>
<% end %>
<a class="image-rotate lazyImage loaded" href="<%= t.url %>" data-src="<%= t.sprite_url.force_encoding('UTF-8') %>" onmouseover="catalog.initMouseMove($(this));">
<div class="product_image">
<img src="<%= t.image_url.force_encoding('UTF-8') %>" onload="catalog.lazyloadShow($(this));" onerror="catalog.onError($(this));" width="150" height="232">
</div>
</a>
<div class="prod-description">
<a class="product-description-catalog-item" href="<%= t.url.force_encoding('UTF-8') %>">
<strong><%= t.brand.force_encoding('UTF-8') %></strong>
- <%= t.product_name.force_encoding('UTF-8') %><br><br>
<% if not t.special_price.nil? %>
<strong>DE:</strong>
<span class="special-price">R$ <%= number_with_precision(t.price, :precision => 2) %></span>
<strong>POR:</strong> R$ <%= number_with_precision(t.special_price, :precision => 2) %>
<br>
<% else %>
<strong>POR:</strong> R$ <%= number_with_precision(t.price, :precision => 2) %>
<br>
<% end %>
</a>
</div>
</div>
</li>
<% end %>
<% end %>
</ul>
</div>
<%= @teste0 %>
</div>
<file_sep><h1>List#htmlfinal</h1>
<p>Find me in app/views/list/htmlfinal.html.erb</p>
<div style="width:1500px;">
<h1>HTML Final</h1>
<div class='wrapper'>
<div style="width:700px; min-height: 600px; float:left;font:14px Arial,Helvetica,sans-serif;">
<textarea rows="100" cols="80">
<% i=0 %>
<% @projects.each do |t| %>
<% link_i = "#{t.url}#{@tracking}" %>
<% if t.banner_link.nil? %>
<% link_banner = "nil" %>
<% else %>
<% link_banner = "#{t.banner_link}#{@tracking}" %>
<% end %>
<% proximo = 0 %>
<% if t.classe == 'banner' %>
<table width="680" border="0" cellpadding="0" cellspacing="0" align="center" style="color:#FFF; font-family:Arial, Helvetica, sans-serif; font-size:12px; text-align:center;">
<tr>
<td align="center">
<% if link_banner != "nil" %>
<a href="<%= link_banner %>">
<img src="<%= t.banner_url %>" width="680">
</a>
<% else %>
<img src="<%= t.banner_url %>" width="680">
<% end %>
</td>
</tr>
</table>
<% end %>
<% if t.classe == 'produto' %>
<% if i==0 %>
<table width="680" border="0" cellpadding="0" cellspacing="0" align="center" style="color:#FFF; font-family:Arial, Helvetica, sans-serif; font-size:12px; text-align:center;">
<tr>
<td width = "227" valign="top">
<!-- inner table, uma table dentro de cada celula inicial... -->
<table width="227" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<!-- special price -->
<% if not t.special_price.nil? %>
<td>
<span align="center" style="background-image: url(http://staticlocal.dafiti.com.br/cms/mkt/news/August2012/discount_background.png); background-repeat: no-repeat; color: white; display: block; float: none; font-family: Arial, Helvetica, sans-serif; font-size: 10px; font-style: normal; font-variant: normal; font-weight: bold; height: 16px; line-height: 16px; list-style-image: none; list-style-position: outside; list-style-type: none; margin-bottom: 0px; margin-left: 1px; margin-right: 0px; margin-top: 1px; width: 46px;">
<%= (number_with_precision(100*(t.special_price.to_f / t.price.to_f - 1), :precision => 0)) %> %
</span>
</td>
<% else %>
<td height="15">
</td>
<% end %>
</tr>
<tr>
<!-- imagem -->
<td align="center" height="232">
<a href="<%= link_i.gsub('www', @shop.to_s).force_encoding('UTF-8') %>">
<img src="<%= t.image_url.force_encoding('UTF-8') %>" width="160" height="232">
</a>
</td>
</tr>
<tr>
<!-- nome produto -->
<td align="center">
<a style="text-decoration:none" href="<%= link_i.gsub('www', @shop.to_s).force_encoding('UTF-8') %>">
<font color="#666"><span style="font-size:14px;color:#666;margin-left:auto; margin-top:10px;"><%= t.product_name.mb_chars.force_encoding('UTF-8') %>
</span></font><br>
<% if not t.special_price.nil? %>
<font color="#666"><span style="font-size:10px;color:#666;margin-left:auto; margin-top:10px;">DE: <strike>R$<%= number_with_precision(t.price, :precision => 2).to_s.gsub('.', ',') %></strike>
</span></font><br>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;">POR:</font>
<font color="#666"><span style="font-size:16px;color:#666;margin-left:auto; margin-top:10px;"><strong> R$ <%= number_with_precision(t.special_price, :precision => 2).to_s.gsub('.', ',') %></strong>
</span></font><br>
<% else %>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;">POR:</font>
<font color="#666"><span style="font-size:16px;color:#666;margin-left:auto; margin-top:10px;;"><strong> R$ <%= number_with_precision(t.price, :precision => 2).to_s.gsub('.', ',') %>
</strong></span></font><br>
<% end %>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;;"><strong>+ SHOP</strong></span></font>
</a>
<br>
<br>
</td>
</tr>
</table>
</td>
<% end %>
<% if i==1 %>
<td width = "227" valign="top">
<!-- inner table, uma table dentro de cada celula inicial... -->
<table width="227" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<!-- special price -->
<% if not t.special_price.nil? %>
<td>
<span align="center" style="background-image: url(http://staticlocal.dafiti.com.br/cms/mkt/news/August2012/discount_background.png); background-repeat: no-repeat; color: white; display: block; float: none; font-family: Arial, Helvetica, sans-serif; font-size: 10px; font-style: normal; font-variant: normal; font-weight: bold; height: 16px; line-height: 16px; list-style-image: none; list-style-position: outside; list-style-type: none; margin-bottom: 0px; margin-left: 1px; margin-right: 0px; margin-top: 1px; width: 46px;">
<%= (number_with_precision(100*(t.special_price.to_f / t.price.to_f - 1), :precision => 0)) %> %
</span>
</td>
<% else %>
<td height="15">
</td>
<% end %>
</tr>
<tr>
<!-- imagem -->
<td align="center" height="232">
<a href="<%= link_i.gsub('www', @shop.to_s).force_encoding('UTF-8') %>">
<img src="<%= t.image_url.force_encoding('UTF-8') %>" width="160" height="232">
</a>
</td>
</tr>
<tr>
<!-- nome produto -->
<td align="center">
<a style="text-decoration:none" href="<%= link_i.gsub('www', @shop.to_s).force_encoding('UTF-8') %>">
<font color="#666"><span style="font-size:14px;color:#666;margin-left:auto; margin-top:10px;"><%= t.product_name.mb_chars.force_encoding('UTF-8') %>
</span></font><br>
<% if not t.special_price.nil? %>
<font color="#666"><span style="font-size:10px;color:#666;margin-left:auto; margin-top:10px;">DE: <strike>R$<%= number_with_precision(t.price, :precision => 2).to_s.gsub('.', ',') %></strike>
</span></font><br>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;">POR:</font>
<font color="#666"><span style="font-size:16px;color:#666;margin-left:auto; margin-top:10px;"><strong> R$ <%= number_with_precision(t.special_price, :precision => 2).to_s.gsub('.', ',') %></strong>
</span></font><br>
<% else %>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;">POR:</font>
<font color="#666"><span style="font-size:16px;color:#666;margin-left:auto; margin-top:10px;;"><strong> R$ <%= number_with_precision(t.price, :precision => 2).to_s.gsub('.', ',') %>
</strong></span></font><br>
<% end %>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;;"><strong>+ SHOP</strong></span></font>
</a>
<br>
<br>
</td>
</tr>
</table>
</td>
<% end %>
<% if i==2 %>
<td width = "227" valign="top">
<!-- inner table, uma table dentro de cada celula inicial... -->
<table width="227" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<!-- special price -->
<% if not t.special_price.nil? %>
<td>
<span align="center" style="background-image: url(http://staticlocal.dafiti.com.br/cms/mkt/news/August2012/discount_background.png); background-repeat: no-repeat; color: white; display: block; float: none; font-family: Arial, Helvetica, sans-serif; font-size: 10px; font-style: normal; font-variant: normal; font-weight: bold; height: 16px; line-height: 16px; list-style-image: none; list-style-position: outside; list-style-type: none; margin-bottom: 0px; margin-left: 1px; margin-right: 0px; margin-top: 1px; width: 46px;">
<%= (number_with_precision(100*(t.special_price.to_f / t.price.to_f - 1), :precision => 0)) %> %
</span>
</td>
<% else %>
<td height="15">
</td>
<% end %>
</tr>
<tr>
<!-- imagem -->
<td align="center" height="232">
<a href="<%= link_i.gsub('www', @shop.to_s).force_encoding('UTF-8') %>">
<img src="<%= t.image_url.gsub('www', @shop.to_s).force_encoding('UTF-8') %>" width="160" height="232">
</a>
</td>
</tr>
<tr>
<!-- nome produto -->
<td align="center">
<a style="text-decoration:none" href="<%= link_i.gsub('www', @shop.to_s).force_encoding('UTF-8') %>">
<font color="#666"><span style="font-size:14px;color:#666;margin-left:auto; margin-top:10px;"><%= t.product_name.mb_chars.force_encoding('UTF-8') %>
</span></font><br>
<% if not t.special_price.nil? %>
<font color="#666"><span style="font-size:10px;color:#666;margin-left:auto; margin-top:10px;">DE: <strike>R$<%= number_with_precision(t.price, :precision => 2).to_s.gsub('.', ',') %></strike>
</span></font><br>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;">POR:</font>
<font color="#666"><span style="font-size:16px;color:#666;margin-left:auto; margin-top:10px;"><strong> R$ <%= number_with_precision(t.special_price, :precision => 2).to_s.gsub('.', ',') %></strong>
</span></font><br>
<% else %>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;">POR:</font>
<font color="#666"><span style="font-size:16px;color:#666;margin-left:auto; margin-top:10px;;"><strong> R$ <%= number_with_precision(t.price, :precision => 2).to_s.gsub('.', ',') %>
</strong></span></font><br>
<% end %>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;;"><strong>+ SHOP</strong></span></font>
</a>
<br>
<br>
</td>
</tr>
</table>
</td>
</tr>
</table>
<% end %>
<% if i==0 && proximo==0 %>
<% i=1 %>
<% proximo = 1 %>
<% end %>
<% if i==1 && proximo==0 %>
<% i=2 %>
<% proximo = 1 %>
<% end %>
<% if i==2 && proximo==0 %>
<% i=0 %>
<% proximo = 1 %>
<% end %>
<% end %>
<% end %>
</textarea>
</div>
<div style="border: 1px solid black; width: 700px; min-height: 600px; float:left">
<% i=0 %>
<% @projects.each do |t| %>
<% link_i = "#{t.url}#{@tracking}" %>
<% if t.banner_link.nil? %>
<% link_banner = "nil" %>
<% else %>
<% link_banner = "#{t.banner_link}#{@tracking}" %>
<% end %>
<% proximo = 0 %>
<% if t.classe == 'banner' %>
<table width="680" border="0" cellpadding="0" cellspacing="0" align="center" style="color:#FFF; font-family:Arial, Helvetica, sans-serif; font-size:12px; text-align:center;">
<tr>
<td align="center">
<% if link_banner != "nil" %>
<a href="<%= link_banner %>">
<img src="<%= t.banner_url %>" width="680">
</a>
<% else %>
<img src="<%= t.banner_url %>" width="680">
<% end %>
</td>
</tr>
</table>
<% end %>
<% if t.classe == 'produto' %>
<% if i==0 %>
<table width="680" border="0" cellpadding="0" cellspacing="0" align="center" style="color:#FFF; font-family:Arial, Helvetica, sans-serif; font-size:12px; text-align:center;">
<tr>
<td width = "227" valign="top">
<!-- inner table, uma table dentro de cada celula inicial... -->
<table width="227" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<!-- special price -->
<% if not t.special_price.nil? %>
<td>
<span align="center" style="background-image: url(http://staticlocal.dafiti.com.br/cms/mkt/news/August2012/discount_background.png); background-repeat: no-repeat; color: white; display: block; float: none; font-family: Arial, Helvetica, sans-serif; font-size: 10px; font-style: normal; font-variant: normal; font-weight: bold; height: 16px; line-height: 16px; list-style-image: none; list-style-position: outside; list-style-type: none; margin-bottom: 0px; margin-left: 1px; margin-right: 0px; margin-top: 1px; width: 46px;">
<%= (number_with_precision(100*(t.special_price.to_f / t.price.to_f - 1), :precision => 0)) %> %
</span>
</td>
<% else %>
<td height="15">
</td>
<% end %>
</tr>
<tr>
<!-- imagem -->
<td align="center">
<a href="<%= link_i.gsub('www', @shop.to_s).force_encoding('UTF-8') %>">
<img src="<%= t.image_url.force_encoding('UTF-8') %>" width="160" height="232">
</a>
</td>
</tr>
<tr>
<!-- nome produto -->
<td align="center">
<a style="text-decoration:none" href="<%= link_i.gsub('www', @shop.to_s).force_encoding('UTF-8') %>">
<font color="#666"><span style="font-size:14px;color:#666;margin-left:auto; margin-top:10px;"><%= t.product_name.mb_chars.force_encoding('UTF-8') %>
</span></font><br>
<% if not t.special_price.nil? %>
<font color="#666"><span style="font-size:10px;color:#666;margin-left:auto; margin-top:10px;">DE: <strike>R$<%= number_with_precision(t.price, :precision => 2).to_s.gsub('.', ',') %></strike>
</span></font><br>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;">POR:</font>
<font color="#666"><span style="font-size:16px;color:#666;margin-left:auto; margin-top:10px;"><strong> R$ <%= number_with_precision(t.special_price, :precision => 2).to_s.gsub('.', ',') %></strong>
</span></font><br>
<% else %>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;">POR:</font>
<font color="#666"><span style="font-size:16px;color:#666;margin-left:auto; margin-top:10px;;"><strong> R$ <%= number_with_precision(t.price, :precision => 2).to_s.gsub('.', ',') %>
</strong></span></font><br>
<% end %>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;;"><strong>+ SHOP</strong></span></font>
</a>
<br>
<br>
</td>
</tr>
</table>
</td>
<% end %>
<% if i==1 %>
<td width = "227" valign="top">
<!-- inner table, uma table dentro de cada celula inicial... -->
<table width="227" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<!-- special price -->
<% if not t.special_price.nil? %>
<td>
<span align="center" style="background-image: url(http://staticlocal.dafiti.com.br/cms/mkt/news/August2012/discount_background.png); background-repeat: no-repeat; color: white; display: block; float: none; font-family: Arial, Helvetica, sans-serif; font-size: 10px; font-style: normal; font-variant: normal; font-weight: bold; height: 16px; line-height: 16px; list-style-image: none; list-style-position: outside; list-style-type: none; margin-bottom: 0px; margin-left: 1px; margin-right: 0px; margin-top: 1px; width: 46px;">
<%= (number_with_precision(100*(t.special_price.to_f / t.price.to_f - 1), :precision => 0)) %> %
</span>
</td>
<% else %>
<td height="15">
</td>
<% end %>
</tr>
<tr>
<!-- imagem -->
<td align="center">
<a href="<%= link_i.gsub('www', @shop.to_s).force_encoding('UTF-8') %>">
<img src="<%= t.image_url.force_encoding('UTF-8') %>" width="160" height="232">
</a>
</td>
</tr>
<tr>
<!-- nome produto -->
<td align="center">
<a style="text-decoration:none" href="<%= link_i.gsub('www', @shop.to_s).force_encoding('UTF-8') %>">
<font color="#666"><span style="font-size:14px;color:#666;margin-left:auto; margin-top:10px;"><%= t.product_name.mb_chars.force_encoding('UTF-8') %>
</span></font><br>
<% if not t.special_price.nil? %>
<font color="#666"><span style="font-size:10px;color:#666;margin-left:auto; margin-top:10px;">DE: <strike>R$<%= number_with_precision(t.price, :precision => 2).to_s.gsub('.', ',') %></strike>
</span></font><br>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;">POR:</font>
<font color="#666"><span style="font-size:16px;color:#666;margin-left:auto; margin-top:10px;"><strong> R$ <%= number_with_precision(t.special_price, :precision => 2).to_s.gsub('.', ',') %></strong>
</span></font><br>
<% else %>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;">POR:</font>
<font color="#666"><span style="font-size:16px;color:#666;margin-left:auto; margin-top:10px;;"><strong> R$ <%= number_with_precision(t.price, :precision => 2).to_s.gsub('.', ',') %>
</strong></span></font><br>
<% end %>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;;"><strong>+ SHOP</strong></span></font>
</a>
<br>
<br>
</td>
</tr>
</table>
</td>
<% end %>
<% if i==2 %>
<td width = "227" valign="top">
<!-- inner table, uma table dentro de cada celula inicial... -->
<table width="227" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<!-- special price -->
<% if not t.special_price.nil? %>
<td>
<span align="center" style="background-image: url(http://staticlocal.dafiti.com.br/cms/mkt/news/August2012/discount_background.png); background-repeat: no-repeat; color: white; display: block; float: none; font-family: Arial, Helvetica, sans-serif; font-size: 10px; font-style: normal; font-variant: normal; font-weight: bold; height: 16px; line-height: 16px; list-style-image: none; list-style-position: outside; list-style-type: none; margin-bottom: 0px; margin-left: 1px; margin-right: 0px; margin-top: 1px; width: 46px;">
<%= (number_with_precision(100*(t.special_price.to_f / t.price.to_f - 1), :precision => 0)) %> %
</span>
</td>
<% else %>
<td height="15">
</td>
<% end %>
</tr>
<tr>
<!-- imagem -->
<td align="center">
<a href="<%= link_i.gsub('www', @shop.to_s).force_encoding('UTF-8') %>">
<img src="<%= t.image_url.gsub('www', @shop.to_s).force_encoding('UTF-8') %>" width="160" height="232">
</a>
</td>
</tr>
<tr>
<!-- nome produto -->
<td align="center">
<a style="text-decoration:none" href="<%= link_i.gsub('www', @shop.to_s).force_encoding('UTF-8') %>">
<font color="#666"><span style="font-size:14px;color:#666;margin-left:auto; margin-top:10px;"><%= t.product_name.mb_chars.force_encoding('UTF-8') %>
</span></font><br>
<% if not t.special_price.nil? %>
<font color="#666"><span style="font-size:10px;color:#666;margin-left:auto; margin-top:10px;">DE: <strike>R$<%= number_with_precision(t.price, :precision => 2).to_s.gsub('.', ',') %></strike>
</span></font><br>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;">POR:</font>
<font color="#666"><span style="font-size:16px;color:#666;margin-left:auto; margin-top:10px;"><strong> R$ <%= number_with_precision(t.special_price, :precision => 2).to_s.gsub('.', ',') %></strong>
</span></font><br>
<% else %>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;">POR:</font>
<font color="#666"><span style="font-size:16px;color:#666;margin-left:auto; margin-top:10px;;"><strong> R$ <%= number_with_precision(t.price, :precision => 2).to_s.gsub('.', ',') %>
</strong></span></font><br>
<% end %>
<font color="#666"><span style="font-size:12px;color:#666;margin-left:auto; margin-top:10px;;"><strong>+ SHOP</strong></span></font>
</a>
<br>
<br>
</td>
</tr>
</table>
</td>
</tr>
</table>
<% end %>
<% if i==0 && proximo==0 %>
<% i=1 %>
<% proximo = 1 %>
<% end %>
<% if i==1 && proximo==0 %>
<% i=2 %>
<% proximo = 1 %>
<% end %>
<% if i==2 && proximo==0 %>
<% i=0 %>
<% proximo = 1 %>
<% end %>
<% end %>
<% end %>
</div>
</div><file_sep> # encoding: utf-8
class ViewController < ApplicationController
def list
logger.debug "hahaha #{params.has_key?(:sku_input)}"
if params.has_key?(:sku_input)
logger.debug "entrou condicional"
lista = params[:sku_input][:lista_produtos].split("\r\n")
# insere na initial products
InitialProduct.destroy_all
lista.each_with_index do |t, index|
logger.debug t
logger.debug index
i = InitialProduct.new(:product_id => t, :position => index)
i.save
end
query_string = "products.id IN (1"
lista.each do |t|
query_string = "#{query_string}, #{t.to_s}"
end
query_string = "#{query_string})"
# initial product list
@initial_list = Product.all(:include => :initial_product, :conditions => [query_string], :order => 'initial_products.position')
prod_destroy = ProjectItem.where("project_id = 1")
prod_destroy.destroy_all
k = 1
@initial_list.each do |a|
i = ProjectItem.new(:position => k, :product_id => a.id.to_i, :classe => 'produto', :project_id => 1)
i.save
k = k + 1
end
end
# @project = ProjectItem.select("project_items.classe, products.price, products.special_price, products.url, products.image_url, products.brand, products.sprite_url, products.product_name").joins("inner join products on project_items.product_id = products.id")
@projects = ProjectItem.find_by_sql("select
project_items.classe,
project_items.product_id,
project_items.banner_id,
project_items.header_id,
products.price,
products.special_price,
products.url,
products.image_url,
products.brand,
products.sprite_url,
products.product_name,
banners.banner_url
from project_items
left join products
on project_items.product_id = products.id
left join banners
on project_items.banner_id = banners.id
order by position ASC")
@banners = Banner.where("tipo <> ?", 'categoria').order("created_at").page(params[:page]).per(10)
end
def sort
# method que salva posição atual via AJAX
# destroy all entries on current project_id
prod_destroy = ProjectItem.where("project_id = 1")
prod_destroy.destroy_all
# achei mais facil destruir tudo e criar do zero
params[:faq].each_with_index do |id, index|
temp = id.split("x") # usando x como split na construção do id
classe = temp[0]
valor = temp[1]
logger.debug "valor = #{valor}"
if classe == "produto"
i = ProjectItem.new(:position => index+1, :product_id => valor.to_i, :classe => classe, :project_id => 1)
i.save
end
if classe == "banner"
i = ProjectItem.new(:position => index+1, :banner_id => valor.to_i, :classe => classe, :project_id => 1)
i.save
end
end
render nothing: true
end
def skuinput
if params[:sku_input].class != NilClass
# teste para saber classes do form..
lista2 = params[:sku_input]
lista3 = params[:sku_input][:lista_produtos].split("\r\n")
query_string = "id IN (1"
lista3.each do |t|
query_string = "#{query_string}, #{t.to_s}"
end
query_string = "#{query_string})"
@teste = query_string
@teste2 = lista3
else
@teste = "lista2"
@teste2 = "lista3"
end
end
def show
# to fetch all user from 'users' table via "User" model
@faixas = Banner.where("tipo = ?", 'categoria').order("banner_url").page(params[:page]).per(10)
end
def faixas
@projects = ProjectItem.find_by_sql("select
project_items.classe,
project_items.product_id,
project_items.banner_id,
project_items.header_id,
products.price,
products.special_price,
products.url,
products.image_url,
products.brand,
products.sprite_url,
products.product_name,
banners.banner_url,
banners.banner_link
from project_items
left join products
on project_items.product_id = products.id
left join banners
on project_items.banner_id = banners.id
order by position ASC")
@faixas = Banner.where("tipo = ?", 'categoria').order("banner_url").page(params[:page]).per(10)
end
def shopselect
@projects = ProjectItem.find_by_sql("select
project_items.classe,
project_items.product_id,
project_items.banner_id,
project_items.header_id,
products.price,
products.special_price,
products.url,
products.image_url,
products.brand,
products.sprite_url,
products.product_name,
banners.banner_url,
banners.banner_link
from project_items
left join products
on project_items.product_id = products.id
left join banners
on project_items.banner_id = banners.id
order by position ASC")
@shopselect = Shop.all
end
def trackingselect
logger.debug "hehhehe #{params.has_key?(:shop)}"
@shop = params[:shop]
@tracking = Tracking.all
@projects = ProjectItem.find_by_sql("select
project_items.classe,
project_items.product_id,
project_items.banner_id,
project_items.header_id,
products.price,
products.special_price,
products.url,
products.image_url,
products.brand,
products.sprite_url,
products.product_name,
banners.banner_url,
banners.banner_link
from project_items
left join products
on project_items.product_id = products.id
left join banners
on project_items.banner_id = banners.id
order by position ASC")
end
def htmlfinal
@shop = params[:shop]
@tracking = params[:tracking]
@projects = ProjectItem.find_by_sql("select
project_items.classe,
project_items.product_id,
project_items.banner_id,
project_items.header_id,
products.price,
products.special_price,
products.url,
products.image_url,
products.brand,
products.sprite_url,
products.product_name,
banners.banner_url,
banners.banner_link
from project_items
left join products
on project_items.product_id = products.id
left join banners
on project_items.banner_id = banners.id
order by position ASC")
end
end
<file_sep>class CreateProjectItems < ActiveRecord::Migration
def change
create_table :project_items do |t|
t.string "classe"
t.integer "product_id"
t.integer "banner_id"
t.integer "project_id"
t.integer "header_id"
t.integer "position"
t.timestamps
end
add_index("project_items", "product_id")
add_index("project_items", "banner_id")
add_index("project_items", "project_id")
add_index("project_items", "header_id")
add_index("project_items", "position")
end
end
<file_sep>class InitialProduct < ActiveRecord::Base
attr_accessible :product_id, :position
belongs_to :product
end
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- saved from url=(0055)http://www.dafiti.com.br/calcados-masculinos/sapatenis/ -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt" lang="pt">
<head>
<%= stylesheet_link_tag('application', :media => 'all')%>
<%= javascript_include_tag('application') %>
</head>
<body>
<%= yield %>
</body>
</html>
| 3bb588f7f37327f656ee3fac3a30e2ee7afd3aa9 | [
"HTML+ERB",
"RDoc",
"Ruby",
"YAML"
] | 12 | HTML+ERB | rictagu/crm_email | 14c9ef707806a5ddf76e922c7196f6e98161c994 | b3584359fead27fbd3e74e14fbfcebaf144eecbd |
refs/heads/master | <file_sep>********************************************************************************
Gatsby
********************************************************************************
JAMstack: JavaScript, API, Markup stack
install: npm install -g gatsby-cli
create project: gatsby new project_name
run project: gastby develop (or npm start)
| 923ff902a620695c9da7caee8eab454520add5b0 | [
"Markdown"
] | 1 | Markdown | jacobzouzou/gatsby | 81aca559926b45fcc82de1ab29db413e94ee4729 | 34cc8eb2086f8cdcd12079168119bc664dad3028 |
refs/heads/master | <repo_name>amritpandey/DiceGame<file_sep>/index.js
var randomNumber1=Math.floor(Math.random()*6)+1;
var randomdDiceImage= "images/dice"+randomNumber1+".png";
var image1=document.querySelectorAll("img")[0];
image1.setAttribute("src",randomdDiceImage);
var randomNumber2=Math.floor(Math.random()*6)+1;
var randomDiceImage2="images/dice"+randomNumber2+".png";
var image2=document.querySelectorAll("img")[1];
image2.setAttribute("src",randomDiceImage2);
if(randomNumber1>randomNumber2){
document.getElementById("refresh").innerHTML="🚩 Player 1 wins"
}else if(randomNumber2===randomNumber1){
document.querySelector("h1").innerHTML="DRAW!!!";
}
else{
document.querySelector("h1").innerHTML="Player 2 wins 🚩";
}
| d90f5fa4a0bfea29504fd310db3cf4b64f487ac5 | [
"JavaScript"
] | 1 | JavaScript | amritpandey/DiceGame | f308c0ad4d5d198af264b563233861ee85d87c9f | caa773b2588945f91fea69f770ff5c7a2cd25666 |
refs/heads/master | <file_sep># scrapy
Practice using scrapy python framework for websraping
This consist of mainly the tutorial source code and a few basics
| bd95438c5b2e6ff297c43efe159b9d9f5a2b850f | [
"Markdown"
] | 1 | Markdown | jhon-swai/webScraping | 4d9d6ffb7e6952009cc61ee46552d96ccbe806b2 | 7f1342e58a0c1c48cc4387d7e5acececf8d7d2a7 |
refs/heads/master | <repo_name>sandersnewmedia/generator-react-webapp<file_sep>/app/templates/server.js
var opbeat = require('opbeat').start()
var express = require('express');
var fs = require('fs');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var csrf = require('csurf');
var csrfProtection = csrf({ cookie: true});
var helmet = require('helmet');
require('node-jsx').install({ extension: '.jsx' });
require('babel-core/register')({});
var manifest;
if (process.env.NODE_ENV !== 'development') {
manifest = JSON.parse(fs.readFileSync('dist/manifest.json'));
} else {
manifest = {
'bundle.js': 'bundle.js',
'bundle.css': 'bundle.css'
};
}
var server = express();
if (process.env.NODE_ENV !== 'development') {
server.use(helmet.hsts({
maxAge: 10886400000,
includeSubdomains: true,
force: true
}));
server.use(helmet.xssFilter())
server.use(helmet.frameguard())
server.use(helmet.hidePoweredBy())
}
server.use('/assets', express.static(path.join(__dirname, 'dist')));
server.use(bodyParser.json());
server.use(cookieParser());
server.use(opbeat.middleware.express());
server.set('views', __dirname + '/src/views');
server.set('view engine', 'jade');
server.get("*", function(req, res) {
return res.render('index', {
bundlePath: '/assets/' + manifest[process.env.BUNDLE],
cssPath: '/assets/' + manifest[process.env.CSS_BUNDLE],
csrf: req.csrfToken && req.csrfToken()
});
});
var port = process.env.PORT;
server.listen(port, function() {
console.log('listening on port ' + port);
});
<file_sep>/app/templates/src/scss/app.scss
// Make sure the charset is set appropriately
@charset "UTF-8";
//Bootstrap
@import "~bootstrap-sass/assets/stylesheets/bootstrap/variables";
@import "base/variables";
@import "~bootstrap-sass/assets/stylesheets/bootstrap";<file_sep>/app/templates/webpack.prod.config.js
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var ManifestPlugin = require('webpack-manifest-plugin');
//postcss plugins
var autoprefixer = require('autoprefixer');
var cssnano = require('cssnano');
module.exports = {
entry: {
bundle: 'index.jsx'
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/assets/',
filename: '[name].[chunkhash:8].js'
},
resolve: {
modulesDirectories: ['node_modules', 'src/app', 'scss', 'src'],
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['babel']
},
{
test: /\.scss?$/,
loader: ExtractTextPlugin.extract('css!postcss!sass')
},
{
test: /\.(png|woff|woff2|eot|ttf|svg|otf|jpg)(\?[a-z0-9=\.]+)?$/,
loader: 'url-loader?limit=100000'
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compress: {
warnings: false
}
}),
new ExtractTextPlugin('style.[contenthash:8].css', {
allChunks: true
}),
new webpack.DefinePlugin({
'process.env': Object.keys(process.env).reduce(function(o, k) {
o[k] = JSON.stringify(process.env[k]);
return o;
}, {})
}),
new ManifestPlugin()
]
};
<file_sep>/app/templates/README.md
# <%= projectname %>
---
## The Stack
- Language: Node.js v6.0.x
- Framework: [React](http://facebook.github.io/react/) + [Flux](https://facebook.github.io/flux/)
- Testing Framework: Mocha + Chai
- Dependency Manager: npm v3.8.x
### Recommended Reading
* [Node](https://nodejs.org/)
* [Webpack](https://webpack.github.io/)
* [React-Router](https://github.com/rackt/react-router)
* [React-Router-Redux](https://github.com/rackt/react-router-redux)
* [Axios](https://github.com/mzabriskie/axios)
* [ESLint](https://medium.com/@dan_abramov/lint-like-it-s-2015-6987d44c5b48)
* [Mocha](https://github.com/mochajs/mocha)
* [Chai](https://github.com/chaijs/chai)
---
## Getting Started
clone the project
cd into app directory
npm install
## Run It
### development
For local dev environments, we use `webpack-dev-server`.
npm run watch
Access it at http://localhost:8081.
### production
npm run build && foreman start
By default, the app will run on port 9966.
## Test It
Run tests:
npm run test
## Deploy It
### staging
git push staging
### production
git push production
---
<file_sep>/app/templates/src/app/components/common/header.jsx
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux'
import {Navbar, Nav, NavItem} from 'react-bootstrap';
import {Link, browserHistory} from 'react-router';
class Header extends Component {
render() {
return (
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<a><h1>Welcome</h1></a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem>Home</NavItem>
</Nav>
<Nav pullRight>
<NavItem>Cart</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
)
}
}
export default Header;
<file_sep>/app/templates/src/app/actions/auth.js
export const authLogin = () => ({
type: 'AUTH_LOGIN'
});
<file_sep>/app/templates/src/app/reducers/index.js
import { combineReducers } from 'redux';
import auth from './auth';
import {routerReducer} from 'react-router-redux';
export default combineReducers({
auth,
routing: routerReducer
});
<file_sep>/app/templates/Procfile
web: NODE_PATH=$NODE_PATH:$NODE_APP_PATH node server.js
<file_sep>/app/templates/src/views/index.jade
doctype html
html
head
meta(charset='UTF-8', name='viewport', content='width=device-width')
title <%= projectname %>
link(rel='stylesheet', media='screen', href!= cssPath)
link(rel='icon', href='/assets/favicon.ico', type='image/x-icon')
body
#main
script(src!= bundlePath)
input(type='hidden', name='_csrf', value!= csrf)
<file_sep>/app/index.js
'use strict';
var file = require('file');
var path = require('path');
var generators = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var mkdirp = require('mkdirp');
var _ = require('lodash');
var jsesc = require('jsesc');
function jsonEscape(str) {
return jsesc(str, {quotes: 'double'});
}
module.exports = generators.Base.extend({
initializing: function() {
this.pkg = require('../package.json');
this.dirname = path.basename(this.destinationRoot());
this.dirnameNoJs = path.basename(this.dirname, '.js');
this.dirnameWithJs = this.dirnameNoJs + '.js';
},
prompting: function() {
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the ' + chalk.red('React Webapp') + ' generator!'
));
const gitName = this.user.git.name();
const gitEmail = this.user.git.email();
let defaultAuthor = gitName ? gitName : '';
if (gitEmail) {
defaultAuthor += ` <${gitEmail}>`;
}
var prompts = [{
type: 'input',
name: 'user',
message: 'What is the Github username/organization for this project?',
store: true
}, {
type: 'input',
name: 'repo',
message: 'What is the repository/project name?',
// This default works when the directory was generated from a cloned
// repository, or when the user intends to make a repo with the same
// name as the directory. We assume this is the most common situation.
default: this.dirname
}, {
type: 'input',
name: 'description',
message: 'What is a short description for this project?'
}, {
type: 'input',
name: 'author',
message: 'Who is the author of this project?',
default: defaultAuthor,
store: true
}, {
type: 'input',
name: 'projectname',
message: 'What is the name of the project?',
default: _.camelCase(this.dirnameNoJs)
}];
var self = this;
return self.prompt(prompts)
.then(function(props) {
self.user = jsonEscape(props.user);
self.repo = jsonEscape(props.repo);
// A good candidate for the module name is the directory, which we assume
// to be derived from the repository name, stripped of any `.js` extension.
// The extension is stripped per the "tips" section of the npm docs:
// https://docs.npmjs.com/files/package.json#name
self.moduleName = jsonEscape(self.dirnameNoJs.toLowerCase());
// The mainFile, on the other hand, must always have an extension. Once
// again we derive this from the name of the directory.
self.fileName = jsonEscape(self.dirnameWithJs.toLowerCase());
self.description = jsonEscape(props.description);
self.author = jsonEscape(props.author);
self.projectname = props.projectname;
});
},
writing: {
app: function() {
var self = this;
self.directory(self.templatePath('src'), self.destinationPath('src'));
self.directory(self.templatePath('test'), self.destinationPath('test'));
self.fs.copyTpl(self.templatePath('_package.json'),
self.destinationPath('package.json'), self);
self.fs.copyTpl(self.templatePath('server.js'),
self.destinationPath('server.js'), self);
self.template('.babelrc', '.babelrc')
self.template('.eslintignore', '.eslintignore')
self.template('.gitignore', '.gitignore')
self.template('.scss-lint.yml', '.scss-lint.yml')
self.template('.travis.yml', '.travis.yml')
self.template('Procfile', 'Procfile')
self.template('.env', '.env')
self.fs.copyTpl(self.templatePath('README.md'),
self.destinationPath('README.md'), self);
self.fs.copyTpl(self.templatePath('webpack.config.js'),
self.destinationPath('webpack.config.js'), self);
self.fs.copyTpl(self.templatePath('webpack.prod.config.js'),
self.destinationPath('webpack.prod.config.js'), self);
}
},
install: function() {
this.installDependencies({
bower: false,
npm: true,
skipInstall: this.options['skip-install']
});
}
});
<file_sep>/app/templates/src/app/reducers/auth.js
export const defaultState = {
token: null,
email: null,
error: null
};
export default (state = defaultState, action) => {
let newState = Object.assign({}, state);
switch (action.type) {
case 'AUTH_RESPONSE':
newState.token = action.payload.token;
newState.email = action.payload.email;
newState.error = null;
return newState;
case 'AUTH_ERROR':
newState.token = null;
newState.error = action.error;
return newState;
case 'AUTH_REQUEST':
newState.token = null;
newState.email = null;
return newState;
default:
return state;
}
};
<file_sep>/app/templates/src/app/stores/configure-store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import { browserHistory } from 'react-router';
import { routerMiddleware } from 'react-router-redux';
import rootReducer from 'reducers/index';
const router = routerMiddleware(browserHistory)
const logger = createLogger({
predicate: () => process.env.NODE_ENV == 'development',
logger: console
});
const createStoreWithMiddleware = applyMiddleware(thunk, logger, router)(createStore);
export default function configureStore(initialState) {
return createStoreWithMiddleware(rootReducer, initialState);
}
| 870a14a41648b9e2d09e5bc4b688d0a052989242 | [
"SCSS",
"Markdown",
"Procfile",
"JavaScript",
"Pug"
] | 12 | SCSS | sandersnewmedia/generator-react-webapp | d313cb97fb9388fe088b397a78a61426990f3403 | 8cb2f70101e54dd764d4afb9cc2b67a0c3f6913f |
refs/heads/master | <repo_name>jianzonggaoshou/dzdpAutoScript<file_sep>/dzdp_test1.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import re
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://account.dianping.com")
time.sleep(1)
frame_xpath = driver.find_element(By.XPATH, '//*[@id="J_login_container"]/div/iframe')
driver.switch_to.frame(frame_xpath)
time.sleep(1)
driver.implicitly_wait(20)
el = driver.find_element(By.XPATH, '/html/body/div/div[2]/div[5]/span')
el.click()
driver.implicitly_wait(20)
el = driver.find_element(By.ID, 'mobile-number-textbox')
#el.send_keys('17782629431')
el.send_keys('15609100803')
driver.implicitly_wait(20)
el = driver.find_element(By.ID, 'send-number-button')
el.click()
verification_code = input("请输入手机上的动态验证码:")
verification_code = str(verification_code)
driver.implicitly_wait(20)
el = driver.find_element(By.ID, 'number-textbox')
el.send_keys(verification_code)
driver.implicitly_wait(20)
el = driver.find_element(By.ID, 'login-button-mobile')
el.click()
#霸王餐
driver.implicitly_wait(20)
el = driver.find_element(By.XPATH, '//*[@id="header-container"]/div[3]/div[1]/div/a[2]')
el.click()
#切换到霸王餐页面
time.sleep(1)
all_hand = driver.window_handles
print(all_hand)
driver.switch_to.window(all_hand[-1])
#美食
time.sleep(1)
driver.implicitly_wait(20)
el_num = driver.find_element(By.XPATH, '//*[@id="s-fix"]/div[2]/div[1]/div[2]/span')
el_num.click()
#电子券
driver.implicitly_wait(20)
el = driver.find_element(By.XPATH, '//*[@id="filter-types"]/div[3]')
el.click()
#加载更多
driver.implicitly_wait(20)
el = driver.find_element(By.XPATH, '/html/body/div[2]/div[2]/div[2]/div[2]/a')
el.click()
#获得循环总数--美食数量
time.sleep(1)
patten = re.compile(r'\d+')
result = patten.findall(el_num.text)
print(el_num.text)
print(result)
result = int(result[0])
print(result)
#循环阶段
#具体图片链接-li元素自增
for i in range(1, result):
time.sleep(1)
driver.implicitly_wait(20)
locator = (By.XPATH, '/html/body/div[2]/div[2]/div[2]/div[2]/ul/li[%s]/a/div[1]/img' %i)
WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
el = driver.find_element(By.XPATH, '/html/body/div[2]/div[2]/div[2]/div[2]/ul/li[%s]/a/div[1]/img' %i)
print('/html/body/div[2]/div[2]/div[2]/div[2]/ul/li[%s]/a/div[1]/img' %i)
el.click()
print('正在点击第%s个图片' %i)
#切换到具体美食页面
time.sleep(1)
all_hand = driver.window_handles
print(all_hand)
driver.switch_to.window(all_hand[-1])
#判断【我要报名】还是【修改报名】
time.sleep(1)
driver.implicitly_wait(20)
locator = (By.XPATH, '/html/body/div[3]/div[1]/div[2]/div[2]/span/a')
WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
el = driver.find_element(By.XPATH, '/html/body/div[3]/div[1]/div[2]/div[2]/span/a')
isSign = el.text
if '我要报名' in isSign:
driver.implicitly_wait(20)
el.click()
#确认
time.sleep(1)
driver.implicitly_wait(20)
locator = (By.ID, 'J_pop_ok')
WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
el = driver.find_element(By.ID, 'J_pop_ok')
el.click()
#点击关闭
time.sleep(1)
driver.implicitly_wait(20)
el = driver.find_element(By.XPATH, '/html/body/div[6]/div[2]/div[1]/a')
el.click()
#关闭当前tab页面
time.sleep(1)
driver.close()
time.sleep(1)
all_hand = driver.window_handles
print(all_hand)
driver.switch_to.window(all_hand[-1])
else:
time.sleep(1)
driver.close()
time.sleep(1)
all_hand = driver.window_handles
print(all_hand)
driver.switch_to.window(all_hand[-1])
time.sleep(10) | b0cd604123a6de9ce4a9beadfab9d22c649a8361 | [
"Python"
] | 1 | Python | jianzonggaoshou/dzdpAutoScript | cacf6a4f6f0e6bb383443cd2ce3917b6a4686c79 | a9969e6f04bcf7d27fafde55ff51bef496e2f487 |
refs/heads/main | <file_sep>
module.exports = {
name: "coinflip",
description: "This is a coinflip command!",
execute(message, args, Discord, client){
let choice = Math.floor(Math.random() * 2)
if(choice === 0) return message.reply('It was heads!')
if(choice === 1) return message.reply('It was tails!')
}
}<file_sep>const { MessageEmbed } = require('discord.js');
const somethingRandom = require('some-random-cat').Random
const subreddits = [
"meme",
"memes",
"dankmemes"
]
module.exports = {
name: "meme",
description: "This is a meme command!",
execute(message, args, Discord, client){
let randomSubReddit = subreddits[Math.floor(Math.random() * subreddits.length)]
somethingRandom.getMeme(randomSubReddit).then(res => {
const embed = new MessageEmbed()
.setTitle(res.title)
.setURL(`https://www.reddit.com/r/${randomSubReddit}`)
.setImage(res.img)
.setFooter(`👍 ${res.upvotes} | 💬 ${res.comments}`)
.setAuthor(`From u/${res.author}`)
.setColor('RANDOM')
message.channel.send(embed)
console.log(res)
}).catch(e => message.channel.send('API Error.'))
}
}<file_sep>const time = require('ms')
let os = require ('os').platform();;
let cpu = require ('os').cpus()[0].model;;
module.exports = {
name: "botstats",
description: "This is a botstats command!",
execute(message, args, Discord, client){
let inline = true
const uptime = time(client.uptime)
message.channel.send('These are my statistics.')
const Embed = new Discord.MessageEmbed()
.addField("My Latency is:", `> ${Date.now() - message.createdTimestamp}ms`)
.addField("My API Latency is:", `> ${Math.round(client.ws.ping)}ms`)
.addField("My OS is:", `> ${os}`)
.setColor("RANDOM")
.setThumbnail("https://media.discordapp.net/attachments/798594125712326737/808783195940192296/b67e65c2ab0428da786c1f53ebfd4243.png")
.addField('I have been up for:', `> ${uptime}`)
.addField("My CPU is:", `> ${cpu}`)
message.channel.send(Embed);
}
}
<file_sep>module.exports = {
name: "ping",
description: "This is a ping command!",
execute(message, args, Discord, client){
message.channel.send('Pong!')
const Embed = new Discord.MessageEmbed()
.addField("My Latency is:", `> ${Date.now() - message.createdTimestamp}ms`)
.setColor("RANDOM")
.setThumbnail('https://media.discordapp.net/attachments/798594125712326737/808933236507017236/ff8c49a85b7fbda0110c66353a9db71e.png')
message.channel.send(Embed);
}
}
<file_sep># Discord.JS, Open-Source, Free to Use Bot
## Introduction
> This bot was made with the idea that people should be able to have a great starting point went making a Discord.JS bot.
## Credit
> All credit goes to @OnlyTense (me) for this repository although not all code is mine.
| 35979f6039183658be5ba72646aab537b09af1d1 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | OnlyTense/DiscordJS-Bot | b12ea3762ca01a031175404c2136bb9342207803 | b920e723db25c7715fa9cc6e1fce32bad0057b92 |
refs/heads/master | <repo_name>ataraciuk/massap<file_sep>/www/js/index.js
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
var music = $('#music');
for(song in app.music) {
music.append('<option value="'+song+'">'+app.music[song].display+'</option>');
}
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
$('#go').click(function(e){
e.preventDefault();
var vibrateT = parseInt($('#vibrateT').val(),10) * 1000;
var waitT = parseInt($('#waitT').val(),10) * 1000;
if(vibrateT > 0 && waitT > 0) {
app.vibrateInterval = setInterval(function(){
navigator.notification.vibrate(vibrateT);
}, vibrateT + waitT);
var wakeT = parseInt($("#restT").val(),10) * 60000;
app.remaining = wakeT;
if(wakeT > 0) app.wakeTimeout = setTimeout(app.playAlarm, wakeT);
$(".remainingMsg").toggle(wakeT > 0);
var intTime = 1000;
app.setInfo();
app.wakeInterval = setInterval(function(){
app.remaining -= intTime;
app.setInfo();
}, intTime);
$('.menu, .onMassage').toggle();
}
else {
if(vibrateT <= 0 || isNaN(vibrateT)) $('#vibrateT').addClass('error');
if(waitT <= 0 || isNaN(waitT)) $('#waitT').addClass('error');
}
});
$('#stop').click(function(e){
e.preventDefault();
app.reset();
})
$('input[type="text"]').focus(function(e){
$(this).removeClass('error');
});
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
console.log('Received Event: ' + id);
},
reset: function() {
console.log('reset');
window.clearInterval(app.vibrateInterval);
window.clearTimeout(app.wakeTimeout);
window.clearInterval(app.wakeInterval);
app.vibrateInterval = null;
app.wakeTimeout = null;
app.wakeInterval = null;
remaining = null;
var stream = document.getElementById('stream');
try{
if(app.media){
app.loopMedia = false;
app.media.stop;
app.media.release();
}else{
stream.pause();
stream.currentTime = 0;
}
}catch(e){}
$('.menu, .onMassage').toggle();
},
setInfo: function() {
$('#minRemaining').html(Math.floor(app.remaining / 60000));
$(".currentDate").html(new Date());
},
vibrateInterval: null,
wakeTimeout: null,
wakeInterval: null,
remaining: null,
music: {
gong : {path: 'gong.mp3', display: 'Gong'},
beep: {path: 'alarmClock.mp3', display: 'Beep alarm'},
ring: {path: 'analogAlarm.mp3', display: 'Old alarm'}
},
playAlarm: function() {
var currentMedia = app.getCurrentMusic();
if(currentMedia) {
if(typeof Media !== 'undefined') {
app.loopMedia = true;
app.media = new Media('http://ataraciuk.github.io/massap/www/mp3/'+app.music[currentMedia].path,
function(){}, function(){},function(status){
if(status == Media.MEDIA_STOPPED && app.loopMedia) app.media.play();
});
app.media.play();
} else {
$('source').attr('src', 'http://ataraciuk.github.io/massap/www/mp3/'+app.music[currentMedia].path);
var stream = document.getElementById('stream');
stream.load();
stream.play();
}
}
},
getCurrentMusic: function() {
return $('#music').val();
},
media: null,
loopMedia: false
};
| 0f2bcac7ff3772277ba1c0b8662b67fa55dfb8fc | [
"JavaScript"
] | 1 | JavaScript | ataraciuk/massap | ce2662690d123dcb34dacc2ced53e0e2be80783d | 898e8ed45cd50ab08b827e38e1f1912c84016de1 |
refs/heads/master | <repo_name>Rektzie/ITF-Lab<file_sep>/README.md
# ITF-Lab 2018
## Author
<NAME> 61070246
| cdc56315f943991c43d7357f244fca7ec95c68f3 | [
"Markdown"
] | 1 | Markdown | Rektzie/ITF-Lab | d0f80eb7496c06a4bc6e14838f929442440a3474 | ea1610031e204210446eeaa40ad4151729ec7b43 |
refs/heads/master | <repo_name>huicongfu/FHCHUD<file_sep>/FHCHUD/FHCHUD/FHCHUD/FHCHUD.h
//
// FHCHUD.h
// FHCHUD
//
// Created by hunuo on 16/9/24.
// Copyright © 2016年 fhc. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger, FHCHUDMode){
/**
* 默认值是菊花动画模式
*/
FHCHUDModeIndicator,
/**
* 只显示标题
*/
FHCHUDModeText
};
@interface FHCHUD : UIView
@property (nonatomic, assign) FHCHUDMode mode;
@property (nonatomic, retain) NSString * labelText;
- (instancetype)initWithView:(UIView *)view;
- (void)show;
- (void)hide;
@end
<file_sep>/FHCHUD/FHCHUD/ViewController.m
//
// ViewController.m
// FHCHUD
//
// Created by hunuo on 16/9/24.
// Copyright © 2016年 fhc. All rights reserved.
//
#import "ViewController.h"
#import "FHCHUD.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
FHCHUD * mode = [[FHCHUD alloc] initWithView:self.view];
[self.view addSubview:mode];
mode.labelText = @"hello world!";
mode.mode = FHCHUDModeText;
[mode show];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
<file_sep>/README.md
# FHCHUD
learn from MBProgressHUD
![image](https://github.com/huicongfu/FHCHUD/blob/master/FHCHUD/Screen%20Shot/Simulator%20Screen%20Shot%202016%E5%B9%B49%E6%9C%8827%E6%97%A5%20%E4%B8%8B%E5%8D%883.35.00.png)
![image](https://github.com/huicongfu/FHCHUD/blob/master/FHCHUD/Screen%20Shot/Simulator%20Screen%20Shot%202016%E5%B9%B49%E6%9C%8827%E6%97%A5%20%E4%B8%8B%E5%8D%883.50.51.png)
| 836f6b3113b961b8c4c2253c97236542e62f1ff7 | [
"Markdown",
"Objective-C"
] | 3 | Markdown | huicongfu/FHCHUD | 351747d04e019bd1c2c886a290f8a744739ed373 | 0c05ddf0be4fdb2f1edd0181e51afdbfc2d3b00c |
refs/heads/main | <file_sep>#Mon Aug 09 16:12:58 ICT 2021
org.eclipse.core.runtime=2
org.eclipse.platform=4.20.0.v20210611-1600
| 654ea59727b47bdf580a6befb1f0621e4ad10f3d | [
"INI"
] | 1 | INI | CHETcica/LooseCoupling | 2647e92dc341002bff754e33ddf44454d0f55c32 | 38370151f172504bddc8fc2b3b638e50cb7fbd4f |
refs/heads/master | <file_sep>#include "Game/Camera2D.hpp"
#include "Game/Tank.hpp"
Camera2D::Camera2D(Tank* Player)
: m_Player(Player)
, m_screenSize(16.f, 9.f)
, m_cameraCenteredOnScreenPosition(m_screenSize.x * 0.5f, m_screenSize.y * 0.2f)
, m_previousPlayerOrientation(0.f)
, m_previousPlayerPosition(0.f, 0.f)
, m_shouldUpdate(true)
{
}
Camera2D::~Camera2D()
{
}
void Camera2D::Update(float deltaTime)
{
UNUSED(deltaTime);
if (m_shouldUpdate)
{
m_previousPlayerPosition = m_Player->GetPosition();
m_previousPlayerOrientation = m_Player->GetOrientation();
}
}
void Camera2D::Render() const
{
TheRenderer::instance->SetOrtho(Vector2(0.f, 0.f), m_screenSize);
TheRenderer::instance->Translate(m_cameraCenteredOnScreenPosition);
TheRenderer::instance->Rotate(-(m_previousPlayerOrientation - 90.f));
TheRenderer::instance->Translate(m_previousPlayerPosition * -1.0f);
}
void Camera2D::ShouldUpdate(bool shouldUpdate)
{
m_shouldUpdate = shouldUpdate;
}
void Camera2D::FollowPlayer(Tank* player)
{
m_Player = player;
}
<file_sep>#include "Engine/Renderer/TheRenderer.hpp"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <gl/gl.h>
#include <math.h>
#include "Engine/Math/Vector2.hpp"
#include "Engine/Math/MathUtils.hpp"
#include "Engine/Renderer/AABB2.hpp"
#include "Engine/Renderer/RGBA.hpp"
#include "Engine/Renderer/Texture.hpp"
#pragma comment( lib, "opengl32" ) // Link in the OpenGL32.lib static library
TheRenderer* TheRenderer::instance = nullptr;
TheRenderer::TheRenderer()
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_LINE_SMOOTH);
}
void TheRenderer::ClearScreen(float red, float green, float blue)
{
glClearColor(red, green, blue, 1.f);
glClear(GL_COLOR_BUFFER_BIT);
}
void TheRenderer::ClearScreen(const RGBA& color)
{
glClearColor(color.red, color.green, color.blue, color.alpha);
glClear(GL_COLOR_BUFFER_BIT);
}
void TheRenderer::SetOrtho(const Vector2& bottomLeft, const Vector2& topRight)
{
glLoadIdentity();
glOrtho(bottomLeft.x, topRight.x, bottomLeft.y, topRight.y, 0.f, 1.f);
}
void TheRenderer::DrawPoint(float x, float y)
{
glBegin(GL_POINTS);
{
glVertex2f(x, y);
}
glEnd();
}
void TheRenderer::DrawPoint(const Vector2& point)
{
DrawPoint(point.x, point.y);
}
void TheRenderer::DrawLine(const Vector2& start, const Vector2& end, float lineThickness)
{
glLineWidth(lineThickness);
glBegin(GL_LINES);
{
glVertex2f(start.x, start.y);
glVertex2f(end.x, end.y);
}
glEnd();
}
void TheRenderer::DrawLines(Vector2* const* verts, int numVerts, float lineThickness)
{
glLineWidth(lineThickness);
glBegin(GL_LINES);
{
for (int i = 0; i < numVerts; i++)
{
glVertex2f(verts[i]->x, verts[i]->y);
}
}
glEnd();
}
void TheRenderer::SetColor(float red, float green, float blue, float alpha)
{
glColor4f(red, green, blue, alpha);
}
void TheRenderer::SetColor(const RGBA& color)
{
glColor4f(color.red, color.green, color.blue, color.alpha);
}
void TheRenderer::SetPointSize(float size)
{
glPointSize(size);
}
void TheRenderer::PushMatrix()
{
glPushMatrix();
}
void TheRenderer::PopMatrix()
{
glPopMatrix();
}
void TheRenderer::Translate(float x, float y, float z)
{
glTranslatef(x, y, z);
}
void TheRenderer::Translate(const Vector2& xy)
{
glTranslatef(xy.x, xy.y, 0.0f);
}
void TheRenderer::Rotate(float rotationDegrees)
{
glRotatef(rotationDegrees, 0.f, 0.f, 1.f);
}
void TheRenderer::Rotate(float rotationDegrees, float x, float y, float z)
{
glRotatef(rotationDegrees, x, y, z);
}
void TheRenderer::Scale(float x, float y, float z)
{
glScalef(x, y, z);
}
void TheRenderer::DrawPolygonOutline(const Vector2& center, float radius, int numSides, float radianOffset)
{
const float radiansTotal = 2.0f * MathUtils::pi;
const float radiansPerSide = radiansTotal / numSides;
glBegin(GL_LINE_LOOP);
{
for (float radians = 0.0f; radians < radiansTotal; radians += radiansPerSide)
{
float adjustedRadians = radians + radianOffset;
float x = center.x + (radius * cos(adjustedRadians));
float y = center.y + (radius * sin(adjustedRadians));
glVertex2f(x, y);
}
}
glEnd();
}
void TheRenderer::DrawPolygon(const Vector2& center, float radius, int numSides, float radianOffset)
{
const float radiansTotal = 2.0f * MathUtils::pi;
const float radiansPerSide = radiansTotal / numSides;
glBegin(GL_POLYGON);
{
for (float radians = 0.0f; radians < radiansTotal; radians += radiansPerSide)
{
float adjustedRadians = radians + radianOffset;
float x = center.x + (radius * cos(adjustedRadians));
float y = center.y + (radius * sin(adjustedRadians));
glVertex2f(x, y);
}
}
glEnd();
}
void TheRenderer::DrawLineLoop(Vector2* const* verts, int numVerts, float lineThickness)
{
glLineWidth(lineThickness);
glBegin(GL_LINE_LOOP);
{
for (int i = 0; i < numVerts; i++)
{
glVertex2f(verts[i]->x, verts[i]->y);
}
}
glEnd();
}
void TheRenderer::DrawAABB(const AABB2& bounds, const RGBA& color)
{
SetColor(color);
glBegin(GL_QUADS);
{
glVertex2f(bounds.mins.x, bounds.mins.y);
glVertex2f(bounds.maxs.x, bounds.mins.y);
glVertex2f(bounds.maxs.x, bounds.maxs.y);
glVertex2f(bounds.mins.x, bounds.maxs.y);
}
glEnd();
}
void TheRenderer::DrawTexturedAABB(const AABB2& bounds, const Vector2& texCoordMins, const Vector2& texCoordMaxs, const Texture& texture, const RGBA& color)
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture.m_openglTextureID);
SetColor(color);
glBegin(GL_QUADS);
{
glTexCoord2f(texCoordMins.x, texCoordMins.y);
glVertex2f(bounds.mins.x, bounds.mins.y);
glTexCoord2f(texCoordMaxs.x, texCoordMins.y);
glVertex2f(bounds.maxs.x, bounds.mins.y);
glTexCoord2f(texCoordMaxs.x, texCoordMaxs.y);
glVertex2f(bounds.maxs.x, bounds.maxs.y);
glTexCoord2f(texCoordMins.x, texCoordMaxs.y);
glVertex2f(bounds.mins.x, bounds.maxs.y);
}
glEnd();
glDisable(GL_TEXTURE_2D);
}
<file_sep>#include "Game/Bullet.hpp"
#include "Game/Map.hpp"
#include "Game/GameCommon.hpp"
#include "Engine/Renderer/Texture.hpp"
#include <math.h>
const float Bullet::BULLET_SIZE = 0.2f;
Bullet::Bullet(Map* map, const Vector2& spawnPosition, float parentOrientation, int factionNumber, float bulletSpeed, float lifespan) : m_texture(Texture::CreateOrGetTexture("Data/Images/Bullet.png"))
, m_bulletSpeed(bulletSpeed)
, m_lifespan(lifespan)
, m_map(map)
{
m_isDead = false;
m_faction = factionNumber;
m_orientation = parentOrientation;
m_angularVelocity = 0.0f;
m_cosmeticRadius = BULLET_SIZE / 2.f;
m_physicalRadius = BULLET_SIZE / 2.5f;
m_boundingBox = AABB2(Vector2(0.f, 0.f), Vector2(BULLET_SIZE, BULLET_SIZE));
m_color = RGBA(1.0f, 1.0f, 1.0f, 1.0f);
Entity::SetMaxHealth(1.f);
m_position = spawnPosition;
Vector2 bulletDiretion = Vector2(cos(MathUtils::DegreesToRadians(m_orientation)), sin(MathUtils::DegreesToRadians(m_orientation)));
m_velocity = (bulletDiretion * m_bulletSpeed);
m_acceleration = Vector2(0.0f, 0.0f);
}
Bullet::~Bullet()
{
}
void Bullet::Update(float deltaTime)
{
Entity::Update(deltaTime);
m_colorTransitionFraction = m_ageInSeconds / m_lifespan;
m_color = RGBA(1.0f, m_colorTransitionFraction, 0.0f, 1.0f);
if (m_map->GetTileAtWorldCoords(m_position)->IsSolid())
{
m_isDead = true;
}
}
void Bullet::Render() const
{
TheRenderer::instance->PushMatrix();
TheRenderer::instance->Translate(m_position);
TheRenderer::instance->Rotate(m_orientation);
TheRenderer::instance->Translate(m_boundingBox.maxs * -0.5);
TheRenderer::instance->DrawTexturedAABB(m_boundingBox, Vector2(0.f, 0.f), Vector2(1.f, 1.f), *m_texture, m_color);
TheRenderer::instance->PopMatrix();
Entity::Render();
}
void Bullet::CollideWith(Entity* ent)
{
this->TakeDamage(1.f);
ent->TakeDamage(1.f);
}<file_sep>#pragma once
#include "Engine/Core/ErrorWarningAssert.hpp"
#include "Engine/Core/StringUtils.hpp"
#include "Engine/Math/MathUtils.hpp"
#include "Engine/Math/Vector2.hpp"
#include "Engine/Math/Vector2Int.hpp"
#include "Engine/Renderer/TheRenderer.hpp"
#include "Engine/Renderer/RGBA.hpp"
#include "Game/TheApp.hpp"
typedef Vector2 WorldCoords;
typedef Vector2Int TileCoords;
typedef int TileIndex;
#define UNUSED(x) (void)(x);<file_sep>#include "Engine/Renderer/SpriteSheet.hpp"
#include "Engine/Renderer/AABB2.hpp"
#include "Engine/Renderer/Texture.hpp"
SpriteSheet::SpriteSheet(const std::string& imageFilePath, int tilesWide, int tilesHigh)
: m_spriteLayout(Vector2Int(tilesWide, tilesHigh))
, m_spriteSheetTexture(Texture::CreateOrGetTexture(imageFilePath))
, m_texCoordsPerTile(Vector2(1.0f / tilesWide, 1.0f / tilesHigh))
{
}
AABB2 SpriteSheet::GetTexCoordsForSpriteCoords(const Vector2Int& spriteCoords) const
{
AABB2 texCoords;
texCoords.mins.x = m_texCoordsPerTile.x * (float)spriteCoords.x;
texCoords.mins.y = m_texCoordsPerTile.y * (float)spriteCoords.y;
texCoords.maxs = texCoords.mins + m_texCoordsPerTile;
return texCoords;
}
AABB2 SpriteSheet::GetTexCoordsForSpriteIndex(int spriteIndex) const
{
AABB2 texCoords;
int tileY = spriteIndex / m_spriteLayout.x;
int tileX = spriteIndex % m_spriteLayout.x;
texCoords.mins.x = m_texCoordsPerTile.x * (float)tileX;
texCoords.mins.y = m_texCoordsPerTile.y * (float)tileY;
texCoords.maxs = texCoords.mins + m_texCoordsPerTile;
return texCoords;
}
int SpriteSheet::GetNumSprites() const
{
return m_spriteLayout.x * m_spriteLayout.y;
}
Texture* SpriteSheet::GetTexture()
{
return m_spriteSheetTexture;
}
<file_sep>#include "Game/Tile.hpp"
#include "Engine/Renderer/AABB2.hpp"
#include "Engine/Renderer/Texture.hpp"
const float Tile::TILE_SIZE = 1.0f;
const float Tile::HALF_TILE_SIZE = TILE_SIZE / 2.f;
Tile::Tile(TileCoords position, TileDefinition* definition) : m_tileCoords(position), m_definition(definition)
{
}
Tile::Tile(int x, int y, TileDefinition* definition) : m_tileCoords(x, y), m_definition(definition)
{
}
Tile::~Tile()
{
}
void Tile::Update(float deltaTime)
{
//We don't need to do anything with this method just yet, but the signature has to match the calling convention.
//I'd rather not introduce a potential bug into my code by modifying it and instead refactor when I can add functionality.
deltaTime = 0;
}
void Tile::Render() const
{
TheRenderer::instance->PushMatrix();
TheRenderer::instance->Translate(GetWorldCoordsFromTileMin());
AABB2 TextureCoords = m_definition->GetTextureCoordinates();
TheRenderer::instance->DrawTexturedAABB(AABB2(Vector2(0.0f, 0.0f), Vector2(TILE_SIZE, TILE_SIZE)), TextureCoords.mins, TextureCoords.maxs, *m_definition->GetTexture(), m_definition->GetColor());
TheRenderer::instance->PopMatrix();
}
TileCoords Tile::GetTileCoords() const
{
return m_tileCoords;
}
WorldCoords Tile::GetWorldCoordsFromTileMin() const
{
return WorldCoords(static_cast<float>(m_tileCoords.x), static_cast<float>(m_tileCoords.y));
}
WorldCoords Tile::GetWorldCoordsFromTileCenter() const
{
return WorldCoords(static_cast<float>(m_tileCoords.x) + HALF_TILE_SIZE, static_cast<float>(m_tileCoords.y) + HALF_TILE_SIZE);
}
TileType Tile::GetType() const
{
return m_definition->GetType();
}
bool Tile::IsSolid() const
{
return m_definition->IsSolid();
}
<file_sep>#include "PlayerTank.hpp"
#include "Map.hpp"
#include "TheGame.hpp"
const float PlayerTank::BULLET_COOLDOWN = 0.3f;
const float PlayerTank::DEGREES_PER_SECOND = 50.0f;
const float PlayerTank::POSITION_PER_SECOND = 2.5f;
const float PlayerTank::TANK_NOSE_LOCATION = 0.5f;
const float PlayerTank::TANK_SIZE = 1.0f;
PlayerTank::PlayerTank(const Vector2& startingPosition, Map* map, const XInputController& controller)
: Tank(startingPosition, map), m_timeSinceLastBullet(BULLET_COOLDOWN), m_controller(controller)
{
m_faction = Entity::PLAYER_FACTION;
Entity::SetMaxHealth(10.f);
}
PlayerTank::~PlayerTank()
{
m_map->playerTankTimeSinceDeath = 0.f;
}
void PlayerTank::Update(float deltaTime)
{
m_controller.Update(deltaTime);
if (TheApp::instance->WasKeyJustPressed('H'))
{
TakeDamage(1.f);
}
if (TheApp::instance->WasKeyJustPressed('G'))
{
Entity::ToggleDebugDraw();
}
UpdateFromController(deltaTime);
Tank::Update(deltaTime);
}
void PlayerTank::Render() const
{
Tank::Render();
}
void PlayerTank::UpdateFromController(float deltaTime)
{
Vector2 leftStickDirection = m_controller.GetLeftStickPosition();
Vector2 rightStickDirection = m_controller.GetRightStickPosition();
if (leftStickDirection.CalculateMagnitude() > XInputController::DEADZONE || rightStickDirection.CalculateMagnitude() > XInputController::DEADZONE)
{
Vector2 newVelocity = Vector2(POSITION_PER_SECOND * cos(MathUtils::DegreesToRadians(m_orientation)), POSITION_PER_SECOND * sin(MathUtils::DegreesToRadians(m_orientation)));
m_velocity = (newVelocity * leftStickDirection.y * 0.5f) + (newVelocity * rightStickDirection.y * 0.5f);
m_orientation -= DEGREES_PER_SECOND * deltaTime * leftStickDirection.y;
m_orientation += DEGREES_PER_SECOND * deltaTime * rightStickDirection.y;
}
else
{
m_velocity = Vector2(0.0f, 0.0f);
}
m_timeSinceLastBullet += deltaTime;
if ((m_controller.GetRightTrigger() > 128 || TheApp::instance->WasKeyJustPressed(' '))
&& m_timeSinceLastBullet > BULLET_COOLDOWN
&& !TheGame::instance->IsPaused())
{
FireBullet();
m_timeSinceLastBullet = 0.f;
}
}
WorldCoords PlayerTank::GetNosePosition()
{
Vector2 tankDirection = Vector2(cos(MathUtils::DegreesToRadians(m_orientation)), sin(MathUtils::DegreesToRadians(m_orientation)));
Vector2 tankNoseDirection = tankDirection * TANK_NOSE_LOCATION;
return m_position + tankNoseDirection;
}
void PlayerTank::FireBullet()
{
m_map->SpawnBullet(GetNosePosition(), m_orientation, m_faction, 10.0f, 0.5f);
}
void PlayerTank::CollideWith(Entity* ent)
{
UNUSED(ent);
}
<file_sep>#include "Game/Entity.hpp"
#include "Game/GameCommon.hpp"
#include "Game/TheApp.hpp"
#include <math.h>
bool Entity::m_displayDebugInfo = false;
Entity::Entity()
: m_position(Vector2(0.0f, 0.0f))
, m_velocity(Vector2(0.0f, 0.0f))
, m_acceleration(Vector2(0.0f, 0.0f))
, m_orientation(0.0f)
, m_angularVelocity(0.0f)
, m_ageInSeconds(0.0f)
, m_isDead(false)
, m_maxHealth(10.f)
, m_health(m_maxHealth)
, m_physicalRadius(0.0f)
, m_cosmeticRadius(0.0f)
, m_faction(ENEMY_FACTION)
{
}
Entity::~Entity()
{
}
void Entity::Update(float deltaTime)
{
m_velocity += m_acceleration * deltaTime;
m_position += m_velocity * deltaTime;
m_orientation += m_angularVelocity * deltaTime;
m_ageInSeconds += deltaTime;
}
void Entity::Render() const
{
if (m_displayDebugInfo)
{
TheRenderer::instance->SetColor(0.0f, 1.0f, 1.0f, 1.0f);
TheRenderer::instance->SetPointSize(3);
TheRenderer::instance->DrawPoint(m_position);
TheRenderer::instance->SetPointSize(1);
TheRenderer::instance->SetColor(1.0f, 1.0f, 0.0f, 1.0f);
Vector2 orientation = m_position + Vector2(cos(MathUtils::DegreesToRadians(m_orientation)), sin(MathUtils::DegreesToRadians(m_orientation)));
TheRenderer::instance->DrawLine(m_position, orientation, 1.f);
TheRenderer::instance->SetColor(1.0f, 0.0f, 0.0f, 1.0f);
TheRenderer::instance->DrawPolygonOutline(m_position, m_physicalRadius, TheRenderer::CIRCLE_SIDES, 0.0f);
TheRenderer::instance->SetColor(0.0f, 0.0f, 1.0f, 1.0f);
TheRenderer::instance->DrawPolygonOutline(m_position, m_cosmeticRadius, TheRenderer::CIRCLE_SIDES, 0.0f);
TheRenderer::instance->SetColor(1.0f, 1.0f, 1.0f, 1.0f);
}
}
bool Entity::Overlaps(const Entity& ent) const
{
return MathUtils::DoDiscsOverlap(this->m_position, this->m_physicalRadius, ent.m_position, ent.m_physicalRadius);
}
Vector2 Entity::GetPosition() const
{
return m_position;
}
Vector2 Entity::GetVelocity() const
{
return m_velocity;
}
float Entity::GetOrientation() const
{
return m_orientation;
}
void Entity::TakeDamage(float damage)
{
m_health = MathUtils::Clamp(m_health - damage, 0.f, m_maxHealth);
if (m_health <= 0.f)
{
m_isDead = true;
}
}
void Entity::SetMaxHealth(float maxHealth)
{
m_maxHealth = maxHealth;
m_health = maxHealth;
}
bool Entity::IsDead() const
{
return m_isDead;
}
int Entity::GetFaction()
{
return m_faction;
}
void Entity::CollideWith(Entity* ent)
{
UNUSED(ent);
}
void Entity::ToggleDebugDraw()
{
m_displayDebugInfo = !m_displayDebugInfo;
}<file_sep>#pragma once
#include "Game/Tank.hpp"
#include "Game/GameCommon.hpp"
class PlayerTank;
class EnemyTank : public Tank
{
public:
EnemyTank(const Vector2& startingPosition, Map* map, PlayerTank* player);
~EnemyTank();
virtual void Update(float deltaTime);
virtual void Render() const;
virtual void FireBullet();
virtual void CollideWith(Entity* ent);
private:
WorldCoords GetNosePosition();
static const float BULLET_COOLDOWN;
static const float DRIVING_RANGE_DEGREES;
static const float FIRING_RANGE_DEGREES;
static const float FIRING_RANGE_DISTANCE_SQUARED;
static const float DEGREES_PER_SECOND;
static const float POSITION_PER_SECOND;
static const float TANK_NOSE_LOCATION;
static const float TANK_SIZE;
static const float TIME_BETWEEN_DIRECTION_CHANGES_SECONDS;
float m_timeSinceLastBullet;
float m_timeSinceLastDirectionChange;
float m_goalAngle;
PlayerTank* m_player;
};
<file_sep>#pragma once
#include "Game/GameCommon.hpp"
#include "Game/TileDefinition.hpp"
class Tile
{
public:
Tile(TileCoords position, TileDefinition* definition);
Tile(int x, int y, TileDefinition* definition);
~Tile();
void Update(float deltaTime);
void Render() const;
TileCoords GetTileCoords() const;
WorldCoords GetWorldCoordsFromTileMin() const;
WorldCoords GetWorldCoordsFromTileCenter() const;
TileType GetType() const;
bool IsSolid() const;
private:
static const float TILE_SIZE;
static const float HALF_TILE_SIZE;
TileCoords m_tileCoords;
Texture* m_texture;
TileDefinition* m_definition;
};
<file_sep>#pragma once
#include "Engine/Renderer/SpriteSheet.hpp"
class AABB2;
enum class AnimTypes
{
ONE_SHOT,
LOOP,
PING_PONG
};
class SpriteAnim
{
public:
SpriteAnim(const SpriteSheet& sheet, float seconds, int startSpriteIndex, int endSpriteIndex);
~SpriteAnim();
void Update(float deltaSeconds);
bool IsDone();
void PlayFromStart();
void StopPlaying();
AABB2 GetCurrentTexCoords() const;
private:
const SpriteSheet& m_sheet;
float m_age;
float m_secondsPerFrame;
bool m_isDone;
SpriteAnim& operator=(const SpriteAnim&);
};
<file_sep>#include "EnemyTank.hpp"
#include "PlayerTank.hpp"
#include "Map.hpp"
const float EnemyTank::BULLET_COOLDOWN = 2.0f;
const float EnemyTank::DRIVING_RANGE_DEGREES = 45.0f;
const float EnemyTank::FIRING_RANGE_DEGREES = 5.0f;
const float EnemyTank::FIRING_RANGE_DISTANCE_SQUARED = 15.0f * 2.0f;
const float EnemyTank::DEGREES_PER_SECOND = 50.0f;
const float EnemyTank::POSITION_PER_SECOND = 0.5f;
const float EnemyTank::TANK_NOSE_LOCATION = 0.5f;
const float EnemyTank::TANK_SIZE = 1.0f;
const float EnemyTank::TIME_BETWEEN_DIRECTION_CHANGES_SECONDS = 3.0f;
EnemyTank::EnemyTank(const Vector2& startingPosition, Map* map, PlayerTank* player)
: Tank(startingPosition, map, "Data/Images/EnemyTank.png")
, m_timeSinceLastBullet(0.f)
, m_player(player)
, m_timeSinceLastDirectionChange(TIME_BETWEEN_DIRECTION_CHANGES_SECONDS)
, m_goalAngle(m_orientation)
{
m_faction = Entity::ENEMY_FACTION;
Entity::SetMaxHealth(3.f);
}
EnemyTank::~EnemyTank()
{
}
void EnemyTank::Update(float deltaTime)
{
m_timeSinceLastBullet += deltaTime;
m_timeSinceLastDirectionChange += deltaTime;
Vector2 playerPosition = m_player->GetPosition();
if ((MathUtils::CalcDistSquaredBetweenPoints(playerPosition, m_position) < FIRING_RANGE_DISTANCE_SQUARED)
&& m_map->HasLineOfSight(m_position, playerPosition))
{
m_velocity = Vector2(0.f, 0.f);
m_goalAngle = MathUtils::RadiansToDegrees(atan2(playerPosition.y - m_position.y, playerPosition.x - m_position.x));
float m_adjustment = MathUtils::CalcShortestAngularDisplacement(m_orientation, m_goalAngle);
float turnDegreesThisFrame = DEGREES_PER_SECOND * deltaTime;
m_orientation += MathUtils::Clamp(m_adjustment, -turnDegreesThisFrame, turnDegreesThisFrame);
if (abs(m_adjustment) < DRIVING_RANGE_DEGREES)
{
Vector2 driveDirection = Vector2(cos(MathUtils::DegreesToRadians(m_orientation)), sin(MathUtils::DegreesToRadians(m_orientation)));
m_velocity = (driveDirection * POSITION_PER_SECOND);
}
if (m_timeSinceLastBullet > BULLET_COOLDOWN && abs(m_adjustment) < FIRING_RANGE_DEGREES)
{
FireBullet();
m_timeSinceLastBullet = 0.f;
}
}
else
{
if (m_timeSinceLastDirectionChange > 3.0f)
{
m_goalAngle = MathUtils::GetRandomFromZeroTo(360.f);
m_timeSinceLastDirectionChange = 0.f;
}
float m_adjustment = MathUtils::CalcShortestAngularDisplacement(m_orientation, m_goalAngle);
float turnDegreesThisFrame = DEGREES_PER_SECOND * deltaTime;
m_orientation += MathUtils::Clamp(m_adjustment, -turnDegreesThisFrame, turnDegreesThisFrame);
Vector2 driveDirection = Vector2(cos(MathUtils::DegreesToRadians(m_orientation)), sin(MathUtils::DegreesToRadians(m_orientation)));
m_velocity = (driveDirection * POSITION_PER_SECOND);
}
Tank::Update(deltaTime);
}
void EnemyTank::Render() const
{
Tank::Render();
}
WorldCoords EnemyTank::GetNosePosition()
{
Vector2 tankDirection = Vector2(cos(MathUtils::DegreesToRadians(m_orientation)), sin(MathUtils::DegreesToRadians(m_orientation)));
Vector2 tankNoseDirection = tankDirection * TANK_NOSE_LOCATION;
return m_position + tankNoseDirection;
}
void EnemyTank::FireBullet()
{
m_map->SpawnBullet(GetNosePosition(), m_orientation, m_faction, 4.0f, 2.0f);
}
void EnemyTank::CollideWith(Entity* ent)
{
UNUSED(ent);
}
<file_sep>#include "Game/TileDefinition.hpp"
#include "Engine/Renderer/Texture.hpp"
#include "Engine/Renderer/SpriteSheet.hpp"
#include "Engine/Renderer/AABB2.hpp"
SpriteSheet* TileDefinition::m_tileSheet = nullptr;
TileDefinition::TileDefinition(TileType type, TileCoords coords, RGBA color, bool isSolid) : m_type(type), m_tileCoords(coords), m_color(color), m_isSolid(isSolid)
{
//Sprite sheet for tiles is hard coded here
if (m_tileSheet == nullptr)
{
m_tileSheet = new SpriteSheet("Data/Images/tiles.png", 4, 4);
}
}
TileDefinition::~TileDefinition()
{
}
Texture* TileDefinition::GetTextureFromType(TileType type)
{
if (type == TileType::GRASS)
{
return Texture::CreateOrGetTexture("Data/Images/Tank.png");
}
}
bool TileDefinition::IsSolid()
{
return m_isSolid;
}
Texture* TileDefinition::GetTexture()
{
return m_tileSheet->GetTexture();
}
AABB2 TileDefinition::GetTextureCoordinates()
{
return m_tileSheet->GetTexCoordsForSpriteCoords(m_tileCoords);
}
TileType TileDefinition::GetType()
{
return m_type;
}
RGBA TileDefinition::GetColor()
{
return m_color;
}
<file_sep>#pragma once
#include "Engine/Input/XInputController.hpp"
#include "Game/GameCommon.hpp"
#include "Game/Entity.hpp"
class Texture;
class Map;
class Tank : public Entity
{
public:
Tank(const Vector2& startingPosition, Map* map);
Tank(const Vector2& startingPosition, Map* map, const std::string& imageFilePath);
virtual ~Tank();
virtual void Update(float deltaTime);
virtual void Render() const;
virtual void FireBullet();
virtual void CollideWith(Entity* ent);
protected:
void CheckForTileCollisions();
void CollideWithCorner(const WorldCoords& cornerPoint);
virtual WorldCoords GetNosePosition();
static const float BULLET_COOLDOWN;
static const float DEGREES_PER_SECOND;
static const float POSITION_PER_SECOND;
static const float TANK_NOSE_LOCATION;
static const float TANK_SIZE;
Texture* m_texture;
Map* m_map;
};
<file_sep>#pragma once
#include "Game/GameCommon.hpp"
class SpriteSheet;
enum class TileType
{
GRASS,
DIRT,
STONE
};
class TileDefinition
{
public:
TileDefinition(TileType type, TileCoords coords, RGBA color, bool isSolid);
~TileDefinition();
TileType GetType();
RGBA GetColor();
Texture* GetTexture();
AABB2 GetTextureCoordinates();
bool IsSolid();
private:
static Texture* GetTextureFromType(TileType type);
static SpriteSheet* m_tileSheet;
TileCoords m_tileCoords;
TileType m_type;
RGBA m_color;
bool m_isSolid;
};<file_sep>#pragma once
#include "Engine/Renderer/AABB2.hpp"
#include "Engine/Renderer/RGBA.hpp"
class Vector2;
enum class type
{
Bullet,
Tank
};
class Entity
{
public:
Entity();
virtual ~Entity();
virtual void Update(float deltaTime);
virtual void Render() const;
virtual void CollideWith(Entity* ent);
bool Overlaps(const Entity& ent) const;
Vector2 GetPosition() const;
Vector2 GetVelocity() const;
float GetOrientation() const;
void TakeDamage(float damage);
void SetMaxHealth(float maxHealth);
bool IsDead() const;
int GetFaction();
static void ToggleDebugDraw();
static const int PLAYER_FACTION = 0;
static const int ENEMY_FACTION = 1;
protected:
AABB2 m_boundingBox;
RGBA m_color;
Vector2 m_position;
Vector2 m_velocity;
Vector2 m_acceleration;
float m_angularVelocity;
float m_orientation;
float m_physicalRadius;
float m_cosmeticRadius;
float m_ageInSeconds;
float m_ageAtDeath;
float m_maxHealth;
float m_health;
int m_faction;
bool m_isDead;
static bool m_displayDebugInfo;
};
<file_sep> _ ______ ______ _ _____ _____ _____ _________
/ \ .' ____ \ .' ____ \ / \ |_ _||_ _||_ _| | _ _ |
/ _ \ | (___ \_|| (___ \_| / _ \ | | | | | | |_/ | | \_|
/ ___ \ _.____`. _.____`. / ___ \ | ' ' | | | _ | |
_/ / \ \_| \____) || \____) | _/ / \ \_\ \__/ / _| |__/ | _| |_
|____| |____|\______.' \______.'|____| |____|`.__.' |________||_____|
================================================================================
Known Issues:
================================================================================
Using the alt key to break out of the window, or any other exploit that causes
time to pass without being able to check for collisions, could result in an
entity getting out of the stage's bounds and creating a crash.
================================================================================
How to Use:
================================================================================
Xbox Controller Controls:
Left & Right Stick Up - Move tank forward
Left & Right Stick Down - Move tank backward
Left Stick Up, Right Stick Down - Rotate tank clockwise
Left Stick Down, Right Stick Up - Rotate tank counterclockwise
Start Button - Pause the game
Right Trigger - Fire bullets
Keyboard Controls:
Esc - Quit the Program
P - Pause the Game
Spacebar - Fire Bullets
G - Turn on debugging radius
H - Take 1 point of damage
================================================================================
Deep Learning:
================================================================================
This milestone, I struggled a lot with morale. Because I had other
responsibilities going on this week, I was hard-pressed to find time to work
on this project. I had decided to work on it all weekend long, which normally
would have worked, but because of various life anxieties and having
the majority of the project ahead of me, I wasn't able to be as productive as
I would have liked to. I struggled in my code, and I wasn't able to write as
high of quality code as I would have liked. I'm beginning to realize that
despite my tendencies and desires to treat myself like a machine, I'm truly not.
I'm a human being, who needs to find a balance between work and play, and needs
to learn how to take a break and step away from his code every now and then to
gain a better perspective. I want to write code that I'm proud of, and I realize
now that I need to manage not only my time, but my morale as well. I plan to
adjust my schedule so that I can manage my morale without losing sight of my
goal; to become a better developer.
<file_sep>#include "Game/Tank.hpp"
#include "Game/GameCommon.hpp"
#include "Engine/Renderer/Texture.hpp"
#include "Game/Map.hpp"
#include "Game/Tile.hpp"
const float Tank::BULLET_COOLDOWN = 0.4f;
const float Tank::DEGREES_PER_SECOND = 50.0f;
const float Tank::POSITION_PER_SECOND = 2.5f;
const float Tank::TANK_NOSE_LOCATION = 0.5f;
const float Tank::TANK_SIZE = 1.0f;
Tank::Tank(const Vector2& startingPosition, Map* map) : m_texture(Texture::CreateOrGetTexture("Data/Images/Tank.png")), m_map(map)
{
m_color = RGBA(1.0f, 1.0f, 1.0f);
m_boundingBox = AABB2(Vector2(0.f, 0.f), Vector2(TANK_SIZE, TANK_SIZE));
m_position = startingPosition;
m_orientation = 0.f;
m_physicalRadius = TANK_SIZE / 2.3f;
m_cosmeticRadius = TANK_SIZE / 1.7f;
SetMaxHealth(10.f);
}
Tank::Tank(const Vector2& startingPosition, Map* map, const std::string& imageFilePath) : m_texture(Texture::CreateOrGetTexture(imageFilePath)), m_map(map)
{
m_color = RGBA(1.0f, 1.0f, 1.0f);
m_boundingBox = AABB2(Vector2(0.f, 0.f), Vector2(TANK_SIZE, TANK_SIZE));
m_position = startingPosition;
m_orientation = 0.f;
m_physicalRadius = TANK_SIZE / 2.3f;
m_cosmeticRadius = TANK_SIZE / 1.7f;
SetMaxHealth(10.f);
}
Tank::~Tank()
{
}
void Tank::Update(float deltaTime)
{
float healthRatio = (m_health / m_maxHealth);
m_color = RGBA(1.0f, healthRatio, healthRatio);
Entity::Update(deltaTime);
CheckForTileCollisions();
}
void Tank::Render() const
{
TheRenderer::instance->PushMatrix();
TheRenderer::instance->Translate(m_position);
TheRenderer::instance->Rotate(m_orientation);
//Translate backwards half of the bounding box so we rotate around the center of the tank.
TheRenderer::instance->Translate(m_boundingBox.maxs * -0.5);
TheRenderer::instance->DrawTexturedAABB(m_boundingBox, Vector2(0.f, 0.f), Vector2(1.f, 1.f), *m_texture, m_color);
TheRenderer::instance->PopMatrix();
Entity::Render();
}
void Tank::FireBullet()
{
}
void Tank::CollideWith(Entity* ent)
{
UNUSED(ent);
}
void Tank::CheckForTileCollisions()
{
const TileCoords NORTH_NEIGHBOR = TileCoords(0, 1);
const TileCoords SOUTH_NEIGHBOR = TileCoords(0, -1);
const TileCoords WEST_NEIGHBOR = TileCoords(1, 0);
const TileCoords EAST_NEIGHBOR = TileCoords(-1, 0);
const TileCoords NORTHWEST_NEIGHBOR = TileCoords(1, 1);
const TileCoords NORTHEAST_NEIGHBOR = TileCoords(-1, 1);
const TileCoords SOUTHWEST_NEIGHBOR = TileCoords(1, -1);
const TileCoords SOUTHEAST_NEIGHBOR = TileCoords(-1, -1);
Tile* currentTile = m_map->GetTileAtWorldCoords(m_position);
TileCoords currentTilePosition = currentTile->GetTileCoords();
Tile* tileToCheck = m_map->GetTileAtCoords(currentTilePosition + NORTH_NEIGHBOR);
if (tileToCheck->IsSolid())
{
float distanceInsideTile = ((m_position.y + m_physicalRadius) - tileToCheck->GetWorldCoordsFromTileMin().y);
if (distanceInsideTile > 0.f)
{
m_position.y -= distanceInsideTile;
}
}
//Edge Cases
tileToCheck = m_map->GetTileAtCoords(currentTilePosition + SOUTH_NEIGHBOR);
if (tileToCheck->IsSolid())
{
float distanceInsideTile = (currentTile->GetWorldCoordsFromTileMin().y - (m_position.y - m_physicalRadius));
if (distanceInsideTile > 0.f)
{
m_position.y += distanceInsideTile;
}
}
tileToCheck = m_map->GetTileAtCoords(currentTilePosition + WEST_NEIGHBOR);
if (tileToCheck->IsSolid())
{
float distanceInsideTile = ((m_position.x + m_physicalRadius) - tileToCheck->GetWorldCoordsFromTileMin().x);
if (distanceInsideTile > 0.f)
{
m_position.x -= distanceInsideTile;
}
}
tileToCheck = m_map->GetTileAtCoords(currentTilePosition + EAST_NEIGHBOR);
if (tileToCheck->IsSolid())
{
float distanceInsideTile = (currentTile->GetWorldCoordsFromTileMin().x - (m_position.x - m_physicalRadius));
if (distanceInsideTile > 0.f)
{
m_position.x += distanceInsideTile;
}
}
//Corner Cases
tileToCheck = m_map->GetTileAtCoords(currentTilePosition + NORTHWEST_NEIGHBOR);
if (tileToCheck->IsSolid())
{
WorldCoords cornerPoint = tileToCheck->GetWorldCoordsFromTileMin();
if (MathUtils::IsPointInDisk(cornerPoint, m_position, m_physicalRadius))
{
CollideWithCorner(cornerPoint);
}
}
tileToCheck = m_map->GetTileAtCoords(currentTilePosition + NORTHEAST_NEIGHBOR);
if (tileToCheck->IsSolid())
{
WorldCoords cornerPoint = tileToCheck->GetWorldCoordsFromTileMin() + WorldCoords(1.0f, 0.0f);
if (MathUtils::IsPointInDisk(cornerPoint, m_position, m_physicalRadius))
{
CollideWithCorner(cornerPoint);
}
}
tileToCheck = m_map->GetTileAtCoords(currentTilePosition + SOUTHWEST_NEIGHBOR);
if (tileToCheck->IsSolid())
{
WorldCoords cornerPoint = currentTile->GetWorldCoordsFromTileMin() + WorldCoords(1.0f, 0.0f);
if (MathUtils::IsPointInDisk(cornerPoint, m_position, m_physicalRadius))
{
CollideWithCorner(cornerPoint);
}
}
tileToCheck = m_map->GetTileAtCoords(currentTilePosition + SOUTHEAST_NEIGHBOR);
if (tileToCheck->IsSolid())
{
WorldCoords cornerPoint = currentTile->GetWorldCoordsFromTileMin();
if (MathUtils::IsPointInDisk(cornerPoint, m_position, m_physicalRadius))
{
CollideWithCorner(cornerPoint);
}
}
}
void Tank::CollideWithCorner(const WorldCoords& cornerPoint)
{
Vector2 pushDir = m_position - cornerPoint;
pushDir.Normalize(); //Normalize so that we can scale by the distance we need to get pushed.
float distToCorner = MathUtils::CalcDistanceBetweenPoints(cornerPoint, m_position);
float pushDist = m_physicalRadius - distToCorner;
pushDir *= pushDist;
m_position += pushDir;
}
WorldCoords Tank::GetNosePosition()
{
Vector2 tankDirection = Vector2(cos(MathUtils::DegreesToRadians(m_orientation)), sin(MathUtils::DegreesToRadians(m_orientation)));
Vector2 tankNoseDirection = tankDirection * TANK_NOSE_LOCATION;
return m_position + tankNoseDirection;
}<file_sep>#pragma once
#include "Game/Entity.hpp"
class Vector2;
class Map;
class Texture;
class Bullet : public Entity
{
public:
Bullet(Map* map, const Vector2& spawnPosition, float parentOrientation, int factionNumber, float bulletSpeed, float lifespan);
~Bullet();
void Update(float deltaTime);
void Render() const;
void CollideWith(Entity* ent);
private:
static const float BULLET_SIZE;
float m_bulletSpeed;
float m_colorTransitionFraction;
float m_lifespan;
Map* m_map;
Texture* m_texture;
};<file_sep>#include "Game/Map.hpp"
#include "Game/GameCommon.hpp"
#include "Game/TheGame.hpp"
#include "Game/PlayerTank.hpp"
#include "Game/EnemyTank.hpp"
#include "Game/EnemyTurret.hpp"
#include "Game/Camera2D.hpp"
#include "Game/Bullet.hpp"
XInputController Map::m_controller = XInputController(0);
const float Map::TIME_TO_RESPAWN = 5.0f;
Map::Map(const TileCoords& size) : m_size(size), m_waitingForRespawn(false)
{
CreateTileDefinitions();
//Map Generation
for (int y = 0; y < m_size.y; y++)
{
for (int x = 0; x < m_size.x; x++)
{
TileDefinition* type = &m_definitions[(int)TileType::GRASS];
//If the tile is on the border, make it stone.
if (y == 0 || x == 0 || y == m_size.y - 1 || x == m_size.x - 1)
{
type = &m_definitions[(int)TileType::STONE];
}
//Set a few tiles to stone inside
else if (MathUtils::GetRandom(0, 10) == 1)
{
type = &m_definitions[(int)TileType::STONE];
}
//Set the last grass tile to be our spawn location.
if (type == &m_definitions[(int)TileType::GRASS])
{
m_playerSpawn = TileCoords(x, y);
}
m_tiles.push_back(Tile(x, y, type));
}
}
m_playerTank = new PlayerTank(Map::GetWorldCoordsFromTileCoords(m_playerSpawn), this, m_controller);
for (int i = 0; i < NUM_TURRETS; i++)
{
int lastTileIndex = m_tiles.size() - 1;
Tile* selectedTile = &m_tiles[MathUtils::GetRandom(0, lastTileIndex)];
while (selectedTile->IsSolid())
{
selectedTile = &m_tiles[MathUtils::GetRandom(0, lastTileIndex)];
}
WorldCoords turretSpawnLocation = selectedTile->GetWorldCoordsFromTileCenter();
EnemyTurret* enemy = new EnemyTurret(turretSpawnLocation, this, m_playerTank);
m_entities.insert(enemy);
}
for (int i = 0; i < NUM_TANKS; i++)
{
int lastTileIndex = m_tiles.size() - 1;
Tile* selectedTile = &m_tiles[MathUtils::GetRandom(0, lastTileIndex)];
while (selectedTile->IsSolid())
{
selectedTile = &m_tiles[MathUtils::GetRandom(0, lastTileIndex)];
}
WorldCoords tankSpawnLocation = selectedTile->GetWorldCoordsFromTileCenter();
EnemyTank* enemy = new EnemyTank(tankSpawnLocation, this, m_playerTank);
m_entities.insert(enemy);
}
m_entities.insert(m_playerTank);
m_Camera = new Camera2D(m_playerTank);
}
Map::~Map()
{
}
void Map::Update(float deltaTime)
{
m_controller.Update(deltaTime);
if ((m_controller.JustPressed(XboxButton::START) || TheApp::instance->WasKeyJustPressed('P')) && !m_waitingForRespawn)
{
TheGame::instance->TogglePause();
}
for (std::set<Entity*>::iterator iter = m_entities.begin(); iter != m_entities.end(); ++iter)
{
Entity* gameObject = *iter;
gameObject->Update(deltaTime);
}
for (std::set<Bullet*>::iterator iter = m_bullets.begin(); iter != m_bullets.end(); ++iter)
{
Entity* gameObject = *iter;
gameObject->Update(deltaTime);
}
for (std::set<Bullet*>::iterator bullet = m_bullets.begin(); bullet != m_bullets.end(); ++bullet)
{
for (std::set<Entity*>::iterator entity = m_entities.begin(); entity != m_entities.end(); ++entity)
{
Entity* bulletToCheck = *bullet;
Entity* entityToCollideWith = *entity;
if (bulletToCheck->GetFaction() != entityToCollideWith->GetFaction() && bulletToCheck->Overlaps(*entityToCollideWith))
{
bulletToCheck->CollideWith(entityToCollideWith);
}
}
}
if (m_playerTank && m_playerTank->IsDead())
{
m_playerTank = nullptr;
m_Camera->ShouldUpdate(false);
m_waitingForRespawn = true;
}
if (m_waitingForRespawn)
{
playerTankTimeSinceDeath += deltaTime;
if (playerTankTimeSinceDeath > TIME_TO_RESPAWN)
{
TheGame::instance->TogglePause();
m_waitingForRespawn = false;
playerTankTimeSinceDeath = 0.f;
}
}
for (std::set<Entity*>::iterator iter = m_entities.begin(); iter != m_entities.end(); ++iter)
{
Entity* gameObject = *iter;
if (gameObject->IsDead())
{
delete gameObject;
iter = m_entities.erase(iter);
}
if (iter == m_entities.end())
{
break;
}
}
for (std::set<Bullet*>::iterator iter = m_bullets.begin(); iter != m_bullets.end(); ++iter)
{
Bullet* gameObject = *iter;
if (gameObject->IsDead())
{
delete gameObject;
iter = m_bullets.erase(iter);
}
if (iter == m_bullets.end())
{
break;
}
}
m_Camera->Update(deltaTime);
}
void Map::Render() const
{
for (int y = 0; y < m_size.y; y++)
{
for (int x = 0; x < m_size.x; x++)
{
TileIndex tileIndex = GetIndexFromTileCoords(TileCoords(x, y));
m_tiles[ tileIndex ].Render();
}
}
for (std::set<Entity*>::iterator iter = m_entities.begin(); iter != m_entities.end(); ++iter)
{
Entity* gameObject = *iter;
gameObject->Render();
}
for (std::set<Bullet*>::iterator iter = m_bullets.begin(); iter != m_bullets.end(); ++iter)
{
Entity* gameObject = *iter;
gameObject->Render();
}
m_Camera->Render();
}
TileCoords Map::GetTileCoordsForTile(const Tile& tile) const
{
return tile.GetTileCoords();
}
Tile* Map::GetTileAtCoords(const TileCoords& tileCoordinates)
{
return &GetTileAtIndex(GetIndexFromTileCoords(tileCoordinates));
}
Tile& Map::GetTileAtIndex(TileIndex index)
{
return (m_tiles.at(index));
}
Tile* Map::GetTileAtWorldCoords(const WorldCoords& worldCoordinates)
{
return &GetTileAtIndex(GetIndexFromTileCoords(GetTileCoordsFromWorldCoords(worldCoordinates)));
}
TileIndex Map::GetIndexFromTileCoords(const TileCoords& tileCoordinates) const
{
return(m_size.x * tileCoordinates.y) + tileCoordinates.x;
}
bool Map::HasLineOfSight(const WorldCoords& start, const WorldCoords& end)
{
Vector2 distance = end - start;
Vector2 current = start;
Vector2 step = distance * .01f;
for (int i = 0; i < 100; i++)
{
current += step;
Tile* currentTile = GetTileAtCoords(GetTileCoordsFromWorldCoords(current));
if (currentTile->IsSolid())
{
return false;
}
}
return true;
}
TileCoords Map::GetTileCoordsFromIndex(int index) const
{
int tileY = index / m_size.x;
int tileX = index % m_size.x;
return TileCoords(tileX, tileY);
}
WorldCoords Map::GetWorldCoordsFromTileCoords(const TileCoords& tileCoords)
{
return WorldCoords(static_cast<float>(tileCoords.x), static_cast<float>(tileCoords.y));
}
void Map::RespawnTank()
{
if (!m_playerTank)
{
m_playerTank = new PlayerTank(Map::GetWorldCoordsFromTileCoords(m_playerSpawn), this, m_controller);
m_entities.insert(m_playerTank);
m_Camera->ShouldUpdate(true);
m_Camera->FollowPlayer(m_playerTank);
}
}
TileCoords Map::GetTileCoordsFromWorldCoords(const WorldCoords& worldCoordinates) const
{
return TileCoords(static_cast<int>(worldCoordinates.x), static_cast<int>(worldCoordinates.y));
}
void Map::CreateTileDefinitions()
{
m_definitions.push_back(TileDefinition(TileType::GRASS, TileCoords(0, 0), RGBA(0.00f, 1.00f, 0.00f, 1.0f), false));
m_definitions.push_back(TileDefinition(TileType::DIRT, TileCoords(1, 0), RGBA(0.58f, 0.30f, 0.00f, 1.0f), false));
m_definitions.push_back(TileDefinition(TileType::STONE, TileCoords(1, 1), RGBA(0.50f, 0.50f, 0.50f, 1.0f), true));
}
void Map::SpawnBullet(const WorldCoords& position, float orientation, int factionNumber, float bulletSpeed, float lifespan)
{
m_bullets.insert(new Bullet(this, position, orientation, factionNumber, bulletSpeed, lifespan));
}<file_sep>#pragma once
class RGBA
{
public:
RGBA();
RGBA(float Red, float Green, float Blue);
RGBA(float Red, float Green, float Blue, float Alpha);
~RGBA();
float red;
float blue;
float green;
float alpha;
static const RGBA WHITE;
private:
};
<file_sep>#pragma once
#include "Game/Tile.hpp"
#include "Game/TileDefinition.hpp"
#include "Engine/Input/XInputController.hpp"
#include <vector>
#include <set>
class Entity;
class Camera2D;
class PlayerTank;
class Bullet;
class Map
{
public:
Map(const TileCoords& size);
~Map();
void Update(float deltaTime);
void Render() const;
void CreateTileDefinitions();
void SpawnBullet(const WorldCoords& position, float orientation, int factionNumber, float bulletSpeed, float lifespan);
Tile* GetTileAtCoords(const TileCoords& tileCoordinates);
Tile* GetTileAtWorldCoords(const WorldCoords& worldCoordinates);
Tile& GetTileAtIndex(TileIndex index);
TileCoords GetTileCoordsForTile(const Tile& tile) const;
TileCoords GetTileCoordsFromWorldCoords(const WorldCoords& worldCoordinates) const;
TileCoords GetTileCoordsFromIndex(int index) const;
TileIndex GetIndexFromTileCoords(const TileCoords& tileCoordinates) const;
bool HasLineOfSight(const WorldCoords& start, const WorldCoords& end);
void RespawnTank();
static WorldCoords GetWorldCoordsFromTileCoords(const TileCoords& tileCoords);
float playerTankTimeSinceDeath;
private:
static const int NUM_TURRETS = 10;
static const int NUM_TANKS = 10;
static const float TIME_TO_RESPAWN;
static XInputController m_controller;
std::vector<TileDefinition> m_definitions;
std::vector<Tile> m_tiles;
TileCoords m_size;
std::set<Entity*> m_entities;
std::set<Bullet*> m_bullets;
Camera2D* m_Camera;
PlayerTank* m_playerTank;
Vector2Int m_playerSpawn;
bool m_waitingForRespawn;
};
<file_sep>#pragma once
#include "Game/Tank.hpp"
#include "Game/GameCommon.hpp"
class PlayerTank : public Tank
{
public:
PlayerTank(const Vector2& startingPosition, Map* map, const XInputController& controller);
~PlayerTank();
virtual void Update(float deltaTime);
virtual void Render() const;
virtual void FireBullet();
virtual void CollideWith(Entity* ent);
private:
void UpdateFromController(float deltaTime);
WorldCoords GetNosePosition();
static const float BULLET_COOLDOWN;
static const float DEGREES_PER_SECOND;
static const float POSITION_PER_SECOND;
static const float TANK_NOSE_LOCATION;
static const float TANK_SIZE;
float m_timeSinceLastBullet;
XInputController m_controller;
};
<file_sep>#include "SpriteAnim.hpp"
#include "Engine/Renderer/AABB2.hpp"
SpriteAnim::~SpriteAnim()
{
}
void SpriteAnim::Update(float deltaSeconds)
{
m_age += deltaSeconds;
}
bool SpriteAnim::IsDone()
{
return !m_isDone;
}
void SpriteAnim::PlayFromStart()
{
m_isDone = false;
m_age = 0.f;
}
void SpriteAnim::StopPlaying()
{
m_isDone = true;
}
// AABB2 SpriteAnim::GetCurrentTexCoords() const
// {
// Multiply m_age by fps instead lel
// (int)floor(m_age / m_secondsPerFrame);
// }
<file_sep>#pragma once
class Vector2
{
public:
Vector2();
Vector2(float initialX, float initialY);
Vector2(const Vector2& other);
void SetXY(float newX, float newY);
float CalculateMagnitude();
void Normalize();
Vector2& operator+=(const Vector2& rhs);
Vector2& operator-=(const Vector2& rhs);
Vector2& operator*=(const float& scalarConstant);
private:
public:
float x;
float y;
};
inline Vector2 operator+(Vector2 lhs, const Vector2& rhs)
{
lhs += rhs;
return lhs;
}
inline Vector2 operator-(Vector2 lhs, const Vector2& rhs)
{
lhs -= rhs;
return lhs;
}
inline Vector2 operator*(Vector2 lhs, const float& scalarConstant)
{
lhs *= scalarConstant;
return lhs;
}<file_sep>#pragma once
#include "Game/GameCommon.hpp"
class Tank;
class Vector2;
class Camera2D
{
public:
Camera2D(Tank* Player);
~Camera2D();
void Update(float deltaTime);
void Render() const;
void ShouldUpdate(bool shouldUpdate);
void FollowPlayer(Tank* player);
private:
WorldCoords m_position;
Vector2 m_screenSize;
Vector2 m_cameraCenteredOnScreenPosition;
Vector2 m_previousPlayerPosition;
float m_previousPlayerOrientation;
float m_orientationDegrees;
float m_numTilesInViewVertically;
Tank* m_Player;
bool m_shouldUpdate;
};
<file_sep>#include "Game/TheGame.hpp"
#include "Game/GameCommon.hpp"
#include "Game/Map.hpp"
#include "Engine/Renderer/AABB2.hpp"
#include "Engine/Renderer/Texture.hpp"
TheGame* TheGame::instance = nullptr;
TheGame::TheGame()
: m_map(nullptr)
, m_isPaused(false)
, m_pauseTexture(Texture::CreateOrGetTexture("Data/Images/Pause.png"))
{
srand(0xDEADBEEF);
m_map = new Map( TileCoords( 40, 40 ) );
}
TheGame::~TheGame()
{
}
void TheGame::Update(float deltaTime)
{
if (m_isPaused)
{
deltaTime = 0.f;
}
m_map->Update(deltaTime);
}
void TheGame::Render() const
{
m_map->Render();
if (m_isPaused)
{
Vector2 screenMins = Vector2(0.f, 0.f);
Vector2 screenMaxs = Vector2(TheApp::instance->GetWindowWidth(), TheApp::instance->GetWindowHeight());
Vector2 gameMaxs = Vector2(16.f, 9.f);
Vector2 pauseGraphicMins = Vector2(TheApp::instance->GetWindowWidth() / 8.f, TheApp::instance->GetWindowHeight() / 8.f);
Vector2 pauseGraphicMaxs = Vector2(TheApp::instance->GetWindowWidth() * (7.f / 8.f), TheApp::instance->GetWindowHeight() * (7.f / 8.f));
RGBA pauseColor = RGBA(0.0f, 0.0f, 0.0f, 0.3f);
TheRenderer::instance->PushMatrix();
TheRenderer::instance->DrawAABB(AABB2(screenMins, screenMaxs), pauseColor);
TheRenderer::instance->SetOrtho(screenMins, screenMaxs);
TheRenderer::instance->DrawTexturedAABB(AABB2(pauseGraphicMins, pauseGraphicMaxs), Vector2(0.f, 0.f), Vector2(1.f, 1.f), *m_pauseTexture, RGBA(1.f, 1.f, 1.f));
TheRenderer::instance->SetOrtho(screenMins, gameMaxs);
TheRenderer::instance->PopMatrix();
}
}
void TheGame::TogglePause()
{
m_isPaused = !m_isPaused;
if (!m_isPaused)
{
m_map->RespawnTank();
}
}
bool TheGame::IsPaused()
{
return m_isPaused;
}
<file_sep>#pragma once
class Map;
class Texture;
class TheGame
{
public:
TheGame();
~TheGame();
void Update(float deltaTime);
void Render() const;
void TogglePause();
bool IsPaused();
static TheGame* instance;
private:
Map* m_map;
Texture* m_pauseTexture;
bool m_isPaused;
};
<file_sep>#include "EnemyTurret.hpp"
#include "PlayerTank.hpp"
#include "Map.hpp"
#include <math.h>
const float EnemyTurret::BULLET_COOLDOWN = 2.0f;
const float EnemyTurret::FIRING_RANGE_DEGREES = 5.0f;
const float EnemyTurret::FIRING_RANGE_DISTANCE_SQUARED = 20.0f * 2.0f;
const float EnemyTurret::DEGREES_PER_SECOND = 90.0f;
const float EnemyTurret::POSITION_PER_SECOND = 2.5f;
const float EnemyTurret::TANK_NOSE_LOCATION = 0.5f;
const float EnemyTurret::TANK_SIZE = 1.0f;
EnemyTurret::EnemyTurret(const Vector2& startingPosition, Map* map, PlayerTank* player) : Tank(startingPosition, map, "Data/Images/EnemyTurret.png"), m_timeSinceLastBullet(0.f), m_player(player)
{
m_faction = Entity::ENEMY_FACTION;
Entity::SetMaxHealth(3.f);
}
EnemyTurret::~EnemyTurret()
{
}
void EnemyTurret::Update(float deltaTime)
{
m_timeSinceLastBullet += deltaTime;
Vector2 playerPosition = m_player->GetPosition();
if ((MathUtils::CalcDistSquaredBetweenPoints(playerPosition, m_position) < FIRING_RANGE_DISTANCE_SQUARED)
&& m_map->HasLineOfSight(m_position, playerPosition))
{
float goalAngle = MathUtils::RadiansToDegrees(atan2(playerPosition.y - m_position.y, playerPosition.x - m_position.x));
float m_adjustment = MathUtils::CalcShortestAngularDisplacement(m_orientation, goalAngle);
float turnDegreesThisFrame = DEGREES_PER_SECOND * deltaTime;
m_orientation += MathUtils::Clamp(m_adjustment, -turnDegreesThisFrame, turnDegreesThisFrame);
if (m_timeSinceLastBullet > BULLET_COOLDOWN && abs(m_adjustment) < FIRING_RANGE_DEGREES)
{
FireBullet();
m_timeSinceLastBullet = 0.f;
}
}
Tank::Update(deltaTime);
}
void EnemyTurret::Render() const
{
Tank::Render();
}
WorldCoords EnemyTurret::GetNosePosition()
{
Vector2 tankDirection = Vector2(cos(MathUtils::DegreesToRadians(m_orientation)), sin(MathUtils::DegreesToRadians(m_orientation)));
Vector2 tankNoseDirection = tankDirection * TANK_NOSE_LOCATION;
return m_position + tankNoseDirection;
}
void EnemyTurret::FireBullet()
{
m_map->SpawnBullet(GetNosePosition(), m_orientation, m_faction, 4.0f, 2.0f);
}
void EnemyTurret::CollideWith(Entity* ent)
{
UNUSED(ent);
}
<file_sep>#pragma once
#include "Game/Tank.hpp"
#include "Game/GameCommon.hpp"
class PlayerTank;
class EnemyTurret : public Tank
{
public:
EnemyTurret(const Vector2& startingPosition, Map* map, PlayerTank* player);
~EnemyTurret();
virtual void Update(float deltaTime);
virtual void Render() const;
virtual void FireBullet();
virtual void CollideWith(Entity* ent);
private:
WorldCoords GetNosePosition();
static const float BULLET_COOLDOWN;
static const float FIRING_RANGE_DEGREES;
static const float FIRING_RANGE_DISTANCE_SQUARED;
static const float DEGREES_PER_SECOND;
static const float POSITION_PER_SECOND;
static const float TANK_NOSE_LOCATION;
static const float TANK_SIZE;
float m_timeSinceLastBullet;
PlayerTank* m_player;
};
| 4dfd7ebb1c669643031922f57005c1519f61ace4 | [
"Text",
"C++"
] | 30 | Text | picoriley/Assault | dee5c4f0171591992227a64f654969e33d18b108 | 6423e5b86c777fa2eaa975a1edabdef1cf29957b |
refs/heads/master | <repo_name>calmon/codejam<file_sep>/lib/codejam/submissions/qualification2012/problem_d.rb
module CodeJam
class ProblemD < Problem
def initialize
super("qualification2012/problem_d/")
end
def solve(input)
input
end
end
end
<file_sep>/lib/codejam/submissions/round1a2012/problem_b.rb
module CodeJam
class Problem
def initialize(problem_path)
input = File.open("data/#{problem_path}input", "r")
output = File.open("data/#{problem_path}output", "w")
x = input.readline.to_i
x.times do |i|
y = input.readline.to_i
datasets = Array.new
y.times do |j|
a = input.readline.to_s.split(" ")
datasets.push(Level.new(a[0], a[1]))
end
output.puts "Case ##{i+1}: #{solve(datasets)}"
end
end
end
class Level
attr_accessor :one, :two, :onefinished
def initialize(one, two)
@one = one
@two = two
@onefinished = false
end
end
class ProblemB < Problem
def initialize
super("round1a2012/problem_b/")
end
def solve(input)
stars=0
actions=0
nothinghappen=true
needtosolve=input.length
while needtosolve>0 do
needtosolve.times do |i|
if input[i].two.to_i <= stars
if (input[i].onefinished)
stars+=1
else
stars+=2
end
needtosolve-=1
actions+=1
nothinghappen=false
input.delete_at(i)
break
end
end
if (nothinghappen)
j=-1
max=-1
needtosolve.times do |i|
if input[i].one.to_i <= stars && input[i].two.to_i>max && !input[i].onefinished
max=input[i].two.to_i
j=i
end
end
if (j>=0)
stars+=1
actions+=1
nothinghappen=false
input[j].onefinished=true
end
end
if (nothinghappen)
actions="Too Bad"
break
else
nothinghappen=true
end
end
actions
end
end
end
<file_sep>/lib/codejam/solve.rb
module CodeJam
class Solve
def initialize(problem)
CodeJam.const_get(problem).new
end
end
end
<file_sep>/lib/codejam/submissions/qualification2012/problem_c.rb
module CodeJam
class ProblemC < Problem
def initialize
super("qualification2012/problem_c/")
end
def solve(input)
input_split = input.split(' ')
hits = 0
a = input_split[0].to_i
b = input_split[1].to_i
list = Array.new
rounds = b-a+1
rounds.times do |i|
check = a+i
temp = ""
it = check.to_s.length-1
it.times do |j|
temp = check.to_s[it-j] + temp
if (temp[0].to_i!=0)
recycled = (temp + check.to_s[0,it-j]).to_i
if (check < recycled && recycled <= b)
if (!list.include?(check.to_s + ',' + recycled.to_s))
list.push(check.to_s + ',' + recycled.to_s)
hits += 1
end
end
end
end
end
hits
end
end
end
<file_sep>/lib/codejam/submissions/practice/2011-2-aiwar.rb
module CodeJam
class Pseudo
attr_accessor :x, :y, :z, :zz
def initialize(x, y, z)
@x=x
@y=y
@z=z
@zz=Array.new
end
end
class TestCase
attr_accessor :a, :b, :c, :d
def initialize(a, b, c)
@a=a
@b=b
@c=c
@d=Array.new
end
end
class Aiwar
def initialize()
problem_path="practice/2011-2-aiwar/"
input = File.open("data/#{problem_path}input", "r")
output = File.open("data/#{problem_path}output", "w")
x = input.readline.to_i
x.times do |i|
a = input.readline.to_s.split(" ")
b = input.readline.to_s.split(" ")
testcase = TestCase.new(a[0], a[1], b)
puts "Case:" +(i+1).to_s
output.puts "Case ##{i+1}: #{solve(testcase)}"
end
end
def check_connections(c,i)
end
def solve(input)
puts "1"
a=input.a
b=input.b
c=input.c
d=input.d
c.length.times do |i|
one, two=c[i].to_s.split(",")
one=one.to_i
two=two.to_i
if d.at(one).nil?
d[one]=Pseudo.new(one, Array.new(1, two), :untouched)
else
d[one].y.push(two)
end
if d.at(two).nil?
d[two]=Pseudo.new(two, Array.new(1, one), :untouched)
else
d[two].y.push(one)
end
end
alien_found=false
d[0].z=:ours
d[0].zz << Array.new(1, 0)
d[1].z=:alien
conquer=0
threaten=0
counter=-1
puts "2"
while (!alien_found) do
counter += 1
helper=Array.new
#puts "Counter" +counter.to_s
a.to_i.times do |i|
#puts helper.length
if !d.at(i).nil?
if d[i].z==:ours
d[i].y.length.times do |j|
neighbour=d[i].y[j].to_i
if d[neighbour].z==:alien || d[neighbour].z==:untouched
if d[neighbour].z==:alien
alien_found=true
#puts "ALIENS FOUND!!" + counter.to_s
else
helper << neighbour
end
d[i].zz.length.times do |l|
temp = Array.new(d[i].zz[l])
temp << neighbour
#puts temp.to_s
d[neighbour].zz << temp
end
end
end
end
d[i].z==:counted
end
end
helper.length.times do |k|
#puts d[helper[k].to_int].z
d[helper[k].to_int].z=:ours
end
end
puts d[1].zz.length.to_s
puts d[1].inspect
d[1].zz.length.times do |i|
tempthreaten=0
a.to_i.times do |j|
if !d.at(j).nil?
if j==0 || d[1].zz[i].include?(j)
d[j].z=:ours
else
d[j].z=:untouched
end
d[1].z=:untouched
end
end
a.to_i.times do |j|
if !d.at(j).nil?
if d[j].z==:ours
d[j].y.length.times do |k|
neighbour=d[j].y[k].to_i
if d[neighbour].z==:untouched
tempthreaten += 1
d[neighbour].z=:counted
end
end
end
end
end
if threaten < tempthreaten
threaten=tempthreaten
end
end
#puts input.inspect
counter.to_s + " " + threaten.to_s
end
end
end
<file_sep>/lib/codejam/submissions/round1a2012/problem_a.rb
module CodeJam
class Password
attr_accessor :a, :b, :odds
def initialize(a, b, odds)
@a=a
@b=b
@odds=odds
end
end
class ProblemA
def initialize()
problem_path="round1a2012/problem_a/"
input = File.open("data/#{problem_path}input", "r")
output = File.open("data/#{problem_path}output", "w")
x = input.readline.to_i
x.times do |i|
a = input.readline.to_s.split(" ")
b = input.readline.to_s.split(" ")
password = Password.new(a[0], a[1], b)
output.puts "Case ##{i+1}: #{solve(password)}"
end
end
def solve(input)
best=[input.b.to_i + 2, input.a.to_i + input.b.to_i+1].min
correct_chance=1
input.a.to_i.times do |i|
correct_chance=input.odds[i].to_f*correct_chance
keysneeded=input.b.to_i-input.a.to_i+1+(input.a.to_i-(i+1))*2
value=correct_chance*(keysneeded)+(1-correct_chance)*(keysneeded+input.b.to_i+1)
if value<best
best=value
end
end
best
end
end
end
<file_sep>/lib/codejam/submissions/qualification2012/problem_b.rb
module CodeJam
class ProblemB < Problem
def initialize
super("qualification2012/problem_b/")
end
def solve(input)
input_split = input.split(' ')
hits = 0
googlers = input_split[0].to_i
surprises = input_split[1].to_i
checkresult = input_split[2].to_i*3
googlers.times do |i|
total = input_split[i+3].to_i
if (total+2>=checkresult)
hits+=1
else
if (total+4>=checkresult && surprises>0 && checkresult>3)
hits+=1
surprises-=1
end
end
end
hits
end
end
end
<file_sep>/lib/codejam/problem.rb
module CodeJam
class Problem
def initialize(problem_path)
input = File.open("data/#{problem_path}input", "r")
output = File.open("data/#{problem_path}output", "w")
x = input.readline.to_i
x.times do |i|
output.puts "Case ##{i+1}: #{solve(input.readline.to_s)}"
end
end
end
end | 43dd69ae3f0b44016c0d946ab794055a168d3586 | [
"Ruby"
] | 8 | Ruby | calmon/codejam | abb5e6d5050583cae47c694adc114d4d51c78158 | 6abbbfe03a3805d2e08a2790b5015fdc0d6efbd1 |
refs/heads/master | <repo_name>Jaiver2012/store<file_sep>/src/App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import GameList from './Components/GameList';
import { render } from '@testing-library/react';
import GameForm from './Components/GameForm';
class App extends Component{
constructor(){
super();
this.state={
gameEdit:{id:"",name:"", type:"",price:""},
owner:"Jaiver",
games:[
{id:1,name:"<NAME>",type:"Acade",price:"3000"},
{id:2,name:"Call of Duty",type:"FPS",price:"2000"},
{id:3,name:"Celeste",type:"Platadormero",price:"45000"},
]
}
}
handleAddGame(game){
let games = this.state.games;
games.push(game);
this.setState({
games: games
})
}
handleOnEdit(game){
console.log(game)
this.setState({
gameEdit:game
})
}
render(){
return (
<div className="App">
<GameList owner={this.state.owner} games={this.state.games} onEdit={this.handleOnEdit.bind(this)}/>
<GameForm onSubmit={this.handleAddGame.bind(this)} game={this.state.gameEdit}/>
</div>
);
}
}
export default App;
| f49d9fa72a75681ac10492ad51f3e4720942e322 | [
"JavaScript"
] | 1 | JavaScript | Jaiver2012/store | 37b16490bb55ed82ae0e677606d4d6583baf1f16 | 39d4ded301fc0d05003ddb3fece00c975b53ae14 |
refs/heads/master | <repo_name>Andreyc4d/python-stepick-2.1<file_sep>/second.py
DescrClass = dict() #description error class 2 dim list
AlreadySet = set()
str1 = []
with open('input.txt', 'r') as f:
n=int(f.readline())
for i in range(n):
str1 = f.readline().strip().split()
if len(str1) == 1:
DescrClass[str1[0]] = []
elif len(str1)>1:
DescrClass[str1[0]] = str1[2:]
n=int(f.readline())
print(DescrClass)
print(len(DescrClass['OSError']))
print('n='+str(n))
tmp1 = 0
for i in range(n):
str2 = f.readline().strip()
for element in DescrClass[str2]:
if element in AlreadySet:
print(str2)
break
AlreadySet.add(str2)
print(AlreadySet)
| d3ce9e6be013232912e2fb619b3c372f043f11b8 | [
"Python"
] | 1 | Python | Andreyc4d/python-stepick-2.1 | e56084461a0fe5d0aac864fac76e48f7b8904e7b | 842ff59b008a736b8ee949529e5eb4120abe1443 |
refs/heads/master | <repo_name>massyao/indeed_crawler<file_sep>/test.js
//var express = require('express');
//var utility = require('utility');
//var app = express();
const cheerio = require('cheerio');
const superagent = require('superagent');
const url = require('url');
const eventproxy = require('eventproxy');
const fs = require('fs');
const xlsx = require('node-xlsx'); //基于Node.js解析excel文件数据及生成excel文件,仅支持xlsx格式文件;
/*
// 存放月报路径
var filepath = 'D:\\node_project\\indeed_crawler\\test_xlsx';
// 整理后文件及路径
var savepath = "D:\\node_project\\indeed_crawler\\indeed.xlsx";
// 获得月报下的文件集合
var filesList = fs.readdirSync(filepath);
//读取文件内容
var obj = xlsx.parse(__dirname+'/test.xlsx');
var excelObj=obj[0].data;
console.log(excelObj);
var data = [];
for(var i in excelObj){
var arr=[];
var value=excelObj[i];
for(var j in value){
arr.push(value[j]);
}
data.push(arr);
}
var buffer = xlsx.build([
{
name:'sheet1',
data:data
}
]);
//将文件内容插入新的文件中
fs.writeFileSync('test1.xlsx',buffer,{'flag':'w'});
*/
function isNULL(e){
return typeof e === 'object' && !(e instanceof Object);
}
function str_trim(a){
return typeof a === 'string' ? a.replace(/\n/g,''): "null" ;
}
function get_real_Date(str){
if(typeof str === 'string'){
var days = 0;
if(str.search(/day/)){
days = parseInt(str.match(/(\d)+.*(?=day)/g)[0]);
return new Date((new Date()).getTime() - days*24*60*60*1000).toString().slice(4,15);
}else{
return 'null' ;
}
}
}
function get_contents(content_url){
var index = 0;
// 用 superagent 去抓取 https://cnodejs.org/ 的内容
superagent.get(content_url).end(function (err, sres) {
// 常规的错误处理
try{
var $ = cheerio.load(sres.text);
//console.log(typeof $);
var items = [];
$('.row.result').each(function (idx, element) {
var $element = $(element);
/*
items.push({
title:$(element).find('.jobtitle a').html(),
company:str_trim($($element).find('.company a').html()),
company_location:$($element).find('.location').html(),
summary:str_trim($($element).find('.summary').html()),
date:get_real_Date($($element).find('.date').html()),
salary:(function(){
var a = $($element).find('.snip div');
if(a.length > 11 ){
return str_trim($($element).find('.snip div').first().text());
}else{
return 'not mentioned';
}
})()
});
*/
var temp_arr = [];
temp_arr[0] = $(element).find('.jobtitle a').html();
temp_arr[1] = str_trim($($element).find('.company a').html());
temp_arr[2] = $($element).find('.location').html();
temp_arr[3] = str_trim($($element).find('.summary').html());
temp_arr[4] = str_trim($($element).find('.summary').html());
temp_arr[5] = get_real_Date($($element).find('.date').html());
temp_arr[6] = (function(){
var a = $($element).find('.snip div');
if(a.length > 11 ){
return str_trim($($element).find('.snip div').first().text());
}else{
return 'null';
}
})();
items.push(temp_arr);
temp_arr = null;
});;
//console.log(items);
console.log('parse items '+(index+1)+' -- '+(index+9)+' success !');
//return items;
//console.log(content);
var buffer = xlsx.build([
{
name:'sheet1',
data:items
}
]);
//将文件内容插入新的文件中
fs.writeFileSync('test1.xlsx',buffer,{'flag':'w'});
console.log('write success !!');
}catch(e){
console.log(e.message);
}
});
}
// https://cnodejs.org/
// https://www.indeed.com/jobs?l=California&start=10
var indeed_url = 'https://www.indeed.com/jobs?q=&l=California';
// var indeed_url = 'https://www.indeed.com/jobs?l=California&start='+10;
var content = get_contents(indeed_url);
/*
app.get('/', function (req, res, next) {
// 用 superagent 去抓取 https://cnodejs.org/ 的内容
superagent.get('https://cnodejs.org/')
.end(function (err, sres) {
// 常规的错误处理
if (err) {
return next(err);
}
// sres.text 里面存储着网页的 html 内容,将它传给 cheerio.load 之后
// 就可以得到一个实现了 jquery 接口的变量,我们习惯性地将它命名为 `$`
// 剩下就都是 jquery 的内容了
var $ = cheerio.load(sres.text);
var items = [];
$('#topic_list .topic_title').each(function (idx, element) {
var $element = $(element);
items.push({
title: $element.attr('title'),
href: $element.attr('href')
});
});
res.send(items);
});
});
app.listen(3000, function (req, res) {
console.log('app is running at port 3000');
});
*/
/*
var sleep = function (time) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve();
}, time);
})
};
var start = async function () {
// 在这里使用起来就像同步代码那样直观
console.log('start');
await sleep(3000);
console.log('end');
};
start();
const http = require('http');
async function ab() {
//这里的关键是await后面要跟一个Promise
await new Promise(function(resolve) {
http.get('http://www.baidu.com/', (res) => {
console.log('1');
resolve();
})
});
console.log('2');
console.log('3');
}
ab();
*/
/*
async function main() {
await ping();
}
async function ping() {
for (var i = 0; i < 10; i++) {
await delay(300);
console.log("ping");
}
}
//function delay(ms: number) {
function delay(ms=300) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main();
*/
/*
function async getTrace () {
let pageContent
try {
pageContent = await fetch('https://www.jdon.com', {
method: 'get'
})
} catch (ex) {
console.error(ex)
}
return pageContent
}
getTrace()
.then()
*/
/*
const fs = require('fs');
const path = require('path');
const request = require('request');
var movieDir = __dirname + '/movies',
exts = ['.mkv', '.avi', '.mp4', '.rm', '.rmvb', '.wmv'];
// 读取文件列表
var readFiles = function () {
return new Promise(function (resolve, reject) {
fs.readdir(movieDir, function (err, files) {
resolve(files.filter((v) => exts.includes(path.parse(v).ext)));
});
});
};
// 获取海报
var getPoster = function (movieName) {
let url = `https://api.douban.com/v2/movie/search?q=${encodeURI(movieName)}`;
return new Promise(function (resolve, reject) {
request({url: url, json: true}, function (error, response, body) {
if (error) return reject(error);
resolve(body.subjects[0].images.large);
})
});
};
// 保存海报
var savePoster = function (movieName, url) {
request.get(url).pipe(fs.createWriteStream(path.join(movieDir, movieName + '.jpg')));
};
(async () => {
let files = await readFiles();
// await只能使用在原生语法
for (var file of files) {
let name = path.parse(file).name;
console.log(`正在获取【${name}】的海报`);
savePoster(name, await getPoster(name));
}
console.log('=== 获取海报完成 ===');
})();
*/
<file_sep>/file_compile.js
const fs = require('fs');
const xlsx = require('node-xlsx');
// 目标excel文件存放路径
var filepath = 'D:\\node_project\\indeed_crawler\\test_xlsx';
// 整理后文件及路径
var savepath = "D:\\node_project\\indeed_crawler\\indeed.xlsx";
var globe_data = [];
main();
async function read_one_excel(index){
var xlsx_arr = xlsx.parse(__dirname+'/test_xlsx/test'+index+'.xlsx');
//console.log(xlsx_arr[0]);
//console.log();
var excel_arr=xlsx_arr[0].data;
for(var j in excel_arr){
var arr=[];
var value=excel_arr[j]; //把array当关联数组用,速度会略慢,下一步改for循环
for(var k in value){
arr.push(value[k]);
}
globe_data.push(arr);
}
console.log('program parsed '+globe_data.length+' rows of data !');
}
async function read_excels(){
// 获得excel文件集合
var filesList = fs.readdirSync(filepath);
for(let i=0;i<filesList.length;i++){
//读取文件内容
await read_one_excel(i);
}
}
async function write_compile_file(){
console.log('build the excel !');
// build the new excel
var buffer = xlsx.build([
{
name:'sheet1',
data:globe_data
}
]);
globe_data = [];//释放内存
//将文件内容插入新的文件中
fs.writeFileSync('compile.xlsx',buffer,{'flag':'w'});
console.log('bingo !');
buffer = null ; //释放内存
}
async function main(){
await read_excels();
write_compile_file();
}
| 3df9157df89e7b9bb668279fb06bd193a1facdb8 | [
"JavaScript"
] | 2 | JavaScript | massyao/indeed_crawler | efb8dbd9be042b423b5c28e6236710cc89eb7e41 | e70378f49cf93e5dcb4705ce23663e13bee57908 |
refs/heads/master | <file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/*
Module Name:
- OutputStateMachineEngine.hpp
Abstract:
- This is the implementation of the client VT output state machine engine.
*/
#pragma once
#include <functional>
#include "../adapter/termDispatch.hpp"
#include "telemetry.hpp"
#include "IStateMachineEngine.hpp"
#include "../../inc/ITerminalOutputConnection.hpp"
namespace Microsoft::Console::VirtualTerminal
{
class OutputStateMachineEngine : public IStateMachineEngine
{
public:
OutputStateMachineEngine(std::unique_ptr<ITermDispatch> pDispatch);
bool ActionExecute(const wchar_t wch) override;
bool ActionExecuteFromEscape(const wchar_t wch) override;
bool ActionPrint(const wchar_t wch) override;
bool ActionPrintString(const std::wstring_view string) override;
bool ActionPassThroughString(const std::wstring_view string) override;
bool ActionEscDispatch(const VTID id) override;
bool ActionVt52EscDispatch(const VTID id, const gsl::span<const size_t> parameters) override;
bool ActionCsiDispatch(const VTID id, const gsl::span<const size_t> parameters) override;
bool ActionClear() noexcept override;
bool ActionIgnore() noexcept override;
bool ActionOscDispatch(const wchar_t wch,
const size_t parameter,
const std::wstring_view string) override;
bool ActionSs3Dispatch(const wchar_t wch,
const gsl::span<const size_t> parameters) noexcept override;
bool ParseControlSequenceAfterSs3() const noexcept override;
bool FlushAtEndOfString() const noexcept override;
bool DispatchControlCharsFromEscape() const noexcept override;
bool DispatchIntermediatesFromEscape() const noexcept override;
void SetTerminalConnection(Microsoft::Console::ITerminalOutputConnection* const pTtyConnection,
std::function<bool()> pfnFlushToTerminal);
const ITermDispatch& Dispatch() const noexcept;
ITermDispatch& Dispatch() noexcept;
private:
std::unique_ptr<ITermDispatch> _dispatch;
Microsoft::Console::ITerminalOutputConnection* _pTtyConnection;
std::function<bool()> _pfnFlushToTerminal;
wchar_t _lastPrintedChar;
std::vector<DispatchTypes::GraphicsOptions> _graphicsOptions;
enum EscActionCodes : uint64_t
{
DECSC_CursorSave = VTID("7"),
DECRC_CursorRestore = VTID("8"),
DECKPAM_KeypadApplicationMode = VTID("="),
DECKPNM_KeypadNumericMode = VTID(">"),
IND_Index = VTID("D"),
NEL_NextLine = VTID("E"),
HTS_HorizontalTabSet = VTID("H"),
RI_ReverseLineFeed = VTID("M"),
SS2_SingleShift = VTID("N"),
SS3_SingleShift = VTID("O"),
ST_StringTerminator = VTID("\\"),
RIS_ResetToInitialState = VTID("c"),
LS2_LockingShift = VTID("n"),
LS3_LockingShift = VTID("o"),
LS1R_LockingShift = VTID("~"),
LS2R_LockingShift = VTID("}"),
LS3R_LockingShift = VTID("|"),
DECALN_ScreenAlignmentPattern = VTID("#8")
};
enum CsiActionCodes : uint64_t
{
ICH_InsertCharacter = VTID("@"),
CUU_CursorUp = VTID("A"),
CUD_CursorDown = VTID("B"),
CUF_CursorForward = VTID("C"),
CUB_CursorBackward = VTID("D"),
CNL_CursorNextLine = VTID("E"),
CPL_CursorPrevLine = VTID("F"),
CHA_CursorHorizontalAbsolute = VTID("G"),
CUP_CursorPosition = VTID("H"),
CHT_CursorForwardTab = VTID("I"),
ED_EraseDisplay = VTID("J"),
EL_EraseLine = VTID("K"),
IL_InsertLine = VTID("L"),
DL_DeleteLine = VTID("M"),
DCH_DeleteCharacter = VTID("P"),
SU_ScrollUp = VTID("S"),
SD_ScrollDown = VTID("T"),
ECH_EraseCharacters = VTID("X"),
CBT_CursorBackTab = VTID("Z"),
HPA_HorizontalPositionAbsolute = VTID("`"),
HPR_HorizontalPositionRelative = VTID("a"),
REP_RepeatCharacter = VTID("b"),
DA_DeviceAttributes = VTID("c"),
DA2_SecondaryDeviceAttributes = VTID(">c"),
DA3_TertiaryDeviceAttributes = VTID("=c"),
VPA_VerticalLinePositionAbsolute = VTID("d"),
VPR_VerticalPositionRelative = VTID("e"),
HVP_HorizontalVerticalPosition = VTID("f"),
TBC_TabClear = VTID("g"),
DECSET_PrivateModeSet = VTID("?h"),
DECRST_PrivateModeReset = VTID("?l"),
SGR_SetGraphicsRendition = VTID("m"),
DSR_DeviceStatusReport = VTID("n"),
DECSTBM_SetScrollingRegion = VTID("r"),
ANSISYSSC_CursorSave = VTID("s"), // NOTE: Overlaps with DECLRMM/DECSLRM. Fix when/if implemented.
DTTERM_WindowManipulation = VTID("t"), // NOTE: Overlaps with DECSLPP. Fix when/if implemented.
ANSISYSRC_CursorRestore = VTID("u"),
DECSCUSR_SetCursorStyle = VTID(" q"),
DECSTR_SoftReset = VTID("!p"),
DECSCPP_SetColumnsPerPage = VTID("$|")
};
enum Vt52ActionCodes : uint64_t
{
CursorUp = VTID("A"),
CursorDown = VTID("B"),
CursorRight = VTID("C"),
CursorLeft = VTID("D"),
EnterGraphicsMode = VTID("F"),
ExitGraphicsMode = VTID("G"),
CursorToHome = VTID("H"),
ReverseLineFeed = VTID("I"),
EraseToEndOfScreen = VTID("J"),
EraseToEndOfLine = VTID("K"),
DirectCursorAddress = VTID("Y"),
Identify = VTID("Z"),
EnterAlternateKeypadMode = VTID("="),
ExitAlternateKeypadMode = VTID(">"),
ExitVt52Mode = VTID("<")
};
enum OscActionCodes : unsigned int
{
SetIconAndWindowTitle = 0,
SetWindowIcon = 1,
SetWindowTitle = 2,
SetWindowProperty = 3, // Not implemented
SetColor = 4,
Hyperlink = 8,
SetForegroundColor = 10,
SetBackgroundColor = 11,
SetCursorColor = 12,
SetClipboard = 52,
ResetForegroundColor = 110, // Not implemented
ResetBackgroundColor = 111, // Not implemented
ResetCursorColor = 112
};
static constexpr DispatchTypes::GraphicsOptions DefaultGraphicsOption = DispatchTypes::GraphicsOptions::Off;
bool _GetGraphicsOptions(const gsl::span<const size_t> parameters,
std::vector<DispatchTypes::GraphicsOptions>& options) const;
static constexpr DispatchTypes::EraseType DefaultEraseType = DispatchTypes::EraseType::ToEnd;
bool _GetEraseOperation(const gsl::span<const size_t> parameters,
DispatchTypes::EraseType& eraseType) const noexcept;
static constexpr size_t DefaultCursorDistance = 1;
bool _GetCursorDistance(const gsl::span<const size_t> parameters,
size_t& distance) const noexcept;
static constexpr size_t DefaultScrollDistance = 1;
bool _GetScrollDistance(const gsl::span<const size_t> parameters,
size_t& distance) const noexcept;
static constexpr size_t DefaultConsoleWidth = 80;
bool _GetConsoleWidth(const gsl::span<const size_t> parameters,
size_t& consoleWidth) const noexcept;
static constexpr size_t DefaultLine = 1;
static constexpr size_t DefaultColumn = 1;
bool _GetXYPosition(const gsl::span<const size_t> parameters,
size_t& line,
size_t& column) const noexcept;
bool _GetDeviceStatusOperation(const gsl::span<const size_t> parameters,
DispatchTypes::AnsiStatusType& statusType) const noexcept;
bool _VerifyHasNoParameters(const gsl::span<const size_t> parameters) const noexcept;
bool _VerifyDeviceAttributesParams(const gsl::span<const size_t> parameters) const noexcept;
bool _GetPrivateModeParams(const gsl::span<const size_t> parameters,
std::vector<DispatchTypes::PrivateModeParams>& privateModes) const;
static constexpr size_t DefaultTopMargin = 0;
static constexpr size_t DefaultBottomMargin = 0;
bool _GetTopBottomMargins(const gsl::span<const size_t> parameters,
size_t& topMargin,
size_t& bottomMargin) const noexcept;
bool _GetOscTitle(const std::wstring_view string,
std::wstring& title) const;
static constexpr size_t DefaultTabDistance = 1;
bool _GetTabDistance(const gsl::span<const size_t> parameters,
size_t& distance) const noexcept;
static constexpr size_t DefaultTabClearType = 0;
bool _GetTabClearType(const gsl::span<const size_t> parameters,
size_t& clearType) const noexcept;
static constexpr DispatchTypes::WindowManipulationType DefaultWindowManipulationType = DispatchTypes::WindowManipulationType::Invalid;
bool _GetWindowManipulationType(const gsl::span<const size_t> parameters,
unsigned int& function) const noexcept;
static bool s_HexToUint(const wchar_t wch,
unsigned int& value) noexcept;
bool _GetOscSetColorTable(const std::wstring_view string,
size_t& tableIndex,
DWORD& rgb) const noexcept;
static bool s_ParseColorSpec(const std::wstring_view string,
DWORD& rgb) noexcept;
bool _GetOscSetColor(const std::wstring_view string,
DWORD& rgb) const noexcept;
static constexpr DispatchTypes::CursorStyle DefaultCursorStyle = DispatchTypes::CursorStyle::BlinkingBlockDefault;
bool _GetCursorStyle(const gsl::span<const size_t> parameters,
DispatchTypes::CursorStyle& cursorStyle) const noexcept;
static constexpr size_t DefaultRepeatCount = 1;
bool _GetRepeatCount(const gsl::span<const size_t> parameters,
size_t& repeatCount) const noexcept;
bool _GetOscSetClipboard(const std::wstring_view string,
std::wstring& content,
bool& queryClipboard) const noexcept;
static constexpr std::wstring_view hyperlinkIDParameter{ L"id=" };
bool _ParseHyperlink(const std::wstring_view string,
std::wstring& params,
std::wstring& uri) const;
void _ClearLastChar() noexcept;
};
}
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "precomp.h"
#include "inc/utils.hpp"
using namespace Microsoft::Console;
static constexpr std::array<til::color, 16> campbellColorTable{
til::color{ 0x0C, 0x0C, 0x0C },
til::color{ 0xC5, 0x0F, 0x1F },
til::color{ 0x13, 0xA1, 0x0E },
til::color{ 0xC1, 0x9C, 0x00 },
til::color{ 0x00, 0x37, 0xDA },
til::color{ 0x88, 0x17, 0x98 },
til::color{ 0x3A, 0x96, 0xDD },
til::color{ 0xCC, 0xCC, 0xCC },
til::color{ 0x76, 0x76, 0x76 },
til::color{ 0xE7, 0x48, 0x56 },
til::color{ 0x16, 0xC6, 0x0C },
til::color{ 0xF9, 0xF1, 0xA5 },
til::color{ 0x3B, 0x78, 0xFF },
til::color{ 0xB4, 0x00, 0x9E },
til::color{ 0x61, 0xD6, 0xD6 },
til::color{ 0xF2, 0xF2, 0xF2 },
};
static constexpr std::array<til::color, 256> standardXterm256ColorTable{
til::color{ 0x00, 0x00, 0x00 },
til::color{ 0x80, 0x00, 0x00 },
til::color{ 0x00, 0x80, 0x00 },
til::color{ 0x80, 0x80, 0x00 },
til::color{ 0x00, 0x00, 0x80 },
til::color{ 0x80, 0x00, 0x80 },
til::color{ 0x00, 0x80, 0x80 },
til::color{ 0xC0, 0xC0, 0xC0 },
til::color{ 0x80, 0x80, 0x80 },
til::color{ 0xFF, 0x00, 0x00 },
til::color{ 0x00, 0xFF, 0x00 },
til::color{ 0xFF, 0xFF, 0x00 },
til::color{ 0x00, 0x00, 0xFF },
til::color{ 0xFF, 0x00, 0xFF },
til::color{ 0x00, 0xFF, 0xFF },
til::color{ 0xFF, 0xFF, 0xFF },
til::color{ 0x00, 0x00, 0x00 },
til::color{ 0x00, 0x00, 0x5F },
til::color{ 0x00, 0x00, 0x87 },
til::color{ 0x00, 0x00, 0xAF },
til::color{ 0x00, 0x00, 0xD7 },
til::color{ 0x00, 0x00, 0xFF },
til::color{ 0x00, 0x5F, 0x00 },
til::color{ 0x00, 0x5F, 0x5F },
til::color{ 0x00, 0x5F, 0x87 },
til::color{ 0x00, 0x5F, 0xAF },
til::color{ 0x00, 0x5F, 0xD7 },
til::color{ 0x00, 0x5F, 0xFF },
til::color{ 0x00, 0x87, 0x00 },
til::color{ 0x00, 0x87, 0x5F },
til::color{ 0x00, 0x87, 0x87 },
til::color{ 0x00, 0x87, 0xAF },
til::color{ 0x00, 0x87, 0xD7 },
til::color{ 0x00, 0x87, 0xFF },
til::color{ 0x00, 0xAF, 0x00 },
til::color{ 0x00, 0xAF, 0x5F },
til::color{ 0x00, 0xAF, 0x87 },
til::color{ 0x00, 0xAF, 0xAF },
til::color{ 0x00, 0xAF, 0xD7 },
til::color{ 0x00, 0xAF, 0xFF },
til::color{ 0x00, 0xD7, 0x00 },
til::color{ 0x00, 0xD7, 0x5F },
til::color{ 0x00, 0xD7, 0x87 },
til::color{ 0x00, 0xD7, 0xAF },
til::color{ 0x00, 0xD7, 0xD7 },
til::color{ 0x00, 0xD7, 0xFF },
til::color{ 0x00, 0xFF, 0x00 },
til::color{ 0x00, 0xFF, 0x5F },
til::color{ 0x00, 0xFF, 0x87 },
til::color{ 0x00, 0xFF, 0xAF },
til::color{ 0x00, 0xFF, 0xD7 },
til::color{ 0x00, 0xFF, 0xFF },
til::color{ 0x5F, 0x00, 0x00 },
til::color{ 0x5F, 0x00, 0x5F },
til::color{ 0x5F, 0x00, 0x87 },
til::color{ 0x5F, 0x00, 0xAF },
til::color{ 0x5F, 0x00, 0xD7 },
til::color{ 0x5F, 0x00, 0xFF },
til::color{ 0x5F, 0x5F, 0x00 },
til::color{ 0x5F, 0x5F, 0x5F },
til::color{ 0x5F, 0x5F, 0x87 },
til::color{ 0x5F, 0x5F, 0xAF },
til::color{ 0x5F, 0x5F, 0xD7 },
til::color{ 0x5F, 0x5F, 0xFF },
til::color{ 0x5F, 0x87, 0x00 },
til::color{ 0x5F, 0x87, 0x5F },
til::color{ 0x5F, 0x87, 0x87 },
til::color{ 0x5F, 0x87, 0xAF },
til::color{ 0x5F, 0x87, 0xD7 },
til::color{ 0x5F, 0x87, 0xFF },
til::color{ 0x5F, 0xAF, 0x00 },
til::color{ 0x5F, 0xAF, 0x5F },
til::color{ 0x5F, 0xAF, 0x87 },
til::color{ 0x5F, 0xAF, 0xAF },
til::color{ 0x5F, 0xAF, 0xD7 },
til::color{ 0x5F, 0xAF, 0xFF },
til::color{ 0x5F, 0xD7, 0x00 },
til::color{ 0x5F, 0xD7, 0x5F },
til::color{ 0x5F, 0xD7, 0x87 },
til::color{ 0x5F, 0xD7, 0xAF },
til::color{ 0x5F, 0xD7, 0xD7 },
til::color{ 0x5F, 0xD7, 0xFF },
til::color{ 0x5F, 0xFF, 0x00 },
til::color{ 0x5F, 0xFF, 0x5F },
til::color{ 0x5F, 0xFF, 0x87 },
til::color{ 0x5F, 0xFF, 0xAF },
til::color{ 0x5F, 0xFF, 0xD7 },
til::color{ 0x5F, 0xFF, 0xFF },
til::color{ 0x87, 0x00, 0x00 },
til::color{ 0x87, 0x00, 0x5F },
til::color{ 0x87, 0x00, 0x87 },
til::color{ 0x87, 0x00, 0xAF },
til::color{ 0x87, 0x00, 0xD7 },
til::color{ 0x87, 0x00, 0xFF },
til::color{ 0x87, 0x5F, 0x00 },
til::color{ 0x87, 0x5F, 0x5F },
til::color{ 0x87, 0x5F, 0x87 },
til::color{ 0x87, 0x5F, 0xAF },
til::color{ 0x87, 0x5F, 0xD7 },
til::color{ 0x87, 0x5F, 0xFF },
til::color{ 0x87, 0x87, 0x00 },
til::color{ 0x87, 0x87, 0x5F },
til::color{ 0x87, 0x87, 0x87 },
til::color{ 0x87, 0x87, 0xAF },
til::color{ 0x87, 0x87, 0xD7 },
til::color{ 0x87, 0x87, 0xFF },
til::color{ 0x87, 0xAF, 0x00 },
til::color{ 0x87, 0xAF, 0x5F },
til::color{ 0x87, 0xAF, 0x87 },
til::color{ 0x87, 0xAF, 0xAF },
til::color{ 0x87, 0xAF, 0xD7 },
til::color{ 0x87, 0xAF, 0xFF },
til::color{ 0x87, 0xD7, 0x00 },
til::color{ 0x87, 0xD7, 0x5F },
til::color{ 0x87, 0xD7, 0x87 },
til::color{ 0x87, 0xD7, 0xAF },
til::color{ 0x87, 0xD7, 0xD7 },
til::color{ 0x87, 0xD7, 0xFF },
til::color{ 0x87, 0xFF, 0x00 },
til::color{ 0x87, 0xFF, 0x5F },
til::color{ 0x87, 0xFF, 0x87 },
til::color{ 0x87, 0xFF, 0xAF },
til::color{ 0x87, 0xFF, 0xD7 },
til::color{ 0x87, 0xFF, 0xFF },
til::color{ 0xAF, 0x00, 0x00 },
til::color{ 0xAF, 0x00, 0x5F },
til::color{ 0xAF, 0x00, 0x87 },
til::color{ 0xAF, 0x00, 0xAF },
til::color{ 0xAF, 0x00, 0xD7 },
til::color{ 0xAF, 0x00, 0xFF },
til::color{ 0xAF, 0x5F, 0x00 },
til::color{ 0xAF, 0x5F, 0x5F },
til::color{ 0xAF, 0x5F, 0x87 },
til::color{ 0xAF, 0x5F, 0xAF },
til::color{ 0xAF, 0x5F, 0xD7 },
til::color{ 0xAF, 0x5F, 0xFF },
til::color{ 0xAF, 0x87, 0x00 },
til::color{ 0xAF, 0x87, 0x5F },
til::color{ 0xAF, 0x87, 0x87 },
til::color{ 0xAF, 0x87, 0xAF },
til::color{ 0xAF, 0x87, 0xD7 },
til::color{ 0xAF, 0x87, 0xFF },
til::color{ 0xAF, 0xAF, 0x00 },
til::color{ 0xAF, 0xAF, 0x5F },
til::color{ 0xAF, 0xAF, 0x87 },
til::color{ 0xAF, 0xAF, 0xAF },
til::color{ 0xAF, 0xAF, 0xD7 },
til::color{ 0xAF, 0xAF, 0xFF },
til::color{ 0xAF, 0xD7, 0x00 },
til::color{ 0xAF, 0xD7, 0x5F },
til::color{ 0xAF, 0xD7, 0x87 },
til::color{ 0xAF, 0xD7, 0xAF },
til::color{ 0xAF, 0xD7, 0xD7 },
til::color{ 0xAF, 0xD7, 0xFF },
til::color{ 0xAF, 0xFF, 0x00 },
til::color{ 0xAF, 0xFF, 0x5F },
til::color{ 0xAF, 0xFF, 0x87 },
til::color{ 0xAF, 0xFF, 0xAF },
til::color{ 0xAF, 0xFF, 0xD7 },
til::color{ 0xAF, 0xFF, 0xFF },
til::color{ 0xD7, 0x00, 0x00 },
til::color{ 0xD7, 0x00, 0x5F },
til::color{ 0xD7, 0x00, 0x87 },
til::color{ 0xD7, 0x00, 0xAF },
til::color{ 0xD7, 0x00, 0xD7 },
til::color{ 0xD7, 0x00, 0xFF },
til::color{ 0xD7, 0x5F, 0x00 },
til::color{ 0xD7, 0x5F, 0x5F },
til::color{ 0xD7, 0x5F, 0x87 },
til::color{ 0xD7, 0x5F, 0xAF },
til::color{ 0xD7, 0x5F, 0xD7 },
til::color{ 0xD7, 0x5F, 0xFF },
til::color{ 0xD7, 0x87, 0x00 },
til::color{ 0xD7, 0x87, 0x5F },
til::color{ 0xD7, 0x87, 0x87 },
til::color{ 0xD7, 0x87, 0xAF },
til::color{ 0xD7, 0x87, 0xD7 },
til::color{ 0xD7, 0x87, 0xFF },
til::color{ 0xD7, 0xAF, 0x00 },
til::color{ 0xD7, 0xAF, 0x5F },
til::color{ 0xD7, 0xAF, 0x87 },
til::color{ 0xD7, 0xAF, 0xAF },
til::color{ 0xD7, 0xAF, 0xD7 },
til::color{ 0xD7, 0xAF, 0xFF },
til::color{ 0xD7, 0xD7, 0x00 },
til::color{ 0xD7, 0xD7, 0x5F },
til::color{ 0xD7, 0xD7, 0x87 },
til::color{ 0xD7, 0xD7, 0xAF },
til::color{ 0xD7, 0xD7, 0xD7 },
til::color{ 0xD7, 0xD7, 0xFF },
til::color{ 0xD7, 0xFF, 0x00 },
til::color{ 0xD7, 0xFF, 0x5F },
til::color{ 0xD7, 0xFF, 0x87 },
til::color{ 0xD7, 0xFF, 0xAF },
til::color{ 0xD7, 0xFF, 0xD7 },
til::color{ 0xD7, 0xFF, 0xFF },
til::color{ 0xFF, 0x00, 0x00 },
til::color{ 0xFF, 0x00, 0x5F },
til::color{ 0xFF, 0x00, 0x87 },
til::color{ 0xFF, 0x00, 0xAF },
til::color{ 0xFF, 0x00, 0xD7 },
til::color{ 0xFF, 0x00, 0xFF },
til::color{ 0xFF, 0x5F, 0x00 },
til::color{ 0xFF, 0x5F, 0x5F },
til::color{ 0xFF, 0x5F, 0x87 },
til::color{ 0xFF, 0x5F, 0xAF },
til::color{ 0xFF, 0x5F, 0xD7 },
til::color{ 0xFF, 0x5F, 0xFF },
til::color{ 0xFF, 0x87, 0x00 },
til::color{ 0xFF, 0x87, 0x5F },
til::color{ 0xFF, 0x87, 0x87 },
til::color{ 0xFF, 0x87, 0xAF },
til::color{ 0xFF, 0x87, 0xD7 },
til::color{ 0xFF, 0x87, 0xFF },
til::color{ 0xFF, 0xAF, 0x00 },
til::color{ 0xFF, 0xAF, 0x5F },
til::color{ 0xFF, 0xAF, 0x87 },
til::color{ 0xFF, 0xAF, 0xAF },
til::color{ 0xFF, 0xAF, 0xD7 },
til::color{ 0xFF, 0xAF, 0xFF },
til::color{ 0xFF, 0xD7, 0x00 },
til::color{ 0xFF, 0xD7, 0x5F },
til::color{ 0xFF, 0xD7, 0x87 },
til::color{ 0xFF, 0xD7, 0xAF },
til::color{ 0xFF, 0xD7, 0xD7 },
til::color{ 0xFF, 0xD7, 0xFF },
til::color{ 0xFF, 0xFF, 0x00 },
til::color{ 0xFF, 0xFF, 0x5F },
til::color{ 0xFF, 0xFF, 0x87 },
til::color{ 0xFF, 0xFF, 0xAF },
til::color{ 0xFF, 0xFF, 0xD7 },
til::color{ 0xFF, 0xFF, 0xFF },
til::color{ 0x08, 0x08, 0x08 },
til::color{ 0x12, 0x12, 0x12 },
til::color{ 0x1C, 0x1C, 0x1C },
til::color{ 0x26, 0x26, 0x26 },
til::color{ 0x30, 0x30, 0x30 },
til::color{ 0x3A, 0x3A, 0x3A },
til::color{ 0x44, 0x44, 0x44 },
til::color{ 0x4E, 0x4E, 0x4E },
til::color{ 0x58, 0x58, 0x58 },
til::color{ 0x62, 0x62, 0x62 },
til::color{ 0x6C, 0x6C, 0x6C },
til::color{ 0x76, 0x76, 0x76 },
til::color{ 0x80, 0x80, 0x80 },
til::color{ 0x8A, 0x8A, 0x8A },
til::color{ 0x94, 0x94, 0x94 },
til::color{ 0x9E, 0x9E, 0x9E },
til::color{ 0xA8, 0xA8, 0xA8 },
til::color{ 0xB2, 0xB2, 0xB2 },
til::color{ 0xBC, 0xBC, 0xBC },
til::color{ 0xC6, 0xC6, 0xC6 },
til::color{ 0xD0, 0xD0, 0xD0 },
til::color{ 0xDA, 0xDA, 0xDA },
til::color{ 0xE4, 0xE4, 0xE4 },
til::color{ 0xEE, 0xEE, 0xEE },
};
// Function Description:
// - Creates a String representation of a guid, in the format
// "{12345678-ABCD-EF12-3456-7890ABCDEF12}"
// Arguments:
// - guid: the GUID to create the string for
// Return Value:
// - a string representation of the GUID. On failure, throws E_INVALIDARG.
std::wstring Utils::GuidToString(const GUID guid)
{
return wil::str_printf<std::wstring>(L"{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
}
// Method Description:
// - Parses a GUID from a string representation of the GUID. Throws an exception
// if it fails to parse the GUID. See documentation of IIDFromString for
// details.
// Arguments:
// - wstr: a string representation of the GUID to parse
// Return Value:
// - A GUID if the string could successfully be parsed. On failure, throws the
// failing HRESULT.
GUID Utils::GuidFromString(const std::wstring wstr)
{
GUID result{};
THROW_IF_FAILED(IIDFromString(wstr.c_str(), &result));
return result;
}
// Method Description:
// - Creates a GUID, but not via an out parameter.
// Return Value:
// - A GUID if there's enough randomness; otherwise, an exception.
GUID Utils::CreateGuid()
{
GUID result{};
THROW_IF_FAILED(::CoCreateGuid(&result));
return result;
}
// Function Description:
// - Creates a String representation of a color, in the format "#RRGGBB"
// Arguments:
// - color: the COLORREF to create the string for
// Return Value:
// - a string representation of the color
std::string Utils::ColorToHexString(const til::color color)
{
std::stringstream ss;
ss << "#" << std::uppercase << std::setfill('0') << std::hex;
// Force the compiler to promote from byte to int. Without it, the
// stringstream will try to write the components as chars
ss << std::setw(2) << static_cast<int>(color.r);
ss << std::setw(2) << static_cast<int>(color.g);
ss << std::setw(2) << static_cast<int>(color.b);
return ss.str();
}
// Function Description:
// - Parses a color from a string. The string should be in the format "#RRGGBB" or "#RGB"
// Arguments:
// - str: a string representation of the COLORREF to parse
// Return Value:
// - A COLORREF if the string could successfully be parsed. If the string is not
// the correct format, throws E_INVALIDARG
til::color Utils::ColorFromHexString(const std::string_view str)
{
THROW_HR_IF(E_INVALIDARG, str.size() != 7 && str.size() != 4);
THROW_HR_IF(E_INVALIDARG, str.at(0) != '#');
std::string rStr;
std::string gStr;
std::string bStr;
if (str.size() == 4)
{
rStr = std::string(2, str.at(1));
gStr = std::string(2, str.at(2));
bStr = std::string(2, str.at(3));
}
else
{
rStr = std::string(&str.at(1), 2);
gStr = std::string(&str.at(3), 2);
bStr = std::string(&str.at(5), 2);
}
const BYTE r = gsl::narrow_cast<BYTE>(std::stoul(rStr, nullptr, 16));
const BYTE g = gsl::narrow_cast<BYTE>(std::stoul(gStr, nullptr, 16));
const BYTE b = gsl::narrow_cast<BYTE>(std::stoul(bStr, nullptr, 16));
return til::color{ r, g, b };
}
// Routine Description:
// - Shorthand check if a handle value is null or invalid.
// Arguments:
// - Handle
// Return Value:
// - True if non zero and not set to invalid magic value. False otherwise.
bool Utils::IsValidHandle(const HANDLE handle) noexcept
{
return handle != nullptr && handle != INVALID_HANDLE_VALUE;
}
// Function Description:
// - Fill the first 16 entries of a given color table with the Campbell color
// scheme, in the ANSI/VT RGB order.
// Arguments:
// - table: a color table with at least 16 entries
// Return Value:
// - <none>, throws if the table has less that 16 entries
void Utils::InitializeCampbellColorTable(const gsl::span<COLORREF> table)
{
THROW_HR_IF(E_INVALIDARG, table.size() < 16);
std::copy(campbellColorTable.begin(), campbellColorTable.end(), table.begin());
}
// Function Description:
// - Fill the first 16 entries of a given color table with the Campbell color
// scheme, in the Windows BGR order.
// Arguments:
// - table: a color table with at least 16 entries
// Return Value:
// - <none>, throws if the table has less that 16 entries
void Utils::InitializeCampbellColorTableForConhost(const gsl::span<COLORREF> table)
{
THROW_HR_IF(E_INVALIDARG, table.size() < 16);
InitializeCampbellColorTable(table);
SwapANSIColorOrderForConhost(table);
}
// Function Description:
// - modifies in-place the given color table from ANSI (RGB) order to Console order (BRG).
// Arguments:
// - table: a color table with at least 16 entries
// Return Value:
// - <none>, throws if the table has less that 16 entries
void Utils::SwapANSIColorOrderForConhost(const gsl::span<COLORREF> table)
{
THROW_HR_IF(E_INVALIDARG, table.size() < 16);
std::swap(til::at(table, 1), til::at(table, 4));
std::swap(til::at(table, 3), til::at(table, 6));
std::swap(til::at(table, 9), til::at(table, 12));
std::swap(til::at(table, 11), til::at(table, 14));
}
// Function Description:
// - Fill the first 255 entries of a given color table with the default values
// of a full 256-color table
// Arguments:
// - table: a color table with at least 256 entries
// Return Value:
// - <none>, throws if the table has less that 256 entries
void Utils::Initialize256ColorTable(const gsl::span<COLORREF> table)
{
THROW_HR_IF(E_INVALIDARG, table.size() < 256);
std::copy(standardXterm256ColorTable.begin(), standardXterm256ColorTable.end(), table.begin());
}
// Function Description:
// - Generate a Version 5 UUID (specified in RFC4122 4.3)
// v5 UUIDs are stable given the same namespace and "name".
// Arguments:
// - namespaceGuid: The GUID of the v5 UUID namespace, which provides both
// a seed and a tacit agreement that all UUIDs generated
// with it will follow the same data format.
// - name: Bytes comprising the name (in a namespace-specific format)
// Return Value:
// - a new stable v5 UUID
GUID Utils::CreateV5Uuid(const GUID& namespaceGuid, const gsl::span<const gsl::byte> name)
{
// v5 uuid generation happens over values in network byte order, so let's enforce that
auto correctEndianNamespaceGuid{ EndianSwap(namespaceGuid) };
wil::unique_bcrypt_hash hash;
THROW_IF_NTSTATUS_FAILED(BCryptCreateHash(BCRYPT_SHA1_ALG_HANDLE, &hash, nullptr, 0, nullptr, 0, 0));
// According to N4713 8.2.1.11 [basic.lval], accessing the bytes underlying an object
// through unsigned char or char pointer *is defined*.
THROW_IF_NTSTATUS_FAILED(BCryptHashData(hash.get(), reinterpret_cast<PUCHAR>(&correctEndianNamespaceGuid), sizeof(GUID), 0));
// BCryptHashData is ill-specified in that it leaves off "const" qualification for pbInput
THROW_IF_NTSTATUS_FAILED(BCryptHashData(hash.get(), reinterpret_cast<PUCHAR>(const_cast<gsl::byte*>(name.data())), gsl::narrow<ULONG>(name.size()), 0));
std::array<uint8_t, 20> buffer;
THROW_IF_NTSTATUS_FAILED(BCryptFinishHash(hash.get(), buffer.data(), gsl::narrow<ULONG>(buffer.size()), 0));
buffer.at(6) = (buffer.at(6) & 0x0F) | 0x50; // set the uuid version to 5
buffer.at(8) = (buffer.at(8) & 0x3F) | 0x80; // set the variant to 2 (RFC4122)
// We're using memcpy here pursuant to N4713 6.7.2/3 [basic.types],
// "...the underlying bytes making up the object can be copied into an array
// of char or unsigned char...array is copied back into the object..."
// std::copy may compile down to ::memcpy for these types, but using it might
// contravene the standard and nobody's got time for that.
GUID newGuid{ 0 };
::memcpy_s(&newGuid, sizeof(GUID), buffer.data(), sizeof(GUID));
return EndianSwap(newGuid);
}
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "TerminalSettings.h"
#include "TerminalSettings.g.cpp"
namespace winrt::TerminalApp::implementation
{
uint32_t TerminalSettings::GetColorTableEntry(int32_t index) const noexcept
{
return _colorTable.at(index);
}
void TerminalSettings::SetColorTableEntry(int32_t index, uint32_t value)
{
auto const colorTableCount = gsl::narrow_cast<decltype(index)>(_colorTable.size());
THROW_HR_IF(E_INVALIDARG, index >= colorTableCount);
_colorTable.at(index) = value;
}
}
<file_sep>#pragma once
#include "ActionAndArgs.g.h"
#include "TerminalWarnings.h"
#include "..\inc\cppwinrt_utils.h"
namespace winrt::TerminalApp::implementation
{
struct ActionAndArgs : public ActionAndArgsT<ActionAndArgs>
{
static const std::map<std::string_view, ShortcutAction, std::less<>> ActionKeyNamesMap;
static winrt::com_ptr<ActionAndArgs> FromJson(const Json::Value& json,
std::vector<::TerminalApp::SettingsLoadWarnings>& warnings);
ActionAndArgs() = default;
hstring GenerateName() const;
GETSET_PROPERTY(TerminalApp::ShortcutAction, Action, TerminalApp::ShortcutAction::Invalid);
GETSET_PROPERTY(IActionArgs, Args, nullptr);
};
}
namespace winrt::TerminalApp::factory_implementation
{
BASIC_FACTORY(ActionAndArgs);
}
<file_sep>/*++
Copyright (c) Microsoft Corporation
Licensed under the MIT license.
Module Name:
- Command.h
Abstract:
- A command represents a single entry in the Command Palette. This is an object
that has a user facing "name" to display to the user, and an associated action
which can be dispatched.
- For more information, see GH#2046, #5400, #5674, and #6635
Author(s):
- <NAME> - June 2020
--*/
#pragma once
#include "Command.g.h"
#include "TerminalWarnings.h"
#include "Profile.h"
#include "..\inc\cppwinrt_utils.h"
#include "SettingsTypes.h"
// fwdecl unittest classes
namespace TerminalAppLocalTests
{
class SettingsTests;
class CommandTests;
};
namespace winrt::TerminalApp::implementation
{
struct Command : CommandT<Command>
{
Command();
static winrt::com_ptr<Command> FromJson(const Json::Value& json,
std::vector<::TerminalApp::SettingsLoadWarnings>& warnings);
static void ExpandCommands(Windows::Foundation::Collections::IMap<winrt::hstring, winrt::TerminalApp::Command>& commands,
gsl::span<const winrt::TerminalApp::Profile> profiles,
gsl::span<winrt::TerminalApp::ColorScheme> schemes,
std::vector<::TerminalApp::SettingsLoadWarnings>& warnings);
static std::vector<::TerminalApp::SettingsLoadWarnings> LayerJson(Windows::Foundation::Collections::IMap<winrt::hstring, winrt::TerminalApp::Command>& commands,
const Json::Value& json);
bool HasNestedCommands();
Windows::Foundation::Collections::IMapView<winrt::hstring, TerminalApp::Command> NestedCommands();
void RefreshIcon();
winrt::Windows::UI::Xaml::Data::INotifyPropertyChanged::PropertyChanged_revoker propertyChangedRevoker;
WINRT_CALLBACK(PropertyChanged, Windows::UI::Xaml::Data::PropertyChangedEventHandler);
OBSERVABLE_GETSET_PROPERTY(winrt::hstring, Name, _PropertyChangedHandlers);
OBSERVABLE_GETSET_PROPERTY(winrt::TerminalApp::ActionAndArgs, Action, _PropertyChangedHandlers);
OBSERVABLE_GETSET_PROPERTY(winrt::hstring, KeyChordText, _PropertyChangedHandlers);
OBSERVABLE_GETSET_PROPERTY(winrt::Windows::UI::Xaml::Controls::IconSource, IconSource, _PropertyChangedHandlers, nullptr);
GETSET_PROPERTY(ExpandCommandType, IterateOn, ExpandCommandType::None);
private:
Json::Value _originalJson;
Windows::Foundation::Collections::IMap<winrt::hstring, winrt::TerminalApp::Command> _subcommands{ nullptr };
winrt::hstring _lastIconPath{};
static std::vector<winrt::TerminalApp::Command> _expandCommand(Command* const expandable,
gsl::span<const winrt::TerminalApp::Profile> profiles,
gsl::span<winrt::TerminalApp::ColorScheme> schemes,
std::vector<::TerminalApp::SettingsLoadWarnings>& warnings);
friend class TerminalAppLocalTests::SettingsTests;
friend class TerminalAppLocalTests::CommandTests;
};
}
namespace winrt::TerminalApp::factory_implementation
{
BASIC_FACTORY(Command);
}
<file_sep>/*++
Copyright (c) Microsoft Corporation
Licensed under the MIT license.
Module Name:
- Profile.hpp
Abstract:
- A profile acts as a single set of terminal settings. Many tabs or panes could
exist side-by-side with different profiles simultaneously.
Author(s):
- <NAME> - March 2019
--*/
#pragma once
#include "Profile.g.h"
#include "TerminalSettings.h"
#include "../inc/cppwinrt_utils.h"
#include "JsonUtils.h"
#include <DefaultSettings.h>
// fwdecl unittest classes
namespace TerminalAppLocalTests
{
class SettingsTests;
class ProfileTests;
};
namespace TerminalAppUnitTests
{
class JsonTests;
class DynamicProfileTests;
};
// GUID used for generating GUIDs at runtime, for profiles that did not have a
// GUID specified manually.
constexpr GUID RUNTIME_GENERATED_PROFILE_NAMESPACE_GUID = { 0xf65ddb7e, 0x706b, 0x4499, { 0x8a, 0x50, 0x40, 0x31, 0x3c, 0xaf, 0x51, 0x0a } };
namespace winrt::TerminalApp::implementation
{
struct Profile : ProfileT<Profile>
{
public:
Profile();
Profile(guid guid);
TerminalApp::TerminalSettings CreateTerminalSettings(const Windows::Foundation::Collections::IMapView<hstring, TerminalApp::ColorScheme>& schemes) const;
Json::Value GenerateStub() const;
static com_ptr<Profile> FromJson(const Json::Value& json);
bool ShouldBeLayered(const Json::Value& json) const;
void LayerJson(const Json::Value& json);
static bool IsDynamicProfileObject(const Json::Value& json);
hstring GetExpandedIconPath() const;
hstring GetExpandedBackgroundImagePath() const;
void GenerateGuidIfNecessary() noexcept;
static guid GetGuidOrGenerateForJson(const Json::Value& json) noexcept;
bool HasGuid() const noexcept;
winrt::guid Guid() const;
void Guid(const winrt::guid& guid) noexcept;
bool HasConnectionType() const noexcept;
winrt::guid ConnectionType() const noexcept;
void ConnectionType(const winrt::guid& conType) noexcept;
// BackgroundImageAlignment is 1 setting saved as 2 separate values
const Windows::UI::Xaml::HorizontalAlignment BackgroundImageHorizontalAlignment() const noexcept;
void BackgroundImageHorizontalAlignment(const Windows::UI::Xaml::HorizontalAlignment& value) noexcept;
const Windows::UI::Xaml::VerticalAlignment BackgroundImageVerticalAlignment() const noexcept;
void BackgroundImageVerticalAlignment(const Windows::UI::Xaml::VerticalAlignment& value) noexcept;
GETSET_PROPERTY(hstring, Name, L"Default");
GETSET_PROPERTY(hstring, Source);
GETSET_PROPERTY(bool, Hidden, false);
GETSET_PROPERTY(hstring, IconPath);
GETSET_PROPERTY(CloseOnExitMode, CloseOnExit, CloseOnExitMode::Graceful);
GETSET_PROPERTY(hstring, TabTitle);
GETSET_PROPERTY(Windows::Foundation::IReference<Windows::UI::Color>, TabColor);
GETSET_PROPERTY(bool, SuppressApplicationTitle, false);
GETSET_PROPERTY(bool, UseAcrylic, false);
GETSET_PROPERTY(double, AcrylicOpacity, 0.5);
GETSET_PROPERTY(Microsoft::Terminal::TerminalControl::ScrollbarState, ScrollState, Microsoft::Terminal::TerminalControl::ScrollbarState::Visible);
GETSET_PROPERTY(hstring, FontFace, DEFAULT_FONT_FACE);
GETSET_PROPERTY(int32_t, FontSize, DEFAULT_FONT_SIZE);
GETSET_PROPERTY(Windows::UI::Text::FontWeight, FontWeight, DEFAULT_FONT_WEIGHT);
GETSET_PROPERTY(hstring, Padding, DEFAULT_PADDING);
GETSET_PROPERTY(hstring, Commandline, L"cmd.exe");
GETSET_PROPERTY(hstring, StartingDirectory);
GETSET_PROPERTY(hstring, BackgroundImagePath);
GETSET_PROPERTY(double, BackgroundImageOpacity, 1.0);
GETSET_PROPERTY(Windows::UI::Xaml::Media::Stretch, BackgroundImageStretchMode, Windows::UI::Xaml::Media::Stretch::Fill);
GETSET_PROPERTY(Microsoft::Terminal::TerminalControl::TextAntialiasingMode, AntialiasingMode, Microsoft::Terminal::TerminalControl::TextAntialiasingMode::Grayscale);
GETSET_PROPERTY(bool, RetroTerminalEffect, false);
GETSET_PROPERTY(bool, ForceFullRepaintRendering, false);
GETSET_PROPERTY(bool, SoftwareRendering, false);
GETSET_PROPERTY(hstring, ColorSchemeName, L"Campbell");
GETSET_PROPERTY(Windows::Foundation::IReference<Windows::UI::Color>, Foreground);
GETSET_PROPERTY(Windows::Foundation::IReference<Windows::UI::Color>, Background);
GETSET_PROPERTY(Windows::Foundation::IReference<Windows::UI::Color>, SelectionBackground);
GETSET_PROPERTY(Windows::Foundation::IReference<Windows::UI::Color>, CursorColor);
GETSET_PROPERTY(int32_t, HistorySize, DEFAULT_HISTORY_SIZE);
GETSET_PROPERTY(bool, SnapOnInput, true);
GETSET_PROPERTY(bool, AltGrAliasing, true);
GETSET_PROPERTY(Microsoft::Terminal::TerminalControl::CursorStyle, CursorShape, Microsoft::Terminal::TerminalControl::CursorStyle::Bar);
GETSET_PROPERTY(uint32_t, CursorHeight, DEFAULT_CURSOR_HEIGHT);
private:
std::optional<winrt::guid> _Guid{ std::nullopt };
std::optional<winrt::guid> _ConnectionType{ std::nullopt };
std::tuple<Windows::UI::Xaml::HorizontalAlignment, Windows::UI::Xaml::VerticalAlignment> _BackgroundImageAlignment{
Windows::UI::Xaml::HorizontalAlignment::Center,
Windows::UI::Xaml::VerticalAlignment::Center
};
static std::wstring EvaluateStartingDirectory(const std::wstring& directory);
static guid _GenerateGuidForProfile(const hstring& name, const hstring& source) noexcept;
friend class TerminalAppLocalTests::SettingsTests;
friend class TerminalAppLocalTests::ProfileTests;
friend class TerminalAppUnitTests::JsonTests;
friend class TerminalAppUnitTests::DynamicProfileTests;
};
}
namespace winrt::TerminalApp::factory_implementation
{
BASIC_FACTORY(Profile);
}
<file_sep>// Copyright (c) Microsoft Corporation
// Licensed under the MIT license.
#include "pch.h"
#include "Utils.h"
std::wstring VisualizeControlCodes(std::wstring str) noexcept
{
for (auto& ch : str)
{
if (ch < 0x20)
{
ch += 0x2400;
}
else if (ch == 0x20)
{
ch = 0x2423; // replace space with ␣
}
else if (ch == 0x7f)
{
ch = 0x2421; // replace del with ␡
}
}
return str;
}
| 23697edd75afdae68facb9a6e07df60e198a159d | [
"C++"
] | 7 | C++ | honza1a/terminal | 1599393dbecc0e5648ab1db8e2e830134a64d2fd | c077452beb5134f433dd8d7dfbb28d759e5d95f7 |
refs/heads/master | <repo_name>antoniookie/nlw06<file_sep>/README.md
# NLW VALORIZA
## Regras:
- Cadastro de Usuário:
- Não é permitido cadastrar mais de um usuário com o mesmo e-mail
- Não é permitido cadastrar usuário sem e-mail
- Cadastro de Tag's:
- Não é permitido cadastrar tag's já criadas
- Não é permitido cadastrar tag's sem nome
- Não é permitido o cadastro de tags por usuários que não tenham permissão de administrador
- Cadastro de elogios:
- Não é permitido um usuário cadastrar um elogio para si
- Não é permitido cadastrar elogios para usuários inválidos. O usuário precisa estar autenticado na aplicação
| e8496ab54d546bd6b5c3e85769d1cc8e27365b02 | [
"Markdown"
] | 1 | Markdown | antoniookie/nlw06 | ddf414375919c394c20dea6dbb4e0d2aef2b5893 | 9d53ce3db7752ade6bdd5a01347b6e80c2ab9c35 |
refs/heads/master | <file_sep>FROM trafex/alpine-nginx-php7:ba1dd422
# 从composer 镜像中获取composer二进制程序
COPY --from=composer /usr/bin/composer /usr/bin/composer
WORKDIR /app
COPY . /app
RUN sed -i 's/\/var\/www\/html/\/app\/public/g' /etc/nginx/nginx.conf
ENV UIM_db_host=localhost
ENV UIM_db_database=sspanel
ENV UIM_db_username=root
ENV UIM_db_password=<PASSWORD>
ENV UIM_key=<KEY>
ENV UIM_muKey=sspanel
ENV UIM_baseUrl=http://localhost
ENV UIM_appName=SSPANEL
RUN apk --no-cache add php7-bcmath apk-cron php7-pdo php7-pdo_mysql
RUN apk --no-cache add --virtual build-dependencies git util-linux
RUN export KEY=$(uuidgen)
RUN cp config/.config.example.php config/.config.php
RUN chmod -R 755 storage
RUN chmod -R 777 storage/framework/smarty/compile/
RUN composer install
RUN php xcat initQQWry
RUN php xcat initdownload
RUN crontab -l | { cat; echo "30 22 * * * php /var/www/xcat sendDiaryMail"; } | crontab -
RUN crontab -l | { cat; echo "0 0 * * * php /var/www/xcat dailyjob"; } | crontab -
RUN crontab -l | { cat; echo "*/1 * * * * php /var/www/xcat checkjob"; } | crontab -
RUN crontab -l | { cat; echo "*/1 * * * * php /var/www/xcat syncnode"; } | crontab -
RUN apk del build-dependencies
CMD /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf | 54770a84e091c78fd242fe2b6bc0e0d1444e68e8 | [
"Dockerfile"
] | 1 | Dockerfile | xiaoliu-heng/SSPanel-Uim | 006d1f62df8cdc6853a94773fac66c600c1db9b2 | d0a0c70fc686a4b4e147a89d79c86dbf77db24cc |
refs/heads/master | <file_sep># ExceptionTutorial
ExceptionsTutorial
<file_sep>using System;
namespace ExceptionsTut
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
double convertedToDouble = Double.Parse(input);
if (convertedToDouble >= 5)
{
Console.WriteLine($"The entered number is {convertedToDouble}");
}
else
{
throw new ArgumentException(" Entered is invalid number !");
// here the system just throws an unhandled exception
}
}
}
}
| ee6d6df813e3d154ad4692f044c64f8bb89c36f5 | [
"C#",
"Markdown"
] | 2 | C# | Blagovest-Todorov/ExceptionTutorial | bd674f08379231ef78b2c6847d22032299016d28 | 2a464dfa879fbb60802a162f1a2e2e6ef2fed39b |
refs/heads/master | <file_sep>var minify = require('html-minifier').minify
test('options', function (t) {
var mini = minify(
'<div class="bar"><!-- Hello, World! --></div>'
, { removeComments: true }
);
t.equal(
mini
, '<div class="bar"></div>'
)
t.end()
})
<file_sep>var fs = require('fs')
, vm = require('vm')
, test = require('tape')
, minifyify = require('../html-minifyify')
, mini = minifyify()
, body = []
mini.on('data', function (chunk) {
body.push(chunk)
})
mini.once('end', function () {
body = Buffer.concat(body).toString()
vm.runInNewContext(body, { test: test })
})
fs.createReadStream(__dirname + '/test.js').pipe(mini)<file_sep>var staticModule = require('static-module')
, through = require('through2')
, minify = require('html-minifier').minify
module.exports = function (file) {
if (/\.json$/.test(file)) return through();
var sm = staticModule({
'html-minifier': {
minify: function (text, options) {
var stream = through()
stream.push(minify(text, options))
stream.push(null)
return stream.pipe(require('quote-stream')())
}
}
})
return sm
} | 75cfd83a4dc5cae8649c57e8daa6cca777b3064d | [
"JavaScript"
] | 3 | JavaScript | kesla/html-minifyify | b5ec2c919b08bc22acf134a508099f2ecce454b3 | 1e0ab20e689daaa245f46467052a313b18c756b8 |
refs/heads/master | <repo_name>Ugly0Brid/SpringBoot<file_sep>/src/main/java/com/example/demo/controller/JsonResult.java
package com.example.demo.controller;
public class JsonResult<T> {
private Integer status;
private String message;
private Integer total;
private T data;
public JsonResult() {
}
public JsonResult(Integer status, String message, Integer total) {
this.status = status;
this.message = message;
this.total = total;
}
public JsonResult(Integer status, String message, Integer total, T data) {
this(status, message, total);
this.setData(data);
}
public static <T> JsonResult<T> successResult(Integer status, String message, Integer total, T data) {
return new JsonResult(status, message, total, data);
}
public static <T> JsonResult<T> errorResult(int status, String message, T data) {
return new JsonResult(status, message, 0, data);
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public void setData(T data) {
this.data = data;
}
}
| 7ee1b71703497dc0bddebb665e15cf0008ee69e8 | [
"Java"
] | 1 | Java | Ugly0Brid/SpringBoot | 672fccc4c8c21b7c2791c55c9d92224142f3d886 | 4767f7a4e1e777b3a6812ea7d61432418369d761 |
refs/heads/master | <repo_name>Zaccornell/FadingWorld<file_sep>/README.md
# FadingWorld
This is a repo for the game fading world.
| 10d7bb0df991d6973e395d9a601e904a54e2feb6 | [
"Markdown"
] | 1 | Markdown | Zaccornell/FadingWorld | 8019bc8a47f7888e4be60ddd444065a31d388836 | a382f53318f885e153198fab2d474521c341eb7c |
refs/heads/master | <repo_name>yunyunyunyun/test1<file_sep>/README.md
# test1
Hello-world
| f6062653377678fcce5dff564ab62082f660372b | [
"Markdown"
] | 1 | Markdown | yunyunyunyun/test1 | 653732c75880443d142f70a0ad1e4669d94fad6d | 372f30b5a9e41dd70e3ce8f90ad6c60b92f938a8 |
refs/heads/main | <repo_name>FerAdame98/imageEnhancementKivy<file_sep>/main.kv
#:kivy 1.1.0
Root:
ima_input: ima_input
img: img
BoxLayout:
orientation: 'vertical'
BoxLayout:
size_hint_y: None
height: 30
Button:
text: 'Cargar'
on_release: root.show_load()
Button:
text: 'Guardar'
on_release: root.show_save()
BoxLayout:
size_hint_y: None
height: 30
Button:
text: 'Ecualización'
on_release:
root.ecualizar()
Button:
text: 'Dos puntos'
on_release:
root.dosPuntos(valor1.value,valor2.value,valor3.value,valor4.value)
Button:
text: 'Unsharp'
on_release:
root.unsharp()
BoxLayout:
Image:
id: ima_input
source: ''
text: "Original"
Image:
id: img
source: ''
text: "Modificada"
BoxLayout:
size_hint_y: None
height: 100
orientation: 'vertical'
BoxLayout:
orientation:'horizontal'
Slider:
id: valor1
visible:True
min:0
max:255
value:50
size_hint_x:1 if self.visible else 0
opacity:1 if self.visible else 0
disabled: not self.visible
on_value:
tv1.text=str(self.value)
root.dosPuntos(valor1.value,valor2.value,valor3.value,valor4.value)
Label:
id:tv1
text: "r1"
visible: valor1.visible
opacity:1 if self.visible else 0
BoxLayout:
orientation:'horizontal'
Slider:
id: valor2
visible:True
min:0
max:255
value:50
size_hint_x:1 if self.visible else 0
opacity:1 if self.visible else 0
disabled: not self.visible
on_value:
tv2.text=str(self.value)
root.dosPuntos(valor1.value,valor2.value,valor3.value,valor4.value)
Label:
id:tv2
text:"s1"
visible: valor2.visible
opacity:1 if self.visible else 0
BoxLayout:
orientation:'horizontal'
Slider:
id: valor3
visible:True
min:0
max:255
value:100
size_hint_x:1 if self.visible else 0
opacity:1 if self.visible else 0
disabled: not self.visible
on_value:
tv3.text=str(self.value)
root.dosPuntos(valor1.value,valor2.value,valor3.value,valor4.value)
Label:
id:tv3
text:"r2"
visible: valor3.visible
opacity:1 if self.visible else 0
BoxLayout:
orientation:'horizontal'
Slider:
id: valor4
visible:True
min:0
max:255
value:100
size_hint_x:1 if self.visible else 0
opacity:1 if self.visible else 0
disabled: not self.visible
on_value:
tv4.text=str(self.value)
root.dosPuntos(valor1.value,valor2.value,valor3.value,valor4.value)
Label:
id:tv4
text:"r2"
visible: valor4.visible
opacity:1 if self.visible else 0
<LoadDialog>:
BoxLayout:
size: root.size
pos: root.pos
orientation: "vertical"
FileChooserListView:
id: filechooser
BoxLayout:
size_hint_y: None
height: 30
Button:
text: "Cancelar"
on_release: root.cancel()
Button:
text: "Cargar"
on_release: root.load(filechooser.selection,filechooser.path)
<SaveDialog>:
text_input: text_input
BoxLayout:
size: root.size
pos: root.pos
orientation: "vertical"
FileChooserListView:
id: filechooser
#rootpath: '/storage/emulated/0/' if platform == 'android' else '/'
on_selection: text_input.text = self.selection and self.selection[0] or ''
TextInput:
id: text_input
size_hint_y: None
height: 30
multiline: False
BoxLayout:
size_hint_y: None
height: 30
Button:
text: "Cancelar"
on_release: root.cancel()
Button:
text: "Guardar"
on_release: root.save(filechooser.path,text_input.text)<file_sep>/main.py
"""
App mejora de imagen
"""
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.factory import Factory
from kivy.properties import ObjectProperty
from kivy.uix.popup import Popup
# from kivy.uix.slider import Slider
# from kivy.core.image import Image as CoreImage
# from kivy.uix.image import Image
# from kivy.uix.camera import Camera
# from kivy.graphics.texture import Texture
# import matplotlib.pyplot as plt
# from skimage import filters, color, io
# import numpy as np
# import math
import funciones
# import tempfile
# import io
import os
import cv2
"""
android
"""
# from android.storage import primary_external_storage_path
# primary_ext_storage=primary_external_storage_path()
import certifi
os.environ['SSL_CERT_FILE'] = certifi.where()
class LoadDialog(FloatLayout):
load = ObjectProperty(None)
cancel = ObjectProperty(None)
class SaveDialog(FloatLayout):
save = ObjectProperty(None)
ima_input = ObjectProperty(None)
img = ObjectProperty(None)
cancel = ObjectProperty(None)
path=ObjectProperty(None)
class Root(FloatLayout):
loadfile = ObjectProperty(None)
savefile = ObjectProperty(None)
ima_input = ObjectProperty(None)
img = ObjectProperty(None)
contador = 1
def dismiss_popup(self):
self._popup.dismiss()
def show_load(self):
content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
self._popup = Popup(title="Cargar", content=content,
size_hint=(0.9, 0.9))
self._popup.open()
def show_save(self):
content = SaveDialog(save=self.save, cancel=self.dismiss_popup)
self._popup = Popup(title="Guardar", content=content,
size_hint=(0.9, 0.9))
self._popup.open()
def reload(self):
path=self.path + "/" + str(self.contador) +"apoyo.jpg"
cv2.imwrite(path,self.ima)
self.ids.img.source=path
os.remove(path)
self.contador=self.contador+1
def load(self,filename,path):
try:
file=filename[0]
self.imaG=funciones.convertir(file)
self.ima=self.imaG
self.ids.ima_input.source = file
self.path=path
self.reload()
except:
pass
self.dismiss_popup()
def save(self,path,text):
if self.contador==1:
print("ingrese una imagen")
else:
dire=os.path.join(path,text)
cv2.imwrite(dire,self.ima)
self.path=path
self.dismiss_popup()
def ecualizar(self):
if self.contador==1:
print("ingrese una imagen")
else:
self.ima=funciones.histEcu(self.imaG)
self.reload()
def dosPuntos(self,r1,s1,r2,s2):
if self.contador==1:
print("ingrese una imagen")
else:
self.ima=funciones.ecDosPuntos(self.imaG,r1,s1,r2,s2)
self.reload()
def unsharp(self):
if self.contador==1:
print("ingrese una imagen")
else:
self.ima=funciones.unsharp_ima(self.imaG)
self.reload()
class main(App):
pass
Factory.register('Root', cls=Root)
Factory.register('LoadDialog', cls=LoadDialog)
Factory.register('SaveDialog', cls=SaveDialog)
if __name__ == '__main__':
main().run()<file_sep>/funciones.py
"""
Funciones
mejora de imagen y
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import filters, color, io
import math
def convertir(ima_path):
ima = io.imread(ima_path)
size=ima.shape
if len(size)==3:
ima=np.uint8(color.rgb2gray(ima)*255)
elif len(size)==2:
ima=ima
else:
print("Ingrese una imagen valida")
return ima
def histograma(ima):
histo=np.zeros(256)
for i in range(ima.shape[0]):
for j in range(ima.shape[1]):
valor=int(ima[i,j])
histo[valor]=histo[valor]+1
return(histo)
### mejoras
def histEcu(ima):
histo=histograma(ima)
pro=histo/(ima.shape[0]*ima.shape[1])
a=0
ecua=np.zeros(256)
for i in range(256):
a=pro[i]+a
ecua[i]=a
salida=np.zeros((ima.shape[0],ima.shape[1]))
for i in range(ima.shape[0]):
for j in range(ima.shape[1]):
valor=int(ima[i,j])
salida[i,j]=(255)*ecua[valor]
return (salida)
def ecDosPuntos(ima, r1, s1, r2, s2):
salida=np.zeros((ima.shape[0],ima.shape[1]))
for i in range (ima.shape[0]):
for j in range (ima.shape[1]):
pixel=int(ima[i,j])
if(pixel<=r1):
salida[i,j]= (s1/r1)*pixel
elif (r1<pixel and pixel<=r2):
salida[i,j]=((s2-s1)/(r2-r1)) * (pixel-r1) + s1
else:
salida[i,j]=((255-s2)/(255-r2)) * (pixel-r2) + s2
return salida
def unsharp_ima(ima):
cantidad=1.0
sig=1.0
umbral=0.0
# unsharp2=unsharp_ima(imagen,can,sig,umb)
pB=filters.gaussian(ima, sigma=sig,mode='constant')
A=(cantidad+1)*ima - cantidad*pB
B=np.maximum(A,np.zeros(A.shape))
C=np.minimum(B,255*np.ones(A.shape))
unsharp=C.round()
if umbral>0:
D=np.absolute(ima-pB)<umbral
np.copyto(unsharp,ima,where=D)
return unsharp
| 2c368518d8001aaeedf01c49420ded3ac4cc558a | [
"Python",
"kvlang"
] | 3 | Python | FerAdame98/imageEnhancementKivy | 81af0da9495a6fe02cc4fe73f8283f9590edfe8c | 27d6c74603d53184b7acdb4f2dcbbdbd3dad250e |
refs/heads/master | <repo_name>soilwear/school_hotel<file_sep>/README.md
# school_hotel
###shcool
```
代码区
```
<file_sep>/src/main/java/com/shop/dao/ShopDao.java
package com.shop.dao;
import com.shop.entity.Shop;
public interface ShopDao {
/**
* 新增店铺
* @param shop
* @return
*/
int insertShop(Shop shop);
/**
* 更新店铺
* shop
*/
int updateShop(Shop shop);
/**
*
* 通过owner_id 查询店铺
*
*/
Shop queryByShopId(long shopId);
}
| be1ec49c9ccb6a913900e368714c1ec52bfb33f4 | [
"Java",
"Markdown"
] | 2 | Java | soilwear/school_hotel | 3327ea6033b57f3e73c0205aef76b04600a34dd8 | 8a9fa843764c134f56ecface7c371e353da48748 |
refs/heads/main | <repo_name>rowaxl/a0520-intro-to-mongoose-starter<file_sep>/controller/memberController.js
import mongoose from 'mongoose'
import Members from '../model/Members'
import { toObjectId, DBError } from '../util/database'
export const getAllMember = async (req, res) => {
const members = await Members.find({}).catch(DBError)
res.json({members})
}
export const getOneMember = async (req, res) => {
const objectId = toObjectId(req.params.id)
const result = await Members.findOne({ _id: objectId }).catch(DBError)
if (!result) {
const APIError = new Error('Failed to find member')
APIError.status = 404
throw APIError
}
res.json({ result })
}
export const createMember = async (req, res) => {
const newMember = new Members({
...req.body,
status: 'active'
})
const result = await newMember.save({ validateBeforeSave: true }).catch(DBError)
if (!result) {
const APIError = new Error('Failed to create member')
APIError.status = 403
throw APIError
}
res.status(200).json({ result })
}
export const updateMember = async (req, res) => {
const objectId = toObjectId(req.params.id)
const target = await Members.findOne({ _id: objectId })
if (!target) {
const APIError = new Error('Cannot found the member')
APIError.status = 404
throw APIError
}
const result = await Members.updateOne(
{ _id: objectId },
{ ...req.body }
).catch(DBError)
if (!result) {
const APIError = new Error('Failed to update member')
APIError.status = 403
throw APIError
}
res.status(200).json({ result })
}
export const deleteMember = async (req, res) => {
const objectId = toObjectId(req.params.id)
const target = await Members.findOne({ _id: objectId })
if (!target) {
const APIError = new Error('Cannot found the member')
APIError.status = 404
throw APIError
}
const result = await Members.deleteOne({ _id: objectId }).catch(DBError)
if (!result) {
const APIError = new Error('Failed to delete member')
APIError.status = 403
throw APIError
}
res.status(200).json({ result })
}
| 5415c0a136ac3b936be458869f3b45f32a12da93 | [
"JavaScript"
] | 1 | JavaScript | rowaxl/a0520-intro-to-mongoose-starter | 114009cf78f27dfaa02e23a08db081aa7c76be8c | 7b3d1d04b250d6346e8ae2950d1edbeb901c0a6a |
refs/heads/master | <file_sep>{% include 'inc-header.html' %}
<div class="container-fluid start-screen h-100">
<div class="tiles-area clear">
<div class=" tiles-group size-2 fg-white">
{% include 'inc-card.html' %}
<br>
<div class="grid">
<div class="row">
<div class="cell-10">
<h2>
<span class="mif-tags"></span>
Consultoria ColdFusion
</h2>
<img src="img/cfml-bordered-turquoise.png" style="margin: 10px;" width="150" align="left">
Possuo abrangente vivência no desenvolvimento <a href="https://www.adobe.com/br/products/coldfusion-family.html" target="_blank" style="font-weight: bold;">ColdFusion</a>, com mais de 10 anos na análise, projeção, desenvolvimento, implantação e suporte de projetos web e soluções tecnológicas específicas, tais como intranets/extranets, lojas virtuais, aplicações responsivas, sistemas de pagamentos on-line (Boleto Bancário e Cartão de Crédito), de gestão de conteúdo (CMS) e de email marketing.
<p></p>
Além de experiência na administração de servidores de aplicação Adobe ColdFusion, TomCat e Adobe JRun 4 em sistemas operacionais RedHat e Ubuntu, no tocante à instalação, configuração, auditoria e manutenção. Desenvolvo ainda, atividades ligadas à tunning de aplicações e de desempenho do application server.
<p></p>
<a href="pdf/ace-2016b.pdf" target="_blank">Sou ACE</a> em ColdFusion MX pela Adobe (Macromedia).
</div>
</div>
</div>
</div>
</div>
</div>
{% include 'inc-footer.html' %}
<file_sep>var express = require('express');
var router = express.Router();
function nocache(req, res, next) {
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
next();
}
//geek-fullstack
router.get('/geek-fullstack', nocache, function (req, res) {
var data = {
title_page: '<NAME>',
} ;
res.render('geek-fullstack.html', data );
});
router.get('/ebooks/o-funcional-que-funciona', (req, res) => {
res.render('landing-pages/ebook-funcional2.html');
});
// principal
router.get('/', nocache, function (req, res) {
var data = {
type_page: 'home',
title_page: '<NAME>',
} ;
res.render('home.html', data );
});
router.get('/rafa-fitness', nocache, function (req, res) {
var data = {
type_page: 'home',
title_page: '<NAME>',
} ;
res.render('enter-fitness.html', data );
});
router.get('/rafa-dev', nocache, function (req, res) {
var data = {
type_page: 'home',
title_page: '<NAME>',
} ;
res.render('enter-dev.html', data );
});
// fitness-mobility
router.get('/fitness-mobility', nocache, function (req, res) {
var data = {
title_page: '<NAME> - Personal - Mobility',
} ;
res.render('fitness-mobility.html', data);
});
router.get('/fitness-cursos', nocache, function (req, res) {
var data = {
title_page: 'Rafael Silva - Personal - Mobility',
} ;
res.render('fitness-cursos.html', data);
});
// fitness-mobility
router.get('/fitness-grupos-especiais', nocache, function (req, res) {
var data = {
title_page: '<NAME> - Personal - Grupos Especiais',
} ;
res.render('fitness-grupos-especiais.html', data);
});
// funcional-hiit
router.get('/funcional-hiit', nocache, function (req, res) {
var data = {
title_page: '<NAME> - Personal - Funcional/HIIT',
} ;
res.render('funcional-hiit.html', data);
});
router.get('/fitness-consultoria-gestao', nocache, function (req, res) {
var data = {
title_page: '<NAME> - Personal - Funcional/HIIT',
} ;
res.render('fitness-consultoria-gestao.html', data);
});
// fitness-zumba-ritmos
router.get('/fitness-kids-active', nocache, function (req, res) {
var data = {
title_page: '<NAME> - Personal - Kids Active',
} ;
res.render('fitness-kids.html', data);
});
// geek-marketing-digital
router.get('/geek-gestao-midias-sociais', nocache, function (req, res) {
var data = {
title_page: '<NAME> - Geek - Gestão Mídias Sociais',
} ;
res.render('geek-gestao-midias-sociais.html', data);
});
// geek-cases
router.get('/geek-cases', nocache, function (req, res) {
var data = {
title_page: '<NAME> - Sistemas - Cases',
} ;
res.render('geek-cases.html', data);
});
router.get('/geek-consultoria-laravel', nocache, function (req, res) {
var data = {
title_page: 'Rafael Silva - Sistemas - Laravel',
} ;
res.render('geek-laravel.html', data);
});
router.get('/geek-consultoria-pg', nocache, function (req, res) {
var data = {
title_page: '<NAME> - Banco de dados - PostGre',
} ;
res.render('geek-pg.html', data);
});
// geek-sistema-web
router.get('/geek-sistema-web', nocache, function (req, res) {
var data = {
title_page: 'Rafael Silva - Sistemas Web',
} ;
res.render('geek-sistema-web.html', data);
});
// geek-marketing-digital
router.get('/geek-consultoria-coldfusion', nocache, function (req, res) {
var data = {
title_page: '<NAME> - Consultoria ColdFusion',
} ;
res.render('geek-consultoria-coldfusion.html', data);
});
// geek-app-celular
router.get('/geek-aplicativos-celular', nocache, function (req, res) {
var data = {
title_page: 'R<NAME> - Apps para Celular',
} ;
res.render('geek-aplicativos-celular.html', data);
});
// download dos curriculos
/*
app.get('/curriculo-fitness', nocache, function (req, res) {
const file = __dirname + '/assets/pdf/CV-FITNESS.pdf';
res.download(file); // Set disposition and send it.
});
app.get('/curriculo-geek', nocache, function (req, res) {
const file = __dirname + '/assets/pdf/CV-GEEK.pdf';
res.download(file); // Set disposition and send it.
});
*/
module.exports = router;<file_sep>import Vue from 'vue';
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)
new Vue({
el: '#app',
delimiters: ['[{', '}]'],
data: {
message: 'Minhas social techs'
},
mounted: function () {
Metro.init();
}
})<file_sep>import Vue from 'vue';
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)
new Vue({
el: '#app',
data: {
produto_nome: 'Testando Vue'
},
components: {
WsPrincipal, WsLogin
},
mounted() {
Metro.init();
}
})<file_sep>demo/* linguist-vendored
test/* linguist-vendored
jquery.tabslet.min.js linguist-vendored=false
jquery.tabslet.test.js linguist-vendored=false
<file_sep>{% include 'inc-header.html' %}
<div class="container-fluid start-screen h-100">
<div class="tiles-area clear">
<div class=" tiles-group size-2 fg-white">
{% include 'inc-card.html' %}
<br>
<div class="grid">
<div class="row">
<div class="cell-10">
<h2>
<span class="mif-tags"></span>
Sites, Sistemas Web e Apps
</h2>
<img src="img/thumb.png" width="450" style="margin: 10px;" align="right">
<b>O que são sistemas web</b>
<P></P>
Por definição, sistemas web ou aplicações web são sistemas informatizados acessíveis através de um navegador ou de um aplicativo, via internet ou rede, capazes de processar informações em servidores para cumprir determinadas regras de negócio.
<P></P>
<b>O que eles podem fazer</b>
<P></P>
Sistemas web moram na internet. Essa característica proporciona o desenvolvimento de recursos praticamente ilimitados, tornando cada vez mais ágil as decisões estratégicas que precisam ser tomadas em um negócio.
<P></P>
<b>Quais são as vantagens</b>
<P></P>
Podem ser acessados de qualquer lugar, de qualquer dispositivo e a qualquer hora via internet;
<br>
Não precisam necessariamente de instalação, pois podem ser acessados através de um navegador;
<br>
Não dependem de sistemas operacionais ou de uma infra-estrutura local para o perfeito funcionamento;
<br>
Dados ficam protegidos em um servidor remoto. Não é necessário investir em sistemas de segurança e backups;
<P></P>
Os sites/sistemas que desenvolvo pela RGS, são programados para garantir alta performance em qualquer dispositivo; são sistemas robustos e com uma infinidade de funções para utilizar, mas são extremamente leves e simples na hora de utilizar. Entre em contato e agende uma reunião para
conhecer melhor meu portifólio e experiência.
</div>
</div>
</div>
</div>
</div>
</div>
{% include 'inc-footer.html' %}
| a256728262f1857e46a93aed39e03fa6f3d25877 | [
"Git Attributes",
"HTML",
"JavaScript"
] | 6 | Git Attributes | rafaNode/rafando-site | ceb8e3259bee09f4d2ed4f86e68553dc66ae7bc6 | e0877620ea6fe4419f82241df38306a8ff9bc386 |
refs/heads/master | <file_sep>c_drbk_exercises
================
Solutions for the exercises in the book "C Programming Language" by <NAME> and <NAME> | c7d63993acd307010702884458945f5907b123cf | [
"Markdown"
] | 1 | Markdown | vijayvenkatesans/c_drbk_exercises | 736d9dbd8fbc02f4259ce88debd94a4e07a4cb68 | 268a9d3514394410662cb41c0907c399a20fba0c |
refs/heads/master | <file_sep># workdata
Python and Database Exerciese
| 66503098985bf20bafa6f9d0ae7c64c71b729818 | [
"Markdown"
] | 1 | Markdown | chanupatel/workdata | 9131bf6096c29b052ead61c92e2417c105e258f7 | babbae578f5f8a7c1b74bcd8969b7137bf821e05 |
refs/heads/master | <file_sep>/*let input = document.querySelector('input');
console.log(input.value);
let paragraph = document.querySelector(p);
paragraph.textContent = input.value;
themeButton.onclick = function() {
};
let lili = document.querySelector('li');
lili.add(input.value)
commentForm.onsubmit = function (evt) {
evt.preventDefault();
};
let newElement = document.createElement('li');
console.log('newElement');*/
let commentList = document.querySelector('.comment-list');
//commentList.textContent = 'Новая строка';
//commentList.append('новый комментарий')
let commentabc = document.querySelector('.comment-abc');
let commentText = document.querySelector('.comment-user-text');
commentabc.onsubmit = function(evt) {
evt.preventDefault();
let newComment = document.createElement('li');
newComment.classList.add('comment-user');
newComment.textContent = '1234';
newComment.textContent = commentText.value;
commentText.value = '';
commentList.append(newComment);
} | 016eb6e5e8de87520fd707f7b028f4b4c2653af7 | [
"JavaScript"
] | 1 | JavaScript | YRentik/one-site | fce90c49e4fc608ebe91def0e813976b5a010ce8 | 71016f78f2f48c0be758899d67780a5cee65e41c |
refs/heads/master | <file_sep><html>
<body>
<table border="1">
<tr>
<td valign="top">
<%-- -------- Include menu HTML code -------- --%>
<jsp:include page="menu.html" />
</td>
<td>
<%-- Set the scripting language to Java and --%>
<%-- Import the java.sql package --%>
<%@ page language="java" import="java.sql.*" %>
<%-- -------- Open Connection Code -------- --%>
<%
Statement stmt = null;
Statement stmt2 = null;
String query = "SELECT DISTINCT course_name, quarter, year_taken FROM course_taken3;";
try {
// Load Oracle Driver class file
DriverManager.registerDriver
(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
// Make a connection to the Oracle datasource "cse132b"
Connection conn = DriverManager.getConnection
("jdbc:sqlserver://localhost:1433;databaseName=cse132b",
"sa", "g");
stmt = conn.createStatement();
stmt2 = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
%>
<form action="1b.jsp" method="get">
Class:
<select name="data">
<option selected disabled>Choose Option</option>
<% while(rs.next()) {%>
<option value='<%=rs.getString("course_name")%>,<%=rs.getString("quarter")%>,<%=rs.getInt("year_taken")%>'><%=rs.getString("course_name")%>, <%=rs.getString("quarter")%>, <%=rs.getInt("year_taken")%></option>
<% } %>
</select>
<input type="submit">
</form>
<table border="1">
<tr>
<th>SID</th>
<th>Firstname</th>
<th>Middlename</th>
<th>Lastname</th>
<th>SSN</th>
<th>Residency</th>
<th>Units</th>
<th>Grade Option</th>
</tr>
<%String dataArray[] = request.getParameter("data").split(",");%>
<%=dataArray[0]%>
<%=dataArray[1]%>
<%=dataArray[2]%>
<%String query2 = "SELECT s.sid, s.firstname, s.middlename, s.lastname, s.ssn, s.residency, ct3.grade_option, ct3.units_taken_for " +
"FROM Student s, course_taken3 ct3 " +
"WHERE s.sid = ct3.sid AND ct3.course_name = '" + dataArray[0] +
"' AND ct3.quarter = '" + dataArray[1] +
"' and ct3.year_taken = " + dataArray[2] + ";";%>
<%ResultSet rs2 = stmt2.executeQuery(query2);%>
<% while(rs2.next()){ %>
<tr>
<td><%=rs2.getInt("sid")%></td>
<td><%=rs2.getString("firstname")%></td>
<td><%=rs2.getString("middlename")%></td>
<td><%=rs2.getString("lastname")%></td>
<td><%=rs2.getInt("ssn")%></td>
<td><%=rs2.getString("residency")%></td>
<td><%=rs2.getInt("units_taken_for")%></td>
<td><%=rs2.getString("grade_option")%></td>
</tr>
<% } %>
</table>
<%-- -------- Close Connection Code -------- --%>
<%
// Close the ResultSet
rs.close();
rs2.close();
// Close the Statement
stmt.close();
stmt2.close();
// Close the Connection
conn.close();
} catch (SQLException sqle) {
out.println(sqle.getMessage());
} catch (Exception e) {
out.println(e.getMessage());
}
//conn.close;
%>
</table>
</td>
</tr>
</table>
</body>
</html>
<file_sep><html>
<body>
<table border="1">
<tr>
<td valign="top">
<%-- -------- Include menu HTML code -------- --%>
<jsp:include page="menu.html" />
</td>
<td>
<%-- Set the scripting language to Java and --%>
<%-- Import the java.sql package --%>
<%@ page language="java" import="java.sql.*" %>
<%-- -------- Open Connection Code -------- --%>
<%
Statement stmt = null;
Statement stmt2 = null;
String query = "SELECT * FROM Student";
try {
// Load Oracle Driver class file
DriverManager.registerDriver
(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
// Make a connection to the Oracle datasource "cse132b"
Connection conn = DriverManager.getConnection
("jdbc:sqlserver://localhost:1433;databaseName=cse132b",
"sa", "g");
stmt = conn.createStatement();
stmt2 = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
%>
<form action="1c.jsp" method="get">
SSN:
<select name="ssn">
<option selected disabled>Choose Option</option>
<% while(rs.next()) {%>
<option value=<%=rs.getInt("ssn")%>><%=rs.getInt("ssn")%>, <%=rs.getString("firstname")%>, <%=rs.getString("middlename")%>, <%=rs.getString("lastname")%></option>
<% } %>
</select>
<input type="submit">
</form>
<table border="1">
<tr>
<th>Section ID</th>
<th>Enrollment Limit</th>
<th>Quarter</th>
<th>Year</th>
<th>Title</th>
<th>Units</th>
<th>Grade</th>
</tr>
<%String query2 = "SELECT section_id, enrollment_limit, quarter, year_, title, units_taken_for, grade " +
"FROM student_quarter_grades, Student s " +
"WHERE s.ssn = " + request.getParameter("ssn") + " AND s.sid = student_quarter_grades.sid " +
"ORDER BY quarter, year_;";%>
<%ResultSet rs2 = stmt2.executeQuery(query2);%>
<% while(rs2.next()){ %>
<tr>
<td><%=rs2.getInt("section_id")%></td>
<td><%=rs2.getInt("enrollment_limit")%></td>
<td><%=rs2.getString("quarter")%></td>
<td><%=rs2.getInt("year_")%></td>
<td><%=rs2.getString("title")%></td>
<td><%=rs2.getInt("units_taken_for")%></td>
<td><%=rs2.getString("grade")%></td>
</tr>
<% } %>
</table>
<br>
<table border = "1">
<tr>
<th>Quarter</th>
<th>Year</th>
<th>Quarter GPA</th>
</tr>
<%String query3 = "SELECT quarter, year_, avg(number_grade) AS quarter_gpa " +
"FROM student_quarter_grades, Student s " +
"WHERE s.ssn = " + request.getParameter("ssn") + " AND s.sid = student_quarter_grades.sid " +
"GROUP BY quarter, year_ " +
"ORDER BY quarter, year_;";%>
<%rs2 = stmt2.executeQuery(query3);%>
<% while(rs2.next()){ %>
<tr>
<td><%=rs2.getString("quarter")%></td>
<td><%=rs2.getInt("year_")%></td>
<td><%=rs2.getFloat("quarter_gpa")%></td>
</tr>
<% } %>
</table>
<br>
<table border = "1">
<tr>
<th>Cumulative GPA</th>
</tr>
<%String query4 = "SELECT avg(number_grade) AS cumulative_gpa " +
"FROM student_quarter_grades, Student s " +
"WHERE s.ssn = " + request.getParameter("ssn") + " AND s.sid = student_quarter_grades.sid;";%>
<%rs2 = stmt2.executeQuery(query4);%>
<% while(rs2.next()){ %>
<tr>
<td><%=rs2.getFloat("cumulative_gpa")%></td>
</tr>
<% } %>
</table>
<%-- -------- Close Connection Code -------- --%>
<%
// Close the ResultSet
rs.close();
rs2.close();
// Close the Statement
stmt.close();
stmt2.close();
// Close the Connection
conn.close();
} catch (SQLException sqle) {
out.println(sqle.getMessage());
} catch (Exception e) {
out.println(e.getMessage());
}
//conn.close;
%>
</table>
</td>
</tr>
</table>
</body>
</html>
<file_sep>insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Benjamin', NULL, 'B', 1, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Kristen', NULL, 'W', 2, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Daniel', NULL, 'F', 3, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Claire', NULL, 'J', 4, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Julie', NULL, 'C', 5, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Kevin', NULL, 'L', 6, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Michael', NULL, 'B', 7, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Joseph', NULL, 'J', 8, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Devin', NULL, 'P', 9, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Logan', NULL, 'F', 10, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Vikram', NULL, 'N', 11, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Rachel', NULL, 'Z', 12, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Zach', NULL, 'M', 13, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Justin', NULL, 'H', 14, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Rahul', NULL, 'R', 15, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Dave', NULL, 'C', 16, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Nelson', NULL, 'H', 17, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Andrew', NULL, 'P', 18, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Nathan', NULL, 'S', 19, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('John', NULL, 'H', 20, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Anwell', NULL, 'W', 21, 'California', 1);
insert into Student (firstname, middlename, lastname, ssn, residency, enrolled) values ('Tim', NULL, 'K', 22, 'California', 1);
insert into Graduate (sid) values (16);
insert into Graduate (sid) values (17);
insert into Graduate (sid) values (18);
insert into Graduate (sid) values (19);
insert into Graduate (sid) values (20);
insert into Graduate (sid) values (21);
insert into Graduate (sid) values (22);
insert into MS (sid, concentration) values (16,NULL);
insert into MS (sid, concentration) values (17,NULL);
insert into MS (sid, concentration) values (18,NULL);
insert into MS (sid, concentration) values (19,NULL);
insert into MS (sid, concentration) values (20,NULL);
insert into MS (sid, concentration) values (21,NULL);
insert into MS (sid, concentration) values (22,NULL);
insert into Department (department_name) values ('Computer Science');
insert into Department (department_name) values ('Mechanical Engineering');
insert into Department (department_name) values ('Philosophy');
insert into Degree (department_id, degree_type, concentration) values (1, 'B.Sc', NULL);
insert into Degree (department_id, degree_type, concentration) values (2, 'B.Sc', NULL);
insert into Degree (department_id, degree_type, concentration) values (3, 'B.A', NULL);
insert into Degree (department_id, degree_type, concentration) values (1, 'M.S', NULL);
insert into Degree (department_id, degree_type, concentration) values (1, 'M.S', 'Databases');
insert into Degree (department_id, degree_type, concentration) values (1, 'M.S', 'AI');
insert into Degree (department_id, degree_type, concentration) values (1, 'M.S', 'Systems');
insert into Major (sid, degree_id) values (1,1);
insert into Major (sid, degree_id) values (2,1);
insert into Major (sid, degree_id) values (3,1);
insert into Major (sid, degree_id) values (4,1);
insert into Major (sid, degree_id) values (5,1);
insert into Major (sid, degree_id) values (6,2);
insert into Major (sid, degree_id) values (7,2);
insert into Major (sid, degree_id) values (8,2);
insert into Major (sid, degree_id) values (9,2);
insert into Major (sid, degree_id) values (10,2);
insert into Major (sid, degree_id) values (11,3);
insert into Major (sid, degree_id) values (12,3);
insert into Major (sid, degree_id) values (13,3);
insert into Major (sid, degree_id) values (14,3);
insert into Major (sid, degree_id) values (15,3);
/*MS*/
insert into Major (sid, degree_id) values (16,4);
insert into Major (sid, degree_id) values (17,4);
insert into Major (sid, degree_id) values (18,4);
insert into Major (sid, degree_id) values (19,4);
insert into Major (sid, degree_id) values (20,4);
insert into Major (sid, degree_id) values (21,4);
insert into Major (sid, degree_id) values (22,4);
insert into Faculty (name, title) values ('<NAME>', 'Associate Professor');
insert into Faculty (name, title) values ('<NAME>', 'Professor');
insert into Faculty (name, title) values ('<NAME>', 'Professor');
insert into Faculty (name, title) values ('Adele', 'Professor');
insert into Faculty (name, title) values ('<NAME>', 'Professor');
insert into Faculty (name, title) values ('<NAME>', 'Professor');
insert into Faculty (name, title) values ('<NAME>', 'Professor');
insert into Faculty (name, title) values ('Bjork', 'Professor');
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'Lower Division','CSE 8A',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'Upper Division','CSE 105',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'Upper Division','CSE 123',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'Graduate Division','CSE 250A',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'Graduate Division','CSE 250B',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'Graduate Division','CSE 255',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'graduate Division','CSE 232A',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'graduate Division','CSE 221',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'Lower Division','MAE 3',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'Upper Division','MAE 107',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'Upper Division','MAE 108',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'Lower Division','PHIL 10',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'Lower Division','PHIL 12',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'Upper Division','PHIL 165',0);
insert into Course (min_units, max_units, grade_options, lab_work_req, category, course_name, consent_req) values (2,4,'Any',0,'Upper Division','PHIL 167',0);
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2014, 'Introduction to Computer Science: Java');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Spring', 2015, 'Introduction to Computer Science: Java');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2015, 'Introduction to Computer Science: Java');
/*10*/insert into Class_ (enrollment_limit, quarter, year_, title) values (5, 'Winter', 2016, 'Introduction to Computer Science: Java');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Spring', 2016, 'Introduction to Computer Science: Java');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Winter' ,2015, 'Intro to Theory');
/*6*/insert into Class_ (enrollment_limit, quarter, year_, title) values (3, 'Winter', 2016, 'Intro to Theory');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2016, 'Intro to Theory');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2014, 'Probabilistic Reasoning');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2015, 'Probabilistic Reasoning');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Spring', 2016, 'Probabilistic Reasoning');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Winter', 2015, 'Machine Learning');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2016, 'Machine Learning');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2015, 'Data Mining and Predictive Analytics');
/*3*/insert into Class_ (enrollment_limit, quarter, year_, title) values (5, 'Winter', 2016, 'Data Mining and Predictive Analytics');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Winter', 2017, 'Data Mining and Predictive Analytics');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2015, 'Databases');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Spring', 2016, 'Databases');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Spring', 2015, 'Operating Systems');
/*2*/insert into Class_ (enrollment_limit, quarter, year_, title) values (5, 'Winter', 2016, 'Operating Systems');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2016, 'Operating Systems');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Spring', 2015, 'Computational Methods');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Spring', 2016, 'Computational Methods');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2014, 'Probability and Statistics');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Winter', 2015, 'Probability and Statistics');
/*1*/insert into Class_ (enrollment_limit, quarter, year_, title) values (2, 'Winter', 2016, 'Probability and Statistics');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2016, 'Probability and Statistics');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2015, 'Intro to Logic');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Winter', 2017, 'Intro to Logic');
/*4*/insert into Class_ (enrollment_limit, quarter, year_, title) values (2, 'Winter', 2016, 'Scientific Reasoning');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Spring', 2016, 'Scientific Reasoning');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Spring', 2015, 'Freedom, Equality, and the Law');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2015, 'Freedom, Equality, and the Law');
/*7*/insert into Class_ (enrollment_limit, quarter, year_, title) values (3, 'Winter', 2016, 'Freedom, Equality, and the Law');
insert into Class_ (enrollment_limit, quarter, year_, title) values (100, 'Fall', 2016, 'Freedom, Equality, and the Law');
/*5*/insert into Class_ (enrollment_limit, quarter, year_, title) values (3, 'Winter', 2016, 'Operating Systems');
/*9*/insert into Class_ (enrollment_limit, quarter, year_, title) values (2, 'Winter', 2016, 'Operating Systems');
/*8*/insert into Class_ (enrollment_limit, quarter, year_, title) values (1, 'Winter', 2016, 'Probability and Statistics');
insert into Course_Class (course_id, section_id) values (1,1);
insert into Course_Class (course_id, section_id) values (1,2);
insert into Course_Class (course_id, section_id) values (1,3);
insert into Course_Class (course_id, section_id) values (1,4);
insert into Course_Class (course_id, section_id) values (1,5);
insert into Course_Class (course_id, section_id) values (2,6);
insert into Course_Class (course_id, section_id) values (2,7);
insert into Course_Class (course_id, section_id) values (2,8);
insert into Course_Class (course_id, section_id) values (4,9);
insert into Course_Class (course_id, section_id) values (4,10);
insert into Course_Class (course_id, section_id) values (4,11);
insert into Course_Class (course_id, section_id) values (5,12);
insert into Course_Class (course_id, section_id) values (5,13);
insert into Course_Class (course_id, section_id) values (6,14);
insert into Course_Class (course_id, section_id) values (6,15);
insert into Course_Class (course_id, section_id) values (6,16);
insert into Course_Class (course_id, section_id) values (7,17);
insert into Course_Class (course_id, section_id) values (7,18);
insert into Course_Class (course_id, section_id) values (8,19);
insert into Course_Class (course_id, section_id) values (8,20);
insert into Course_Class (course_id, section_id) values (8,21);
insert into Course_Class (course_id, section_id) values (10,22);
insert into Course_Class (course_id, section_id) values (10,23);
insert into Course_Class (course_id, section_id) values (11,24);
insert into Course_Class (course_id, section_id) values (11,25);
insert into Course_Class (course_id, section_id) values (11,26);
insert into Course_Class (course_id, section_id) values (11,27);
insert into Course_Class (course_id, section_id) values (12,28);
insert into Course_Class (course_id, section_id) values (12,29);
insert into Course_Class (course_id, section_id) values (13,30);
insert into Course_Class (course_id, section_id) values (13,31);
insert into Course_Class (course_id, section_id) values (14,32);
insert into Course_Class (course_id, section_id) values (14,33);
insert into Course_Class (course_id, section_id) values (14,34);
insert into Course_Class (course_id, section_id) values (14,35);
insert into Course_Class (course_id, section_id) values (8,36);
insert into Course_Class (course_id, section_id) values (8,37);
insert into Course_Class (course_id, section_id) values (11,38);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',1,'Fall',2014);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',14,'Spring',2015);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',1,'Fall',2015);
insert into Taught_By (name, course_id, quarter, year_) values ('Adele',11,'Fall',2014);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',2,'Winter',2016);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',1,'Spring',2015);
insert into Taught_By (name, course_id, quarter, year_) values ('Bjork',4,'Fall',2014);
insert into Taught_By (name, course_id, quarter, year_) values ('Bjork',12,'Fall',2015);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',5,'Winter',2015);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',6,'Fall',2015);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',11,'Winter',2015);
insert into Taught_By (name, course_id, quarter, year_) values ('Adele',1,'Winter',2016);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',2,'Winter',2015);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',7,'Fall',2015);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',14,'Fall',2015);
insert into Taught_By (name, course_id, quarter, year_) values ('Bjork',10,'Spring',2015);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',6,'Winter',2016);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',11,'Winter',2016);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',13,'Winter',2016);
insert into Taught_By (name, course_id, quarter, year_) values ('Bjork',4,'Fall',2015);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',14,'Winter',2016);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',8,'Spring',2015);
insert into Taught_By (name, course_id, quarter, year_) values ('<NAME>',8,'Winter',2016);
insert into Course_Offered (course_id, department_id) values (1,1);
insert into Course_Offered (course_id, department_id) values (2,1);
insert into Course_Offered (course_id, department_id) values (3,1);
insert into Course_Offered (course_id, department_id) values (4,1);
insert into Course_Offered (course_id, department_id) values (5,1);
insert into Course_Offered (course_id, department_id) values (6,1);
insert into Course_Offered (course_id, department_id) values (7,1);
insert into Course_Offered (course_id, department_id) values (8,1);
insert into Course_Offered (course_id, department_id) values (9,2);
insert into Course_Offered (course_id, department_id) values (10,2);
insert into Course_Offered (course_id, department_id) values (11,2);
insert into Course_Offered (course_id, department_id) values (12,3);
insert into Course_Offered (course_id, department_id) values (13,3);
insert into Course_Offered (course_id, department_id) values (14,3);
insert into Course_Offered (course_id, department_id) values (15,3);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (1,1,'Fall',2014,4,'Letter','A-');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (3,1,'Fall',2014,4,'Letter','B+');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (2,2,'Spring',2015,4,'Letter','C-');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (4,3,'Fall',2015,4,'Letter','A-');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (5,3,'Fall',2015,4,'Letter','B');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (1,6,'Winter',2015,4,'Letter','A-');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (5,6,'Winter',2015,4,'Letter','B+');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (4,6,'Winter',2015,4,'Letter','C');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (16,9,'Fall',2014,4,'Letter','C');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (22,10,'Fall',2015,4,'Letter','B+');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (18,10,'Fall',2015,4,'Letter','D');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (19,10,'Fall',2015,4,'Letter','F');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (17,12,'Winter',2015,4,'Letter','A');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (19,12,'Winter',2015,4,'Letter','A');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (20,14,'Fall',2015,4,'Letter','B-');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (18,14,'Fall',2015,4,'Letter','B');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (21,14,'Fall',2015,4,'Letter','F');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (17,17,'Fall',2015,4,'Letter','A-');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (22,19,'Spring',2015,4,'Letter','A');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (20,19,'Spring',2015,4,'Letter','A');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (10,22,'Spring',2015,4,'Letter','B+');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (8,24,'Fall',2014,2,'Letter','B-');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (7,24,'Fall',2014,2,'Letter','A-');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (6,25,'Winter',2015,2,'Letter','B');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (10,25,'Winter',2015,2,'Letter','B+');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (11,28,'Fall',2015,4,'Letter','A');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (12,28,'Fall',2015,4,'Letter','A');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (13,28,'Fall',2015,4,'Letter','C-');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (14,28,'Fall',2015,4,'Letter','C+');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (15,32,'Spring',2015,2,'Letter','F');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (12,32,'Spring',2015,2,'Letter','D');
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (11,33,'Fall',2015,2,'Letter','A-');
/*current*/
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (16,20,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (17,37,'Winter',2016,4,'S/U',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (18,36,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (19,20,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (20,37,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (21,36,'Winter',2016,4,'S/U',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (22,15,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (16,15,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (17,15,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (1,4,'Winter',2016,4,'S/U',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (5,4,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (3,4,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (7,26,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (8,26,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (9,38,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (4,7,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (12,30,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (13,34,'Winter',2016,4,'S/U',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (14,30,'Winter',2016,4,'Letter',NULL);
insert into Course_Taken (sid, section_id, quarter, year_taken, units_taken_for, grade_option, grade) values (15,34,'Winter',2016,4,'Letter',NULL);
/*still need total and tech electives*/
insert into Degree_Required (degree_id, category, units_completed, min_gpa) values (1,'Lower Division',10,NULL);
insert into Degree_Required (degree_id, category, units_completed, min_gpa) values (1,'Upper Division',15,NULL);
insert into Degree_Required (degree_id, category, units_completed, min_gpa) values (1,'Tech Elective',15,NULL);
insert into Degree_Required (degree_id, category, units_completed, min_gpa) values (2,'Lower Division',15,NULL);
insert into Degree_Required (degree_id, category, units_completed, min_gpa) values (2,'Upper Division',20,NULL);
insert into Degree_Required (degree_id, category, units_completed, min_gpa) values (2,'Tech Elective',0,NULL);
insert into Degree_Required (degree_id, category, units_completed, min_gpa) values (3,'Lower Division',20,NULL);
insert into Degree_Required (degree_id, category, units_completed, min_gpa) values (3,'Upper Division',20,NULL);
insert into Degree_Required (degree_id, category, units_completed, min_gpa) values (3,'Tech Elective',10,NULL);
insert into Degree_Required (degree_id, category, units_completed, min_gpa) values (4,'Graduate Division',45,NULL);
insert into Degree_Required (degree_id, category, units_completed, min_gpa) values (5,'Graduate Division',4,3);
insert into Degree_Required (degree_id, category, units_completed, min_gpa) values (6,'Graduate Division',8,3.1);
insert into Degree_Required (degree_id, category, units_completed, min_gpa) values (7,'Graduate Division',4,3.3);
insert into grade_conversion values('A+', 4.0);
insert into grade_conversion values('A', 4.0);
insert into grade_conversion values('A-', 3.7);
insert into grade_conversion values('B+', 3.3);
insert into grade_conversion values('B', 3.0);
insert into grade_conversion values('B-', 2.7);
insert into grade_conversion values('C+', 2.3);
insert into grade_conversion values('C', 2.0);
insert into grade_conversion values('C-', 1.7);
insert into grade_conversion values('D', 1.0);
insert into grade_conversion values('F', 0.0);
insert into grade_conversion values('S', NULL);
insert into grade_conversion values('U', NULL);
insert into extra_category (course_id, category) values (4,'Tech Elective');
insert into extra_category (course_id, category) values (8,'Tech Elective');
insert into extra_category (course_id, category) values (2,'Tech Elective');
insert into extra_category (course_id, category) values (10,'Tech Elective');
insert into extra_category (course_id, category) values (9,'Tech Elective');
insert into concentration (course_id, concentration_name, min_gpa, units) values (7,'Databases',3,4);
insert into concentration (course_id, concentration_name, min_gpa, units) values (4,'AI',3.1,8);
insert into concentration (course_id, concentration_name, min_gpa, units) values (6,'AI',3.1,8);
insert into concentration (course_id, concentration_name, min_gpa, units) values (8,'Systems',3.3,4);
/*1 MAE108*/
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Monday','10:00','11:00','109','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Wednesday','10:00','11:00','109','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Friday','10:00','11:00','109','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Tuesday','10:00','11:00','2001','Warren',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Thursday','10:00','11:00','2001','Warren',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lab','Friday','18:00','19:00','2001','Warren',1);
/*2 CSE221*/
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Monday','10:00','11:00','214','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Wednesday','10:00','11:00','214','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Friday','10:00','11:00','214','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Tuesday','11:00','12:00','2001','Warren',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Thursday','11:00','12:00','2001','Warren',1);
/*3 CSE255*/
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Monday','12:00','13:00','214','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Wednesday','12:00','13:00','214','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Friday','12:00','13:00','214','Center',1);
/*4 PHIL12*/
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Monday','12:00','13:00','109','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Wednesday','12:00','13:00','109','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Friday','12:00','13:00','109','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Wednesday','13:00','14:00','2001','Warren',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Friday','13:00','14:00','2001','Warren',1);
/*5 CSE221*/
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Monday','12:00','13:00','101','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Wednesday','12:00','13:00','101','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Friday','12:00','13:00','101','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Tuesday','12:00','13:00','2011','Warren',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Thursday','12:00','13:00','2011','Warren',1);
/*6 CSE105*/
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Tuesday','14:00','15:00','109','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Thursday','14:00','15:00','109','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Friday','18:00','19:00','109','Center',1);
/*7 PHIL 165*/
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Tuesday','15:00','16:00','109','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Thursday','15:00','16:00','109','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Thursday','13:00','14:00','2001','Warren',1);
/*8 MAE108*/
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Tuesday','15:00','16:00','101','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Thursday','15:00','16:00','101','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Monday','15:00','16:00','2101','Warren',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lab','Friday','17:00','18:00','212','Center',1);
/*9 CSE221*/
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Tuesday','17:00','18:00','109','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Thursday','17:00','18:00','109','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Monday','9:00','10:00','2101','Warren',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Friday','9:00','10:00','2101','Warren',1);
/*10 CSE8A*/
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Tuesday','17:00','18:00','101','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lecture','Thursday','17:00','18:00','101','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Discussion','Wednesday','19:00','20:00','109','Center',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lab','Tuesday','15:00','16:00','2001','Warren',1);
insert into Meeting(type_, day_of_week, start_time,end_time,room,building, mandatory) values('Lab','Thursday','15:00','16:00','2001','Warren',1);
insert into Class_Meeting(section_id, meeting_id) values (26,1);
insert into Class_Meeting(section_id, meeting_id) values (26,2);
insert into Class_Meeting(section_id, meeting_id) values (26,3);
insert into Class_Meeting(section_id, meeting_id) values (26,4);
insert into Class_Meeting(section_id, meeting_id) values (26,5);
insert into Class_Meeting(section_id, meeting_id) values (26,6);
insert into Class_Meeting(section_id, meeting_id) values (20,7);
insert into Class_Meeting(section_id, meeting_id) values (20,8);
insert into Class_Meeting(section_id, meeting_id) values (20,9);
insert into Class_Meeting(section_id, meeting_id) values (20,10);
insert into Class_Meeting(section_id, meeting_id) values (20,11);
insert into Class_Meeting(section_id, meeting_id) values (15,12);
insert into Class_Meeting(section_id, meeting_id) values (15,13);
insert into Class_Meeting(section_id, meeting_id) values (15,14);
insert into Class_Meeting(section_id, meeting_id) values (30,15);
insert into Class_Meeting(section_id, meeting_id) values (30,16);
insert into Class_Meeting(section_id, meeting_id) values (30,17);
insert into Class_Meeting(section_id, meeting_id) values (30,18);
insert into Class_Meeting(section_id, meeting_id) values (30,19);
insert into Class_Meeting(section_id, meeting_id) values (36,20);
insert into Class_Meeting(section_id, meeting_id) values (36,21);
insert into Class_Meeting(section_id, meeting_id) values (36,22);
insert into Class_Meeting(section_id, meeting_id) values (36,23);
insert into Class_Meeting(section_id, meeting_id) values (36,24);
insert into Class_Meeting(section_id, meeting_id) values (7,25);
insert into Class_Meeting(section_id, meeting_id) values (7,26);
insert into Class_Meeting(section_id, meeting_id) values (7,27);
insert into Class_Meeting(section_id, meeting_id) values (34,28);
insert into Class_Meeting(section_id, meeting_id) values (34,29);
insert into Class_Meeting(section_id, meeting_id) values (34,30);
insert into Class_Meeting(section_id, meeting_id) values (38,31);
insert into Class_Meeting(section_id, meeting_id) values (38,32);
insert into Class_Meeting(section_id, meeting_id) values (38,33);
insert into Class_Meeting(section_id, meeting_id) values (38,34);
insert into Class_Meeting(section_id, meeting_id) values (37,35);
insert into Class_Meeting(section_id, meeting_id) values (37,36);
insert into Class_Meeting(section_id, meeting_id) values (37,37);
insert into Class_Meeting(section_id, meeting_id) values (37,38);
insert into Class_Meeting(section_id, meeting_id) values (4,39);
insert into Class_Meeting(section_id, meeting_id) values (4,40);
insert into Class_Meeting(section_id, meeting_id) values (4,41);
insert into Class_Meeting(section_id, meeting_id) values (4,42);
insert into Class_Meeting(section_id, meeting_id) values (4,43);
insert into review_time(id,start_time) values (1,'8:00');
insert into review_time(id,start_time) values (2,'9:00');
insert into review_time(id,start_time) values (3,'10:00');
insert into review_time(id,start_time) values (4,'11:00');
insert into review_time(id,start_time) values (5,'12:00');
insert into review_time(id,start_time) values (6,'13:00');
insert into review_time(id,start_time) values (7,'14:00');
insert into review_time(id,start_time) values (8,'15:00');
insert into review_time(id,start_time) values (9,'16:00');
insert into review_time(id,start_time) values (10,'17:00');
insert into review_time(id,start_time) values (11,'18:00');
insert into review_time(id,start_time) values (12,'19:00');
/*1 MAE108*/
insert into meeting2b values (1,26,'Lecture',null,3,null,3,null,3,null);
/*2 CSE221*/
insert into meeting2b values (2,20,'Lecture',null,3,null,3,null,3,null);
/*3 CSE255*/
insert into meeting2b values (3,15,'Lecture',null,5,null,5,null,5,null);
/*4 PHIL12*/
insert into meeting2b values (4,30,'Lecture',null,5,null,5,null,5,null);
/*5 CSE221*/
insert into meeting2b values (5,36,'Lecture',null,5,null,5,null,5,null);
/*6 CSE105*/
insert into meeting2b values (6,7,'Lecture',null,null,7,null,7,null,null);
insert into meeting2b values (7,7,'Discussion',null,null,null,null,null,11,null);
/*7 PHIL165*/
insert into meeting2b values (8,34,'Lecture',null,null,8,null,8,null,null);
/*8 MAE108*/
insert into meeting2b values (9,38,'Lecture',null,null,8,null,8,null,null);
/*9 CSE221*/
insert into meeting2b values (10,37,'Lecture',null,null,10,null,10,null,null);
/*10 CSE8A*/
insert into meeting2b values (11,4,'Lecture',null,null,10,null,10,null,null);
insert into meeting2b values (12,4,'Discussion',null,null,null,12,null,null,null);
<file_sep>create table Student(sid integer not null identity(1,1),
firstname varchar(255) not null,
middlename varchar(255),
lastname varchar(255) not null,
ssn char(9) not null unique,
residency varchar(255) not null,
enrolled bit not null,
primary key (sid));
create table Undergraduate(sid integer not null,
college varchar(20) not null,
primary key (sid),
foreign key (sid) references Student(sid));
create table Graduate(sid integer not null,
primary key(sid),
foreign key (sid) references Student(sid));
create table MS(sid integer not null,
concentration varchar(255),
primary key (sid),
foreign key (sid) references Graduate(sid));
create table PhD(sid integer not null,
type_ varchar(20) not null,
primary key (sid),
foreign key (sid) references Graduate(sid));
create table Time_Period(time_id integer not null identity(1,1),
start_quarter varchar(10) not null,
start_year integer not null,
end_quarter varchar(10) not null,
end_year integer not null,
primary key(time_id),
unique(start_quarter, start_year, end_quarter, end_year));
create table Attends(sid integer not null,
time_id integer not null,
primary key(sid, time_id),
foreign key (sid) references Student(sid),
foreign key (time_id) references Time_Period(time_id));
create table Probation(sid integer not null,
time_id integer not null,
primary key(sid, time_id),
foreign key (sid) references Student(sid),
foreign key (time_id) references Time_Period(time_id));
create table Previous_Degree(degree_id integer not null identity(1,1),
degree_type varchar(255) not null,
university varchar(255) not null,
unique (degree_type, university),
primary key(degree_id));
create table Owns_Degree(sid integer not null,
degree_id integer not null,
primary key (sid, degree_id),
foreign key (sid) references Student(sid),
foreign key (degree_id) references Previous_Degree(degree_id));
create table Course(course_id integer not null identity(1,1),
min_units integer not null,
max_units integer not null,
grade_options varchar(20) not null,
lab_work_req bit not null,
category varchar(255) not null,
course_name varchar(255) not null unique,
consent_req bit not null,
primary key (course_id));
create table prereq(course_id integer not null,
prereq_id integer not null,
primary key (course_id, prereq_id),
foreign key (course_id) references Course(course_id),
foreign key (prereq_id) references Course(course_id),
check (course_id <> prereq_id));
create table Class_(section_id integer not null identity(1,1),
enrollment_limit integer not null,
quarter varchar(20) not null,
year_ integer not null,
title varchar(255) not null,
primary key (section_id));
create table Course_Taken(id integer not null identity(1,1),
sid integer not null,
section_id integer not null,
quarter varchar(20) not null,
year_taken integer not null,
units_taken_for integer not null,
grade_option varchar(255) not null,
grade varchar(20),
primary key (id),
unique(sid, section_id, quarter, year_taken),
foreign key (sid) references Student(sid),
foreign key (section_id) references Class_(section_id));
create table Course_Class(course_id integer not null,
section_id integer not null,
primary key (course_id, section_id),
foreign key (course_id) references Course(course_id),
foreign key (section_id) references Class_(section_id));
create table Waitlisted(waitlist_id integer not null identity(1,1),
sid integer not null,
section_id integer not null,
primary key (sid, section_id),
foreign key (sid) references Student(sid),
foreign key (section_id) references Class_(section_id));
create table Enrolled(sid integer not null,
section_id integer not null,
grade_options varchar(20) not null,
units_taken_for integer not null,
primary key (sid, section_id),
foreign key (sid) references Student(sid),
foreign key (section_id) references Class_(section_id));
create table Meeting(meeting_id integer not null identity(1,1),
type_ varchar(255) not null,
day_of_week varchar(20) not null,
start_time time not null,
end_time time not null,
room varchar(255) not null,
building varchar(255) not null,
mandatory bit not null,
primary key (meeting_id),
unique(type_,day_of_week,start_time,end_time,room,building,mandatory));
create table Review(meeting_id integer not null,
date_ date not null,
primary key(meeting_id, date_),
foreign key (meeting_id) references Meeting(meeting_id));
create table Class_Meeting(section_id integer not null,
meeting_id integer not null,
primary key (section_id, meeting_id),
unique (meeting_id),
foreign key (section_id) references Class_(section_id),
foreign key (meeting_id) references Meeting(meeting_id));
create table Faculty(name varchar(255),
title varchar(255) not null,
primary key (name));
create table Taught_By(name varchar(255),
course_id integer not null,
quarter varchar(20) not null,
year_ integer not null,
primary key(name, course_id, quarter, year_),
foreign key (name) references Faculty(name),
foreign key (course_id) references Course(course_id));
create table Department(department_id integer not null identity(1,1),
department_name varchar(255) not null unique,
primary key (department_id));
create table Faculty_Department(name varchar(255) not null,
department_id integer not null,
primary key (name, department_id),
foreign key (name) references Faculty(name),
foreign key (department_id) references Department(department_id));
create table Course_Offered(course_id integer not null,
department_id integer not null,
primary key (course_id, department_id),
foreign key (course_id) references Course(course_id),
foreign key (department_id) references Department(department_id));
create table Belongs_To(sid integer not null,
department_id integer not null,
primary key (sid, department_id),
foreign key (sid) references Graduate(sid),
foreign key (department_id) references Department(department_id));
/*create table Degree(degree_id integer not null identity(1,1),
concentration varchar(255) not null,
degree_type varchar(255) not null,
unique(concentration, degree_type),
primary key (degree_id));*/
create table Degree(degree_id integer not null identity(1,1),
department_id integer not null,
degree_type varchar(255) not null,
concentration varchar(255),
foreign key (department_id) references Department(department_id),
primary key (degree_id));
create table Major(sid integer not null,
degree_id integer not null,
primary key (sid, degree_id),
foreign key (sid) references Student(sid),
foreign key (degree_id) references Degree(degree_id));
create table Minor(sid integer not null,
degree_id integer not null,
primary key (sid, degree_id),
foreign key (sid) references Student(sid),
foreign key (degree_id) references Degree(degree_id));
/*create table Degree_Required(department_id integer not null,
degree_id integer not null,
category varchar(255) not null,
units_completed integer not null,
primary key (department_id, degree_id),
foreign key (department_id) references Department(department_id),
foreign key (degree_id) references Degree(degree_id));*/
create table Degree_Required(degree_id integer not null,
category varchar(255) not null,
units_completed integer not null,
min_gpa float,
primary key (degree_id, category, units_completed),
foreign key (degree_id) references Degree(degree_id));
create table Health_Insurance(health_id integer not null identity(1,1),
type_ varchar(255) not null,
primary key (health_id));
create table Insured(sid integer not null,
health_id integer not null,
primary key(sid),
foreign key (sid) references Student(sid),
foreign key (health_id) references Health_Insurance(health_id));
create table Thesis_Committee(sid integer not null,
name varchar(255) not null,
primary key(sid, name),
foreign key (sid) references Graduate(sid),
foreign key (name) references Faculty(name));
create table Other_Department_Thesis(sid integer not null,
name varchar(255) not null,
department_id integer not null,
primary key(sid, name),
foreign key (sid) references PhD(sid),
foreign key (name) references Faculty(name),
foreign key (department_id) references Department(department_id));
create table Advises(sid integer not null,
name varchar(255) not null,
primary key(sid, name),
foreign key (sid) references Graduate(sid),
foreign key (name) references Faculty(name));
create table BachelorsMS(sid integer not null,
primary key (sid),
foreign key(sid) references Undergraduate(sid),
foreign key(sid) references MS(sid));
create table GRADE_CONVERSION(LETTER_GRADE CHAR(2) NOT NULL,
NUMBER_GRADE DECIMAL(2,1));
create table extra_category(id integer not null identity(1,1),
course_id integer not null,
category varchar(255) not null,
primary key(id),
foreign key (course_id) references Course(course_id));
create table concentration(id integer not null identity(1,1),
course_id integer not null,
concentration_name varchar(255) not null,
min_gpa float not null,
units integer not null,
primary key(id),
foreign key (course_id) references Course(course_id));
create table review_time(id integer not null,
start_time time not null);
create table meeting2b(meeting_id integer not null,
section_id integer not null,
type_ varchar(255) not null,
sunday integer,
monday integer,
tuesday integer,
wednesday integer,
thursday integer,
friday integer,
saturday integer,
primary key (meeting_id));
create table cpqg2 (course_name varchar(255),
quarter varchar(255),
year_ integer,
professor varchar(255),
a_grade varchar(255) not null,
b_grade varchar(255) not null,
c_grade varchar(255) not null,
d_grade varchar(255) not null,
other_grade varchar(255) not null);
create table cpg2 (course_name varchar(255),
professor varchar(255),
a_grade varchar(255) not null,
b_grade varchar(255) not null,
c_grade varchar(255) not null,
d_grade varchar(255) not null,
other_grade varchar(255) not null);
<file_sep><html>
<body>
<table border="1">
<tr>
<td valign="top">
<%-- -------- Include menu HTML code -------- --%>
<jsp:include page="menu.html" />
</td>
<td>
<%-- Set the scripting language to Java and --%>
<%-- Import the java.sql package --%>
<%@ page language="java" import="java.sql.*" %>
<%-- -------- Open Connection Code -------- --%>
<%
Statement stmt = null;
Statement stmt2 = null;
Statement stmt3 = null;
String query = "SELECT s.* from Student s, MS m WHERE s.sid = m.sid and s.enrolled = 1;";
String query10 = "SELECT deg.degree_id, dept.department_name, deg.degree_type FROM Department dept, Degree deg WHERE dept.department_id = deg.department_id AND " +
"deg.degree_type ='M.S' and deg.concentration IS NULL;";
try {
// Load Oracle Driver class file
DriverManager.registerDriver
(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
// Make a connection to the Oracle datasource "cse132b"
Connection conn = DriverManager.getConnection
("jdbc:sqlserver://localhost:1433;databaseName=cse132b",
"sa", "g");
stmt = conn.createStatement();
stmt2 = conn.createStatement();
stmt3 = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSet rs10 = stmt2.executeQuery(query10);
%>
<form action="1e.jsp" method="get">
SSN:
<select name="ssn">
<option selected disabled>Choose Option</option>
<% while(rs.next()) {%>
<option value=<%=rs.getInt("ssn")%>><%=rs.getInt("ssn")%>, <%=rs.getString("firstname")%>, <%=rs.getString("middlename")%>, <%=rs.getString("lastname")%></option>
<% } %>
</select>
Degree:
<select name="degree_id">
<option selected disabled>Choose Option</option>
<% while(rs10.next()) {%>
<option value='<%=rs10.getInt("degree_id")%>,<%=rs10.getString("department_name")%>,<%=rs10.getString("degree_type")%>'><%=rs10.getString("department_name")%>, <%=rs10.getString("degree_type")%></option>
<% } %>
</select>
<input type="submit">
</form>
<table border="1">
<tr>
<th>Department</th>
<th>Degree Type</th>
<th>Category</th>
<th>Units Req.</th>
<th>Units Done</th>
<th>Units Left</th>
</tr>
<%String dataArray[] = request.getParameter("degree_id").split(",");%>
<%=dataArray[0]%>
<%=dataArray[1]%>
<%=dataArray[2]%>
<%String query2 = "SELECT dept.department_name, deg.degree_type, dr.category, dr.units_completed AS units_req, sum(ct3.units_taken_for) AS units_done, (dr.units_completed - sum(ct3.units_taken_for)) AS units_left " +
"FROM Department dept, Degree deg, Degree_required dr, Student s, course_taken3 ct3, Course_Offered co " +
"WHERE deg.department_id = dept.department_id AND dept.department_name = '" + dataArray[1] + "' AND degree_type = '" + dataArray[2] + "' " +
"AND dr.degree_id = deg.degree_id AND s.ssn = " + request.getParameter("ssn") + " and s.sid = ct3.sid and ct3.category = dr.category " +
"and co.course_id = ct3.course_id and co.department_id = dept.department_id and deg.concentration IS NULL " +
"GROUP BY dept.department_name, deg.degree_type, dr.category, dr.units_completed;";%>
<%ResultSet rs2 = stmt2.executeQuery(query2);%>
<% while(rs2.next()){ %>
<tr>
<td><%=rs2.getString("department_name")%></td>
<td><%=rs2.getString("degree_type")%></td>
<td><%=rs2.getString("category")%></td>
<td><%=rs2.getInt("units_req")%></td>
<td><%=rs2.getInt("units_done")%></td>
<td><%=rs2.getInt("units_left")%></td>
</tr>
<% } %>
</table>
<hr>
Completed Concentrations
<table border="1">
<tr>
<th>Concentration</th>
<th>Units Req</th>
<th>Units Done</th>
<th>Min GPA</th>
<th>GPA</th>
</tr>
<%String query3 = "SELECT c.concentration_name, units AS units_req, sum(units_taken_for) AS units_done, c.min_gpa, avg(gc.number_grade) AS gpa " +
"FROM course_taken3 ct3, Student s, concentration c, grade_conversion gc " +
"WHERE s.ssn = " + request.getParameter("ssn") + " AND s.sid = ct3.sid and ct3.course_id = c.course_id and ct3.grade = gc.letter_grade " +
"GROUP BY c.concentration_name, c.units, min_gpa;";%>
<%ResultSet rs3 = stmt3.executeQuery(query3);%>
<% while(rs3.next()){ %>
<%if((rs3.getInt("units_done") >= rs3.getInt("units_req")) && (rs3.getFloat("gpa") >= rs3.getFloat("min_gpa"))){%>
<tr>
<td><%=rs3.getString("concentration_name")%></td>
<td><%=rs3.getInt("units_req")%></td>
<td><%=rs3.getInt("units_done")%></td>
<td><%=rs3.getFloat("min_gpa")%></td>
<td><%=rs3.getFloat("gpa")%></td>
</tr>
<% } %>
<% } %>
</table>
<hr>
<table border="1">
<tr>
<th>Course Name</th>
<th>Quarter</th>
<th>Year</th>
</tr>
<%String query4 = "SELECT t2.course_name, cl.quarter, cl.year_ FROM (SELECT * FROM (SELECT course_name FROM concentration c, course co " +
"WHERE c.course_id = co.course_id) t1 EXCEPT (SELECT ct3.course_name " +
"FROM student s, concentration c, course_taken3 ct3 " +
"WHERE s.ssn = " + request.getParameter("ssn") + " and s.sid = ct3.sid and c.course_id = ct3.course_id)) t2, Course co, Class_ cl, Course_Class cc " +
"WHERE t2.course_name = co.course_name and cc.section_id = cl.section_id and cc.course_id = co.course_id AND " +
"cl.year_ >= 2016 AND NOT (cl.year_ = 2016 and cl.quarter = 'Winter');";%>
<%ResultSet rs4 = stmt3.executeQuery(query4);%>
<% while(rs4.next()){ %>
<tr>
<td><%=rs4.getString("course_name")%></td>
<td><%=rs4.getString("quarter")%></td>
<td><%=rs4.getInt("year_")%></td>
</tr>
<% } %>
</table>
<%-- -------- Close Connection Code -------- --%>
<%
// Close the ResultSet
rs.close();
rs2.close();
// Close the Statement
stmt.close();
stmt2.close();
// Close the Connection
conn.close();
} catch (SQLException sqle) {
out.println(sqle.getMessage());
} catch (Exception e) {
out.println(e.getMessage());
}
//conn.close;
%>
</table>
</td>
</tr>
</table>
</body>
</html>
<file_sep>create table cpqg2 (course_name varchar(255),
quarter varchar(255),
year_ integer,
professor varchar(255),
a_grade varchar(255) not null,
b_grade varchar(255) not null,
c_grade varchar(255) not null,
d_grade varchar(255) not null,
other_grade varchar(255) not null);
create table cpg2 (course_name varchar(255),
professor varchar(255),
a_grade varchar(255) not null,
b_grade varchar(255) not null,
c_grade varchar(255) not null,
d_grade varchar(255) not null,
other_grade varchar(255) not null);<file_sep><html>
<body>
<table border="1">
<tr>
<td valign="top">
<%-- -------- Include menu HTML code -------- --%>
<jsp:include page="menu.html" />
</td>
<td>
<%-- Set the scripting language to Java and --%>
<%-- Import the java.sql package --%>
<%@ page language="java" import="java.sql.*" %>
<%-- -------- Open Connection Code -------- --%>
<%
Statement stmt = null;
Statement stmt2 = null;
String query = "SELECT DISTINCT ct.section_id, co.course_name FROM Course_Taken ct, Course_Class cc, Course co"+
" WHERE ct.section_id = cc.section_id AND cc.course_id = co.course_id AND ct.quarter = 'Winter' AND ct.year_taken = '2016'";
try {
// Load Oracle Driver class file
DriverManager.registerDriver
(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
// Make a connection to the Oracle datasource "cse132b"
Connection conn = DriverManager.getConnection
("jdbc:sqlserver://localhost:1433;databaseName=cse132b",
"sa", "g");
stmt = conn.createStatement();
stmt2 = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
%>
<form action="2b.jsp" method="get">
Section:
<select name="section_id">
<option selected disabled>Choose Option</option>
<% while(rs.next()) {%>
<option value=<%=rs.getInt("section_id")%>><%=rs.getInt("section_id")%>, <%=rs.getString("course_name")%></option>
<% } %>
</select>
Start Date:
<Input value = "" name = 'start_day'>
End Date:
<Input value = "" name = 'end_day'>
<input type="submit">
</form>
<table border="1">
<tr>
<th>Day of week</th>
<th>Start Time</th>
</tr>
<%String query2 = "SELECT * FROM ( "+
"(SELECT '1. Sunday' as day, rt.start_time as time FROM review_time rt WHERE id NOT IN (SELECT distinct(m.sunday) FROM Course_Taken ct INNER JOIN meeting2b m ON ct.section_id = m.section_id INNER JOIN Student s on s.sid = ct.sid WHERE m.sunday IS NOT NULL AND s.ssn IN (SELECT s.ssn FROM Course_taken ct INNER JOIN Student s on s.sid = ct.sid WHERE section_id = "+ request.getParameter("section_id")+"))) "+
"UNION "+
"(SELECT '2. Monday' as day, rt.start_time as time FROM review_time rt WHERE id NOT IN (SELECT distinct(m.monday) FROM Course_Taken ct INNER JOIN meeting2b m ON ct.section_id = m.section_id INNER JOIN Student s on s.sid = ct.sid WHERE m.monday IS NOT NULL AND s.ssn IN (SELECT s.ssn FROM Course_taken ct INNER JOIN Student s on s.sid = ct.sid WHERE section_id = "+ request.getParameter("section_id")+" ))) "+
"UNION "+
"(SELECT '3. Tuesday' as day, rt.start_time as time FROM review_time rt WHERE id NOT IN (SELECT distinct(m.tuesday) FROM Course_Taken ct INNER JOIN meeting2b m ON ct.section_id = m.section_id INNER JOIN Student s on s.sid = ct.sid WHERE m.tuesday IS NOT NULL AND s.ssn IN (SELECT s.ssn FROM Course_taken ct INNER JOIN Student s on s.sid = ct.sid WHERE section_id = "+ request.getParameter("section_id")+"))) "+
"UNION "+
"(SELECT '4. Wednesday' as day, rt.start_time as time FROM review_time rt WHERE id NOT IN (SELECT distinct(m.wednesday) FROM Course_Taken ct INNER JOIN meeting2b m ON ct.section_id = m.section_id INNER JOIN Student s on s.sid = ct.sid WHERE m.wednesday IS NOT NULL AND s.ssn IN (SELECT s.ssn FROM Course_taken ct INNER JOIN Student s on s.sid = ct.sid WHERE section_id = "+ request.getParameter("section_id")+" ))) "+
"UNION "+
"(SELECT '5. Thursday' as day, rt.start_time as time FROM review_time rt WHERE id NOT IN (SELECT distinct(m.thursday) FROM Course_Taken ct INNER JOIN meeting2b m ON ct.section_id = m.section_id INNER JOIN Student s on s.sid = ct.sid WHERE m.thursday IS NOT NULL AND s.ssn IN (SELECT s.ssn FROM Course_taken ct INNER JOIN Student s on s.sid = ct.sid WHERE section_id = "+ request.getParameter("section_id")+" ))) "+
"UNION "+
"(SELECT '6. Friday' as day, rt.start_time as time FROM review_time rt WHERE id NOT IN (SELECT distinct(m.friday) FROM Course_Taken ct INNER JOIN meeting2b m ON ct.section_id = m.section_id INNER JOIN Student s on s.sid = ct.sid WHERE m.friday IS NOT NULL AND s.ssn IN (SELECT s.ssn FROM Course_taken ct INNER JOIN Student s on s.sid = ct.sid WHERE section_id = "+ request.getParameter("section_id")+" ))) "+
"UNION "+
"(SELECT '7. Saturday' as day, rt.start_time as time FROM review_time rt WHERE id NOT IN (SELECT distinct(m.saturday) FROM Course_Taken ct INNER JOIN meeting2b m ON ct.section_id = m.section_id INNER JOIN Student s on s.sid = ct.sid WHERE m.saturday IS NOT NULL AND s.ssn IN (SELECT s.ssn FROM Course_taken ct INNER JOIN Student s on s.sid = ct.sid WHERE section_id = "+ request.getParameter("section_id")+" ))))fs "+
"WHERE fs.day >= '" +request.getParameter("start_day") +"' AND fs.day <= '"+request.getParameter("end_day")+"' "+
"ORDER BY day, time";%>
<%ResultSet rs2 = stmt2.executeQuery(query2);%>
<% while(rs2.next()){ %>
<tr>
<td><%=rs2.getString("day")%></td>
<td><%=rs2.getString("time")%></td>
</tr>
<% } %>
</table>
<%-- -------- Close Connection Code -------- --%>
<%
// Close the ResultSet
rs.close();
rs2.close();
// Close the Statement
stmt.close();
stmt2.close();
// Close the Connection
conn.close();
} catch (SQLException sqle) {
out.println(sqle.getMessage());
} catch (Exception e) {
out.println(e.getMessage());
}
//conn.close;
%>
</table>
</td>
</tr>
</table>
</body>
</html><file_sep>/*
SELECT DISTINCT Row_Number() OVER(ORDER BY m.meeting_id) AS Row, cm.meeting_id, m.day_of_week, m.start_time INTO meetDk
FROM Class_Meeting cm, MEETING m
WHERE 42 <> cm.meeting_id AND cm.section_id = 4 AND cm.meeting_id = m.meeting_id;
SELECT * FROM meetDk;
SELECT DISTINCT cm.meeting_id, Row_Number() OVER(ORDER BY m.meeting_id) AS Row_, cc.section_id,tb.name, m.day_of_week, m.start_time INTO courseA
FROM Class_Meeting cm, MEETING m, Course_Class cc, Taught_By tb
WHERE cc.section_id <> 20 AND cc.course_id = tb.course_id AND cc.section_id = cm.section_id AND cm.meeting_id = m.meeting_id AND tb.name = '<NAME>'
AND tb.quarter = 'Winter' AND tb.year_= '2016';
SELECT DISTINCT Row_Number() OVER(ORDER BY m.meeting_id) AS RowA, tb.name, cm.meeting_id, m.day_of_week, m.start_time INTO courseB
FROM Class_Meeting cm, MEETING m, Course_Class cc, Taught_By tb
WHERE cc.section_id = 20 AND cc.course_id = tb.course_id AND cc.section_id = cm.section_id AND cm.meeting_id = m.meeting_id AND tb.name = '<NAME>'
AND tb.quarter = 'Winter' AND tb.year_= '2016';*/
/*trigger to insert a particular meeting for Class_Meeting*/
CREATE TRIGGER sections
ON Class_Meeting
AFTER INSERT
AS
BEGIN
DECLARE @sect integer;
DECLARE @istart time;
DECLARE @iDay varchar(255);
DECLARE @meet integer;
/* DECLARE @m varchar(255);*/
DECLARE @inc integer;
SET @sect = (SELECT section_id FROM Inserted);
SET @meet = (SELECT meeting_id FROM Inserted);
SET @istart = (SELECT start_time FROM Inserted cm, Meeting m WHERE cm.meeting_id = m.meeting_id);
SET @iDay = (SELECT day_of_week FROM Inserted cm, Meeting m WHERE cm.meeting_id = m.meeting_id);
SET @inc = 0;
BEGIN
SELECT DISTINCT Row_Number() OVER(ORDER BY m.meeting_id) AS Row_, cm.meeting_id, m.day_of_week, m.start_time INTO meetDup
FROM Class_Meeting cm, MEETING m
WHERE cm.meeting_id <> @meet AND cm.section_id = @sect AND cm.meeting_id = m.meeting_id;
END
/*SET @m = (SELECT count(*) FROM meetDup);*/
BEGIN
WHILE ( @inc <= (SELECT count(*) FROM meetDup))
BEGIN
IF( (SELECT day_of_week FROM meetDup WHERE row_ = @inc) = @iDay
AND (SELECT start_time FROM meetDup WHERE row_ = @inc) = @istart)
BEGIN
ROLLBACK TRANSACTION
RAISERROR('Meeting %d conflicts',11,11,@meet);
/*Print'Breaking'*/
BREAK;
END
SET @inc = @inc+1;
/*Print @m;
Print 'Dropping row';*/
END
END
DROP TABLE meetDup;
END
CREATE TRIGGER prof
ON Class_Meeting
AFTER INSERT
AS
BEGIN
DECLARE @sect integer;
DECLARE @istart time;
DECLARE @iDay varchar(255);
DECLARE @meet integer;
/* DECLARE @m varchar(255);*/
DECLARE @inc integer;
DECLARE @pname varchar(255);
SET @sect = (SELECT section_id FROM Inserted);
SET @meet = (SELECT meeting_id FROM Inserted);
SET @istart = (SELECT start_time FROM Inserted cm, Meeting m WHERE cm.meeting_id = m.meeting_id);
SET @iDay = (SELECT day_of_week FROM Inserted cm, Meeting m WHERE cm.meeting_id = m.meeting_id);
SET @inc = 0;
SET @pname = (SELECT DISTINCT name FROM taught_by tb, inserted i, course_class cc WHERE tb.course_id = cc.course_id AND cc.section_id = i.section_id AND quarter = 'Winter' AND year_ = 2016);
BEGIN
SELECT DISTINCT Row_Number() OVER(ORDER BY m.meeting_id) AS Row_, cm.meeting_id, m.day_of_week, m.start_time INTO profDup
FROM Class_Meeting cm, MEETING m , Taught_By tb, Course_Class cc
WHERE cm.meeting_id <> @meet AND tb.name = @pname AND cm.meeting_id = m.meeting_id AND cc.course_id = tb.course_id AND cm.section_id = cc.section_id AND
tb.quarter = 'Winter' AND tb.year_ = 2016;
END
/*SET @m = (SELECT count(*) FROM meetDup);*/
BEGIN
WHILE ( @inc <= (SELECT count(*) FROM profDup))
BEGIN
IF( (SELECT day_of_week FROM profDup WHERE row_ = @inc) = @iDay
AND (SELECT start_time FROM profDup WHERE row_ = @inc) = @istart)
BEGIN
ROLLBACK TRANSACTION
RAISERROR('Meeting %d conflicts with %s',11,11,@meet,@pname);
/*Print'Breaking'*/
BREAK;
END
SET @inc = @inc+1;
/*Print @m;
Print 'Dropping row';*/
END
END
DROP TABLE profDup;
END
/*enrollment*/
CREATE TRIGGER enrollments
ON Course_Taken
AFTER INSERT
AS
BEGIN
DECLARE @section_id integer;
SET @section_id = (SELECT section_id FROM INSERTED);
IF( (SELECT count (*) FROM Course_Taken ct WHERE ct.section_id = @section_id) > (SELECT ab.enrollment_limit FROM (SELECT DISTINCT c.section_id, c.enrollment_limit FROM INSERTED ct, Class_ c WHERE ct.section_id = c.section_id AND c.Quarter = 'winter' AND c.year_= 2016)ab))
BEGIN
ROLLBACK TRANSACTION
RAISERROR('Section %d is full',11,11,@section_id);
END
END
GO
<file_sep>CREATE VIEW student_quarter_grades AS
SELECT s.sid, c.section_id, c.enrollment_limit, c.quarter, c.year_, c.title, ct.units_taken_for, ct.grade, gc.number_grade
FROM Class_ c, Course_Taken ct, Student s, grade_conversion gc
WHERE s.sid = ct.sid AND ct.section_id = c.section_id AND ct.grade = gc.letter_grade;
CREATE VIEW course_taken2 AS
SELECT ct.*, cc.course_id, c.course_name, c.category, co.department_id, tb.name
FROM Course_Taken ct, Course_Class cc, Course c, Course_Offered co, Taught_By tb
WHERE ct.section_id = cc.section_id AND cc.course_id = c.course_id AND c.course_id = co.course_id AND c.course_id = tb.course_id AND ct.quarter = tb.quarter and ct.year_taken = tb.year_;
CREATE VIEW all_deg_info AS
SELECT deg.*, dept.department_name, dr.category, dr.units_completed, dr.min_gpa
FROM Degree deg, Department dept, Degree_Required dr
WHERE deg.degree_id = dr.degree_id AND deg.department_id = dept.department_id;
CREATE VIEW ms_gpa as
SELECT s.sid, c.section_id, c.quarter, c.year_, c.title, ct.units_taken_for, ct.grade, gc.number_grade, co.category
FROM Class_ c, Course_Taken ct, Student s, grade_conversion gc, Course co, Course_class cc
WHERE s.sid = ct.sid AND ct.section_id = c.section_id AND ct.grade = gc.letter_grade AND cc.section_id = ct.section_id AND cc.course_id = co.course_id;
CREATE VIEW course_taken3 AS
SELECT ct.*, cc.course_id, c.course_name, c.category, co.department_id, tb.name
FROM Course_Taken ct, Course_Class cc, Course c, Course_Offered co, Taught_By tb
WHERE ct.section_id = cc.section_id AND cc.course_id = c.course_id AND c.course_id = co.course_id AND c.course_id = tb.course_id AND ct.quarter = tb.quarter and ct.year_taken = tb.year_;<file_sep>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER cpqg2InsertTrigger
ON course_taken
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @quarter varchar(255);
DECLARE @year_taken integer;
DECLARE @grade varchar(255);
DECLARE @professor varchar(255);
DECLARE @course_name varchar(255);
SET @quarter = (SELECT quarter FROM INSERTED);
SET @year_taken = (SELECT year_taken FROM INSERTED);
SET @grade = (SELECT grade FROM INSERTED);
SET @course_name = (SELECT c.course_name
FROM INSERTED ct, Course_Class cc, Course c, Course_Offered co, Taught_By tb
WHERE ct.section_id = cc.section_id AND cc.course_id = c.course_id AND c.course_id = co.course_id AND c.course_id = tb.course_id AND ct.quarter = tb.quarter and ct.year_taken = tb.year_);
SET @professor = (SELECT tb.name
FROM INSERTED ct, Course_Class cc, Course c, Course_Offered co, Taught_By tb
WHERE ct.section_id = cc.section_id AND cc.course_id = c.course_id AND c.course_id = co.course_id AND c.course_id = tb.course_id AND ct.quarter = tb.quarter and ct.year_taken = tb.year_);
if (EXISTS (SELECT course_name, professor, quarter, year_ FROM cpqg2 WHERE course_name = @course_name AND professor = @professor AND quarter = @quarter AND year_ = @year_taken))
BEGIN
if(@grade LIKE 'A%')
BEGIN
UPDATE cpqg2
SET a_grade = a_grade + 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
else if(@grade LIKE 'B%')
BEGIN
UPDATE cpqg2
SET b_grade = b_grade + 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
else if(@grade LIKE 'C%')
BEGIN
UPDATE cpqg2
SET c_grade = c_grade + 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
else if(@grade LIKE 'D%')
BEGIN
UPDATE cpqg2
SET d_grade = d_grade + 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
else
BEGIN
UPDATE cpqg2
SET other_grade = other_grade + 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
END
else
BEGIN
if(@grade LIKE 'A%')
BEGIN
INSERT INTO cpqg2(course_name, quarter, year_, professor, a_grade, b_grade, c_grade, d_grade, other_grade) values (@course_name, @quarter, @year_taken, @professor, 1, 0, 0 ,0 ,0);
END
else if(@grade LIKE 'B%')
BEGIN
INSERT INTO cpqg2(course_name, quarter, year_, professor, a_grade, b_grade, c_grade, d_grade, other_grade) values (@course_name, @quarter, @year_taken, @professor, 0, 1, 0 ,0 ,0);
END
else if(@grade LIKE 'C%')
BEGIN
INSERT INTO cpqg2(course_name, quarter, year_, professor, a_grade, b_grade, c_grade, d_grade, other_grade) values (@course_name, @quarter, @year_taken, @professor, 0, 0, 1 ,0 ,0);
END
else if(@grade LIKE 'D%')
BEGIN
INSERT INTO cpqg2(course_name, quarter, year_, professor, a_grade, b_grade, c_grade, d_grade, other_grade) values (@course_name, @quarter, @year_taken, @professor, 0, 0, 0 ,1 ,0);
END
else
BEGIN
INSERT INTO cpqg2(course_name, quarter, year_, professor, a_grade, b_grade, c_grade, d_grade, other_grade) values (@course_name, @quarter, @year_taken, @professor, 0, 0, 0 ,0 ,1);
END
END
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER cpqg2UpdateTrigger
ON course_taken
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @quarter varchar(255);
DECLARE @year_taken integer;
DECLARE @oldGrade varchar(255);
DECLARE @newGrade varchar(255);
DECLARE @professor varchar(255);
DECLARE @course_name varchar(255);
SET @quarter = (SELECT quarter FROM INSERTED);
SET @year_taken = (SELECT year_taken FROM INSERTED);
SET @oldGrade = (SELECT grade FROM DELETED);
SET @newGrade = (SELECT grade FROM INSERTED);
SET @course_name = (SELECT c.course_name
FROM INSERTED ct, Course_Class cc, Course c, Course_Offered co, Taught_By tb
WHERE ct.section_id = cc.section_id AND cc.course_id = c.course_id AND c.course_id = co.course_id AND c.course_id = tb.course_id AND ct.quarter = tb.quarter and ct.year_taken = tb.year_);
SET @professor = (SELECT tb.name
FROM INSERTED ct, Course_Class cc, Course c, Course_Offered co, Taught_By tb
WHERE ct.section_id = cc.section_id AND cc.course_id = c.course_id AND c.course_id = co.course_id AND c.course_id = tb.course_id AND ct.quarter = tb.quarter and ct.year_taken = tb.year_);
BEGIN
if(@oldGrade LIKE 'A%')
BEGIN
UPDATE cpqg2
SET a_grade = a_grade - 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
else if(@oldGrade LIKE 'B%')
BEGIN
UPDATE cpqg2
SET b_grade = b_grade - 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
else if(@oldGrade LIKE 'C%')
BEGIN
UPDATE cpqg2
SET c_grade = c_grade - 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
else if(@oldGrade LIKE 'D%')
BEGIN
UPDATE cpqg2
SET d_grade = d_grade - 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
else
BEGIN
UPDATE cpqg2
SET other_grade = other_grade - 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
END
BEGIN
if(@newGrade LIKE 'A%')
BEGIN
UPDATE cpqg2
SET a_grade = a_grade + 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
else if(@newGrade LIKE 'B%')
BEGIN
UPDATE cpqg2
SET b_grade = b_grade + 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
else if(@newGrade LIKE 'C%')
BEGIN
UPDATE cpqg2
SET c_grade = c_grade + 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
else if(@newGrade LIKE 'D%')
BEGIN
UPDATE cpqg2
SET d_grade = d_grade + 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
else
BEGIN
UPDATE cpqg2
SET other_grade = other_grade + 1
WHERE course_name = @course_name AND quarter = @quarter AND year_ = @year_taken AND professor = @professor;
END
END
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER cpg2InsertTrigger
ON course_taken
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @grade varchar(255);
DECLARE @professor varchar(255);
DECLARE @course_name varchar(255);
SET @grade = (SELECT grade FROM INSERTED);
SET @course_name = (SELECT c.course_name
FROM INSERTED ct, Course_Class cc, Course c, Course_Offered co, Taught_By tb
WHERE ct.section_id = cc.section_id AND cc.course_id = c.course_id AND c.course_id = co.course_id AND c.course_id = tb.course_id AND ct.quarter = tb.quarter and ct.year_taken = tb.year_);
SET @professor = (SELECT tb.name
FROM INSERTED ct, Course_Class cc, Course c, Course_Offered co, Taught_By tb
WHERE ct.section_id = cc.section_id AND cc.course_id = c.course_id AND c.course_id = co.course_id AND c.course_id = tb.course_id AND ct.quarter = tb.quarter and ct.year_taken = tb.year_);
if (EXISTS (SELECT course_name, professor FROM cpg2 WHERE course_name = @course_name AND professor = @professor))
BEGIN
if(@grade LIKE 'A%')
BEGIN
UPDATE cpg2
SET a_grade = a_grade + 1
WHERE course_name = @course_name AND professor = @professor;
END
else if(@grade LIKE 'B%')
BEGIN
UPDATE cpg2
SET b_grade = b_grade + 1
WHERE course_name = @course_name AND professor = @professor;
END
else if(@grade LIKE 'C%')
BEGIN
UPDATE cpg2
SET c_grade = c_grade + 1
WHERE course_name = @course_name AND professor = @professor;
END
else if(@grade LIKE 'D%')
BEGIN
UPDATE cpg2
SET d_grade = d_grade + 1
WHERE course_name = @course_name AND professor = @professor;
END
else
BEGIN
UPDATE cpg2
SET other_grade = other_grade + 1
WHERE course_name = @course_name AND professor = @professor;
END
END
else
BEGIN
if(@grade LIKE 'A%')
BEGIN
INSERT INTO cpg2(course_name, professor, a_grade, b_grade, c_grade, d_grade, other_grade) values (@course_name, @professor, 1, 0, 0 ,0 ,0);
END
else if(@grade LIKE 'B%')
BEGIN
INSERT INTO cpg2(course_name, professor, a_grade, b_grade, c_grade, d_grade, other_grade) values (@course_name, @professor, 0, 1, 0 ,0 ,0);
END
else if(@grade LIKE 'C%')
BEGIN
INSERT INTO cpg2(course_name, professor, a_grade, b_grade, c_grade, d_grade, other_grade) values (@course_name, @professor, 0, 0, 1 ,0 ,0);
END
else if(@grade LIKE 'D%')
BEGIN
INSERT INTO cpg2(course_name, professor, a_grade, b_grade, c_grade, d_grade, other_grade) values (@course_name, @professor, 0, 0, 0 ,1 ,0);
END
else
BEGIN
INSERT INTO cpg2(course_name, professor, a_grade, b_grade, c_grade, d_grade, other_grade) values (@course_name, @professor, 0, 0, 0 ,0 ,1);
END
END
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER cpg2UpdateTrigger
ON course_taken
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @oldGrade varchar(255);
DECLARE @newGrade varchar(255);
DECLARE @professor varchar(255);
DECLARE @course_name varchar(255);
SET @oldGrade = (SELECT grade FROM DELETED);
SET @newGrade = (SELECT grade FROM INSERTED);
SET @course_name = (SELECT c.course_name
FROM INSERTED ct, Course_Class cc, Course c, Course_Offered co, Taught_By tb
WHERE ct.section_id = cc.section_id AND cc.course_id = c.course_id AND c.course_id = co.course_id AND c.course_id = tb.course_id AND ct.quarter = tb.quarter and ct.year_taken = tb.year_);
SET @professor = (SELECT tb.name
FROM INSERTED ct, Course_Class cc, Course c, Course_Offered co, Taught_By tb
WHERE ct.section_id = cc.section_id AND cc.course_id = c.course_id AND c.course_id = co.course_id AND c.course_id = tb.course_id AND ct.quarter = tb.quarter and ct.year_taken = tb.year_);
BEGIN
if(@oldGrade LIKE 'A%')
BEGIN
UPDATE cpg2
SET a_grade = a_grade - 1
WHERE course_name = @course_name AND professor = @professor;
END
else if(@oldGrade LIKE 'B%')
BEGIN
UPDATE cpg2
SET b_grade = b_grade - 1
WHERE course_name = @course_name AND professor = @professor;
END
else if(@oldGrade LIKE 'C%')
BEGIN
UPDATE cpg2
SET c_grade = c_grade - 1
WHERE course_name = @course_name AND professor = @professor;
END
else if(@oldGrade LIKE 'D%')
BEGIN
UPDATE cpg2
SET d_grade = d_grade - 1
WHERE course_name = @course_name AND professor = @professor;
END
else
BEGIN
UPDATE cpg2
SET other_grade = other_grade - 1
WHERE course_name = @course_name AND professor = @professor;
END
END
BEGIN
if(@newGrade LIKE 'A%')
BEGIN
UPDATE cpg2
SET a_grade = a_grade + 1
WHERE course_name = @course_name AND professor = @professor;
END
else if(@newGrade LIKE 'B%')
BEGIN
UPDATE cpg2
SET b_grade = b_grade + 1
WHERE course_name = @course_name AND professor = @professor;
END
else if(@newGrade LIKE 'C%')
BEGIN
UPDATE cpg2
SET c_grade = c_grade + 1
WHERE course_name = @course_name AND professor = @professor;
END
else if(@newGrade LIKE 'D%')
BEGIN
UPDATE cpg2
SET d_grade = d_grade + 1
WHERE course_name = @course_name AND professor = @professor;
END
else
BEGIN
UPDATE cpg2
SET other_grade = other_grade + 1
WHERE course_name = @course_name AND professor = @professor;
END
END
END
GO | 55cd0035f27e6badfb80e4ace5da0580ea7a4c25 | [
"TSQL",
"SQL",
"Java Server Pages"
] | 10 | TSQL | kyolf/Tritonlink-2.0 | bff2ce8bc75c7782f8849fd503f2989556ca25da | bdbad3e03da3100448ac1c8bf2f20c531b504736 |
refs/heads/master | <file_sep># Jeux du Puissance 4
*******************
## <NAME>
### DEV8
*******************
### Règle du puissance 4 :
Aligner 4 jetons a la suite(vertical, horizontalement, en diagonale) avant l'adversaire.
Jeux tour a tour.
*******************
Développer en Javascript sans framework
*******************
Le jeu permet de joueur contre un autre joueur ou contre l'ordinateur.
Les scores et le nom des joueur est stocker en localStorage
On peut recommencer une partie
Pour jouer un jeton il suffit de cliquer sur n'importe quel colonne.
Concernant l'IA (partie la plus compliquer).
La première chose qu'il fait:
regarder si le joueur a déjà placer 3 jetons verticalement ou horizontalement et qu'il risque de placer un quatrième ce qui lui permettrai de gagner la partie. Si c'est le cas on place le jeton de l'ordinateur a la suite ou entre les jetons si cela est horizontalement.
Pour essayer de gagner une partie, l'ordinateur va toujours regarder si il peut placer 4 jetons de suite horizontalement ou verticalement.
Il va parcourir le tableau pour trouvé l'emplacement qui lui permettrai de gagner. Il ne place pas de jetons au hazard.
Mais la priorité sera toujours la défense.
Bug connu.
Si l'ordinateur détecte a la deuxième ligne par exemple un emplacement qui lui permet de mettre 4 jetons de suite.Mais qu'a la première ligne il y a une case vide,ce qui fait que le jeton prévu a la deuxième ligne passe sur la première ligne.
*******************
## Avis de Dinh
Première utilisation :
Partie contre IA : trop facile ? j'ai gagné en 4 coups CD capture 1
L'IA est un peu prévisible==> Petite amélioration en défense
Sur le board de la partie contre L'IA, manque le lien pour le menu ==> fait
au cas où si une personne veut jouer avec moi. de même pour le joueur contre joueur.
==> L'ia de l'ordinateur n'est pas complet. Une fois que l'ont connais les failles, il est très facile de gagner. Avec plus de temps, il est certain qu'il peut être plus performant.
Partie joueur contre joueur :
Il serait plus agréable de savoir a qui est le tour.==> fait
Pour les noms des joueurs : Il serait bien de proposer une liste de joueur ayant déjà joué a l'application. C'est un peu chiant de retaper son nom à chaque fois. Mais en soi c'est pas très gênant si on veut faire une petite partie.==> Si on recommence plusieurs partie sans retourner au menu, le nom des joueurs est sauvegarder et il n'est pas nécessaire de retaper son nom.
Expérience utilisateur :
Design classique. ==> Je ne voulais pas perdre une journée sur du design(pas ma qualité première en plus). Il y a largement ce qu'il faut pour que le jeux soit intuitif et un "minimum beau".
Un titre parlant mais qui manque de classe. ==> J'ai peur quand changeant le titre, le joueur ne sais pas a quoi il joue!
Utilisation des alert JS un peu abusif. ==> A part pour demander le nom des joueur il n'y a aucune alert.
Commentaire dev :
Fichier bien commenté
fichier tout en un !
les noms des joueur sont sauvegarder dans des localStorages, on pourrait en faire une utilisation plus conséquentes.
Code agréable a lire.
Conclusion :
Un puissance 4 fonctionnelle ! Manque juste du style et une IA un peu plus corsée.
| 11b0606316c05bf4e5df92f8c705ad5324100d72 | [
"Markdown"
] | 1 | Markdown | arnaud71120/Puissance-4-Javascript | d53d01e544822e44a54180887a40aa3141938614 | 3c0e81c4708436510510bdaf292cc68f72b2a882 |
refs/heads/master | <file_sep><?php
# PHP Livereload. This package will enable livereload for development when files are updated on the server.
# GitHub: https://github.com/nathangrove/php-livereload.git
# Usage: Include script tag in your HTML
# <script src="livereload.php?delay=2000"></script>
# the delay param is optional defaults to (2000) milliseconds before next check.
# what paths do we monitor file changes?
$paths = ['.'];
# is this call the javascript performing a check?
if ($_GET['check']){
$time = 0; $dh = opendir($path);
foreach ($paths as $path){
$files = getDirContents($path);
foreach($files as $file){
$t = filemtime($file);
if ($t > $time) $time = $t;
}
}
print $time;
} else {
# pass in a "delay" parameter when fetching the javascript to check...
$delay = isset($_GET['delay']) ? $_GET['delay'] : 2000;
# create the javascript to spit out
$javascript = "var t = ".time().";function r(){ if (this.responseText > t) window.location.reload(); };function c(){ var g = new XMLHttpRequest();g.addEventListener('load', r);g.open('GET', '/livereload.php?check=1');g.send();};window.setInterval(c,$delay);";
header("Content-type: application/javascript");
print $javascript;
}
# helper funciton to get directory contents
function getDirContents($dir, &$results = array()){
$files = scandir($dir);
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
$results[] = $path;
} else if($value != "." && $value != "..") {
getDirContents($path, $results);
$results[] = $path;
}
}
return $results;
}
?>
| ea5f98c25af78611193b452f602ecc70bd2e8358 | [
"PHP"
] | 1 | PHP | nathangrove/php-livereload | a61163a2e0b441ff62ab36e2a005633628a1e6ab | 91f52032f73bafa979beed81ccf29227f2dbf01d |
refs/heads/master | <repo_name>Sheldonlv/Blog<file_sep>/README.md
# Blog
### 基于django框架编写的个人博客
- Python 2.7
- Django 1.8.3
- 测试环境:ubuntu14
* 博客主页
![博客主页](https://github.com/Sheldonlv/Blog/blob/master/static/images/BlogIndex.png)
* 博客个人介绍
![博客介绍](https://github.com/Sheldonlv/Blog/blob/master/static/images/BlogAbout.png)
* 博客随笔
![博客随笔](https://github.com/Sheldonlv/Blog/blob/master/static/images/BlogEasy.png)
!!!以上是其中的的几个主要页面,该博客开发还不算完整,有待改进,抽空会把这坑给填上
<file_sep>/base/views.py
#encoding:utf-8
from django.shortcuts import render
from django.http import HttpResponse
from .models import para_data,essay_data,article_data
# 首页
def index(request):
size = 6
rec_sum = para_data.objects.filter(reco='yes').count()
print rec_sum
if rec_sum <= size:
rec_start = 0
else:
rec_start = rec_num - size
rec_end = rec_sum
datas = para_data.objects.filter(reco='yes')[rec_start:rec_end]
datas = reverse(datas.count(),datas)
new_para = get_news('All')
new_para = reverse(new_para.count(),new_para) # 获取最新文章信息
max_para = get_max('All') # 获取点击最高文章信息
return render(request, 'index.html',{'datas':datas,'new_para':new_para,'max_para':max_para})
# 关于我
def about(request):
return render(request,'about.html')
# 心情随笔
def essay(request):
'''处理页码逻辑'''
page = request.GET['page']
size = 10
essay_sum = essay_data.objects.all().count()
essay_start = essay_sum - int(page) * size
essay_end = essay_sum - (int(page) - 1) * size
if essay_start < 0:
essay_start = 0
datas = essay_data.objects.all()[essay_start:essay_end]
page_data = list()
url = '/essay?page='
pages = get_pages(essay_sum,size) # 获取碎言碎语总页数
page_data = arr_page(url,page,pages) # 获取有关页码的数据
print(pages)
print(page_data)
# 处理img链接问题(img存储none字节,就不设置图片)
for data in datas:
if data.img != "none":
data.img = '<img src="' + data.img + '">'
else:
data.img = ''
datas = reverse(datas.count(),datas) # 数据倒序
return render(request,'saylist.html',{'datas':datas,'page_data':page_data})
# 倒转数据
def reverse(datas_sum,datas):
resuit = list()
for i in range(0,datas_sum):
resuit.append(datas[datas_sum-i-1])
return resuit
# 获取页面总数
def get_pages(essay_sum,size):
remainder = essay_sum % size
if remainder <= 0:
pages = essay_sum / size
if remainder > 0:
pages = essay_sum / size + 1
return pages
# 页码处理
def arr_page(url,page,pages):
page_data = list()
page_data.append('<a title="Total record"><b>' + str(pages) + '</b></a>')
if int(page) == 1:
page_data.append('<b>' + page + '</b>')
for i in range(2,pages+1):
if i <= 5:
page_data.append('<a href="'+url+str(i)+'">'+str(i)+'</a>')
if int(page) != pages:
page_data.append('<a href="'+url+ str(2) +'">></a>')
page_data.append('<a href="'+url+ str(pages) +'">>></a>')
if int(page) > 1 and int(page) <= pages:
page_data.append('<a href="'+url+ str(1) +'"><<</a>')
page_data.append('<a href="'+url+ str(int(page)-1) +'"><</a>')
for i in range(0,2):
num = int(page) - 2 + i
if num >= 1:
page_data.append('<a href="'+url+str(num)+'">'+str(num)+'</a>')
page_data.append('<b>' + page + '</b>')
for i in range(int(page)+1,pages+1):
if i <= int(page)+2:
page_data.append('<a href="'+url+str(i)+'">'+str(i)+'</a>')
if int(page) != pages:
page_data.append('<a href="'+url+ str(int(page)+1) +'">></a>')
page_data.append('<a href="'+url+ str(pages) +'">>></a>')
return page_data
# 获取点击排行
def get_max(kind):
piece = 5
find_sum = para_data.objects.all().count()
dt = list(article_data.objects.all())
fdata = list(para_data.objects.all())
# 创建两个列表用于存储数据
data = list()
find_data = list()
# 筛选不同的类型的文章数据
if kind != 'All':
for i in range(0,find_sum):
if fdata[i].doc_type == kind:
print fdata[i].doc_type
data.append(dt[i])
find_data.append(fdata[i])
else:
data = dt
find_data = fdata
find_sum = len(find_data)
# 冒泡算法进行排序
for i in range(0,find_sum):
for j in range(i+1,find_sum):
if int(data[i].viewed) < int(data[j].viewed):
data[i],data[j] = data[j],data[i]
find_data[i],find_data[j] = find_data[j],find_data[i]
# 讲排名前五的数据筛选出来
resuit = list()
for i in range(0,piece):
if i < find_sum:
resuit.append(find_data[i])
return resuit
# 获取最新文章
def get_news(kind):
piece = 5 # 设置获取篇数
# 判断获取的文章类型
if kind == 'All':
find_sum = para_data.objects.all().count()
else:
find_sum = para_data.objects.filter(doc_type=kind).count()
# 计算查询的范围
if find_sum <= piece:
find_start = 0
else:
find_start = find_sum - piece
find_end = find_sum
# 根据文章类型来获取数据
if kind =='All':
data = para_data.objects.all()[find_start:find_end]
else:
data = para_data.objects.filter(doc_type=kind)[find_start:find_end]
return data
# Create your views here.
<file_sep>/body/views.py
#coding:utf-8
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from base.models import para_data,article_data
from base import views as base
from django.contrib import messages
# 时光荏苒
def time(request):
kind = request.GET['type']
page = request.GET['page']
size = 5
new_para = base.get_news(kind) # 获取最新文章信息
new_para = base.reverse(new_para.count(),new_para) # 对信息进行顺序调整
max_para = base.get_max(kind) # 获取点击最高文章信息
# 根据请求文章的类型进行数据索引
if kind == 'All':
find_sum = para_data.objects.all().count()
else:
find_sum = para_data.objects.filter(doc_type=kind).count()
find_start = find_sum - int(page) * size
find_end = find_sum - (int(page) - 1) * size
if find_start < 0:
find_start = 0
# 同上根据文章类型进行数据索引
if kind == 'All':
datas = para_data.objects.all()[find_start:find_end]
else:
datas = para_data.objects.filter(doc_type=kind)[find_start:find_end]
page_data = list()
url = '/time?type=' + kind + '&page='
pages = base.get_pages(find_sum,size) # 获取该类文章总页数
page_data = base.arr_page(url,page,pages) # 获取有关页码的数据
datas = base.reverse(datas.count(),datas) # 数据倒序
return render(request,'diarylist.html',{'new_para':new_para,'max_para':max_para,'datas':datas,'page_data':page_data})
# 阅读全文
def article(request):
ID = request.GET['id']
para_datas = para_data.objects.get(Num=ID)
article_datas = article_data.objects.get(Num=ID)
article_datas.viewed = add_viewed(article_datas.viewed)
article_datas.save()
kind = para_datas.doc_type
new_para = base.get_news(kind) # 获取最新文章信息
new_para = base.reverse(new_para.count(),new_para) # 对信息进行顺序调整
max_para = base.get_max(kind) # 获取点击最高文章信息
link = list() # 存储上下文索引的列表
# 上一篇文章索引
if (int(ID)-1) > 100:
last = para_data.objects.get(Num=str(int(ID)-1)).title
link.append(u'上一篇:<a href="/article?id='+str(int(ID)-1)+'">'+last+'</a>')
else:
link.append(u'上一篇:<a href="#">'+''+'</a>')
# 下一篇文章索引
count = para_data.objects.all().count() - 1
num = int(para_data.objects.all()[count].Num)
if int(ID) == num:
link.append(u'下一篇:<a href="#">'+''+'</a>')
else:
next = para_data.objects.get(Num=str(int(ID)+1))
link.append(u'下一篇:<a href="/article?id='+str(int(ID)+1)+'">'+next.title+'</a>')
return render(request,'new.html',{'para':para_datas,'article':article_datas,'new_para':new_para,'max_para':max_para,'link':link})
# 编辑文章的版面
# 该版面仅为实现功能而设立,暂不做过多优化
def edit(request):
if request.method == 'POST':
# 获取最新文章的ID
num = para_data.objects.all().count()
ID = para_data.objects.all()[num-1].Num
# 从表单中获取各个数据
title = request.POST['title'].encode('utf-8') # 标题
img = request.POST['img'].encode('utf-8') # logo
writer = request.POST['writer'].encode('utf-8') # 作者
doc_type = request.POST['type'].encode('utf-8') # 文章类型
reco = request.POST['reco'].encode('utf-8') # 是否推荐
abstract = request.POST['abstract'].encode('utf-8') # 摘要
content = request.POST['content'].encode('utf-8') # 内容
ps = request.POST['ps'].encode('utf-8') # 密码
ID = str(int(ID) + 1) # 文章ID
viewed = 0 # 阅读次数
# 进行密码判定
if ps == '753951':
# 然后将这些数据保存到数据库中
para = para_data(Num = ID,title = title,img = img,writer = writer,doc_type = doc_type,reco = reco,content = abstract)
para.save()
article = article_data(Num = ID,content = content,viewed = viewed)
article.save()
return HttpResponseRedirect('/') # 重定向回首页
else:
return HttpResponse(u"你的密码有误!")
return render(request,'edit.html')
# 留言板
def gustbook(request):
return render(request,'gustbook.html')
# 阅读次数+1
def add_viewed(num):
num = str(int(num) + 1)
return num
# Create your views here.
<file_sep>/base/admin.py
from django.contrib import admin
from .models import essay_data,para_data,article_data
class essayAdmin(admin.ModelAdmin):
list_display = ('Num', 'pub_time',)
class paraAdmin(admin.ModelAdmin):
list_display = ('Num', 'title','pub_time',)
admin.site.register(essay_data,essayAdmin)
admin.site.register(para_data,paraAdmin)
admin.site.register(article_data)
# Register your models here.
<file_sep>/.gitattributes
*.png linguist-language=python
*.wav linguist-language=php
<file_sep>/base/models.py
#coding:utf-8
from django.db import models
import django.utils.timezone as timezone
class essay_data(models.Model):
Num = models.CharField(u'ID', max_length=20)
img = models.CharField(u'img', max_length=500)
content = models.TextField(u'内容')
pub_time = models.DateTimeField(u'发表时间',default = timezone.now)
up_time = models.DateTimeField(u'更新时间',auto_now=True, null=True)
def __unicode__(self):
return self.Num
class para_data(models.Model):
Num = models.CharField(u'ID', max_length=20)
title = models.CharField(u'标题', max_length=30)
img = models.CharField(u'img', max_length=500)
writer = models.CharField(u'作者', max_length=30)
doc_type = models.CharField(u'类型', max_length=20)
reco = models.CharField(u'推荐', max_length=5)
content = models.TextField(u'摘要')
pub_time = models.DateTimeField(u'发表时间',default = timezone.now)
up_time = models.DateTimeField(u'更新时间',auto_now=True, null=True)
def __unicode__(self):
return self.Num
class article_data(models.Model):
Num = models.CharField(u'ID', max_length=20)
content = models.TextField(u'内容')
viewed = models.CharField(u'阅读次数', max_length=20)
def __unicode__(self):
return self.Num
# Create your models here.
<file_sep>/base/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='article_data',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Num', models.CharField(max_length=20, verbose_name='ID')),
('content', models.TextField(verbose_name='\u5185\u5bb9')),
('viewed', models.CharField(max_length=20, verbose_name='\u9605\u8bfb\u6b21\u6570')),
],
),
migrations.CreateModel(
name='essay_data',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Num', models.CharField(max_length=20, verbose_name='ID')),
('img', models.CharField(max_length=200, verbose_name='img')),
('content', models.TextField(verbose_name='\u5185\u5bb9')),
('pub_time', models.DateTimeField(default=django.utils.timezone.now, verbose_name='\u53d1\u8868\u65f6\u95f4')),
('up_time', models.DateTimeField(auto_now=True, verbose_name='\u66f4\u65b0\u65f6\u95f4', null=True)),
],
),
migrations.CreateModel(
name='para_data',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('Num', models.CharField(max_length=20, verbose_name='ID')),
('title', models.CharField(max_length=30, verbose_name='\u6807\u9898')),
('img', models.CharField(max_length=200, verbose_name='img')),
('writer', models.CharField(max_length=30, verbose_name='\u4f5c\u8005')),
('doc_type', models.CharField(max_length=20, verbose_name='\u7c7b\u578b')),
('reco', models.CharField(max_length=5, verbose_name='\u63a8\u8350')),
('content', models.TextField(verbose_name='\u6458\u8981')),
('pub_time', models.DateTimeField(default=django.utils.timezone.now, verbose_name='\u53d1\u8868\u65f6\u95f4')),
('up_time', models.DateTimeField(auto_now=True, verbose_name='\u66f4\u65b0\u65f6\u95f4', null=True)),
],
),
]
| 8421dc86415e4589a7f7c74fffccc97c62648580 | [
"Git Attributes",
"Markdown",
"Python"
] | 7 | Git Attributes | Sheldonlv/Blog | 7422c995c7bffe54d96c1954cc131970dee08b1d | 347640f1e1abe38d8d3f02bda8b866b03c3dc909 |
refs/heads/main | <file_sep># DaibetesPrediction
Machine Learning Model to Predict weather a person is Diabetic or not from certain input data.
| 8dcf378d7beff7a78e99f6e00b2cb3c3f8548f3c | [
"Markdown"
] | 1 | Markdown | adhikari-amit/DaibetesPrediction | 4d92d69e9f2b65ce7e0a1eccd76362df30b757f4 | 6f5eae7c77b4cc0d1af2c96129e9305a7dc3e56f |
refs/heads/master | <repo_name>MercuialC/Sentimental<file_sep>/.gitignore/4.cpp
#include<stdio.h>
int main()
{
char x;
int y=0;
while((x=getchar())!=EOF)
{
if(x=='\n')
y++;
}
printf("%d",y);
return 0;
}
<file_sep>/.gitignore/3.cpp
#include<stdio.h>
int main()
{
int i,t,j;
for(j=0;j<n;j++)
{
for(i=0,i<n-1;i++)
{
if(a[i]>a[i+1])
{
t=a[i];
a[i]=a[i+1];
a[i+1]=t;
}
}
}
}
<file_sep>/.gitignore/1.cpp
#include<stdio.h>
int mian()
{
int i;
for(i=0;i<n;i++)
{
b[i]=a[i];
}
return 0;
}
<file_sep>/.gitignore/2.cpp
#include<stdio.h>
int main()
{
int i=0,j=0;
for(i=0;i<n;i++)
{
if(a[i]==5)
{
j=1;
break;
}
}
if(j==1)
{
printf("YES");
}
else
{
printf("NO");
}
return 0;
}
| ec748d92d82b88c2a3a69fac2ab77aeb9e035774 | [
"C++"
] | 4 | C++ | MercuialC/Sentimental | 957f88467c4d4aa5b1910a37d0cc34fca772db68 | 91382c995a015c9ea8f2e2b2dfe3759b2efea7aa |
refs/heads/main | <file_sep>file(REMOVE_RECURSE
"CMakeFiles/STL_ALGO.dir/ACM.cpp.obj"
"CMakeFiles/STL_ALGO.dir/Course.cpp.obj"
"CMakeFiles/STL_ALGO.dir/IEEE.cpp.obj"
"CMakeFiles/STL_ALGO.dir/Student.cpp.obj"
"CMakeFiles/STL_ALGO.dir/main.cpp.obj"
"STL_ALGO.exe"
"STL_ALGO.exe.manifest"
"STL_ALGO.lib"
"STL_ALGO.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/STL_ALGO.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>
# Consider dependencies only in project.
set(CMAKE_DEPENDS_IN_PROJECT_ONLY OFF)
# The set of languages for which implicit dependencies are needed:
set(CMAKE_DEPENDS_LANGUAGES
"CXX"
)
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
"C:/Users/asus/CLionProjects/STL_ALGO/ACM.cpp" "C:/Users/asus/CLionProjects/STL_ALGO/cmake-build-debug/CMakeFiles/STL_ALGO.dir/ACM.cpp.obj"
"C:/Users/asus/CLionProjects/STL_ALGO/Course.cpp" "C:/Users/asus/CLionProjects/STL_ALGO/cmake-build-debug/CMakeFiles/STL_ALGO.dir/Course.cpp.obj"
"C:/Users/asus/CLionProjects/STL_ALGO/IEEE.cpp" "C:/Users/asus/CLionProjects/STL_ALGO/cmake-build-debug/CMakeFiles/STL_ALGO.dir/IEEE.cpp.obj"
"C:/Users/asus/CLionProjects/STL_ALGO/Student.cpp" "C:/Users/asus/CLionProjects/STL_ALGO/cmake-build-debug/CMakeFiles/STL_ALGO.dir/Student.cpp.obj"
"C:/Users/asus/CLionProjects/STL_ALGO/main.cpp" "C:/Users/asus/CLionProjects/STL_ALGO/cmake-build-debug/CMakeFiles/STL_ALGO.dir/main.cpp.obj"
)
set(CMAKE_CXX_COMPILER_ID "MSVC")
# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
)
# The set of dependency files which are needed:
set(CMAKE_DEPENDS_DEPENDENCY_FILES
)
# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
)
# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")
<file_sep>cmake_minimum_required(VERSION 3.20)
project(STL_ALGO)
set(CMAKE_CXX_STANDARD 14)
add_executable(STL_ALGO main.cpp Course.cpp Course.h ACM.h ACM.cpp IEEE.h IEEE.cpp Student.cpp Student.h)
<file_sep>#include <iostream>
#include <string>
#ifndef STL_ALGO_COURSE_H
#define STL_ALGO_COURSE_H
class Course{
public:
void assign();
std::string getCourseName();
std::string getLecturer();
int getStudentNum();
void setCourseName(std::string s);
void setLecturer(std::string lec);
void setStudentNum(int i);
private:
std::string course_name;
int student_num;
std::string lecturer;
};
#endif //STL_ALGO_COURSE_H
<file_sep>#include <iostream>
#include "Student.h"
#include "Course.h"
int main() {
Student<void> s;
s.PrintC();
return 0;
}
<file_sep>#include <iostream>
#include "Course.h"
#ifndef STL_ALGO_STUDENT_H
#define STL_ALGO_STUDENT_H
template <typename T>
class Student {
public:
std::string student_name;
int id;
int age;
std::string course;
Course c;
Student(){
student_name = "";
id = 0;
age = 0;
};
Student(std::string s, int i, int e){
this->student_name = s;
this->id = i;
this->age = e;
};
void PrintC();
// void operator()(int a){ //overloaded operator~~~ //Third Example
// std::cout << (a+a)*a << std::endl;
// };
bool operator()(int i){
if (i % 2 == 0)
return true;
else
return false;
};
friend std::ostream &operator<<( std::ostream &output, const Student &S ) {
output << "Name: " << S.student_name << " ID: " << S.id << " Age: " << S.age;
return output;
}
friend std::istream &operator>>( std::istream &input, Student &S ) {
input >> S.student_name >> S.id >> S.age;
return input;
}
};
#endif //STL_ALGO_STUDENT_H
<file_sep>#include <iostream>
#include "Course.h"
#include "Student.h"
#include "ACM.h"
#include "IEEE.h"
#include <vector>
#include <algorithm>
template<> void Student<void>::PrintC() {
Course course;
Course course1;
Course course2;
Course course3;
Course course4;
Course course5;
course.setCourseName("Math");
course.setStudentNum(21);
course.setLecturer("<NAME>");
course1.setCourseName("Physics");
course1.setStudentNum(12);
course1.setLecturer("<NAME>");
course2.setCourseName("Biology");
course2.setStudentNum(15);
course2.setLecturer("<NAME>");
course3.setCourseName("History");
course3.setStudentNum(20);
course3.setLecturer("<NAME>");
course4.setCourseName("Russian");
course4.setStudentNum(14);
course4.setLecturer("<NAME>");
course5.setCourseName("Math");
course5.setStudentNum(21);
course5.setLecturer("<NAME>");
Student student("Mark", 22222222, 21);
std::cout << "--------------Please Enter The 5 Students:----------------" << std::endl;
std::cout << std::endl;
std::cout << "First Student: " << std::endl;
Student student1;
std::cin >> student1;
std::cout << std::endl;
std::cout << "Second Student: " << std::endl;
Student student2;
std::cin >> student2;
std::cout << std::endl;
std::cout << "Third Student: " << std::endl;
Student student3;
std::cin >> student3;
std::cout << std::endl;
std::cout << "Fourth Student: " << std::endl;
Student student4;
std::cin >> student4;
std::cout << std::endl;
std::cout << "Fifth Student: " << std::endl;
Student student5;
std::cin >> student5;
std::cout << student << " Course: " << course.getCourseName() << " Number of Students: " << course.getStudentNum() << " Lecturer: " << course.getLecturer() <<" Activities: ACM" << std::endl;
std::cout << std::endl;
std::cout << student1 << " Course: " << course1.getCourseName() << " Number of Students: " << course1.getStudentNum() << " Lecturer: " << course1.getLecturer() << " Activities: ACM" << std::endl;
std::cout << std::endl;
std::cout << student2 << " Course: " << course2.getCourseName() << " Number of Students: " << course2.getStudentNum() << " Lecturer: " << course2.getLecturer() << " Activities: IEEE" << std::endl;
std::cout << std::endl;
std::cout << student3 << " Course: " << course3.getCourseName() << " Number of Students: " << course3.getStudentNum() << " Lecturer: " << course3.getLecturer() << " Activities: ACM" << std::endl;
std::cout << std::endl;
std::cout << student4 << " Course: " << course4.getCourseName() << " Number of Students: " << course4.getStudentNum() << " Lecturer: " << course4.getLecturer() << " Activities: IEEE" << std::endl;
std::cout << std::endl;
std::cout << student5 << " Course: " << course5.getCourseName() << " Number of Students: " << course5.getStudentNum() << " Lecturer: " << course5.getLecturer() << " Activities: IEEE" << std::endl;
std::cout << std::endl;
//First Example:
// std::vector<int> vec{course.getStudentNum(), course1.getStudentNum(), course2.getStudentNum(), course3.getStudentNum(), course4.getStudentNum(), course5.getStudentNum()};
// std::cout << " Total Appearance: " << std::count(vec.begin(), vec.end(), 21) << std::endl;
//Second Example
// std::vector<int> vec{course.getStudentNum(), course1.getStudentNum(), course2.getStudentNum(), course3.getStudentNum(), course4.getStudentNum(), course5.getStudentNum()};
// auto iter_vector = std::find(vec.begin(), vec.end(), 14);
//
// if(iter_vector != vec.end())
// std::cout << " And We Found: " << *iter_vector << std::endl;
//Third Example
// Student s;
// std::vector<int> vec{course.getStudentNum(), course1.getStudentNum(), course2.getStudentNum(), course3.getStudentNum(), course4.getStudentNum(), course5.getStudentNum()};
// std::for_each(vec.begin(), vec.end(), s);
//Fourth Example
Student s;
std::vector<int> vec{course.getStudentNum(), course1.getStudentNum(), course2.getStudentNum(), course3.getStudentNum(), course4.getStudentNum(), course5.getStudentNum()};
std::cout << " Even Numbers Of Enrolled Students:" << std::count_if(vec.begin(), vec.end(), s);
}
| b554d045737b758374c505b521573ea5300a4dd5 | [
"C++",
"CMake"
] | 7 | C++ | HollowCloud/Student_Information | 1c320266bb2dcdf793ed2993d4341d68310feca6 | 7cba3ed877230110151e9a4a17f3a4a305329806 |
refs/heads/main | <file_sep><template>
<v-app>
<v-app-bar
app
color="primary"
dark
/>
<v-main>
<Autocomplete
:list-movies="listMovies"
:requesting="waitingProgress"
@change-title="changeTitle"
/>
</v-main>
</v-app>
</template>
<script>
import Autocomplete from '@/components/Autocomplete'
import debounce from '@/utils/debounce'
export default {
name: 'App',
components: {
Autocomplete
},
data: () => ({
quantityResults: 0,
movies: [],
requesting: false,
delay: 150
}),
computed: {
listMovies () {
return this.movies
},
waitingProgress () {
return this.requesting
},
executeDebouncedTitle () {
return debounce(this.fetchOMDB, this.delay)
}
},
methods: {
fetchOMDB (title) {
window.fetch(`http://localhost:8080/search?q=${title}`, {
"headers": {
'accept': 'application/json'
}
})
.then(resp => resp.json())
.then(({ totalResults, Search }) => {
this.quantityResults = totalResults
this.movies = Search
this.requesting = false
})
.catch(console.error)
},
changeTitle (title) {
if (title.length > 3) {
this.requesting = true
this.executeDebouncedTitle(title)
}
}
}
};
</script>
<file_sep><template>
<v-card
class="mx-auto"
max-width="250"
max-height="500"
tile
>
<input
class="rounded-md"
placeholder="Busque por um titulo"
autocomplete="off"
autofocus
:autosave="false"
:size="25"
@input="changeTitle"
/>
<v-progress-circular
v-if="requesting"
class="my-5"
indeterminate
color="primary"
/>
<v-card
v-else
class="mx-auto autocomplete"
max-width="250"
max-height="500"
tile
>
<v-list-item
class="list-movies .d-flex py-2"
v-for="movie in listMovies"
:key="movie.imdbID"
>
<v-list-item-content
class="movie rounded"
>
<v-list-item-title>{{ movie.Title }}</v-list-item-title>
<v-list-item-subtitle>{{ movie.Year }}</v-list-item-subtitle>
<v-img
class="rounded-xl"
max-height="150"
max-width="250"
dark
:src="resolveImage(movie.Poster)"
/>
</v-list-item-content>
</v-list-item>
</v-card>
</v-card>
</template>
<script>
import fallback from '../assets/fallback.png'
export default {
props: {
listMovies: {
type: Array,
default: () => []
},
requesting: {
type: Boolean,
default: false
}
},
methods: {
changeTitle (event) {
this.$emit('change-title', event.target.value)
},
resolveImage(image) {
return image !== 'N/A' ? image : fallback
}
}
}
</script>
<style scoped>
.autocomplete {
overflow-y: auto;
}
.movie {
background-color: #EEEEEE;
}
</style> | 16f6ab4f5c874b02765f0554ef7e544be3baa2a5 | [
"Vue"
] | 2 | Vue | andersonrostirolla/vuetify-omdb | 9f33e6ba5e587c83c063d8cb6e534da7dd155617 | 2d56c9e6254041d1f0dd38b96a89b334a0ed0671 |
refs/heads/master | <file_sep><?php
echo "@awen 球项目 求技术共享";
<file_sep>#include <stdio.h>
//选择排序算法
int main(){
int iArr[10];
int i, j, temp;
int ipos;
//循环输入10个数到iArr数组中
for(i=0; i<10; i++){
scanf("%d", &iArr[i]);
}
printf("最初的10个数:\n");
//输出这10个数
for(i=0; i<10; i++){
printf("%d ", iArr[i]);
}
printf("\n");
//进行选择排序
for(i=0; i<9; i++){
temp = iArr[i];
ipos = i;
for(j=i+1; j<10; j++){
if(temp>iArr[j]){
temp = iArr[j]; //获取到最小的值
ipos = j;
}
}
iArr[ipos] = iArr[i];
iArr[i] = temp;
}
printf("选择排序法排序之后的数组:\n");
//输出排序后的数组
for(i=0; i<10; i++){
printf("%d ", iArr[i]);
}
printf("\n");
return 0;
}
<file_sep><?php
$arr = array(1,9,8,7,3,6,5);
function selectSort($arr){
if(empty($arr)){
return ;
}
for($i=0; $i<count($arr)-1; $i++){
$min = $arr[$i]; //假设他是最小的
$pos = $i;
for($j=$i+1; $j<count($arr); $j++){
if($min>$arr[$j]){
$min = $arr[$j];
$pos = $j;
}
}
//交换
$arr[$pos] = $arr[$i];
$arr[$i] = $min;
}
return $arr;
}
//开始
echo "<pre>";
print_r($arr);
echo "</pre>";
echo "<pre>";
print_r(selectSort($arr));
echo "</pre>";
?><file_sep><?php
echo "大学在打飞机!";
<file_sep><?php
/*
* 比较相邻的两个数,小的往前交换,大的往后交换
*/
function maopao($arr){
if(!is_array($arr)){
return;
}
$length = count($arr);
for($i=0; $i<$length; $i++){
for($j=0; $j<9; $j++){
if($arr[$j]>$arr[$j+1]){
$temp = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $temp;
}
}
}
return $arr;
}
$arr = array(
3, 10, 2, 6, 9, 4, 1, 7, 8, 5
);
print_r(maopao($arr));
?><file_sep>#include <stdio.h>
//冒泡算法
/*
** 比较相邻的两个数,大的往后放,小的放在前
*/
int main(){
int i,j;
int arr[10];
int temp;
//接受用户的输入
for(i=0; i<10; i++){
scanf("%d", &arr[i]);
}
//输出数组
for(i=0; i<10; i++){
printf("%d ", arr[i]);
if(i==4){
printf("\n");
}
}
//排序
for(i=0; i<10; i++){
for(j=0; j<9; j++){
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
printf("\n");
//输出数组
for(i=0; i<10; i++){
printf("%d ", arr[i]);
if(i==4){
printf("\n");
}
}
return 0;
}
| 006bcaffa91ecaefcc315d2552caa736f2fd13ce | [
"C",
"PHP"
] | 6 | C | yuwensong/mymvc | ed18f93458c8434414f0fb8856d349eb995b4104 | 4772c0f36df853922a7d5d857d905c06e5e03e8e |
refs/heads/master | <repo_name>chuckSMASH/fall-2014-math<file_sep>/tasks.py
from invoke import run, task
@task(name='build', help={
'clean': 'Remove output files for this homework from the build dir',
'homework': 'The number of the assignment you want to build'
})
def build_pdf(homework, clean=True):
"""
Generate PDF representation of a LaTeX document.
"""
try:
homework = int(homework)
input_file_name = "hw{}.tex".format(homework)
output_file_pattern = "hw{}.*".format(homework)
except ValueError, TypeError:
input_file_name = "{}.tex".format(homework)
output_file_pattern = "{}.*".format(homework)
if clean:
print "Cleaning previously built files named like {}...".format(output_file_pattern)
run('find build/ -name {} -exec rm "{{}}" \;'.format(output_file_pattern))
print "Creating PDF for {}...".format(input_file_name)
run('pdflatex --output-directory=build homework/{}'.format(input_file_name))
print "PDF successfully created in build directory"
<file_sep>/homework/hw8.tex
\documentclass[10pt]{article}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\usepackage{float}
\graphicspath{ {./homework/images/} }
\newenvironment{answer}
{ \\Answer:\\ }
{ \\ }
\newcommand{\dd}[2]{\dfrac{d#1}{d#2}}
\newcommand{\bigint}{\displaystyle\int}
\begin{document}
\title{Math E-15 HW8 Solutions}
\author{<NAME>}
\date{12/03/2014}
\maketitle
\begin{enumerate}
\item Compute the exact value of each of the following.
\begin{enumerate}
\item $\bigint_{-8}^{-1}\dfrac{5}{x}\,dx$
\item the area under the curve $y = \sqrt{x}$ on the interval
$[1,9]$
\item the area between the curves $y = x^2 - 8x + 24$ and $y = 3x$
\item the average value of $f(x) = x^3$ on the interval $[1,4]$
\end{enumerate}
\item Find the following indefinite integrals (\textit{i.e.},
antiderivatives).
\begin{enumerate}
\item $\bigint (2 + 3x + x^4 + \sqrt[5]{x} + \dfrac{1}{x^6} + 7^x +
\dfrac{8}{1 + x^2})\,dx$
\item $\bigint \dfrac{x + 3}{x^2}\,dx$
\end{enumerate}
\item Is it true that $\bigint x^2\cos x\,dx = \dfrac{x^3}{3}\sin x +
C$? Explain your answer.
\item Use substitution to find each of the following. Clearly indicate
your choice of substitution.
\begin{enumerate}
\item $\bigint_{-1}^{0} 5x^4(1 + x^5)^{99}\,dx$
\item $\bigint \dfrac{\sqrt{\ln x}}{x}\,dx$
\item $\bigint \dfrac{x^2}{1 + x^3}\,dx$
\item $\bigint \dfrac{12x^2}{1 + x^6}\,dx$
\end{enumerate}
\item The rate of change of the temperature on the interval $[0,10]$
hours is given by $f(t) = 8 - 2t$ degrees per hour. What is the net
(or total) change in the temperature during this time period?
\end{enumerate}
\end{document}
<file_sep>/homework/hw4.tex
\documentclass[10pt]{article}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\graphicspath{ {./homework/images/} }
\newenvironment{answer}
{ \\Answer:\\ }
{ \\ }
\newcommand{\ddx}[1][]{\dfrac{d#1}{dx}}
\newcommand{\ddt}[1][]{\dfrac{d#1}{dt}}
\begin{document}
\title{Math E-15 HW4 Solutions}
\author{<NAME>}
\date{10/15/2014}
\maketitle
\begin{enumerate}
\item Find the derivative of each of the following functions.
\begin{enumerate}
\item $y = x^7 + \sqrt[7]{x} + \dfrac{1}{x^7}$
\begin{answer}
\begin{align*}
y &= x^7 + \sqrt[7]{x} + \dfrac{1}{x^7} \\
&= x^7 + x^{1/7} + x^{-7} \\\\
\ddx[y] &= \ddx(x^7 + x^{1/7} + x^{-7})\\
&= \ddx x^7 + \ddx x^{1/7} + \ddx x^{-7}\\
&= 7x^6 + \dfrac{1}{7}x^{-6/7} + (-7x^{-8})\\
\ddx[y] &= 7x^6 + \dfrac{1}{7}x^{-6/7} - 7x^{-8}
\end{align*}
\end{answer}
\item $y = e^x - x^e + e^7 - \pi^x$
\begin{answer}
\begin{align*}
y &= e^x - x^e + e^7 - \pi^x\\\\
\ddx[y] &= \ddx(e^x - x^e + e^7 - \pi^x)\\
&= \ddx e^x - \ddx x^e + \ddx e^7 - \ddx \pi^x\\
&= e^x\ln e - ex^{e-1} + 0 + \pi^x\ln\pi\\
\ddx[y] &= e^x - ex^{e-1} + \pi^x\ln\pi
\end{align*}
\end{answer}
\pagebreak
\item $y = (x^8)(9^x)$
\begin{answer}
\begin{align*}
y &= (x^8)(9^x)\\\\
\ddx[y] &= \ddx \left((x^8)(9^x)\right)\\
&= (\ddx x^8)(9^x) + (\ddx 9^x)(x^8)\\
&= 8x^7 9^x + x^89^x\ln9
\end{align*}
\end{answer}
\item $y = \dfrac{x^4 - e^2}{3^x + 17}$
\begin{answer}
\begin{align*}
y &= \dfrac{x^4 - e^2}{3^x + 17}\\\\
\ddx[y] &= \ddx\left(\dfrac{x^4 - e^2}{3^x + 17}\right)\\
&= \dfrac{\left(\ddx (x^4 - e^2)\right)(3^x + 17) - \left(\ddx (3^x + 17)\right)(x^4 - e^2)}{(3^x + 17)^2}\\
&= \dfrac{\left(\ddx x^4 - \ddx e^2\right)(3^x + 17) - \left(\ddx 3^x + \ddx 17\right)(x^4 - e^2)}{(3^x + 17)^2}\\
&= \dfrac{(4x^3 - 0)(3^x + 17) - (3^x\ln3 + 0)(x^4 - e^2)}{(3^x + 17)^2}\\
\ddx[y] &= \dfrac{4x^3(3^x + 17) - 3^x\ln3(x^4 - e^2)}{(3^x + 17)^2}
\end{align*}
\end{answer}
\item $y = 5^{3x}$
\begin{answer}
\begin{align*}
y &= 5^{3x}\\
&= (5^3)^x\\
&= 125^x\\\\
\ddx[y] &= \ddx 125^x\\
\ddx[y] &= 125^x\ln125
\end{align*}
\end{answer}
\end{enumerate}
\pagebreak
\item Consider the function $f(x) = x^4 - 4x^2$.\hfill
\vspace{1pt}
Note: Be sure to show enough work on parts (b) and (c) that it is clear to the grader how you used calculus (and not a graphing calulator or someone else's paper) to do the problem.
\begin{enumerate}
\item What are the roots (zeros) of $f$? (This simply means the solution to the equation $f(x) = 0$ - no calculus needed.)
\begin{answer}
\begin{align*}
f(x) &= x^4 - 4x^2\\
&= x^2(x^2 - 4)\\\\
x^2(x^2 - 4) &= 0\\\\
x^2 &= 0\\
x &= 0\\\\
x^2 - 4 &= 0\\
x^2 &= 4\\
x &= \pm 2
\end{align*}
{\bf Therefore, the roots of $f(x)$ are $x=0$, $x=-2$, and $x=2$.}
\end{answer}
\pagebreak
\item Where is $f$ increasing? Where is $f$ decreasing?
\begin{answer}
\begin{align*}
f(x) &= x^4 - 4x^2\\\\
\ddx[f] &= \ddx (x^4 - 4x^2)\\
&= \ddx x^4 - \ddx 4x^2\\
\ddx[f] &= 4x^3 - 8x = 4x(x^2 - 2)\\\\
4x(x^2 - x) &= 0\\\\
4x &= 0\\
x &= 0\\\\
x^2 - 2 &= 0\\
x^2 &= 2\\
x &= \pm\sqrt{2}
\end{align*}
Given the roots of $f'$, we want to investigate the sign of $f'(x)$ on the intervals $(-\infty,-\sqrt{2})$,$(-\sqrt{2}, 0)$,$(0, \sqrt{2})$ and $(\sqrt{2}, \infty)$.
\begin{align*}
f'(-2) &= 4(-2^3) - 8(-2)\\
&= -32 + 16 = -16\\\\
f'(-1) &= 4(-1^3) - 8(-1)\\
&= -4 + 8 = 4\\\\
f'(1) &= 4(1^3) - 8(1)\\
&= 4 - 8 = -4\\\\
f'(2) &= 4(2^3) - 8(2)\\
&= 32 - 16 = 16
\end{align*}
Thus, $f$ is decreasing on the intervals $(-\infty,-\sqrt{2})\cup(0,\sqrt{2})$ and increasing on the intervals $(-\sqrt{2}, 0)\cup(\sqrt{2}, \infty)$.
\end{answer}
\pagebreak
\item Where is $f$ concave up? Where is $f$ concave down?
\begin{answer}
\begin{align*}
f'(x) &= 4x^3 - 8x\\\\
f''(x) &= \ddx (4x^3 - 8x)\\
&= \ddx 4x^3 - \ddx 8x\\
f''(x) &= 12x^2 - 8\\\\
12x^2 - 8 &= 0\\
12x^2 &= 8\\
x^2 &= \dfrac{2}{3}\\
x &= \pm \sqrt{\dfrac{2}{3}}
\end{align*}
Given the roots of $f''$, we want to investigate the sign of $f''$ on the intervals $\left(-\infty, -\sqrt{\dfrac{2}{3}}\right)$, $\left(-\sqrt{\dfrac{2}{3}}, \sqrt{\dfrac{2}{3}}\right)$, and $\left(\sqrt{\dfrac{2}{3}}, \infty\right)$.
\begin{align*}
f''(-1) &= 12(-1)^2 - 8(-1)\\
&= 12 + 8 = 20\\\\
f''(-0.5) &= 12(-0.5)^2 - 8(-0.5)\\
&= 3 + 4 = 7\\\\
f''(1) &= 12(1)^2 - 8(1)\\
&= 12 - 8 = 4\\
\end{align*}
Thus $f$ is concave up on the interval $(-\infty, \infty)$.
\end{answer}
\pagebreak
\item Sketch a graph of $f$, labeling the points you found above.
\end{enumerate}
\pagebreak
\item The equation that describes the height of the object thrown off the 80-foot high roof with initial vertical velocity 64 feet per second, as described in HW3a problem \#4, is $h(t) = -16t^2 + 64t + 80$, where $t=0$ corresponds to the moment of launch.
\begin{enumerate}
\item Find an equation for the object's velocity.
\begin{answer}
\begin{align*}
h(t) &= -16t^2 + 64t + 80\\
\ddt[h] &= \ddt (-16t^2 + 64t - 80)\\
&= \ddt (-16t^2) + \ddt 64t - \ddt 80\\
&= -32t + 64 - 0\\
h'(t) = \ddt[h] &= -32t + 64
\end{align*}
\end{answer}
\item For how long is the object rising?
\begin{answer}
\begin{align*}
h'(t) &= -32t + 64\\\\
-32t + 64 &= 0\\
-32t &= -64\\
t &= 2
\end{align*}
The object will continue to rise for 2 seconds.
\end{answer}
\item What is the maximum height above ground that the object reaches?
\begin{answer}
\begin{align*}
h(2) &= -16(2)^2 + 64(2) + 80\\
&= -64 + 128 + 80\\
&= 144 \text{ (feet)}
\end{align*}
\end{answer}
\pagebreak
\item With what velocity does the object hit the ground?
\begin{answer}
\begin{align*}
0 &= -16t^2 + 64t + 80\\
&= -16(t^2 - 4 - 5)\\
&= -16(t - 5)(t + 1)\\\\
0 &= t + 1\\
-1 &= t\\\\
0 &= t - 5\\
5 &= t
\end{align*}
So the object will be at height 0 (feet) at $t = 5$ (seconds).
\begin{align*}
h'(5) = -32(5) + 64\\
= -224 + 64\\
= -160 \text{ (ft/sec)}
\end{align*}
\end{answer}
\end{enumerate}
\item A population of bacteria grows at a rate of 30\% per hour. If it starts with 6000 bacteria, how fast (to the nearest bacterium) is it increasing 12 hours later? Include units in your answer.
\begin{answer}
\begin{align*}
P(t) &= 6000(1.3)^t\\
P'(t) &= \ddt \left(6000(1.3)^t\right)\\
&= 6000 \ddt(1.3^t)\\
&= 6000(1.3)^t\ln1.3\\
P'(12) &= 6000(1.3)^{12}\ln1.3\\
&= 36675 \text{ (bacterium)}
\end{align*}
\end{answer}
\end{enumerate}
\end{document}
<file_sep>/homework/hw6.tex
\documentclass[10pt]{article}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\usepackage{float}
\graphicspath{ {./homework/images/} }
\newenvironment{answer}
{ \\Answer:\\ }
{ \\ }
\newcommand{\dd}[2]{\dfrac{d#1}{d#2}}
\begin{document}
\title{Math E-15 HW6 Solutions}
\author{<NAME>}
\date{10/28/2014}
\maketitle
\begin{enumerate}
\item Find $\dd{y}{x}$ for the curve $x^2 + xy + y^2 = 3$.
\begin{answer}
\begin{align*}
x^2 + xy + y^2 &= 3\\
\dd{}{x}\left[ x^2 + xy + y^2 \right] &= \dd{}{x}3\\
2x + (1)(y) + (x)(1)\dd{y}{x} + 2y\dd{y}{x} &= 0\\
x\dd{y}{x} + 2y\dd{y}{x} &= -2x - y\\
\dd{y}{x}(x + 2y) &= -2x - y\\
\dd{y}{x} &=\dfrac{-2x - y}{x + 2y}
\end{align*}
\end{answer}
\item User local linearization to estimate $\sqrt[3]{29}$. Leave your
answer as a simplified fraction.
\begin{answer}
\begin{align*}
f(x) &= \sqrt[3]{x}\\
&= x^{1/3}\\
f'(x) &= \dfrac{1}{3}x^{-2/3}\\
f(x) &\approx f(a) + f'(a)(x - a)\text{ [We'll use
$27$ as $a$]}\\
&\approx \sqrt[3]{27} + \dfrac{1}{3}27^{-2/3}(29-27)\\
&\approx 3 + \dfrac{2}{3}27^{-2/3}\\
f(x) &\approx 3\dfrac{2}{27}
\end{align*}
\end{answer}
\pagebreak
\item Evaluate the following limits. Simplify your answers as much as
possible; for example, expressions such as $\dfrac{10}{\infty}$,
$\dfrac{0}{4}$, $\dfrac{\infty}{2}$ should be simplified to 0, 0,
and $\infty$, respectively.
\begin{enumerate}
\item $\lim\limits_{x \to 0}\dfrac{\sin(7x)}{11x}$
\begin{answer}
Both the numerator and denominator tend toward $0$. We have to apply L'Hopital's Rule.\\
\begin{align*}
\lim_{x \to 0}\dfrac{\sin(7x)}{11x} &= \lim_{x \to 0}\dfrac{\dd{}{x}\sin(7x)}{\dd{}{x}11x}\\
&= \lim_{x \to 0}\dfrac{7\cos(7x)}{11}\\
&= \dfrac{7}{11}
\end{align*}
\end{answer}
\item $\lim\limits_{x \to 0}\dfrac{1 - \cos x}{5x^2}$
\begin{answer}
Both the numerator and denominator tend toward $0$. We have to apply L'Hopital's Rule.\\
\begin{align*}
\lim_{x \to 0}\dfrac{1 - \cos x}{5x^2} &= \lim_{x \to 0}\dfrac{\dd{}{x}\left( 1 - \cos x \right)}{\dd{}{x} \left( 5x^2 \right)}\\
&= \lim_{x \to 0}\dfrac{0 - (-\sin x )}{10x}\\
&= \lim_{x \to 0}\dfrac{\sin x}{10x}\\
\end{align*}
Both the numerator and the denominator still tend toward $0$. We apply L'Hopital's Rule again.\\
\begin{align*}
\lim_{x \to 0}\dfrac{\sin x}{10x} &= \lim_{x \to 0}\dfrac{\dd{}{x}\sin x}{\dd{}{x}10x}\\
&= \lim_{x \to 0}\dfrac{\cos x}{10}\\
&= \dfrac{1}{10}
\end{align*}
\end{answer}
\item $\lim\limits_{x \to 0}\dfrac{x^2}{\cos x}$
\begin{answer}
$x^2$ goes to $0$ while $\cos x$ goes to $1$. Therefore this limit goes to $0$ as $x$ goes to $0$.
\end{answer}
\pagebreak
\item $\lim\limits_{x \to \infty}\dfrac{\ln x}{x}$
\begin{answer}
Both the numerator and the denominator tend toward $\infty$. We apply L'Hopital's Rule.\\
\begin{align*}
\lim_{x \to \infty}\dfrac{\ln x}{x} &= \lim_{x \to \infty}\dfrac{\dd{}{x}\left[ \ln x \right]}{\dd{}{x}x}\\
&= \lim_{x \to \infty}\left( \dfrac{\dfrac{1}{x}}{1}\right)\\
&= \lim_{x \to \infty}\dfrac{1}{x}\\
&= 0
\end{align*}
\end{answer}
\item $\lim\limits_{x \to \infty}\dfrac{e^x}{x^3}$
\begin{answer}
Both the numerator and the denominator tend toward $\infty$. We apply L'Hopital's Rule. Specifically, we'll need to continue to apply it until the denominator doesn't contain an $x$ (since $e^x$ will persist no matter how many times we apply it).\\
\begin{align*}
\lim_{x \to \infty}\dfrac{e^x}{x^3} &= \lim_{x \to \infty}\dfrac{\dd{}{x}e^x}{\dd{}{x}x^3}\\
&= \lim_{x \to \infty}\dfrac{e^x}{3x^2}\\
\lim_{x \to \infty}\dfrac{e^x}{3x^2} &= \lim_{x \to \infty}\dfrac{\dd{}{x}e^x}{\dd{}{x}3x^2}\\
&= \lim_{x \to \infty}\dfrac{e^x}{6x}\\
\lim_{x \to \infty}\dfrac{e^x}{6x} &= \lim_{x \to \infty}\dfrac{\dd{}{x}e^x}{\dd{}{x}6x}\\
&= \lim_{x \to \infty} \dfrac{e^x}{6}\\
&= \infty
\end{align*}
\end{answer}
\item $\lim\limits_{x \to 5}\dfrac{x^2 - 13x + 40}{2x - 10}$
\begin{answer}
The limit fails to exist because the function has a vertical asymptote at $x = 5$.
\end{answer}
\end{enumerate}
\pagebreak
\item Consider the function $f(x) = 8x^5 - 5x^4$ on the domain $[-1,
2]$.\hfill
\vspace{1pt}
Note: Be sure to show enough works on parts (a), (b), and (c) that it
is clear to the grader how you used calculus (and not a graphing
calculator or someone else's paper) to do the problem.
\begin{enumerate}
\item Find the $x$-coordinate(s) of all critical points and classify
each as a local maximum, local minimum, or neither.
\begin{answer}
\begin{align*}
f(x) &= 8x^5 - 5x^4\\
\dd{f}{x} &= \dd{}{x}\left( 8x^5 - 5x^4 \right)\\
&= 40x^4 - 20x^3
\end{align*}
$\dd{f}{x}$ has no values x for which it is undefined.
\begin{align*}
40x^4 - 20x^3 &= 0\\
20x^3(2x - 1) &= 0\\\\
20x^3 &= 0\\
x &= 0\\\\
2x - 1 &= 0\\
2x &= 1\\
x &= \dfrac{1}{2}
\end{align*}
The critical points of the function $f$ are at $x=0$ and $x=0.5$.
\begin{align*}
f'(-0.25) &= 20(-0.25)^3(2(-0.25) - 1)\\
&= (-)(-) = (+)\\
f'(0.25) &= 20(0.25)^3(2(0.25) - 1)\\
&= (+)(-) = (-)\\
f'(1) &= 20(1)^3(2(1) - 1)\\
&= (+)(+) = (+)
\end{align*}
Looking at the behavior of $f'$ in the intervals between and
surrounding the critical points of $f$, we see that $f$ has a
local maximum at $x = 0$ and a local minimum at $x = 0.5$.
\end{answer}
\pagebreak
\item Find the $x$-coordinate(s) of all global extrema and classify
each as a global maximum or global minimum.
\begin{answer}
Since $f$ has no vertical asymptotes and it is defined on an
interval we only have to check the local extrema and the
endpoints of the interval to determine the global extrema of
$f$.
\begin{align*}
f(x) &= 8x^5 - 5x^4\\
f(-1) &= 8(-1)^5 - 5(-1)^4\\
&= -8 - 5 = -13\\
f(0) &= 8(0)^5 - 5(0)^4 = 0\\
f(0.5) &= 8(0.5)^5 - 5(0.5)^4\\
&= 8(2^{-1})^5 - 5(2^{-1})^4\\
&= \dfrac{8}{32} - \dfrac{10}{32} = -\dfrac{1}{16}\\
f(2) &= 8(2)^5 - 5(2)^4\\
&= 2^32^5 - 5(2^4)\\
&= 2^8 - 5 \cdot 16\\
&= 256 - 80 = 176\\
\end{align*}
The global maximum is at $x=2$; the global minimum is at $x=-1$.
\end{answer}
\pagebreak
\item Find the $x$-coordinate(s) of all inflection points.
\begin{answer}
\begin{align*}
\dd{f}{x} &= 40x^4 - 20x^3\\
\dd{^2f}{x^2} &= 160x^3 - 60x^2\\
&= 20x^2(8x - 3)\\\\
20x^2(8x - 3) &= 0\\\\
20x^2 &= 0\\
x &= 0\\\\
8x - 3 &= 0\\
8x &= 3\\
x &= \dfrac{3}{8}\\\\
f''(-1) &= 20(-1)^2(8(-1) - 3)\\
&= (+)(-) = (-)\\
f''(0.25) &= 20(0.25)^2(8(0.25) - 3)\\
&= (+)(-) = (-)\\
f''(1) &= 20(1)^2(8(1) - 3)\\
&= (+)(+) = (+)
\end{align*}
There is an inflection point at $x= \dfrac{3}{8}$ where $f$ goes
from being concave down to concave up.
\end{answer}
\end{enumerate}
\end{enumerate}
\end{document}
<file_sep>/homework/hw1.tex
\documentclass[10pt]{article}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\graphicspath{ {./homework/images/} }
\newcommand{\finv}{f^{-1}}
\begin{document}
\title{Math E-15 HW1 Solutions}
\author{<NAME>}
\date{09/10/2014}
\maketitle
\begin{enumerate}
\item $y = f(x)$ is a linear function that gives the cost (in
dollars) of using $x$ minutes per month on a certain cellular phone
plan. If you use 100 minutes, the cost is \$10; if you use 500
minutes, the cost is \$18.
\begin{enumerate}
\item Find a formula for $f(x)$.\\\\
Answer:
\begin{align*}
m &= \frac{f(500) - f(100)}{500 - 100}\\
&= \frac{18 - 10}{500 - 100}\\
&= \frac{8}{400} \\
&= \frac{1}{50}\\
&= 0.02\\
\\
y &= mx + b\\
y &= 0.02x + b\\
10 &= 0.02(100) + b\\
10 &= 2 + b\\
8 &= b\\
\\
y &= 0.02x + 8
\end{align*}
\item Interpret the $y$-intercept of your formula in terms of the
situation described above, including units in your answer.\\\\
Answer:\\
In this case the $y$-intercept represents the base price per month (in dollars) of the cellular phone plan when no minutes are used. (It is \$8)\\
\item Interpret the slope of your formula in terms of the
situation described above, including units in your answer.\\\\
Answer:\\
The slope ($m=0.02$) is the number of dollars that each additional minute of cell phone usage will add to the total monthly bill.\\
\end{enumerate}
\item The actual attendance at Game 1 of the 2004 World Series was
35,035. Let's assume that on that day, the only people claiming to
have attended were those who really had attended. However, each
year the number who claim to have been in attendance increases by
12\%.
\begin{enumerate}
\item Write an equation that gives the number of people who claim
to have attended that game $t$ years after the game took place.\\\\
Answer:\\
\begin{align*}
A_0 &= 35035\\
r &= 0.12\\
a &= 1 + r = 1.12\\
A(t) &= A_0(a)^t\\
A(t) &= 35035(1.12)^t
\end{align*}
\item 20 years after the game, how many people (to the nearest
whole number) will claim to have been there?\\\\
Answer:\\
\begin{align*}
A(t) &= 35035(1.12)^t\\
A(20) &= 35035(1.12)^{20}\\
A(20) &= 337958\text{ people}
\end{align*}
\end{enumerate}
\item <NAME> is famous for writing that, if left unchecked,
the world's human population would double every 25 years. He wrote
this in 1798, when the population was about 0.9 billion.
\begin{enumerate}
\item Write an equation that gives the population (in billions)
$t$ years after 1798 if it had really doubled every 25 years.\\\\
Answer:\\
\begin{align*}
P_0 &= 0.9\\
P(t) &= P_0(2)^{t/25}\\
P(t) &= 0.9(2)^{t/25}
\end{align*}
\item According to your equation, what would be the population in
2015 (at time $t = 217$)? Give your answer to the nearest
billion.\\\\
Answer:\\
\begin{align*}
P(t) &= 0.9(2)^{t/25}\\
P(217) &= 0.9(2)^{217/25}\\
P(217) &= 369 \text{ billion people}
\end{align*}
\item What is the annual percentage growth rate of your equation?
Give an answer correct to three decimal places (as in 1.234\%).\\\\
Answer:\\
The form in which I gave the equation takes advantage of the
fact that we are doubling every 25 years. Converting the
equation to one in which the percentage growth is given in an
annual basis:\\
\begin{align*}
0.9(2)^{t/25} &= 0.9(a)^t\\
2^{t/25} &= a^t\\
2^{25/25} &= a^{25} & \text{[Substitute 25 for $t$]}\\
2 &= a^{25}\\
2^{1/25} &= a\\
1.02811 &\approx a\\
r &= a - 1 \approx 1.02811 - 1 = 0.2811\\
r &= 2.811\%\\
\end{align*}
\end{enumerate}
\item The function $f(x)$ gives the cost (in thousands of dollars)
of buying $x$ acres of land in a remote area of Vermont. Carefully
interpret the following.
\begin{enumerate}
\item $f(50)$\hfill[Your answer should take the form ``$f(50)$ is
...'']\\\\
Answer:\\
$f(50)$ is the cost in thousands of dollars of buying 50 acres
of land in a remote area of Vermont.\\
\item $\finv(50)$\hfill[Your answer should take the form
``$\finv(50)$ is...'']\\\\
Answer:\\
$\finv(50)$ is the number of acres of land in a remote area of
Vermont that \$50000 can buy.\\
\end{enumerate}
\item Let $f(x) = 3^x$.
\begin{enumerate}
\item Write an equation for the graph obtained by first stretching
$f$ vertically by a factor of 5 and then shifting it up 2
units. Sketch your graph, labeling the $y$-intercept and the
$y$-value of the horizontal asymptote.\\\\
Answer:\\
\begin{align*}
f(x) &= 3^x\\
g(x) &= 5x\\
h(x) &= x + 2\\
h(g(f(x))) &= g(f(x)) + 2\\
&= 5(f(x)) + 2\\
&= 5(3^x) + 2\\
\end{align*}\\
\includegraphics{hw1-5-a}
\item If the order of operations above were reversed (that is,
first shift up 2 then stretch vertically by a factor of 5),
would the resulting function be the same? Explain your
answer.\\\\
Answer:\\
No. Composition of functions is not a commutative operation.\\
\begin{align*}
h(g(f(x))) &= 5(3^x) + 2\\\\
g(h(f(x))) &= 5 \cdot h(f(x))\\
&= 5 \cdot (f(x) + 2)\\
&= 5(3^x + 2)\\
&= 5(3^x) + 10
\end{align*}
\end{enumerate}
\item The function $f(x)$ has a domain of all real numbers and a
range of all positive real numbers. It has an inverse function
$\finv(x)$. We are given that $f(2) = 17$.\\
For each of the following expressions, state
\begin{itemize}
\item the numerical value of the expression, or
\item that the value of the expression is known to be undefined,
or
\item that more information is needed in order to determine the
value of the expression.
\end{itemize}
\begin{enumerate}
\item $\finv(17)$\\\\
Answer:\\
$\finv(17) = 2$\\
\item $f(\finv(5))$\\\\
Answer:\\
$f(\finv(5)) = 5$\\
\item $\finv(f(5))$\\\\
Answer:\\
$\finv(f(5)) = 5$\\
\item $\finv(2)$\\\\
Answer:\\
More information is needed in order to determine the value of
the expression.\\
\item $\finv(-17)$\\\\
Answer:\\
The value of the expression is known to be undefined.
\end{enumerate}
\end{enumerate}
\end{document}
<file_sep>/homework/study_guide_exam2.tex
\documentclass[10pt]{article}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\usepackage{float}
\usepackage{multicol}
\graphicspath{ {./homework/images/} }
\newcommand{\dd}[2]{\dfrac{d#1}{d#2}}
\newcommand{\ddx}{\dd{}{x}}
\newcommand{\ssep}{\mid}
\begin{document}
\title{Study Guide Exam II}
\author{<NAME>}
\maketitle
\section{Derivative Rules \& Equations}
\begin{multicols}{2}
\begin{enumerate}
\item $\ddx k = 0$
\item $\ddx kf(x) = kf'(x)$
\item $\ddx \left[f(x) + g(x)\right] = f'(x) + g'(x)$
\item $\ddx x^m = mx^{m-1}$ $\{m \in \mathbb{R} \ssep m \neq 0\}$
\item $\ddx \left[f(x)g(x)\right] = f'(x)g(x) + g'(x)f(x)$
\item $\ddx \left[\dfrac{f(x)}{g(x)}\right] = \dfrac{f'(x)g(x) - g'(x)f(x)}{g(x)^2}$
\item $\ddx b^x = b^x\ln b$ $\{b \in \mathbb{R} \ssep b > 0\}$
\item $\ddx f(g(x)) = f'(g(x)) \cdot g'(x)$
\item $\ddx \sin x = \cos x$
\item $\ddx \cos x = -\sin x$
\item $\ddx \tan x = \sec^2x$
\item $\ddx \arctan x = \dfrac{1}{1 + x^2}$
\item $\ddx \arcsin x = \dfrac{1}{\sqrt{1 - x^2}}$
\item $\ddx \arccos x = - \dfrac{1}{\sqrt{1 - x^2}}$
\item $\ddx \ln x = \dfrac{1}{x}$ $\{x \in \mathbb{R} \ssep x > 0 \}$
\item $\ddx \log_bx =\dfrac{1}{x \ln b}$ $\{x,b \in \mathbb{R} \ssep x,b > 0 \wedge b \neq 1\}$
\item $\ddx x^x = x^x(\ln x + 1)$
\end{enumerate}
\end{multicols}
\pagebreak
\section{Integral Calculus}
Differential calculus involved finding the rate of change for a given
quantity. \textit{Integral calculus} solves the inverse problem:
given a rate of change, we try to determine what we can say about the
quantity itself.
\subsection{Riemann Sums}
The \textit{Riemann sum} is an approximation of the area under a
curve. We talk about LHS, left-handed sums, and RHS, right-handed
sums. The math is simpler when working with an LHS but as the number
of rectangles comprising the Riemann sum approaches infinity both sums
approach the same value. To find the area under the curve on the
interval $[a, b]$ we divide the area into $n$ rectangles each of equal
width $\Delta x = \dfrac{b-a}{n}$ and take one of the sums:
\begin{align*}
\mathbf{LHS}(n) &= \sum\limits_{i=0}^{n-1} f(x_i)\Delta x\\
\mathbf{RHS}(n) &= \sum\limits_{i=1}^n f(x_i)\Delta x
\end{align*}
To find the exact area under a curve, we calculate:
\begin{align*}
\lim_{n \to \infty}\mathbf{LHS}(n)
\end{align*}
\subsection{Definite Integral}
We define the following notation for taking the above limit to
determine the area under a curve on the interval $[a,b]$:
\begin{align*}
\int_a^bf(x)dx = \lim_{n \to \infty}\mathbf{LHS}(n)
\end{align*}
In the above equation $dx$ is a symbolism related to $\Delta x$ from
the \textbf{LHS} in the same way $\dd{y}{x}$ was related to the
difference $\dfrac{\Delta y}{\Delta x}$ when we moved from finding
average rate of change (the slope of the secant) to finding
instantenous rate of change (the slope of the tangent).
\subsection{Fundamental Theorem of Calculus}
If $F' = f$, then $\int_a^bf(x)dx = F(b) - F(a) = F(x)\mid_a^b$ and we
can say that $F$ is the antiderivative of $f$.
\pagebreak
\section{Algebra/Trig Identities}
\subsection{Exponent Rules}
\begin{multicols}{2}
\begin{enumerate}
\item $a^ma^n = a^{m+n}$
\item $(a^m)^n = a^{mn}$
\item $\dfrac{a^m}{a^n} = a^{m-n}$
\item $a^0 = 1$
\item $a^{-m} = \dfrac{1}{a^m}$
\item $a^{1/n} = \sqrt[n]{a}$
\item $a^{m/n} = \left(\sqrt[n]{a}\right)^m = \sqrt[n]{a^m}$
\end{enumerate}
\end{multicols}
\subsection{Logarithmic Identities \& Rules}
\begin{enumerate}
\item $\log_bb^x = x$ $\{x \in \mathbb{R} \}$
\item $b^{\log_bx} = x$ $\{x \in \mathbb{R} \ssep x > 0\}$
\item $\log_b(xy) = \log_bx + \log_by$
\item $\log_b\left(\dfrac{x}{y}\right) = \log_bx - \log_by$
\item $\log_b\left(x^y\right) = y\log_bx$
\end{enumerate}
\subsection{Sinusoidal Functions}
A function is \textit{sinusoidal} if it can be written in the one of
the following forms:
\begin{align*}
y &= A\sin(Bx + D) + C & y &= A\cos(Bx + D) + C
\end{align*}
\begin{itemize}
\item The \textit{amplitude} is $\dfrac{1}{2}$ the vertical distance
from maximum to minimum: $\mathbf{amplitude} = |A|$
\item The \textit{period} is the smallest $p > 0$ for which
$f(x) = f(x+p)$ for all $x$. $\mathbf{period} = \dfrac{\pi}{|B|}$
\item The \textit{midline} is the horizontal line that bisects the
graph. $\mathbf{midline}$ at $y = c$.
\end{itemize}
\subsection{Trigonometric Identities \& Rules}
\begin{multicols}{2}
\begin{enumerate}
\item $\tan\Theta = \dfrac{\sin\Theta}{\cos\Theta}$
\item $\sec\Theta = \dfrac{1}{\cos\Theta}$
\item $\csc\Theta = \dfrac{1}{\sin\Theta}$
\item $\cot\Theta = \dfrac{1}{\tan\Theta}$
\item $\sin^2\Theta +\cos^2\Theta = 1$
\item $1 + \tan^2\Theta = \sec^2\Theta$
\item $1 + \cot^2\Theta = \csc^2\Theta$
\end{enumerate}
\end{multicols}
\pagebreak
\section{Miscellaneous Techniques}
\subsection{Logarithmic Differentiation}
We can use \textit{logarithmic differentiation} to solve some
derivatives which are otherwise unsolveable. To wit:
\begin{align*}
f(x) &= x^x\\
\ln f(x) &= \ln x^x\\
\ln f(x) &= x\ln x\\
\ddx \left(\ln f(x)\right) &= \ddx \left( x\ln x\right)\\
\dfrac{1}{f(x)}f'(x) &= (1)(\ln x) + \dfrac{1}{x}(x)\\
f'(x) &= \left(\ln x + 1\right)\cdot f(x)\\
f'(x) &= x^x(\ln x + 1)
\end{align*}
\subsection{Implicit Differentiation}
We can use \textit{implicit differentiation} to find $\dd{y}{x}$ when
it is very difficult or impossible to solve for $y$ explicitly in
terms of $x$. For example:
\begin{align*}
x^3 + y^3 &= \dfrac{9}{2}xy\\
\ddx \left[x^3 + y^3\right] &= \ddx \left[\dfrac{9}{2}xy\right]\\
3x^2 + 3y^2\dd{y}{x} &= \left[\dfrac{9}{2}(1)(y) +
\dfrac{9}{2}\dd{y}{x}(1)(x)\right]\\
3x^2 + 3y^2\dd{y}{x} &= \left[\dfrac{9}{2}y +
\dfrac{9}{2}x\dd{y}{x}\right]\\
\dd{y}{x}\left(3y^2 - \dfrac{9}{2}x\right) &= \dfrac{9}{2}y -
3x^2\\
\dd{y}{x} &= \dfrac{\dfrac{9}{2}y - 3x^2}{3y^2 - \dfrac{9}{2}x}
\end{align*}
\subsection{Local Linearization}
The \textit{local linearization} or \textit{tangent line
approximation} of a function $f(x)$ at a point $x=a$ is\\ $f(x)
\approx f(a) + f'(a)(x - a)$.
\subsection{L'Hopital's Rule}
Indeterminate are fractions that tend toward one of
$\dfrac{\infty}{\infty}$ or $\dfrac{0}{0}$ when one attempts to
take their limit. We can sometimes use calculus to evaluate these
limits - specifically the technique called \textit{L'Hopital's Rule}.
L'Hopital's Rule states that for an indeterminate fraction
$\dfrac{f(x)}{g(x)}$ (provided the limit on the left exists at all):
\begin{align*}
\lim_{x \to c}\dfrac{f(x)}{g(x)} = \lim_{x \to c}\dfrac{f'(x)}{g'(x)}
\end{align*}
\subsection{Local and Global Extrema}
The extrema of a graph/function are all the points at which it has
either local or global maxima or minima.\\
To find local extrema:
\begin{enumerate}
\item Find the critical points of $f$ (where $f'(x) = 0$ or $f'(x)$ is
undefined).
\item Check the behavior of $f'$ on the intervals enclosing each of
these critical points. A point $x$ is a \textit{local minimum} if
$f'(x)$ is decreasing before the point and increasing afterward. It
is a \textit{local maximum} if it is increasing prior to the point
and decreasing afterward.
\end{enumerate}
To find global extrema:
\begin{enumerate}
\item Check $y$-values of $f$ at the endpoints of the function's
domain (if any).
\item Check $y$-values of any local extrema
\item Check what happens as $x \to \pm\infty$
\item Check for vertical asymptotes
\end{enumerate}
The \textit{global maximum} will be the point with the largest
$y$-value. The \textit{global minimum} will be the point with the
smallest $y$-value.
\subsection{Families of Curves}
Up to this point we have restricted ourselves to analyzing a single
function at a time. By studying a family of curves, we may analyze
infinitely many related functions at once.
Common families of curves:
\begin{enumerate}
\item $f(x) = mx + b$
\item $f(x) = ax^2 + bx + c$
\item $f(x) = A\sin(Bx) + C$
\end{enumerate}
When analyzing families of curves, we are applying the exact analyses
we have applied previously to single functions (finding the roots of
the function, finding the extrema, finding the inflection points and
sketching the graph). The only difference is that we replace the
numeric constants with algebraic constants. The general process to
follow when analyzing a family of curves:
\begin{enumerate}
\item Find the roots of the $f(x)$
\item Take the first derivative of $f(x)$
\item Find all local and global minima/maxima
\item Take the second derivative of $f(x)$
\item Find all inflection points of $f(x)$
\end{enumerate}
\subsection{Optimization}
\textit{Optimization} is generally either about maximizing a quantity
(something we would like more of) or minimizing a quantity (because
sometimes less is more). The general algorithm for solving an
optimization problem is as follows:
\begin{enumerate}
\item Briefly state the goal of the problem
\item Restate the given word problem as a set of equations
\item If the set of equations is in more than one indenpendent
variable, rearrange the equation of the quantity we are looking to
minimize such that it is given in terms of 1 variable
\item Take the first derivative of the function
\item Check the critical points, looking for either a global maximum
or a global minimum as the problem dictates
\item Final step: If a problem consists of two variables, often it
asks you for the value of both of the variables. Make sure you do
this once you have found the extreme you sought.
\end{enumerate}
\end{document}
<file_sep>/homework/hw7.tex
\documentclass[10pt]{article}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\usepackage{float}
\graphicspath{ {./homework/images/} }
\newenvironment{answer}
{ \\Answer:\\ }
{ \\ }
\newcommand{\dd}[2]{\dfrac{d#1}{d#2}}
\begin{document}
\title{Math E-15 HW7 Solutions}
\author{<NAME>}
\date{11/06/2014}
\maketitle
\begin{enumerate}
\item Consider the family of curves $f(x) = x^ne^{-7x}$ where $n$ is a
positive even integer.
\begin{enumerate}
\item Find the roots of $f$. (That is, solve $f(x) = 0$.)
\begin{answer}
\begin{align*}
f(x) &= x^ne^{-7x}\\\\
x^ne^{-7x} &= 0\\
x^ne^{-7x} = 0 \implies x^n &= 0\\
x &= 0 \text{ [$x=0$ is a root]}\\
x^ne^{-7x} = 0 \implies e^{-7x} &= 0\\
-7x &= \ln 0 \text{ [$\ln 0$ is undefined, not a
root] }
\end{align*}
The only root of $f$ is at $x=0$.
\end{answer}
\pagebreak
\item Find the $x$- AND $y$-coordinate(s) of all critical points
and classify each as a local maximum, local minimum, or neither.
\begin{answer}
\begin{align*}
f(x) &= x^ne^{-7x}\\
\dd{f}{x} &= \dd{}{x}\left[x^ne^{-7x}\right]\\
&= nx^{n-1}e^{-7x} + x^ne^{-7x}\cdot-7\\
&= x^{n-1}e^{-7x}\left(n - 7x\right)\\
x^{n-1}e^{-7x}\left(n - 7x\right) &= 0\\
\implies x^{n-1}e^{-7x} &= 0\\
x^{n-1} &= 0\\
x &= 0\\
e^{-7x} &\neq 0\\
\implies (n - 7x) &= 0\\
x &= \dfrac{n}{7}
\end{align*}
The critical points are at $x=0$ and $x=\dfrac{n}{7}$. In
calculating the sign of $f'$ at various points below, we keep
in mind that $n$ is a positive even integer (and therefore
that $n - 1$ is a positive odd integer).
\begin{align*}
f'(x) &= x^{n-1}e^{-7x}\left(n - 7x\right)\\
f'(-1) &= (-1)^{n-1}e^{-7(-1)}\left(n - 7(-1)\right)\\
&= (-1)^{n-1}e^{7}\left(n + 7\right)\\
&= (-)(+)(+) = (-)\\
f'\left(\dfrac{n}{14}\right) &=
\left(\dfrac{n}{14}\right)^{n-1}e^{-7(n/14)}\left(n -
7\left(\dfrac{n}{14}\right)\right)\\
&= (+)(+)(+) = (+)\\
f'(n) &= (n)^{n-1}e^{-7n}(n - 7n)\\
&= (+)(+)(-) = (-)
\end{align*}
We see that $x=0$ is a local minimum and $x=\dfrac{n}{7}$ is a
local maximum. Now we calculate the y-coordinates.
\begin{align*}
f(0) &= 0^ne^{-7(0)}\\
&= 0\\
f(n/7) &= (n/7)^ne^{-7(n/7)}\\
&= \dfrac{(n/7)^n}{e^n}
\end{align*}
\end{answer}
\pagebreak
\item Sketch $f$, labeling all the points you found above.
\begin{figure}[H]
\centering
\includegraphics[width=0.8\textwidth]{hw7-1-c}\\
\caption{The graph of $f(x) = x^ne^{-7x}$.}
\label{fig:hw7-1-c}
\end{figure}
\end{enumerate}
\pagebreak
\item You wish to buld an outdoor rectangular enclosure for your
pets. One side of the rectangle will be one of the outer walls of
your house. If you have 80 feet of fencing, what are the dimensions
that will enclose the maximum possible area? Be sure to show how you
know you have found the absolute maximum.\\\\
Remember that you do NOT need to use fence for the side that is
already there (the wall of your house).
\begin{answer}
Goal: Maximize area
\begin{align*}
Perimeter = P &= 2L + W \text{ [We only need 3 sides]}\\
Area = A &= LW\\
W &= P - 2L = 80 - 2L\\
\implies A(L) &= L(80 - 2L) = 80L - 2L^2\\\\
A'(L) &= 80 - 4L\\
80 - 4L &= 0\\
L &= 20\\
A'(10) &= (+)\\
A'(30) &= (-)\\
\end{align*}
So there is at least a local maximum at $L = 20$. At $A(20) = 800$. $A$ is a second degree polynomial with a negative
coeffecient for the $L^2$ term so we know the graph of the
function is a parabola that opens downward - ergo the local
maximum must also be the global maximum.\\\\
\begin{align*}
A &= 800 \text{ feet$^2$}\\
L &= 20 \text{ feet}\\
W &= \dfrac{A}{L} = \dfrac{800}{20} = 40 \text{ feet}
\end{align*}
So the side parallel to the wall of the house is $40$ feet in
length while the other two sides will each be $20$ feet.
\end{answer}
\pagebreak
\item As shown below, a newly drilled oil well is 7 kilometers
offshore and 10 kilometers east of an oil refinery that is already
in place on the shoreline. If connecting pipe costs \$5 million per
kilometer in the water and \$3 million per kilometer on the shore,
what path will minimize the total cost of connecting the new well to
the refinery? Be sure to show how you know you have found the
absolute minimum.\\\\
Please include a sketch that shows the amount of pipe in the water
and the amount on the shoreline.
\begin{answer}
Goal: Minimize cost.\\
We define $x$ as $10$ minus the number of kilometers we are
going to travel along the shoreline. $y$ is defined as the
distance we will travel once we enter the water.
\begin{align*}
Distance = D &= (10 - x) + y\\
Cost = C &= 3(10 - x) + 5(y) \text{ [in milions of
dollars]}\\
&= 30 - 3x + 5y\\
y &= \sqrt{7^2 + x^2}\\
C(x) &= 30 - 3x + 5\sqrt{7^2 + x^2}\\
&= 30 - 3x + 5(7^2 + x^2)^{1/2}\\
C'(x) &= -3 + \dfrac{5}{2}(7^2 + x^2)^{-1/2}2x\\
&= -3 + \dfrac{5x}{\sqrt{49 + x^2}}\\
-3 + \dfrac{5x}{\sqrt{49 + x^2}} &= 0\\
\dfrac{5x}{\sqrt{49 + x^2}} &= 3\\
5x &= 3\sqrt{49 + x^2}\\
25x^2 &= 9(49 + x^2)\\
25x^2 &= 441 + 9x^2\\
16x^2 &= 441\\
x^2 &= \dfrac{441}{16}\\
x &= \sqrt{\dfrac{441}{16}} = 5.25 \text{ [$-5.25$ is
outside problem domain]}\\
C'(1) &= -3 + 5(1)(49 + (1)^2)^{-1/2} = (-)\\
C'(10) &= -3 + 5(10)(49 + (10)^2)^{-1/2} = (+)\\
\end{align*}
The critical point at $x = 5.25$ is a local
minimum. Since $C$ is decreasing in either direction as we
move away from this value of $x$ and both $C(x)$ and $C'(x)$ are
defined for all values of $x$ in the problem domain $0 \leq x
\leq 10$, we know this is also the global maximum. $C(5.25) =
58$ (million dollars). The path that minimizes the cost is
achieved by building the pipeline $4.75$km along the beach and
then $8.75$km directly toward the oil well.
\end{answer}
\pagebreak
\begin{figure}[H]
\centering
\includegraphics[width=0.8\textwidth]{hw7-3}\\
\caption{The graph of the most cost effective path to the oil well.}
\label{fig:hw7-3}
\end{figure}
\end{enumerate}
\end{document}
<file_sep>/homework/hw2.tex
\documentclass[10pt]{article}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\graphicspath{ {./homework/images/} }
\newenvironment{answer}
{ \\Answer:\\ }
{ \\ }
\begin{document}
\title{Math E-15 HW2 Solutions}
\author{<NAME>}
\date{09/15/2014}
\maketitle
\begin{enumerate}
\item Find all solutions $x$ for each equation below. Give both exact answers and approximations correct to three decimal places.
\begin{enumerate}
\item $3e^x = 12(7^{2x})$
\begin{answer}
\begin{align*}
3e^x &= 12(7^{2x})\\
e^x &= 4(7^{2x})\\
\ln e^x &= \ln[4(7^{2x})]\\
x &= \ln[4(7^{2x})]\\
x &= \ln4 + \ln7^{2x}\\
x &= \ln4 + 2x\ln7\\
x - 2x\ln7 &= \ln4\\
x(1 - 2\ln7) &= \ln4\\
x &= \frac{\ln4}{1 - 2\ln7}\\
x &\approx -0.479
\end{align*}
\end{answer}
\item $\ln x = -2$
\begin{answer}
\begin{align*}
\ln x &= -2\\
e^{\ln x} &= e^{-2}\\
x &= e^{-2}\\
x &\approx 0.135
\end{align*}
\end{answer}
\pagebreak
\item $x^{3}e^{x} - 6xe^{x} = 0$
\begin{answer}
\begin{align*}
x^3e^x - 6xe^x &= 0 \\
x(x^2e^x - 6e^x) &= 0 \\
x(e^x)(x^2 - 6) &= 0 \\
\end{align*}
\begin{align*}
x = 0 \vee x^2 - 6 &= 0 \vee e^x = 0
\end{align*}
\begin{align*}
x &= 0\\\\
x^2 - 6 &= 0\\
x^2 &= 6\\
x &= \pm\sqrt{6} \\
x &\approx \pm2.449\\\\
e^x &= 0\\
x &= \ln 0\\
&= \text{Undefined}
\end{align*}
\end{answer}
\end{enumerate}
\item The radioactive element iodine-131 is commonly used in treating medical problems. It has a half-life of 8.1 days. How long does it take for 99\% of a sample of iodine-131 to \underline{decay}? Give both an exact answer and an approximation correct to three decimal places.
\begin{answer}
\begin{align*}
I_0 &= 1 & \text{[$1 = 100\%$]}\\
I(t) &= I_0(d)^{t/8.1}\\
I(t) &= 1(0.5)^{t/8.1}\\
0.01 &= 0.5^{t/8.1}\\
\ln 0.01 &= \ln 0.5^{t/8.1}\\
\ln 0.01 &= \frac{t}{8.1}\ln 0.5\\
t &= \frac{8.1\ln 0.01}{\ln 0.5}\\
t &\approx 53.815
\end{align*}
\end{answer}
\pagebreak
\item If an investment grows exponentially and doubles every 10 years, how long will it take to triple? Give both an exact answer and an approximation correct to three decimal places.
\begin{answer}
\begin{align*}
V(t) &= V_0(2)^{t/10}\\
3V_0 &= V_0(2)^{t/10}\\
3 &= 2^{t/10}\\
\ln 3 &= \ln 2^{t/10}\\
\ln 3 &= \frac{t}{10}\ln 2\\
t &= \frac{10\ln 3}{\ln 2}\\
t &\approx 15.850
\end{align*}
\end{answer}
\item Evaluate the following limits.
\begin{enumerate}
\item \(\lim\limits_{x \to \infty} \dfrac{3}{x^2} \)\\
\begin{answer}\\
$\lim\limits_{x \to \infty}\dfrac{1}{x^2}$ goes to 0 so its limit multiplied by any constant value will also go to 0.
\end{answer}
\item \(\lim\limits_{x \to -\infty} -5x^3\)\\
\begin{answer}\\
$\lim\limits_{x \to -\infty} x^3$ goes to $-\infty$. Multiplying by a negative constant reverses it, meaning the value approaches $+\infty$.
\end{answer}
\item \(\lim\limits_{x \to -\infty} (6 - 2^x)\)\\
\begin{answer}\\
$\lim\limits_{x \to -\infty} -2^x$ does not exist because for every value of $x$ of the form $x = m/n$ where $m$ is an odd integer and $n$ is an even integer, $-2^x$ does not have a real value.
\end{answer}
\end{enumerate}
\pagebreak
\item On a particular day, a town's electricity usage can be approximated by a sinusoidal function $U(t)$, where $t=0$ corresponds to midnight. The function has a period of 24 hours and goes from a low of 30,000 kilowatts at 6 a.m. to a high of 60,000 kilowatts at 6 p.m. Write a formula for $U(t)$ where $t$ is measured in hours.
\begin{answer}
\begin{align*}
\mathbf{amplitude} &= \left| \frac{60000 - 30000}{2}\right| \\
&= \left| \frac{30000}{2}\right| \\
&= 15000 \text{ (kilowatts)} \\\\
\mathbf{period} &= 24 \text{ (hours)}\\\\
\mathbf{midline} &= \frac{60000 + 30000}{2}\\
&= \frac{90000}{2}\\
&= 45000 \text{ (kilowatts)}\\\\
U(t) &= \mathbf{amplitude} \cdot -\sin\left(\frac{2\pi}{\mathbf{period}}t\right) + \mathbf{midline}\\
U(t) &= -15000\sin\left(\frac{\pi}{12}t\right) + 45000
\end{align*}
\end{answer}
\pagebreak[4]
\item Simplify $\cos(\arcsin x)$ by rewriting it as an expression that contains no trigonometric or inverse trigonometric functions. Please draw a triangle as part of showing your work.
\begin{answer}
\begin{figure}
\centering
\includegraphics{hw2-6}\\
\caption{A right triangle with hypotenuse length 1 and and a side of length $x$.}
\label{fig:hw2-6}
\end{figure}
We define $\theta = \arcsin x$ as shown in Figure~\ref{fig:hw2-6}. This allows us to rewrite the original expression as:
\[ \cos(\theta) \]
Now we use the Pythagorean theorem to solve for the length of the unspecified side adjacent to $\theta$:
\begin{align*}
a^2 + b^2 = c^2\\
x^2 + b^2 = 1^2\\
b^2 = 1 - x^2\\
b = \sqrt{1 - x^2}
\end{align*}
Thus $\cos(\arcsin x) = \sqrt{1 - x^2}$.
\end{answer}
\end{enumerate}
\end{document}
<file_sep>/homework/hw3.tex
\documentclass[10pt]{article}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\graphicspath{ {./homework/images/} }
\newenvironment{answer}
{ \\Answer:\\ }
{ \\ }
\begin{document}
\title{Math E-15 HW3 Solutions}
\author{<NAME>}
\date{09/25/2014}
\maketitle
\begin{enumerate}
\item Consider the function $f(x) = 5x^3$. Do not round off your
answers to the following.
\begin{enumerate}
\item What is the average rate of change of $f$ on the interval
$[2, 2.1]$?
\begin{answer}
\begin{align*}
m &= \frac{f(2.1) - f(2)}{2.1 - 2}\\
&= \frac{5\cdot2.1^3 - 5\cdot2^3}{0.1}\\
&= \frac{5\cdot(9.261 - 8)}{0.1}\\
&= \frac{5\cdot1.261}{0.1}\\
&= 50\cdot1.261\\
m &= 63.05
\end{align*}
\end{answer}
\item What is the average rate of change of $f$ on the interval
$[2, 2.01]$?
\begin{answer}
\begin{align*}
m &= \frac{f(2.01) - f(2)}{2.01 - 2}\\
&= \frac{5\cdot2.01^3 - 5\cdot2^3}{0.01}\\
&= \frac{5\cdot(8.120601 - 8)}{0.01}\\
&= 500\cdot0.120601\\
m &= 60.3005
\end{align*}
\end{answer}
\pagebreak
\item What is the average rate of change of $f$ on the interval
$[2, 2.001]$?
\begin{answer}
\begin{align*}
m &= \frac{f(2.001) - f(2)}{2.001 - 2}\\
&= \frac{5\cdot2.001^3 - 5\cdot2^3}{0.001}\\
&= \frac{5\cdot(8.012006001 - 8)}{0.001}\\
&= 5000\cdot0.012006001\\
m &= 40.060030005
\end{align*}
\end{answer}
\item Use the limit definition to compute $f'(x)$.
\begin{answer}
\begin{align*}
f'(x) &= \lim_{h \to 0} \frac{f(x+h) - f(x)}{x + h - x}\\
&= \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}\\
&= \lim_{h \to 0} \frac{5(x+h)^3 - 5x^3}{h}\\
&= \lim_{h \to 0} \frac{5((x^3 + 3x^2h + 3xh^2 + h^3) - x^3)}{h}\\
&= \lim_{h \to 0} \frac{5(3x^2h + 3xh^2 + h^3)}{h}\\
&= \lim_{h \to 0} 5(3x^2 + 3xh + h^2)\\
f'(x) &= 5\cdot3x^2 = 15x^2
\end{align*}
\end{answer}
\item Use your answer to (d) to compute the instantaneous rate of
change of f at $x = 2$.
\begin{answer}
\begin{align*}
f'(x) &= 15x^2\\
f'(2) &= 15\cdot2^2\\
f'(2) &= 60
\end{align*}
\end{answer}
\pagebreak
\item Find the equation of the tangent line to $f$ at $x = 2$.
\begin{answer}
\begin{align*}
m_{x=2} &= f'(2) = 60\\\\
y &= m_{x=2}x + b\\
y &= 60x + b\\
5 &= 60\cdot1 + b\\
b &= 5 - 60 = -55\\
y &= 60x - 55
\end{align*}
\end{answer}
\end{enumerate}
\item Let $f(x) = \dfrac{2}{4 - x}$.
\begin{enumerate}
\item Use the limit definition of the derivative to find $f'(x)$.
\begin{answer}
\begin{align*}
f'(x) &= \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}\\
&= \lim_{h \to 0} \left(\dfrac{\dfrac{2}{4 - x - h} - \dfrac{2}{4 - x}}{h}\right)\\
&= \lim_{h \to 0} \left(\dfrac{\dfrac{2(4-x) - 2(4-x-h)}{(4-x-h)(4-x)}}{h}\right)\\
&= \lim_{h \to 0} \left(\dfrac{\dfrac{2(4-x-4+x+h)}{(4-x-h)(4-x)}}{h}\right)\\
&= \lim_{h \to 0} \left(\dfrac{\dfrac{2h}{(4-x-h)(4-x)}}{h}\right)\\
&= \lim_{h \to 0} \left(\dfrac{2h}{(4-x-h)(4-x)}\cdot\dfrac{1}{h}\right)\\
&= \lim_{h \to 0} \dfrac{2}{(4-x-h)(4-x)}\\
f'(x) &= \dfrac{2}{(4-x)(4-x)} = \dfrac{2}{(4-x)^2}
\end{align*}
\end{answer}
\pagebreak
\item Find the equation of the tangent line to $f$ at $x = 1$.
\begin{answer}
\begin{align*}
f'(x) &= \dfrac{2}{(4-x)^2}\\
f'(1) &= \dfrac{2}{(4-1)^2}\\
&= \frac{2}{9}\\\\
y &= \frac{2}{9}x + b\\
0.5 &= \frac{2}{9}(0) + b\\
0.5 &= b\\\\
y &= \frac{2}{9}x + 0.5
\end{align*}
\end{answer}
\end{enumerate}
\item Let $f(x) = 1 - 2x - 3x^2$.
\begin{enumerate}
\item Use the limit definition of the derivative to find $f'(x)$.
\begin{answer}
\begin{align*}
f'(x) &= \lim_{h \to 0}\dfrac{f(x+h) - f(x)}{h}\\
&= \lim_{h \to 0}\left(\dfrac{(1-2(x+h)-3(x+h)^2)-(1-2x-3x^2)}{h}\right)\\
&= \lim_{h \to 0}\left(\dfrac{(1-2x-2h-3(x^2+2xh+h^2))-1+2x+3x^2}{h}\right)\\
&= \lim_{h \to 0}\left(\dfrac{1-2x-2h-3x^2-6xh-3h^2-1+2x+3x^2}{h}\right)\\
&= \lim_{h \to 0}\dfrac{-2h-6xh-3h^2}{h}\\
&= \lim_{h \to 0}(-2-6x-3h)\\
f'(x) &= -2-6x
\end{align*}
\end{answer}
\item At what $x$-value(s) does $f$ have a horizontal tangent line?
\begin{answer}
\begin{align*}
f'(x) &= -2-6x\\
0 &= -2-6x\\
6x &= -2\\
x &= -\frac{2}{6} = -\frac{1}{3}
\end{align*}
\end{answer}
\end{enumerate}
\item Shown below [see assignment] is a graph of $f'$ on its entire
domain. This graph is NOT $f$.\\\\
At which labelled $x$-value(s) (that is, the letters $a$ through
$k$)
\begin{enumerate}
\item is $f$ greatest?
\begin{answer}
At point $f$
\end{answer}
\item is $f$ least?
\begin{answer}
Cannot determine.
\end{answer}
\item is $f'$ greatest?
\begin{answer}
At point $e$
\end{answer}
\item is $f'$ least?
\begin{answer}
At point $h$
\end{answer}
\item is the slope of $f'$ greatest?
\begin{answer}
At point $i$
\end{answer}
\item is the slope of $f'$ least?
\begin{answer}
At point $g$
\end{answer}
\end{enumerate}
On what interval(s) is
\begin{enumerate}
\item $f$ increasing?
\begin{answer}
$(d,f)$
\end{answer}
\item $f$ decreasing?
\begin{answer}
$[a,d)\cup(f,k]$
\end{answer}
\item $f'$ increasing?
\begin{answer}
$[a,e)\cup(h,j)$
\end{answer}
\item $f'$ decreasing?
\begin{answer}
$(e,h)\cup(j,k]$
\end{answer}
\end{enumerate}
\end{enumerate}
\end{document}
<file_sep>/homework/hw5.tex
\documentclass[10pt]{article}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\usepackage{float}
\graphicspath{ {./homework/images/} }
\newenvironment{answer}
{ \\Answer:\\ }
{ \\ }
\newcommand{\dd}[2]{\dfrac{d#1}{d#2}}
\begin{document}
\title{Math E-15 HW5 Solutions}
\author{<NAME>}
\date{10/21/2014}
\maketitle
\begin{enumerate}
\item Find the derivative of each of the following functions.
\begin{enumerate}
\item $y = \sin(7x)$
\begin{answer}
\begin{align*}
y &= \sin(7x)\\
\dd{y}{x} &= \dd{}{x}\left(\sin(7x)\right)\\
&= 7\cos(7x)
\end{align*}
\end{answer}
\item $y = 2^{\sin(7x)}$
\begin{answer}
\begin{align*}
y &= 2^{\sin(7x)}\\
\dd{y}{x} &= \dd{}{x}\left(2^{\sin(7x)}\right)\\
&= 2^{\sin(7x)}\ln2 \cdot \cos(7x) \cdot 7
\end{align*}
\end{answer}
\item $y = \cos(2^{sin(7x)})$
\begin{answer}
\begin{align*}
y &= \cos(2^{sin(7x)})\\
\dd{y}{x} &= \dd{}{x}\left( \cos(2^{sin(7x)}) \right)\\
&= -\sin(2^{sin(7x)}) \cdot 2^{sin(7x)}\ln2 \cdot \cos(7x) \cdot 7
\end{align*}
\end{answer}
\item $y = \ln(\sin(x^3))$
\begin{answer}
\begin{align*}
y &= \ln(\sin(x^3))\\
\dd{y}{x} &= \dd{}{x}\left( \ln(\sin(x^3)) \right)\\
&= \dfrac{1}{\sin(x^3)} \cdot \cos(x^3) \cdot 3x^2
\end{align*}
\end{answer}
\pagebreak
\item $y = \sqrt{\arctan(\log_{10}(5x))}$
\begin{answer}
\begin{align*}
y &= \sqrt{\arctan(\log_{10}(5x))}\\
&= \left( \arctan(\log_{10}(5x))\right)^{1/2}\\
\dd{y}{x} &= \dd{}{x} \left[ \left( \arctan(\log_{10}(5x))\right)^{1/2} \right]\\
&= \dfrac{1}{2} \left( \arctan(\log_{10}(5x))\right)^{-1/2} \cdot \dfrac{1}{1 + \left( \log_{10}(5x) \right)^2} \cdot \dfrac{1}{5x\ln10} \cdot 5\\
\end{align*}
\end{answer}
\item $y = e^{3x} \cdot \tan(2x^4)$
\begin{answer}
\begin{align*}
y &= e^{3x} \cdot \tan(2x^4)\\
\dd{y}{x} &= \dd{}{x} \left( e^{3x} \cdot \tan(2x^4) \right)\\
&= e^{3x} \cdot 3 \cdot \tan(2x^4) + e^{3x} \cdot \sec^2(2x^4) \cdot 8x^3\\
&= 3e^{3x}\tan(2x^4) + 8x^3e^{3x}\sec^2(2x^4)
\end{align*}
\end{answer}
\item $y = \sin(\cos(x \cdot 2^{3x}))$
\begin{answer}
\begin{align*}
y &= \sin(\cos(x \cdot 2^{3x}))\\
\dd{y}{x} &= \dd{}{x} \left( \sin(\cos(x \cdot 2^{3x})) \right)\\
&= \cos(\cos(x \cdot 2^{3x})) \cdot -\sin(x \cdot 2^{3x}) \cdot ((1)(2^{3x}) + (x)(2^{3x}\ln2 \cdot 3)))\\
&= \cos(\cos(x \cdot 2^{3x})) \cdot -\sin(x \cdot 2^{3x}) \cdot (2^{3x} + 3x2^{3x}\ln2)
\end{align*}
\end{answer}
\pagebreak
\item $y = (1 + x^6)^{8x}$
\begin{answer}
\begin{align*}
y &= (1 + x^6)^{8x}\\
\ln y &= \ln \left( (1 + x^6)^{8x} \right)\\
\ln y &= 8x \cdot \ln \left( (1 + x^6) \right)\\
\dfrac{1}{y} \cdot \dd{y}{x} &= \dd{}{x} \left( 8x \cdot \ln (1 + x^6) \right)\\
\dfrac{1}{y} \cdot \dd{y}{x} &= 8 \cdot \ln (1 + x^6) + 8x \cdot \dfrac{1}{1 + x^6} \cdot 6x^5\\
\dd{y}{x} &= \left( 8 \cdot \ln (1 + x^6) + 8x \cdot \dfrac{1}{1 + x^6} \cdot 6x^5 \right) \cdot y\\
\dd{y}{x} &= \left( 8 \cdot \ln (1 + x^6) + 8x \cdot \dfrac{1}{1 + x^6} \cdot 6x^5 \right) \cdot (1 + x^6)^{8x}
\end{align*}
\end{answer}
\item $y = e^2 + \ln 3 + \sin 4 + \arctan 5$
\begin{answer}
\begin{align*}
y &= e^2 + \ln 3 + \sin 4 + \arctan 5\\
\dd{y}{x} &= \dd{}{x} \left( e^2 + \ln 3 + \sin 4 + \arctan 5 \right)\\
\dd{y}{x} &= 0 + 0 + 0 + 0 = 0
\end{align*}
\end{answer}
\end{enumerate}
\pagebreak
\item Consider the function $f(x) = e^{-x^2}$. \hfill
\vspace{1pt}
[Remember that $e^{-x^2}$ means $e^{(-x^2)}$, NOT $(e^{-x})^2$ and that $-x^2$ means $-(x^2)$, NOT $(-x)^2$.]\\
Note: Be sure to show enough work on parts (a) and (b) that it is clear to the grader how you used calculus (and not a graphing calculator or someone else's paper) to do the problem.
\begin{enumerate}
\item Where is $f$ increasing? Where is $f$ decreasing?
\begin{answer}
\begin{align*}
f(x) &= e^{-x^2}\\
\dd{f}{x} &= \dd{}{x} \left( e^{-x^2} \right)\\
\dd{f}{x} &= e^{-x^2} \cdot -2x\\\\
(e^{-x^2})(-2x) &= 0\\\\
e^{-x^2} &= 0\\
-x^2 &= \ln 0 \text{ [$\ln 0$ is undefined so $e^{-x^2}$ is not a root of the first derivative]}\\\\
-2x &= 0\\
x &= 0 \text{ [x=0 is a root of the first derivative]}\\\\
f'(-1) &= (e^{-(-1)^2})(-2(-1))\\
&= (e^{-1})(2) = (+)(+) = (+)\\
f'(1) &= (e^{-(1)^2})(-2(1))\\
&= (e^{-1})(-2) = (+)(-) = (-)\\
\end{align*}
Therefore $f$ is increasing on the interval $(-\infty, 0)$ and decreasing on the interval $(0, \infty)$.
\end{answer}
\pagebreak
\item Where is $f$ concave up? Where is $f$ concave down?
\begin{answer}
\begin{align*}
\dd{f}{x} &= e^{-x^2} \cdot -2x\\
\dd{^2f}{x^2} &= \dd{}{x} \left( e^{-x^2} \cdot -2x \right)\\
&= (e^{-x^2} \cdot -2x) \cdot -2x + (-2)(e^{-x^2})\\
&= 4x^2e^{-x^2} - 2e^{-x^2}\\
&= 2e^{-x^2}(2x^2 - 1)\\\\
2e^{-x^2}(2x^2 - 1) &= 0\\\\
2e^{-x^2} &= 0\\
e^{-x^2} &= 0\\
-x^2 &= \ln 0 \text{ [$\ln 0$ is undefined so $e^{-x^2}$ is not a root of the first derivative]}\\\\
2x^2 -1 &= 0\\
2x^2 &= 1\\
x^2 &= \dfrac{1}{2}\\
x &= \pm \sqrt{\dfrac{1}{2}}\\
x &= \pm \dfrac{\sqrt{1}}{\sqrt{2}}\\
&= \pm \dfrac{\sqrt{2}}{2}\\\\
f''(-1) &= 2e^{-(-1)^2}(2(-1)^2 - 1)\\
&= 2e^{-1}(2(1) - 1) = (+)(+) = (+)\\
f''(0) &= 2e^{-(0)^2}(2(0)^2 - 1)\\
&= 2e^0(0 - 1) = (+)(-) = (-)\\
f''(1) &= 2e^{-(1)^2}(2(1)^2 - 1)\\
&= 2e^{-1}(2 - 1) = (+)(+) = (+)
\end{align*}
Therefore $f$ is concave up on the intervals $\left(-\infty, -\dfrac{\sqrt{2}}{2}\right)\cup\left(\dfrac{\sqrt{2}}{2}, \infty\right)$ and concave down on the interval $\left(-\dfrac{\sqrt{2}}{2}, \dfrac{\sqrt{2}}{2}\right)$.
\end{answer}
\pagebreak
\item Sketch a graph of $f$, labeling the points you found above.
\begin{figure}[H]
\centering
\includegraphics[width=0.8\textwidth]{hw5-2-c}\\
\caption{The graph of $f(x) = e^{-x^2}$.}
\label{fig:hw5-2-c}
\end{figure}
\end{enumerate}
\end{enumerate}
\end{document}
| 432e5bda0b58758aad48ffb76a3cadcad77cbdb6 | [
"TeX",
"Python"
] | 10 | TeX | chuckSMASH/fall-2014-math | 5bf68c490fb01c9ab03c64e0c8272d215683ad6b | 498e714b2c024d5551aa666031fd902d0ac6025c |
refs/heads/master | <repo_name>ajdobbs/mica<file_sep>/include/mica/AnalyserFactory.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef ANALYSERFACTORY_HH
#define ANALYSERFACTORY_HH
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "mica/AnalyserBase.hh"
#include "mica/AnalyserGroup.hh"
namespace mica {
/** @class AnalyserFactory
* Singleton factory class for the creation of MICA analysers. New MICA analyser
* types should be registered with the the CreateAnalyser method.
* @author <NAME>
*/
class AnalyserFactory {
public:
/** Create a new instance of the analyser type represented by the string arg */
static AnalyserBase* CreateAnalyser(const std::string& aName);
AnalyserGroup CreateAnalyserGroup(const std::vector<std::string>& aNames);
/** Create a vector of analysers, with the specific types defined the vector of strings arg */
static std::vector<AnalyserBase*> CreateAnalysers(const std::vector<std::string>& aNames);
/** Create a new instance of the analyser type represented by the string arg */
static std::shared_ptr<AnalyserBase> CreateSharedAnalyser(const std::string& aName);
/** Create a vector of analysers, with the specific types defined the vector of strings arg */
static std::vector<std::shared_ptr<AnalyserBase>>
CreateSharedAnalysers(const std::vector<std::string>& aNames);
/** Create a new instance of the analyser type represented by the string arg */
static std::unique_ptr<AnalyserBase> CreateUniqueAnalyser(const std::string& aName);
/** Create a vector of analysers, with the specific types defined the vector of strings arg */
static std::vector<std::unique_ptr<AnalyserBase>>
CreateUniqueAnalysers(const std::vector<std::string>& aNames);
};
} // ~namespace mica
#endif
<file_sep>/src/AnalyserTrackerSpacePointSearchStation.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "mica/AnalyserTrackerSpacePointSearchStation.hh"
#include <string>
namespace mica {
AnalyserTrackerSpacePointSearchStation::AnalyserTrackerSpacePointSearchStation() {
for (int i = 0; i < 5; ++i) {
std::string seeds_title = "Seed Pull vs NPE Station " + std::to_string(i+1);
std::string seeds_name= "hSeedsS" + std::to_string(i+1);
mHSeeds.push_back(new TH2D(seeds_name.c_str(), seeds_title.c_str(), 100, 0, 30, 100, 0, 200));
mHSeeds[i]->GetXaxis()->SetTitle("Pull (mm)");
mHSeeds[i]->GetYaxis()->SetTitle("NPE");
std::string addons_title = "Add-On Seed Pull vs NPE Station " + std::to_string(i+1);
std::string addons_name= "hAddOnsS" + std::to_string(i+1);
mHAddOns.push_back(new TH2D(addons_name.c_str(), addons_title.c_str(),
100, 0, 30, 100, 0, 200));
mHAddOns[i]->GetXaxis()->SetTitle("Pull (mm)");
mHAddOns[i]->GetYaxis()->SetTitle("NPE");
}
}
bool AnalyserTrackerSpacePointSearchStation::analyse(MAUS::ReconEvent* const aReconEvent,
MAUS::MCEvent* const aMCEvent) {
if (!aReconEvent)
return false;
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
for (auto trk : sfevt->helicalprtracks()) {
for (auto sp : trk->get_spacepoints_pointers()) {
double npe = sp->get_npe();
double pull = sp->get_prxy_pull();
mHSeeds[sp->get_station() - 1]->Fill(pull, npe);
if (sp->get_add_on()) {
mHAddOns[sp->get_station() - 1]->Fill(pull, npe);
}
} // Loop over seed spacepoints
} // ~Loop over tracks
return true;
}
bool AnalyserTrackerSpacePointSearchStation::draw(std::shared_ptr<TVirtualPad> aPad) {
GetPads()[0]->Divide(5, 2);
for (int i = 0; i < 5; ++i) {
GetPads()[0]->cd(i+1);
mHSeeds[i]->Draw("COLZ");
GetPads()[0]->cd(i+6);
mHAddOns[i]->Draw("COLZ");
}
return true;
}
} // ~namespace mica
<file_sep>/src/AnalyserTrackerSpacePoints.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "mica/AnalyserTrackerSpacePoints.hh"
#include "TCanvas.h"
#include "src/common_cpp/DataStructure/SciFiEvent.hh"
#include "src/common_cpp/DataStructure/SciFiSpacePoint.hh"
namespace mica {
AnalyserTrackerSpacePoints::AnalyserTrackerSpacePoints() : mHNpeTKU{nullptr},
mHNpeTKD{nullptr},
mHStationNumTKU{nullptr},
mHStationNumTKD{nullptr},
mHXYTKU{nullptr},
mHXYTKD{nullptr} {
// Some parameters for the plots
int nbins = 100;
double xmax = 200.0;
double xmin = -200.0;
double ymax = 200.0;
double ymin = -200.0;
std::string xlabel = "x (mm)";
std::string ylabel = "y (mm)";
// Initialise the general spacepoint info plots
mHNpeTKU = std::unique_ptr<TH1D>(new TH1D("hNpeTKU", "Spacepoint NPE TkU", nbins, 0, 200));
mHNpeTKU->GetXaxis()->SetTitle("NPE");
mHNpeTKD = std::unique_ptr<TH1D>(new TH1D("hNpeTKD", "Spacepoint NPE TkD", nbins, 0, 200));
mHNpeTKD->GetXaxis()->SetTitle("NPE");
mHStationNumTKU = std::unique_ptr<TH1D>(new TH1D("hStationNumTKU",
"Spacepoints per Station TkU", 5, 1, 6));
mHStationNumTKU->GetXaxis()->SetTitle("Station Number");
mHStationNumTKD = std::unique_ptr<TH1D>(new TH1D("hStationNumTKD",
"Spacepoints per Station TkD", 5, 1, 6));
mHStationNumTKD->GetXaxis()->SetTitle("Station Number");
mHXYTKU = std::unique_ptr<TH2D>(new TH2D("hXYTKU", "Spacepoints XY TkU",
nbins, xmin, xmax, nbins, ymin, ymax));
mHXYTKU->GetXaxis()->SetTitle(xlabel.c_str());
mHXYTKU->GetYaxis()->SetTitle(ylabel.c_str());
mHXYTKD = std::unique_ptr<TH2D>(new TH2D("hXYTKD", "Spacepoints XY TkD",
nbins, xmin, xmax, nbins, ymin, ymax));
mHXYTKD->GetXaxis()->SetTitle(xlabel.c_str());
mHXYTKD->GetYaxis()->SetTitle(ylabel.c_str());
// Initialise the x-y per station spacepoint plots (for all, triplets only, doublets only)
for (int iStation = 0; iStation < mNStations; ++iStation) {
std::string name = "S" + std::to_string(iStation+1);
std::string tku_title = "TkU Spacepoints XY " + name;
std::string tku_name = "hTkUXY" + name;
std::string tkd_title = "TkD Spacepoints XY " + name;
std::string tkd_name = "hTkDXY" + name;
mXYPerStationTkU.push_back(std::unique_ptr<TH2D>(new TH2D(tku_name.c_str(), tku_title.c_str(),
nbins, xmin, xmax, nbins, ymin, ymax)));
mXYPerStationTkD.push_back(std::unique_ptr<TH2D>(new TH2D(tkd_name.c_str(), tkd_title.c_str(),
nbins, xmin, xmax, nbins, ymin, ymax)));
mXYPerStationTkU[iStation]->GetXaxis()->SetTitle(xlabel.c_str());
mXYPerStationTkU[iStation]->GetYaxis()->SetTitle(ylabel.c_str());
mXYPerStationTkD[iStation]->GetXaxis()->SetTitle(xlabel.c_str());
mXYPerStationTkD[iStation]->GetYaxis()->SetTitle(ylabel.c_str());
std::string tku_tri_title = "TkU Triplet Spacepoints XY " + name;
std::string tku_tri_name = "hTkUXYTriplets" + name;
std::string tkd_tri_title = "TkD Triplet Spacepoints XY " + name;
std::string tkd_tri_name = "hTkDXYTriplets" + name;
mXYPerStationTripletsTkU.push_back(std::unique_ptr<TH2D>(new TH2D(tku_tri_name.c_str(),
tku_tri_title.c_str(), nbins, xmin, xmax, nbins, ymin, ymax)));
mXYPerStationTripletsTkD.push_back(std::unique_ptr<TH2D>(new TH2D(tkd_tri_name.c_str(),
tkd_tri_title.c_str(), nbins, xmin, xmax, nbins, ymin, ymax)));
mXYPerStationTripletsTkU[iStation]->GetXaxis()->SetTitle(xlabel.c_str());
mXYPerStationTripletsTkU[iStation]->GetYaxis()->SetTitle(ylabel.c_str());
mXYPerStationTripletsTkD[iStation]->GetXaxis()->SetTitle(xlabel.c_str());
mXYPerStationTripletsTkD[iStation]->GetYaxis()->SetTitle(ylabel.c_str());
std::string tku_dou_title = "TkU Doublet Spacepoints XY " + name;
std::string tku_dou_name = "hTkUXYDoublets" + name;
std::string tkd_dou_title = "TkD Doublets Spacepoints XY " + name;
std::string tkd_dou_name = "hTkDXYDoublets" + name;
mXYPerStationDoubletsTkU.push_back(std::unique_ptr<TH2D>(new TH2D(tku_dou_name.c_str(),
tku_dou_title.c_str(), nbins, xmin, xmax, nbins, ymin, ymax)));
mXYPerStationDoubletsTkD.push_back(std::unique_ptr<TH2D>(new TH2D(tkd_dou_name.c_str(),
tkd_dou_title.c_str(), nbins, xmin, xmax, nbins, ymin, ymax)));
mXYPerStationDoubletsTkU[iStation]->GetXaxis()->SetTitle(xlabel.c_str());
mXYPerStationDoubletsTkU[iStation]->GetYaxis()->SetTitle(ylabel.c_str());
mXYPerStationDoubletsTkD[iStation]->GetXaxis()->SetTitle(xlabel.c_str());
mXYPerStationDoubletsTkD[iStation]->GetYaxis()->SetTitle(ylabel.c_str());
}
}
bool AnalyserTrackerSpacePoints::analyse(MAUS::ReconEvent* const aReconEvent,
MAUS::MCEvent* const aMCEvent) {
if (!aReconEvent)
return false;
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
if (!sfevt)
return false;
// std::cerr << "Found " << sfevt->scifitracks().size() << " tracks" << std::endl;
for (auto sp : sfevt->spacepoints()) {
if (sp->get_tracker() == 0) {
mHNpeTKU->Fill(sp->get_npe());
mHStationNumTKU->Fill(sp->get_station());
mHXYTKU->Fill(sp->get_position().x(), sp->get_position().y());
mXYPerStationTkU[sp->get_station() - 1]->Fill(sp->get_position().x(), sp->get_position().y());
if (sp->get_channels_pointers().size() == 3) {
mXYPerStationTripletsTkU[sp->get_station() - 1]->Fill(sp->get_position().x(),
sp->get_position().y());
} else if (sp->get_channels_pointers().size() == 2) {
mXYPerStationDoubletsTkU[sp->get_station() - 1]->Fill(sp->get_position().x(),
sp->get_position().y());
}
} else {
mHNpeTKD->Fill(sp->get_npe());
mHStationNumTKD->Fill(sp->get_station());
mHXYTKD->Fill(sp->get_position().x(), sp->get_position().y());
mXYPerStationTkD[sp->get_station() - 1]->Fill(sp->get_position().x(), sp->get_position().y());
if (sp->get_channels_pointers().size() == 3) {
mXYPerStationTripletsTkD[sp->get_station() - 1]->Fill(sp->get_position().x(),
sp->get_position().y());
} else if (sp->get_channels_pointers().size() == 2) {
mXYPerStationDoubletsTkD[sp->get_station() - 1]->Fill(sp->get_position().x(),
sp->get_position().y());
}
}
}
return true;
}
bool AnalyserTrackerSpacePoints::draw(std::shared_ptr<TVirtualPad> aPad) {
// Draw the general spacepoint information plots
GetPads()[0]->Divide(3, 2);
GetPads()[0]->cd(1);
mHXYTKU->Draw("COLZ");
GetPads()[0]->cd(2);
mHStationNumTKU->Draw();
GetPads()[0]->cd(3);
mHNpeTKU->Draw();
GetPads()[0]->cd(4);
mHXYTKD->Draw("COLZ");
GetPads()[0]->cd(5);
mHStationNumTKD->Draw();
GetPads()[0]->cd(6);
mHNpeTKD->Draw();
// Draw the real space plots per station
int nStations = 5;
std::shared_ptr<TVirtualPad> padXY = std::shared_ptr<TVirtualPad>(new TCanvas());
std::shared_ptr<TVirtualPad> padXYTriplets = std::shared_ptr<TVirtualPad>(new TCanvas());
std::shared_ptr<TVirtualPad> padXYDoublets = std::shared_ptr<TVirtualPad>(new TCanvas());
padXY->Divide(nStations, 2);
padXYTriplets->Divide(nStations, 2);
padXYDoublets->Divide(nStations, 2);
for (int iStation = 0; iStation < nStations; ++iStation) {
padXY->cd(iStation+1);
mXYPerStationTkU[iStation]->Draw("COLZ");
padXYTriplets->cd(iStation+1);
mXYPerStationTripletsTkU[iStation]->Draw("COLZ");
padXYDoublets->cd(iStation+1);
mXYPerStationDoubletsTkU[iStation]->Draw("COLZ");
padXY->cd(nStations+iStation+1);
mXYPerStationTkD[iStation]->Draw("COLZ");
padXYTriplets->cd(nStations+iStation+1);
mXYPerStationTripletsTkD[iStation]->Draw("COLZ");
padXYDoublets->cd(nStations+iStation+1);
mXYPerStationDoubletsTkD[iStation]->Draw("COLZ");
}
// Add the pads
AddPad(padXY);
AddPad(padXYTriplets);
AddPad(padXYDoublets);
return true;
}
void AnalyserTrackerSpacePoints::merge(AnalyserTrackerSpacePoints* aAnalyser) {
mHNpeTKU->Add(aAnalyser->mHNpeTKU.get());
mHNpeTKD->Add(aAnalyser->mHNpeTKD.get());
mHStationNumTKU->Add(aAnalyser->mHStationNumTKU.get());
mHStationNumTKD->Add(aAnalyser->mHStationNumTKD.get());
mHXYTKU->Add(aAnalyser->mHXYTKU.get());
mHXYTKD->Add(aAnalyser->mHXYTKD.get());
for (int i = 0; i < mNStations; ++i) {
mXYPerStationTkU[i]->Add(aAnalyser->mXYPerStationTkU[i].get());
mXYPerStationTkD[i]->Add(aAnalyser->mXYPerStationTkD[i].get());
mXYPerStationTripletsTkU[i]->Add(aAnalyser->mXYPerStationTripletsTkU[i].get());
mXYPerStationTripletsTkD[i]->Add(aAnalyser->mXYPerStationTripletsTkD[i].get());
mXYPerStationDoubletsTkU[i]->Add(aAnalyser->mXYPerStationDoubletsTkU[i].get());
mXYPerStationDoubletsTkD[i]->Add(aAnalyser->mXYPerStationDoubletsTkD[i].get());
}
}
} // ~namespace mica
<file_sep>/include/mica/AnalyserTrackerMCPRResiduals.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef AnalyserTrackerMCPRResiduals_HH
#define AnalyserTrackerMCPRResiduals_HH
#include <vector>
#include "TVirtualPad.h"
#include "TH1.h"
#include "TH2.h"
#include "mica/IAnalyser.hh"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
namespace mica {
/** @class AnalyserTrackerMCPRResiduals
* Analyser class which calculates pattern recognition position and momentum residuals.
* @author <NAME>
*/
class AnalyserTrackerMCPRResiduals : public IAnalyser<AnalyserTrackerMCPRResiduals> {
public:
AnalyserTrackerMCPRResiduals();
virtual ~AnalyserTrackerMCPRResiduals() {}
private:
virtual bool analyse(MAUS::ReconEvent* const aReconEvent,
MAUS::MCEvent* const aMCEvent) override;
virtual bool draw(std::shared_ptr<TVirtualPad> aPad) override;
virtual void merge(AnalyserTrackerMCPRResiduals* aAnalyser) override;
const double mBfield = 3.0;
TH1D* mHTkUMCPositionX;
TH1D* mHTkUMCPositionY;
TH1D* mHTkUMCMomentumT;
TH1D* mHTkUMCMomentumZ;
TH1D* mHTkURecPositionX;
TH1D* mHTkURecPositionY;
TH1D* mHTkURecMomentumT;
TH1D* mHTkURecMomentumZ;
TH1D* mHTkUPositionResidualsX;
TH1D* mHTkUPositionResidualsY;
TH1D* mHTkUMomentumResidualsT;
TH1D* mHTkUMomentumResidualsZ;
TH2D* mHTkUPtResPt;
TH2D* mHTkUPzResPt;
TH2D* mHTkUPtResPzRec;
TH2D* mHTkUPzResPzRec;
TH1D* mHTkDMCPositionX;
TH1D* mHTkDMCPositionY;
TH1D* mHTkDMCMomentumT;
TH1D* mHTkDMCMomentumZ;
TH1D* mHTkDRecPositionX;
TH1D* mHTkDRecPositionY;
TH1D* mHTkDRecMomentumT;
TH1D* mHTkDRecMomentumZ;
TH1D* mHTkDPositionResidualsX;
TH1D* mHTkDPositionResidualsY;
TH1D* mHTkDMomentumResidualsT;
TH1D* mHTkDMomentumResidualsZ;
TH2D* mHTkDPtResPt;
TH2D* mHTkDPzResPt;
TH2D* mHTkDPtResPzRec;
TH2D* mHTkDPzResPzRec;
};
} // ~namespace mica
#endif
<file_sep>/src/CutsBase.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
<file_sep>/include/mica/AnalyserTrackerMC.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef ANALYSERTRACKERMC_HH
#define ANALYSERTRACKERMC_HH
#include <vector>
#include <map>
#include "TVirtualPad.h"
#include "TH2.h"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
#include "mica/AnalyserBase.hh"
#include "src/common_cpp/Recon/SciFi/SciFiLookup.hh"
namespace mica {
/** @struct MCTrackData
* Simple data container to hold tracker track info deduced from MC
* @author <NAME>
*/
struct MCTrackData {
int tracker; ///< The tracker number, 0 = TkU, 1 = TkD
int track_id; ///< The track id number
int pid; ///< The PGD particle id
double energy; ///< The track energy at the analysis plane
MAUS::ThreeVector pos; ///< The track position at the analysis plane
MAUS::ThreeVector mom; ///< The track momentum at the analysis plane
std::vector<int> stations_hit; ///< The tracker stations the track created hits in
};
/** @class AnalyserTrackerMC
* Analyser class which calculates tracker data using MC info.
* Daughter classes then use that data for actual analysis. The data produced is held in
* MCTrackData members for TkU and TkD separately.
* @author <NAME>
*/
class AnalyserTrackerMC : public AnalyserBase {
public:
AnalyserTrackerMC();
~AnalyserTrackerMC();
/** @brief Delete the lookup table and set the member pointer to nullptr */
virtual void clear_lookup();
/** @brief Cycle through data vectors, delete every object, set vectors to zero size */
virtual void clear_mc_data();
/** @brief Return the scifi MC lookup table */
MAUS::SciFiLookup* GetLookup() const { return mLookup; }
/** @brief Return the calculated mc data for TkU */
std::vector<MCTrackData*> GetMCDataTkU() const { return mMCDataTkU; }
/** @brief Return the calculated mc data for TkD */
std::vector<MCTrackData*> GetMCDataTkD() const { return mMCDataTkD; }
/** Create a map from mc track ids to vectors containing the station numbers for which
* that track generated hits in mNPlanes or more planes (usually = 3) i.e. a spacepoint
* from the track is expected in each of the stations listed in the vector.
* To be used with one tracker at a time.
* @param[in] hit_map A map from mc track ids to the the SciFiHits produced by that tracker
* for a single tracker.
* @param[in] aNPlanes The number planes per station which need to be hit for the station
* to count as one hit by the track
* @return A map from mc track ids to vectors containing the station numbers for which
* that track generated hits in mNPlanes or more planes, for a single tracker
*/
std::map<int, std::vector<int> > calc_stations_hit_by_track( \
std::map<int, std::vector<MAUS::SciFiHit*> >& hit_map, int aNPlanes);
private:
virtual bool analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) override;
/** @brief Analyse MC data, calls fill_mc_track_data and make_lookup
* @param[in] aMCEvent MCEvent to analyse
* @return Did the analysis succeed
*/
virtual bool analyse_mc(MAUS::MCEvent* const aMCEvent);
/** @brief Analyse the recon data, to be implemented in daughter classes
* @param[in] aReconEvent MAUS::ReconEvent to analyse, corresponding to aMCEvent
* @return Did the analysis succeed
*/
virtual bool analyse_recon(MAUS::ReconEvent* const aReconEvent) = 0;
int mRefStation; ///< Reference surface to use
int mRefPlane; ///< Reference plane to use
int mNStations; ///< # of stations hit for event to be classed as reconstructible
int mNPlanes; ///< # of planes hit per station hit for event to be classed as reconstructible
std::vector<MCTrackData*> mMCDataTkU; ///< MC data for TkU, AnalyserTrackerMC owns the memory
std::vector<MCTrackData*> mMCDataTkD; ///< MC data for TkD, AnalyserTrackerMC owns the memory
MAUS::SciFiLookup* mLookup; ///< The Lookup table, AnalyserTrackerMC owns the memory
/** @brief Populate the mMCData members
* @param[in] aMCEvent MAUS::MCEvent to analyse
* @return Did the data members get populated successfully
*/
bool fill_mc_track_data(MAUS::MCEvent* const aMCEvent);
/** @brief Populate the lookup table member
* @param[in] aMCEvent MCEvent to analyse
* @return Was the lookup successfully created
*/
bool make_lookup(MAUS::MCEvent* const aMCEvent);
};
} // ~namespace mica
#endif
<file_sep>/README.md
# MICA - Muon Ionization Cooling Analysis
Author - <NAME>
MICA is an analysis framework for the Muon Ionization Cooling Experiment. It is dependent on the MICE reconstruction software, MAUS.
## Installation instructions
* Make a directory for the project
```bash
mkdir mica
cd mica
```
* Obtain the source code by cloning the MICA repository with git into a subdirectory:
```bash
git clone <EMAIL>:ajdobbs/mica.git source
```
or, if you do not have a github login, clone anonymously with:
```bash
git clone https://github.com/ajdobbs/mica.git source
```
* Source an existing MAUS installation (see http://micewww.pp.rl.ac.uk/projects/maus/wiki/Install)
```bash
source /path/to/maus/env.sh
```
* Make a build directory
```bash
mkdir build
cd build
```
* Build using CMake
```bash
cmake ../source/ -DCMAKE_INSTALL_PREFIX:PATH=/path/to/install/directory
make -jN
```
where the last argument to cmake is optional, specifying a custom installation directory, and N is the
number of cores to build with.
* To clean a build, simply delete everything in your build directory
* Installation
If you wish you to install MICA rather than running from the build directory, do:
```bash
make install
```
Note: if using a custom installation directory, you may need to update LD_LIBRARY_PATH and PATH:
```bash
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/path/to/install/directory/lib
export PATH=${PATH}:/path/to/install/directory/bin
```
## Usage
Run an analysis with:
```bash
./bin/mica /path/to/maus/recon/data/maus_output.root
```
The output can then be found in ```analysis.pdf```.
<file_sep>/src/AnalyserTrackerPREfficiency.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include <string>
#include <vector>
#include "TCanvas.h"
#include "TLatex.h"
#include "mica/AnalyserTrackerPREfficiency.hh"
#include "src/common_cpp/DataStructure/TOFEvent.hh"
#include "src/common_cpp/DataStructure/SciFiEvent.hh"
#include "src/common_cpp/DataStructure/SciFiBasePRTrack.hh"
#include "src/common_cpp/DataStructure/SciFiHelicalPRTrack.hh"
#include "src/common_cpp/DataStructure/SciFiStraightPRTrack.hh"
#include "src/common_cpp/DataStructure/SciFiSpacePoint.hh"
namespace mica {
AnalyserTrackerPREfficiency::AnalyserTrackerPREfficiency() : mCheckTOF(true),
mCheckTOFSpacePoints(true),
mAllowMultiHitStations(true),
mCheckTkU(true),
mCheckTkD(true),
mNEvents(0),
mTkUGoodEvents(0),
mTkU5ptTracks(0),
mTkU4to5ptTracks(0),
mTkDGoodEvents(0),
mTkD5ptTracks(0),
mTkD4to5ptTracks(0),
mLowerTimeCut(27.0),
mUpperTimeCut(50.0) {
// mOf1.open("tracker-patrec-efficiency.txt");
}
AnalyserTrackerPREfficiency::~AnalyserTrackerPREfficiency() {
// mOf1.close();
}
bool AnalyserTrackerPREfficiency::analyse(MAUS::ReconEvent* const aReconEvent,
MAUS::MCEvent* const aMCEvent) {
if (!aReconEvent)
return false;
++mNEvents;
MAUS::TOFEvent* tofevt = aReconEvent->GetTOFEvent();
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
// Check if we a good expected track event in TkU and separately in TkD
// --------------------------------------------------------------------
// Bools to hold if after considering all relevant detectors including trackers
// we expect to have reconstructed one track in the trackers (tku and tkd separately)
bool good_event_tku = false;
bool good_event_tkd = false;
// Check TOF
bool good_tof = check_good_tof_event(tofevt);
// Check TkU, but don't don't look at recon tracks yet, only up to spacepoints
bool good_tku_4pt = false; // Should reconstruct a 4pt, not enough sp for 5pt
bool good_tku_5pt = false; // Should reconstrcut full 5pt
if (mCheckTkU) {
check_good_tk_event(sfevt, 0, good_tku_4pt, good_tku_5pt);
} else {
good_tku_4pt = true;
good_tku_5pt = true;
}
// For now, only call an event good if we expect a full 5pt track
if (good_tof && good_tku_5pt) {
good_event_tku = true;
++mTkUGoodEvents;
}
// Check TkD but don't don't look at recon tracks yet, only up to spacepoints
bool good_tkd_4pt = false; // Should reconstruct a 4pt, not enough sp for 5pt
bool good_tkd_5pt = false; // Should reconstrcut full 5pt
if (mCheckTkD) {
check_good_tk_event(sfevt, 1, good_tkd_4pt, good_tkd_5pt);
} else {
good_tkd_4pt = true;
good_tkd_5pt = true;
}
// For now, only call an event good if we expect a full 5pt track
if (good_tof && good_tkd_5pt) {
good_event_tkd = true;
++mTkDGoodEvents;
}
// Save some time and stop here is neither tracker has a good event
if (!good_event_tku && !good_event_tkd)
return true;
// Check if patrec actually reconstructed the track as expected
// ------------------------------------------------------------
// Sort by tracker
std::vector<MAUS::SciFiBasePRTrack*> tku;
std::vector<MAUS::SciFiBasePRTrack*> tkd;
std::vector<MAUS::SciFiHelicalPRTrack*> htrks = sfevt->helicalprtracks();
for (auto trk : htrks) {
if (trk->get_tracker() == 0) {
tku.push_back(trk);
} else {
tkd.push_back(trk);
}
}
std::vector<MAUS::SciFiStraightPRTrack*> strks = sfevt->straightprtracks();
for (auto trk : strks) {
if (trk->get_tracker() == 0) {
tku.push_back(trk);
} else {
tkd.push_back(trk);
}
}
// If we have a good event and only one track, increment the counters
if (good_event_tku && tku.size() == 1) {
++mTkU4to5ptTracks;
if (tku[0]->get_num_points() == 5)
++mTkU5ptTracks;
}
if (good_event_tkd && tkd.size() == 1) {
++mTkD4to5ptTracks;
if (tkd[0]->get_num_points() == 5)
++mTkD5ptTracks;
}
// All done for this event
return true;
}
void AnalyserTrackerPREfficiency::clear() {
mNEvents = 0;
mTkUGoodEvents = 0;
mTkU5ptTracks = 0;
mTkU4to5ptTracks = 0;
mTkDGoodEvents = 0;
mTkD5ptTracks = 0;
mTkD4to5ptTracks = 0;
}
void AnalyserTrackerPREfficiency::check_good_tk_event(MAUS::SciFiEvent* evt, int trker_num,
bool& good4pt, bool& good5pt) {
good4pt = false;
good5pt = false;
if (!evt)
return;
// Check number of spacepoints per station meets cuts
std::vector<int> num_spoints_per_station(5, 0); // length 5, all zeros
for (auto sp : evt->spacepoints()) {
if (sp->get_tracker() != trker_num)
continue;
++(num_spoints_per_station.at(sp->get_station() - 1));
}
int stations_empty = 0; // num stations with less than 1 sp
int stations_multi = 0; // num stations with more than 1 sp
int stations_hit = 0; // num stations with more than 0 sp
int stations_ideal = 0; // num stations with exactly 1 sp
for (int n : num_spoints_per_station) {
if (n < 1)
++stations_empty;
if (n > 1)
++stations_multi;
if (n > 0)
++stations_hit;
if (n == 1)
++stations_ideal;
}
// Do we want idea events only (1 sp only per tracker station) or allow multiple sp
// per station, just not in enough stations for more than one track to be possible?
int stations_multi_cut = 4; // Non ideal allowed
if (!mAllowMultiHitStations)
stations_multi_cut = 1; // Ideal events only
// Require 4 stations ONLY are hit
if (stations_hit == 4 && stations_multi < stations_multi_cut)
good4pt = true;
// Require all 5 stations are hit
if (stations_hit == 5 && stations_multi < stations_multi_cut)
good5pt = true;
return;
}
bool AnalyserTrackerPREfficiency::check_good_tof_event(MAUS::TOFEvent* evt) {
// Do we care about TOF? If not return true
if (!mCheckTOF && !mCheckTOFSpacePoints)
return true;
// If we care about TOF but the data is missing, return false
if (!evt)
return false;
if (!evt->GetTOFEventSpacePointPtr())
return false;
// Check the TOF spacepoints - 1 and only 1 in TOF1 and 1 and only 1 in TOF2
// Note: If we are checking the actual time-of-flight we need this to be true, so we do not
// need to mCheckTOFSpacePoints, as we already know one of our two flags must be true
std::vector<MAUS::TOFSpacePoint>* tof1_spoints = \
evt->GetTOFEventSpacePointPtr()->GetTOF1SpacePointArrayPtr();
std::vector<MAUS::TOFSpacePoint>* tof2_spoints = \
evt->GetTOFEventSpacePointPtr()->GetTOF2SpacePointArrayPtr();
if (!tof1_spoints || !tof2_spoints) {
return false;
}
if ((tof1_spoints->size() != 1) || (tof2_spoints->size() != 1))
return false;
// OK, if we have reached this point, then the tof spacepoints criteria is satisfied,
// if we are not looking at tof timing we can return true
if (!mCheckTOF)
return true;
// Lastly, check the time-of-flight between TOF1 and TOF2
double dt = tof2_spoints->at(0).GetTime() - tof1_spoints->at(0).GetTime();
if (dt > mLowerTimeCut && dt < mUpperTimeCut)
return true;
// We should only arrive here if everything passed except the time-of-flight cut
return false;
}
bool AnalyserTrackerPREfficiency::draw(std::shared_ptr<TVirtualPad> aPad) {
double tku_5pt_eff = static_cast<double>(mTkU5ptTracks) / static_cast<double>(mTkUGoodEvents);
double tku_4to5pt_eff =
static_cast<double>(mTkU4to5ptTracks) / static_cast<double>(mTkUGoodEvents);
double tkd_5pt_eff = static_cast<double>(mTkD5ptTracks) / static_cast<double>(mTkDGoodEvents);
double tkd_4to5pt_eff =
static_cast<double>(mTkD4to5ptTracks) / static_cast<double>(mTkDGoodEvents);
std::cerr << mNEvents << " "
<< mTkU5ptTracks << " " << mTkU4to5ptTracks << " " << mTkUGoodEvents << " "
<< mTkD5ptTracks << " " << mTkD4to5ptTracks << " " << mTkDGoodEvents << " "
<< tku_5pt_eff << " " << tku_4to5pt_eff
<< " " << tkd_5pt_eff << " " << tkd_4to5pt_eff << std::endl;
TLatex tl;
tl.SetTextSize(0.05);
tl.DrawLatex(0.1, 0.9, "PatRec Efficiency");
tl.SetTextSize(0.03);
std::string boolstring_tku = "false";
std::string boolstring_tkd = "false";
std::string boolstring_tof = "false";
std::string boolstring_tof_sp = "false";
if (mCheckTkU)
boolstring_tku = "true";
else
boolstring_tku = "false";
if (mCheckTkD)
boolstring_tkd = "true";
else
boolstring_tkd = "false";
if (mCheckTOF)
boolstring_tof = "true";
else
boolstring_tof = "false";
if (mCheckTOF || mCheckTOFSpacePoints)
boolstring_tof_sp = "true";
else
boolstring_tof_sp = "false";
double tline = 0.8;
double sep = 0.075;
tl.DrawLatex(0.1, tline, ("Check TkU spacepoints: " + boolstring_tku).c_str());
tl.DrawLatex(0.1, tline-sep, ("Check TkD spacepoints: " + boolstring_tkd).c_str());
tl.DrawLatex(0.1, tline-sep*2, ("Check TOF1 and TOF2 spacepoints: "
+ boolstring_tof_sp).c_str());
tl.DrawLatex(0.1, tline-sep*3, ("Check time-of-flight TOF2 - TOF1 : " + boolstring_tof).c_str());
tl.DrawLatex(0.1, tline-sep*4, ("Total Number of Events: " + std::to_string(mNEvents)).c_str());
tl.DrawLatex(0.1, tline-sep*5, ("TkU 5pt Efficiency: " + std::to_string(tku_5pt_eff) + " ("
+ std::to_string(mTkU5ptTracks) + "/" + std::to_string(mTkUGoodEvents) + ")").c_str());
tl.DrawLatex(0.1, tline-sep*6, ("TkU 4-5pt Efficiency: " + std::to_string(tku_4to5pt_eff) + " ("
+ std::to_string(mTkU4to5ptTracks) + "/" + std::to_string(mTkUGoodEvents) + ")").c_str());
tl.DrawLatex(0.1, tline-sep*7, ("TkD 5pt Efficiency: " + std::to_string(tkd_5pt_eff) + " ("
+ std::to_string(mTkD5ptTracks) + "/" + std::to_string(mTkDGoodEvents) + ")").c_str());
tl.DrawLatex(0.1, tline-sep*8, ("TkU 4-5pt Efficiency: " + std::to_string(tkd_4to5pt_eff) + " ("
+ std::to_string(mTkD4to5ptTracks)+ "/" + std::to_string(mTkDGoodEvents) + ")").c_str());
GetPads()[0]->cd();
tl.Draw();
GetPads()[0]->Update();
return true;
}
} // ~namespace mica
<file_sep>/src/AnalyserTrackerPRSeedResidual.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "mica/AnalyserTrackerPRSeedResidual.hh"
#include <string>
namespace mica {
AnalyserTrackerPRSeedResidual::AnalyserTrackerPRSeedResidual() : mLogScale {false} {
for (int i = 0; i < 5; ++i) {
std::string tku_title = "TkU Seed Residual Station " + std::to_string(i+1);
std::string tku_name= "hResidualsTkUS" + std::to_string(i+1);
mHResidualsTkU.push_back(new TH1D(tku_name.c_str(), tku_title.c_str(), 100, -30, 30));
mHResidualsTkU[i]->GetXaxis()->SetTitle("Residual (mm)");
std::string tkd_title = "TkD Seed Residual Station " + std::to_string(i+1);
std::string tkd_name = "hResidualsTkDS" + std::to_string(i+1);
mHResidualsTkD.push_back(new TH1D(tkd_name.c_str(), tkd_title.c_str(), 100, -30, 30));
mHResidualsTkD[i]->GetXaxis()->SetTitle("Residual (mm)");
}
}
bool AnalyserTrackerPRSeedResidual::analyse(MAUS::ReconEvent* const aReconEvent,
MAUS::MCEvent* const aMCEvent) {
if (!aReconEvent)
return false;
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
for (auto trk : sfevt->helicalprtracks()) {
for (auto sp : trk->get_spacepoints_pointers()) {
double npe = sp->get_npe();
double pull = sp->get_prxy_pull();
if (sp->get_tracker() == 0) {
mHResidualsTkU[sp->get_station() - 1]->Fill(pull);
} else {
mHResidualsTkD[sp->get_station() - 1]->Fill(pull);
}
} // Loop over seed spacepoints
} // ~Loop over tracks
return true;
}
bool AnalyserTrackerPRSeedResidual::draw(std::shared_ptr<TVirtualPad> aPad) {
GetStyle()->SetOptStat(111111);
GetPads()[0]->Divide(5, 2);
for (int i = 0; i < 5; ++i) {
GetPads()[0]->cd(i+1);
if (mLogScale) GetPads()[0]->GetPad(i+1)->SetLogy(1);
mHResidualsTkU[i]->Draw();
GetPads()[0]->cd(i+6);
if (mLogScale) GetPads()[0]->GetPad(i+6)->SetLogy(1);
mHResidualsTkD[i]->Draw();
}
return true;
}
} // ~namespace mica
<file_sep>/include/mica/CutsBase.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef CUTSBASE_HH
#define CUTSBASE_HH
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
namespace mica {
/** @class CutsBase
* Base class for cuts, main Cut method returns true if event passes cut, false otherwise
* @author <NAME>
*/
class CutsBase {
public:
CutsBase() {}
virtual ~CutsBase() {}
/** @brief Apply the cut to the event, return true if passed, false if not */
virtual bool Cut(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) = 0;
};
} // ~namespace mica
#endif
<file_sep>/src/AnalyserFactory.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "mica/AnalyserFactory.hh"
#include "mica/AnalyserTofTracker.hh"
#include "mica/AnalyserTrackerAngularMomentum.hh"
#include "mica/AnalyserTrackerChannelHits.hh"
#include "mica/AnalyserTrackerKFMomentum.hh"
#include "mica/AnalyserTrackerKFStats.hh"
#include "mica/AnalyserTrackerMCPRResiduals.hh"
#include "mica/AnalyserTrackerMCPurity.hh"
#include "mica/AnalyserTrackerPREfficiency.hh"
#include "mica/AnalyserTrackerPRSeedNPEResidual.hh"
#include "mica/AnalyserTrackerPRSeedResidual.hh"
#include "mica/AnalyserTrackerPRStats.hh"
#include "mica/AnalyserTrackerSpacePoints.hh"
#include "mica/AnalyserTrackerSpacePointSearch.hh"
#include "mica/AnalyserTrackerSpacePointSearchStation.hh"
#include "mica/AnalyserViewerRealSpace.hh"
namespace mica {
AnalyserBase* AnalyserFactory::CreateAnalyser(const std::string& aName) {
if (aName == "AnalyserTofTracker") return new AnalyserTofTracker();
if (aName == "AnalyserTrackerAngularMomentum") return new AnalyserTrackerAngularMomentum();
if (aName == "AnalyserTrackerChannelHits") return new AnalyserTrackerChannelHits();
if (aName == "AnalyserTrackerKFMomentum") return new AnalyserTrackerKFMomentum();
if (aName == "AnalyserTrackerKFStats") return new AnalyserTrackerKFStats();
if (aName == "AnalyserTrackerMCPRResiduals") return new AnalyserTrackerMCPRResiduals();
if (aName == "AnalyserTrackerMCPurity") return new AnalyserTrackerMCPurity();
if (aName == "AnalyserTrackerPREfficiency") return new AnalyserTrackerPREfficiency();
if (aName == "AnalyserTrackerPRSeedNPEResidual") return new AnalyserTrackerPRSeedNPEResidual();
if (aName == "AnalyserTrackerPRSeedResidual") return new AnalyserTrackerPRSeedResidual();
if (aName == "AnalyserTrackerPRStats") return new AnalyserTrackerPRStats();
if (aName == "AnalyserTrackerSpacePoints") return new AnalyserTrackerSpacePoints();
if (aName == "AnalyserTrackerSpacePointSearch") return new AnalyserTrackerSpacePointSearch();
if (aName == "AnalyserTrackerSpacePointSearchStation")
return new AnalyserTrackerSpacePointSearchStation();
if (aName == "AnalyserViewerRealSpace") return new AnalyserViewerRealSpace();
return nullptr;
}
std::vector<AnalyserBase*> AnalyserFactory::CreateAnalysers(const std::vector<std::string>& aNames) {
std::vector<AnalyserBase*> analysers;
for (auto s : aNames) {
analysers.push_back(CreateAnalyser(s));
}
return analysers;
}
AnalyserGroup AnalyserFactory::CreateAnalyserGroup(const std::vector<std::string>& aNames) {
AnalyserGroup analysers;
for (auto s : aNames) {
analysers.AddAnalyser(CreateAnalyser(s));
}
return analysers;
}
std::shared_ptr<AnalyserBase> AnalyserFactory::CreateSharedAnalyser(const std::string &aName) {
return std::shared_ptr<AnalyserBase>(CreateAnalyser(aName));
}
std::vector<std::shared_ptr<AnalyserBase>>
AnalyserFactory::CreateSharedAnalysers(const std::vector<std::string>& aNames) {
std::vector<std::shared_ptr<AnalyserBase>> analysers;
for (auto s : aNames) {
analysers.push_back(CreateSharedAnalyser(s));
}
return analysers;
}
std::unique_ptr<AnalyserBase> AnalyserFactory::CreateUniqueAnalyser(const std::string &aName) {
return std::unique_ptr<AnalyserBase>(CreateAnalyser(aName));
}
std::vector<std::unique_ptr<AnalyserBase>>
AnalyserFactory::CreateUniqueAnalysers(const std::vector<std::string>& aNames) {
std::vector<std::unique_ptr<AnalyserBase>> analysers;
for (auto s : aNames) {
analysers.push_back(CreateUniqueAnalyser(s));
}
return analysers;
}
} // ~namespace mica
<file_sep>/src/AnalyserTrackerPRStats.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "mica/AnalyserTrackerPRStats.hh"
#include "src/common_cpp/DataStructure/SciFiEvent.hh"
#include "src/common_cpp/DataStructure/SciFiSpacePoint.hh"
namespace mica {
AnalyserTrackerPRStats::AnalyserTrackerPRStats() : mHCircleChiSqTKU(NULL),
mHCircleChiSqTKD(NULL),
mHSZChiSqTKU(NULL),
mHSZChiSqTKD(NULL) {
int nbins = 100;
mHCircleChiSqTKU = new TH1D("hCircleChiSqTKU", "PR Circle #chi^{2}_{\nu} TkU", nbins, 0, 20);
mHCircleChiSqTKU->GetXaxis()->SetTitle("Circle #chi^{2}_{\nu} ");
mHCircleChiSqTKD = new TH1D("hCircleChiSqTKD", "PR Circle #chi^{2}_{\nu} TkD", nbins, 0, 20);
mHCircleChiSqTKD->GetXaxis()->SetTitle("Circle #chi^{2}_{\nu} ");
mHSZChiSqTKU = new TH1D("hSZChiSqTKU", "PR SZ #chi^{2}_{\nu} TkU", nbins, 0, 50);
mHSZChiSqTKU->GetXaxis()->SetTitle("SZ #chi^{2}_{\nu} ");
mHSZChiSqTKD = new TH1D("hSZChiSqTKD", "PR SZ #chi^{2}_{\nu} TkD", nbins, 0, 50);
mHSZChiSqTKD->GetXaxis()->SetTitle("SZ #chi^{2}_{\nu} ");
}
bool AnalyserTrackerPRStats::analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) {
if (!aReconEvent)
return false;
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
if (!sfevt)
return false;
for (auto trk : sfevt->helicalprtracks()) {
if (trk->get_tracker() == 0) {
mHCircleChiSqTKU->Fill(trk->get_circle_chisq() / trk->get_circle_ndf());
mHSZChiSqTKU->Fill(trk->get_line_sz_chisq() / trk->get_line_sz_ndf() );
} else if (trk->get_tracker() == 1) {
mHCircleChiSqTKD->Fill(trk->get_circle_chisq() / trk->get_circle_ndf());
mHSZChiSqTKD->Fill(trk->get_line_sz_chisq() / trk->get_line_sz_ndf());
}
}
}
bool AnalyserTrackerPRStats::draw(std::shared_ptr<TVirtualPad> aPad) {
GetStyle()->SetOptStat(111111);
GetPads()[0]->Divide(4, 2);
GetPads()[0]->cd(1);
mHCircleChiSqTKU->Draw();
GetPads()[0]->cd(2);
GetPads()[0]->GetPad(2)->SetLogy(1);
mHCircleChiSqTKU->Draw();
GetPads()[0]->cd(3);
mHSZChiSqTKU->Draw();
GetPads()[0]->cd(4);
GetPads()[0]->GetPad(4)->SetLogy(1);
mHSZChiSqTKU->Draw();
GetPads()[0]->cd(5);
mHCircleChiSqTKD->Draw();
GetPads()[0]->cd(6);
GetPads()[0]->GetPad(6)->SetLogy(1);
mHCircleChiSqTKD->Draw();
GetPads()[0]->cd(7);
mHSZChiSqTKD->Draw();
GetPads()[0]->cd(8);
GetPads()[0]->GetPad(8)->SetLogy(1);
mHSZChiSqTKD->Draw();
return true;
}
} // ~namespace mica
<file_sep>/src/AnalyserBase.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "TCanvas.h"
#include "mica/AnalyserBase.hh"
namespace mica {
AnalyserBase::AnalyserBase() {
mStyle = std::make_shared<TStyle>(*gStyle); // Make a style for this analyser
// AddPad(std::shared_ptr<TVirtualPad>(new TCanvas())); // Have a default canvas ready
}
AnalyserBase::~AnalyserBase() {
// Do nothing (members are shared pointers which will take care of themselves)
}
bool AnalyserBase::ApplyCuts(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) {
for (auto cut : mCuts) {
bool result = cut->Cut(aReconEvent, aMCEvent);
if (!result)
return false;
}
return true;
}
bool AnalyserBase::Analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) {
bool result = ApplyCuts(aReconEvent, aMCEvent);
if (!result)
return false;
return analyse(aReconEvent, aMCEvent);
}
std::shared_ptr<TVirtualPad> AnalyserBase::Draw() {
if (mPads.size() == 0) { // No canvases ready so set one up
AddPad(std::shared_ptr<TVirtualPad>(new TCanvas()));
}
bool success = draw(GetPads()[0]);
return mPads[0];
}
} // ~namespace mica
<file_sep>/src/AnalyserGroup.cc
#include "mica/AnalyserGroup.hh"
namespace mica {
bool AnalyserGroup::Analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) {
bool success = true;
for (auto an : mAnalysers) {
bool lSuccess = an->Analyse(aReconEvent, aMCEvent);
if (!lSuccess) success = false;
}
return success;
}
// AnalyserGroup* AnalyserGroup::Clone() {
// AnalyserGroup* newGroup = new AnalyserGroup();
// for (auto an : mAnalysers) {
// newGroup->AddAnalyser(mAnalysers.Clone());
// }
// }
std::vector<std::shared_ptr<TVirtualPad>> AnalyserGroup::Draw() {
std::vector<std::shared_ptr<TVirtualPad>> pads;
for (auto an : mAnalysers) {
an->Draw();
auto new_pads = an->GetPads();
pads.insert(std::end(pads), std::begin(new_pads), std::end(new_pads));
}
return pads;
}
void AnalyserGroup::MakePlots(const std::string& ofname) {
std::vector<std::shared_ptr<TVirtualPad>> pads;
std::vector<std::shared_ptr<TStyle> > styles;
for (auto an : mAnalysers) {
an->Draw();
for (auto pad : an->GetPads()) {
if (pad) {
pads.push_back(pad);
styles.push_back(an->GetStyle());
}
}
}
std::cout << "Found " << pads.size() << " canvases, saving to pdf." << std::endl;
for (size_t i = 0; i < pads.size(); ++i) {
if (styles[i]) styles[i]->cd();
pads[i]->Update();
if (i == 0) {
pads[i]->SaveAs((ofname + "(").c_str(), "pdf");
} else if (i == (pads.size() - 1)) {
pads[i]->SaveAs((ofname + ")").c_str(), "pdf");
} else {
pads[i]->SaveAs(ofname.c_str(), "pdf");
}
}
}
bool AnalyserGroup::Merge(AnalyserGroup* aAnalyserGroup) {
if (mAnalysers.size() != aAnalyserGroup->size())
return false;
bool success = true;
for (size_t i = 0; i < mAnalysers.size(); ++i) {
bool lSuccess = mAnalysers[i]->Merge((*aAnalyserGroup)[i]);
if (!lSuccess) success = false;
}
return success;
}
} // ~namespace mica
<file_sep>/include/mica/AnalyserViewerRealSpace.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef ANALYSERVIEWERREALSPACE_HH
#define ANALYSERVIEWERREALSPACE_HH
#include <vector>
#include <memory>
#include "TVirtualPad.h"
#include "TGraph.h"
#include "TF1.h"
#include "TArc.h"
#include "mica/AnalyserBase.hh"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
#include "src/common_cpp/DataStructure/SciFiHelicalPRTrack.hh"
namespace mica {
/** @class AnalyserViewerRealSpace
* Anayser class which produces event viewer plots of real space
* @author <NAME>
*/
class AnalyserViewerRealSpace : public AnalyserBase {
public:
AnalyserViewerRealSpace();
virtual ~AnalyserViewerRealSpace() {}
private:
virtual bool analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) override;
virtual bool draw(std::shared_ptr<TVirtualPad> aPad) override;
virtual void update() override;
void clear_vectors();
TArc make_helix_xy(double x0, double y0, double rad);
TF1 make_str_track(double c, double m, double zmin, double zmax);
TF1 make_helix_xz(int handness, double circle_x0, double rad, double dsdz, double sz_c,
double zmin, double zmax);
TF1 make_helix_yz(double circle_x0, double circle_y0, double rad, double dsdz,
double x0, double y0, double zmin, double zmax);
void print_track_info(const MAUS::SciFiHelicalPRTrack* const trk);
const double mRadToPt = 0.9; //< Assumes 3T field, then bfield * 0.3
const double mZMin = 0.0;
const double mZMax = 1200.0;
std::vector<double> mXTkU;
std::vector<double> mYTkU;
std::vector<double> mZTkU;
std::vector<double> mXTkD;
std::vector<double> mYTkD;
std::vector<double> mZTkD;
std::vector<TArc> mHtrkXYTkU;
std::vector<TF1> mHtrkZXTkU;
std::vector<TF1> mHtrkZYTkU;
std::vector<TArc> mHtrkXYTkD;
std::vector<TF1> mHtrkZXTkD;
std::vector<TF1> mHtrkZYTkD;
std::unique_ptr<TGraph> mGrXYTkU;
std::unique_ptr<TGraph> mGrXYTkD;
std::unique_ptr<TGraph> mGrZXTkU;
std::unique_ptr<TGraph> mGrZXTkD;
std::unique_ptr<TGraph> mGrZYTkU;
std::unique_ptr<TGraph> mGrZYTkD;
};
} // ~namespace mica
#endif
<file_sep>/src/IAnalyser.cc
#include "mica/IAnalyser.hh"
<file_sep>/src/AnalyserTofTracker.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "mica/AnalyserTofTracker.hh"
#include <algorithm>
#include <cmath>
#include "TRef.h"
#include "src/common_cpp/DataStructure/TOFEvent.hh"
#include "src/common_cpp/DataStructure/TOFEventSpacePoint.hh"
#include "src/common_cpp/DataStructure/TOFSpacePoint.hh"
#include "src/common_cpp/DataStructure/SciFiTrack.hh"
#include "src/common_cpp/DataStructure/SciFiTrackPoint.hh"
namespace mica {
AnalyserTofTracker::AnalyserTofTracker() : mAnalysisStation{1},
mAnalysisPlane{0},
mHPTkU{nullptr},
mHPTkD{nullptr},
mHPtTkU{nullptr},
mHPtTkD{nullptr},
mHPzTkU{nullptr},
mHPzTkD{nullptr} {
int nbins = 100;
mHPTkU = std::unique_ptr<TH2D>(new TH2D("hPTkU", "ToF12 Time vs TkU Momentum",
nbins, 25, 50, nbins, 0, 300));
mHPTkU->GetXaxis()->SetTitle("tof12 (ns)");
mHPTkU->GetYaxis()->SetTitle("Total Momentum (MeV/c)");
mHPTkD = std::unique_ptr<TH2D>(new TH2D("hPTkD", "ToF12 Time vs TkD Momentum",
nbins, 25, 50, nbins, 0, 300));
mHPTkD->GetXaxis()->SetTitle("tof12 (ns)");
mHPTkD->GetYaxis()->SetTitle("Total Momentum (MeV/c)");
mHPtTkU = std::unique_ptr<TH2D>(new TH2D("hPtTkU", "ToF12 Time vs TkU pt",
nbins, 25, 50, nbins, 0, 300));
mHPtTkU->GetXaxis()->SetTitle("tof12 (ns)");
mHPtTkU->GetYaxis()->SetTitle("pt (MeV/c)");
mHPtTkD = std::unique_ptr<TH2D>(new TH2D("hPtTkD", "ToF12 Time vs TkD pt",
nbins, 25, 50, nbins, 0, 300));
mHPtTkD->GetXaxis()->SetTitle("tof12 (ns)");
mHPtTkD->GetYaxis()->SetTitle("pt (MeV/c)");
mHPzTkU = std::unique_ptr<TH2D>(new TH2D("hPzTkU", "ToF12 Time vs TkU pz",
nbins, 25, 50, nbins, 0, 300));
mHPzTkU->GetXaxis()->SetTitle("tof12 (ns)");
mHPzTkU->GetYaxis()->SetTitle("pz (MeV/c)");
mHPzTkD = std::unique_ptr<TH2D>(new TH2D("hPzTkD", "ToF12 Time vs TkD pz",
nbins, 25, 50, nbins, 0, 300));
mHPzTkD->GetXaxis()->SetTitle("tof12 (ns)");
mHPzTkD->GetYaxis()->SetTitle("pz (MeV/c)");
}
bool AnalyserTofTracker::analyse(MAUS::ReconEvent* const aReconEvent,
MAUS::MCEvent* const aMCEvent) {
if (!aReconEvent) return false;
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
if (!sfevt) return false;
MAUS::TOFEvent* tofevt = aReconEvent->GetTOFEvent();
if (!tofevt) return false;
// Check and pull out the tof data
MAUS::TOFEventSpacePoint* tofevtsp = tofevt->GetTOFEventSpacePointPtr();
if (!tofevtsp) return false;
std::vector<MAUS::TOFSpacePoint> tof1sps = tofevtsp->GetTOF1SpacePointArray();
std::vector<MAUS::TOFSpacePoint> tof2sps = tofevtsp->GetTOF2SpacePointArray();
if (tof1sps.size() != 1 || tof2sps.size() != 1) return false;
double tof12 = tof2sps[0].GetTime() - tof1sps[0].GetTime();
// Check and pull out the tracker data
std::vector<MAUS::SciFiTrack*> trks = sfevt->scifitracks();
if (trks.size() != 2) return false;
std::vector<MAUS::SciFiTrack*> tku_trks;
std::vector<MAUS::SciFiTrack*> tkd_trks;
for (auto trk : trks) {
if (trk->tracker() == 0)
tku_trks.push_back(trk);
else if (trk->tracker() == 1)
tkd_trks.push_back(trk);
}
if (tku_trks.size() != 1 && tkd_trks.size() != 1) return false;
// Pull out the associated trackpoints, get the momentum
MAUS::ThreeVector mom_tku;
MAUS::ThreeVector mom_tkd;
bool tku_good = GetMomentum(tku_trks[0], mom_tku);
bool tkd_good = GetMomentum(tkd_trks[0], mom_tkd);
// Fill the histograms
// if (!tku_good && !tkd_good) return false;
double tku_mag =
sqrt(mom_tku.x()*mom_tku.x() + mom_tku.y()*mom_tku.y() + mom_tku.z()*mom_tku.z());
double tkd_mag =
sqrt(mom_tkd.x()*mom_tkd.x() + mom_tkd.y()*mom_tkd.y() + mom_tkd.z()*mom_tkd.z());
if (tku_good) {
mHPTkU->Fill(tof12, tku_mag);
mHPtTkU->Fill(tof12, sqrt(mom_tku.x()*mom_tku.x() + mom_tku.y()*mom_tku.y()));
mHPzTkU->Fill(tof12, mom_tku.z());
}
if (tkd_good) {
mHPTkD->Fill(tof12, tkd_mag);
mHPtTkD->Fill(tof12, sqrt(mom_tkd.x()*mom_tkd.x() + mom_tkd.y()*mom_tkd.y()));
mHPzTkD->Fill(tof12, mom_tkd.z());
}
return true;
}
bool AnalyserTofTracker::draw(std::shared_ptr<TVirtualPad> aPad) {
GetStyle()->SetOptStat(111111);
GetPads()[0]->Divide(3, 2);
update();
return true;
}
void AnalyserTofTracker::update() {
GetPads()[0]->cd(1);
mHPTkU->Draw("COLZ");
GetPads()[0]->cd(2);
mHPtTkU->Draw("COLZ");
GetPads()[0]->cd(3);
mHPzTkU->Draw("COLZ");
GetPads()[0]->cd(4);
mHPTkD->Draw("COLZ");
GetPads()[0]->cd(5);
mHPtTkD->Draw("COLZ");
GetPads()[0]->cd(6);
mHPzTkD->Draw("COLZ");
}
bool AnalyserTofTracker::GetMomentum(const MAUS::SciFiTrack* const trk, MAUS::ThreeVector& mom) {
MAUS::ThreeVector mom_out;
bool found = false;
for (auto tp : trk->scifitrackpoints()) {
if ((tp->station() == mAnalysisStation) && (tp->plane() == mAnalysisPlane)) {
mom_out = tp->mom();
found = true;
}
}
if (found) mom = mom_out;
return found;
}
} // ~namespace mica
<file_sep>/CMakeLists.txt
# MICA top level CMake build script - <NAME>
cmake_minimum_required(VERSION 3.2 FATAL_ERROR)
project(mica VERSION 1.1.1 LANGUAGES CXX)
set (CMAKE_CXX_STANDARD 11)
# Specify where build output should go
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin)
# Pull in ROOT
list(APPEND CMAKE_PREFIX_PATH $ENV{ROOTSYS})
find_package(ROOT)
include(${ROOT_USE_FILE}) # Define useful ROOT functions and macros (e.g. ROOT_GENERATE_DICTIONARY)
# Pull in MAUS
include_directories(include $ENV{MAUS_ROOT_DIR} $ENV{MAUS_ROOT_DIR}/src/common_cpp)
link_directories($ENV{MAUS_ROOT_DIR}/build)
# Build the MICA library
add_library(MicaCore SHARED src/AnalyserBase.cc
src/AnalyserFactory.cc
src/IAnalyser.cc
src/AnalyserGroup.cc
src/AnalyserTrackerAngularMomentum.cc
src/AnalyserTrackerMC.cc
src/AnalyserTrackerMCPRResiduals.cc
src/AnalyserTrackerMCPurity.cc
src/AnalyserTrackerPREfficiency.cc
src/AnalyserTrackerPRSeedNPEResidual.cc
src/AnalyserTrackerPRSeedResidual.cc
src/AnalyserTrackerPRStats.cc
src/AnalyserTrackerSpacePoints.cc
src/AnalyserTrackerSpacePointSearch.cc
src/AnalyserTrackerSpacePointSearchStation.cc
src/AnalyserTrackerChannelHits.cc
src/AnalyserTrackerKFStats.cc
src/AnalyserTofTracker.cc
src/AnalyserTrackerKFMomentum.cc
src/AnalyserViewerRealSpace)
target_link_libraries(MicaCore ${ROOT_LIBRARIES} MausCpp)
# Build the MICA app
link_directories(${CMAKE_BINARY_DIR})
add_executable(mica app/mica.cc)
target_link_libraries(mica ${ROOT_LIBRARIES} MausCpp MicaCore)
# Build the event viewer app
link_directories(${CMAKE_BINARY_DIR})
add_executable(event-viewer app/event-viewer.cc)
target_link_libraries(event-viewer ${ROOT_LIBRARIES} MausCpp MicaCore)
# Specify where installing will place the output
install(TARGETS mica event-viewer MicaCore
RUNTIME DESTINATION bin
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib)
# Generate the Doxygen documentation
# First we can indicate the documentation build as an option and set it to ON by default
# option(BUILD_DOC "Build documentation" OFF)
#
# # Check if Doxygen is installed
# find_package(Doxygen)
# if (DOXYGEN_FOUND)
# # Set input and output files
# set(DOXYGEN_IN ${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in)
# set(DOXYGEN_OUT ${CMAKE_CURRENT_BINARY_DIR}/doc/Doxyfile)
#
# # Request to configure the file
# configure_file(${DOXYGEN_IN} ${DOXYGEN_OUT} @ONLY)
# message("Doxygen build started")
#
# # Note the option ALL which allows to build the docs together with the application
# add_custom_target( doc_doxygen ALL
# COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_OUT}
# WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
# COMMENT "Generating API documentation with Doxygen"
# VERBATIM )
# else (DOXYGEN_FOUND)
# message("Doxygen need to be installed to generate the doxygen documentation")
# endif (DOXYGEN_FOUND)
<file_sep>/include/mica/AnalyserTrackerKFMomentum.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef ANALYSERTRACKERKFMOMENTUM_HH
#define ANALYSERTRACKERKFMOMENTUM_HH
#include <vector>
#include <memory>
#include "TVirtualPad.h"
#include "TH2.h"
#include "mica/AnalyserBase.hh"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
#include "src/common_cpp/DataStructure/SciFiSeed.hh"
#include "src/common_cpp/DataStructure/SciFiTrack.hh"
namespace mica {
/** @class AnalyserTrackerKFMomentum
* Anayser class which produces plots of the kalman fit momentum
* @author <NAME>
*/
class AnalyserTrackerKFMomentum : public AnalyserBase {
public:
AnalyserTrackerKFMomentum();
virtual ~AnalyserTrackerKFMomentum() {}
/** @brief Return the tracker station at which parameters are evaluated */
int GetAnalysisStation() const { return mAnalysisStation; }
/** @brief Set the tracker station at which parameters are evaluated */
void SetAnalysisStation(int aAnalysisStation) { mAnalysisStation = aAnalysisStation; }
/** @brief Get the tracker plane at which parameters are evaluated */
int GetAnalysisPlane() const { return mAnalysisPlane; }
/** @brief Set the tracker plane at which parameters are evaluated */
void SetAnalysisPlane(int aAnalysisPlane) { mAnalysisPlane = aAnalysisPlane; }
private:
virtual bool analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) override;
virtual bool draw(std::shared_ptr<TVirtualPad> aPad) override;
virtual void update() override;
/** @brief Extract the momentum at the specified surface
* @param[in] trk The SciFiTrack
* @param[out] mom The momentum
* @return Bool representing success of fail
*/
bool GetMomentum(const MAUS::SciFiTrack* const trk, MAUS::ThreeVector& mom);
int mAnalysisStation; ///< The tracker station to calculate all values at (default 1)
int mAnalysisPlane; ///< The tracker plane to calculate all values at (default 0)
std::unique_ptr<TH2D> mHPUSDS; ///< Plot tku vs tkd p
std::unique_ptr<TH2D> mHPtPzTkU; ///< Plot pt vs pz for tku
std::unique_ptr<TH2D> mHPtPzTkD; ///< Plot pt vs pz for tkd
};
} // ~namespace mica
#endif
<file_sep>/include/mica/AnalyserTrackerChannelHits.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef AnalyserTrackerChannelHits_hh
#define AnalyserTrackerChannelHits_hh
#include <vector>
#include <memory>
#include "TVirtualPad.h"
#include "TH1.h"
#include "TH2D.h"
#include "mica/AnalyserBase.hh"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
namespace mica {
/** @class AnalyserTrackerChannelHits
* Anayser class which produces histos of tracker channel occupancy
* @author <NAME>
*/
class AnalyserTrackerChannelHits : public AnalyserBase {
public:
AnalyserTrackerChannelHits();
virtual ~AnalyserTrackerChannelHits() {}
private:
virtual bool analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) override;
virtual bool draw(std::shared_ptr<TVirtualPad> aPad) override;
std::vector<std::unique_ptr<TH1I> > mTkU; ///< Plots for TkU, order by station then by plane
std::vector<std::unique_ptr<TH1I> > mTkD; ///< Plots for TkD, order by station then by plane
std::vector<std::unique_ptr<TH2D> > mNPETkU; ///< Plots for TkU, order by station then by plane
std::vector<std::unique_ptr<TH2D> > mNPETkD; ///< Plots for TkD, order by station then by plane
};
} // ~namespace mica
#endif
<file_sep>/src/CutsTOFTime.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include <vector>
#include "mica/CutsTOFTime.hh"
#include "src/common_cpp/DataStructure/TOFEvent.hh"
#include "src/common_cpp/DataStructure/TOFEventSpacePoint.hh"
#include "src/common_cpp/DataStructure/TOFSpacePoint.hh"
namespace mica {
CutsTOFTime::CutsTOFTime() : mLowerTimeCut(27.0), mUpperTimeCut(50.0) {}
bool CutsTOFTime::Cut(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) {
if (!aReconEvent)
return false;
MAUS::TOFEvent* tofEvent = aReconEvent->GetTOFEvent();
if (!tofEvent)
return false;
std::vector<MAUS::TOFSpacePoint>* tof1Spoints =
tofEvent->GetTOFEventSpacePointPtr()->GetTOF1SpacePointArrayPtr();
std::vector<MAUS::TOFSpacePoint>* tof2Spoints =
tofEvent->GetTOFEventSpacePointPtr()->GetTOF2SpacePointArrayPtr();
if (tof1Spoints->size() != 1 || tof2Spoints->size() != 1)
return false;
double dt = tof2Spoints->at(0).GetTime() - tof1Spoints->at(0).GetTime();
if (dt > mLowerTimeCut && dt < mUpperTimeCut)
return true;
return false;
}
} // ~namespace mica
<file_sep>/app/mica.cc
/** The main application for the Muon Ionization Cooling Analysis (MICA) framework */
// std library headers
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <memory>
// ROOT headers
#include "TStyle.h"
#include "TFile.h"
#include "TTree.h"
#include "TVirtualPad.h"
// MAUS headers
#include "src/common_cpp/DataStructure/Spill.hh"
#include "src/common_cpp/DataStructure/Data.hh"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
// MICA headers
#include "mica/AnalyserBase.hh"
#include "mica/AnalyserFactory.hh"
#include "mica/AnalyserTrackerPRSeedResidual.hh"
#include "mica/AnalyserTrackerPREfficiency.hh"
/** Analyse one ROOT file, using a given set of MICE analysers */
void analyse_file(TFile& aFile, std::vector<mica::AnalyserBase*>& analysers);
/** Draw and save to pdf the data contained in a given set of MICA analysers */
void make_plots(const std::string& ofname, std::vector<mica::AnalyserBase*>& analysers);
/** The main MICA app function - prepare the input file, analyse, plot, save to pdf */
int main(int argc, char *argv[]) {
// Instantiate the analysers required
std::vector<std::string> analyser_names {"AnalyserTrackerChannelHits",
"AnalyserTrackerSpacePoints",
"AnalyserTrackerPRSeedResidual",
"AnalyserTrackerPRSeedNPEResidual",
"AnalyserTrackerPRStats",
"AnalyserTrackerAngularMomentum",
"AnalyserTrackerMCPRResiduals",
"AnalyserTrackerPREfficiency",
"AnalyserTrackerKFStats",
"AnalyserTrackerKFMomentum",
"AnalyserTofTracker"};
std::vector<mica::AnalyserBase*> analysers
= mica::AnalyserFactory::CreateAnalysers(analyser_names);
// Customise a few specific analyser options
// Use a log scale for patrec seed residual plots
dynamic_cast<mica::AnalyserTrackerPRSeedResidual*>(analysers[2])->setLogScale(true);
// Don't restrict efficiency calc to ideal events (false = ideal events only, true = non-ideal ok)
dynamic_cast<mica::AnalyserTrackerPREfficiency*>(analysers[7])->SetAllowMultiHitStations(false);
// Only use the TOFs to define an expected good event, not tracker spacepoints
dynamic_cast<mica::AnalyserTrackerPREfficiency*>(analysers[7])->SetCheckTkU(false);
dynamic_cast<mica::AnalyserTrackerPREfficiency*>(analysers[7])->SetCheckTkD(false);
// Set up the input and output files using the programme arguments
std::string infile = "";
std::string outfile = "analysis.pdf";
if (argc > 1) {
infile = std::string(argv[1]); // 1st arg to code should be input ROOT file name
} else {
std::cerr << "Please enter the input file name as the first argument and try again\n";
return -1;
}
TFile f1(infile.c_str());
if (!f1.IsOpen()) {
std::cerr << "Failed to find file: " << infile <<std::endl;
return -1;
}
std::cout << "Input file " << infile << std::endl;
if (argc > 2) outfile = std::string(argv[2]);
std::cout << "Output file " << outfile << std::endl;
// Analyse the input ROOT file using the analysers
analyse_file(f1, analysers);
// Plot the results contained in the analysers
make_plots(outfile, analysers);
// Wrap up
for (auto an : analysers) {
delete an;
}
return 0;
}
void analyse_file(TFile& aFile, std::vector<mica::AnalyserBase*>& analysers) {
// Set up access to ROOT data from input file
TTree* T = static_cast<TTree*>(aFile.Get("Spill"));
MAUS::Data* data = nullptr; // Don't forget = nullptr or you get a seg fault
T->SetBranchAddress("data", &data); // Yes, this is the *address* of a *pointer*
int nentries = T->GetEntries();
std::cerr << "Found " << nentries << " spills\n";
// Loop over all spills
int spills_processed = 0;
int events_processed = 0;
for (int i = 0; i < nentries; ++i) {
++spills_processed;
T->GetEntry(i);
if (!data) {
std::cout << "Data is NULL\n";
continue;
}
MAUS::Spill* spill = data->GetSpill();
if (spill == nullptr) {
std::cout << "Spill is NULL\n";
continue;
}
if (spill->GetDaqEventType() != "physics_event") {
// std::cout << "Spill is of type " << spill->GetDaqEventType() << ", not a usable spill\n";
continue;
}
// Call the analysers
int event_counter = 0;
for (auto revt : (*(spill->GetReconEvents()))) {
MAUS::MCEvent* mevt = nullptr;
if (event_counter < static_cast<int>(spill->GetMCEvents()->size()))
mevt = spill->GetMCEvents()->at(event_counter);
for (auto an : analysers) {
an->Analyse(revt, mevt);
}
++event_counter;
++events_processed;
}
std::cout << "Spills processed: " << spills_processed << " of " << nentries
<< ", events processed: " << events_processed << std::endl;
} // ~Loop over all spills
}
void make_plots(const std::string& ofname, std::vector<mica::AnalyserBase*>& analysers) {
std::vector<std::shared_ptr<TVirtualPad>> pads;
std::vector<std::shared_ptr<TStyle> > styles;
for (auto an : analysers) {
an->Draw();
for (auto pad : an->GetPads()) {
if (pad) {
pads.push_back(pad);
styles.push_back(an->GetStyle());
}
}
}
std::cout << "Found " << pads.size() << " canvases, saving to pdf." << std::endl;
for (size_t i = 0; i < pads.size(); ++i) {
if (styles[i]) styles[i]->cd();
pads[i]->Update();
if (i == 0) {
pads[i]->SaveAs((ofname + "(").c_str(), "pdf");
} else if (i == (pads.size() - 1)) {
pads[i]->SaveAs((ofname + ")").c_str(), "pdf");
} else {
pads[i]->SaveAs(ofname.c_str(), "pdf");
}
}
}
<file_sep>/src/AnalyserTrackerMC.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include <string>
#include "TCanvas.h"
#include "TLatex.h"
#include "mica/AnalyserTrackerMC.hh"
#include "src/common_cpp/DataStructure/TOFEvent.hh"
#include "src/common_cpp/DataStructure/SciFiEvent.hh"
#include "src/common_cpp/DataStructure/SciFiBasePRTrack.hh"
#include "src/common_cpp/DataStructure/SciFiHelicalPRTrack.hh"
#include "src/common_cpp/DataStructure/SciFiStraightPRTrack.hh"
#include "src/common_cpp/DataStructure/SciFiSpacePoint.hh"
namespace mica {
AnalyserTrackerMC::AnalyserTrackerMC() : mRefStation {1},
mRefPlane {0},
mNStations {5},
mNPlanes {3},
mLookup {nullptr} {
// Do nothing
}
AnalyserTrackerMC::~AnalyserTrackerMC() {
clear_mc_data();
clear_lookup();
}
bool AnalyserTrackerMC::analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) {
if (!aMCEvent)
return false;
if (analyse_mc(aMCEvent)) {
return analyse_recon(aReconEvent);
} else {
return false;
}
return false;
}
bool AnalyserTrackerMC::analyse_mc(MAUS::MCEvent* const aMCEvent) {
bool lookup_pass = make_lookup(aMCEvent);
if (!lookup_pass) {
std::cerr << "WARNING: AnalyserTrackerMC::analyse_mc: Failed to make SciFiLookup\n";
} else if (mLookup->get_hits_map().size() == 0) {
lookup_pass = false;
} else {
// std::cerr << "INFO: AnalyserTrackerMC::analyse_mc: Lookup hit map size: "
// << mLookup->get_hits_map().size() << std::endl;
}
if (!lookup_pass) return false;
bool data_pass = fill_mc_track_data(aMCEvent);
return (lookup_pass && data_pass);
}
void AnalyserTrackerMC::clear_lookup() {
if (mLookup) delete mLookup;
mLookup = nullptr;
}
void AnalyserTrackerMC::clear_mc_data() {
for (auto datum : mMCDataTkU) {
if (datum) delete datum;
}
for (auto datum : mMCDataTkD) {
if (datum) delete datum;
}
mMCDataTkU.resize(0);
mMCDataTkD.resize(0);
}
std::map<int, std::vector<int> > \
AnalyserTrackerMC::calc_stations_hit_by_track(std::map<int,
std::vector<MAUS::SciFiHit*> >& hit_map,
int aNPlanes) {
std::map<int, std::vector<int> > stations_hit_by_track; // stations_hit_by_track[trk_id]
for (auto& station : hit_map) {
// planes_hit_by_track[track_id][plane] = true or false - did track generate hit in this plane
std::map<int, std::map<int, bool> > planes_hit_by_track;
for (auto hit : station.second) {
planes_hit_by_track[hit->GetTrackId()][hit->GetChannelId()->GetPlaneNumber()] = true;
}
for (auto& trk : planes_hit_by_track) {
if (trk.second.size() >= aNPlanes) { // Did track produce hits in >= 2 planes of this station
stations_hit_by_track[trk.first].push_back(station.first);
}
}
}
return stations_hit_by_track;
}
bool AnalyserTrackerMC::fill_mc_track_data(MAUS::MCEvent* const aMCEvent) {
if (!aMCEvent) return false;
auto hits = aMCEvent->GetSciFiHits();
std::map<int, std::vector<MAUS::SciFiHit*> > hit_map_tku;
std::map<int, std::vector<MAUS::SciFiHit*> > hit_map_tkd;
// Sort scifi hits into a map from station number to a vector holding the hits for that station
for (auto&& hit_ref : *hits) {
MAUS::SciFiHit* hit = &hit_ref;
if (hit->GetChannelId()->GetTrackerNumber() == 0) {
hit_map_tku[hit->GetChannelId()->GetStationNumber()].push_back(hit);
} else if (hit->GetChannelId()->GetTrackerNumber() == 1) {
hit_map_tkd[hit->GetChannelId()->GetStationNumber()].push_back(hit);
}
}
// Loop over each station, & see what tracks produced hits in >= mNPlanes planes for that station
std::map<int, std::vector<int> > trk_id_to_stations_hit_tku = \
calc_stations_hit_by_track(hit_map_tku, mNPlanes);
std::map<int, std::vector<int> > trk_id_to_stations_hit_tkd = \
calc_stations_hit_by_track(hit_map_tkd, mNPlanes);
// We now have a map for each tracker from mc track id to the station numbers for which it
// generated hits in 2 or more planes. Next, see which track ids produced such hits in mNStations
// or more stations, that is all the track ids which could have created a reconstructible track
for (auto trk : trk_id_to_stations_hit_tku) {
if (trk.second.size() >= mNStations) {
MCTrackData* data = nullptr;
for (auto hit : hit_map_tku[trk.first]) {
if (hit->GetChannelId()->GetStationNumber() == mRefStation && \
hit->GetChannelId()->GetPlaneNumber() == mRefPlane) {
data = new MCTrackData();
data->tracker = 0;
data->track_id = trk.first;
data->pid = hit->GetParticleId();
data->energy = hit->GetEnergy();
data->pos = hit->GetPosition();
data->mom = hit->GetMomentum();
mMCDataTkU.push_back(data);
break;
}
}
if (!data) {
// std::cerr << "WARNING: No hit present in TkU reference plane\n";
} else {
// std::cerr << "INFO: Created MCTrackData for TkU\n";
}
}
}
for (auto trk : trk_id_to_stations_hit_tkd) {
if (trk.second.size() >= mNStations) {
MCTrackData* data = nullptr;
for (auto hit : hit_map_tkd[trk.first]) {
if (hit->GetChannelId()->GetStationNumber() == mRefStation && \
hit->GetChannelId()->GetPlaneNumber() == mRefPlane) {
data = new MCTrackData();
data->tracker = 1;
data->track_id = trk.first;
data->pid = hit->GetParticleId();
data->energy = hit->GetEnergy();
data->pos = hit->GetPosition();
data->mom = hit->GetMomentum();
mMCDataTkD.push_back(data);
break;
}
}
if (!data) {
// std::cerr << "WARNING: No hit present in TkD reference plane\n";
} else {
// std::cerr << "INFO: Created MCTrackData for TkD\n";
}
}
}
return true;
}
bool AnalyserTrackerMC::make_lookup(MAUS::MCEvent* const aMCEvent) {
if (!aMCEvent) return false;
if (mLookup) delete mLookup;
mLookup = new MAUS::SciFiLookup();
return mLookup->make_hits_map(aMCEvent);
}
} // ~namespace mica
<file_sep>/include/mica/AnalyserBase.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef ANALYSERBASE_HH
#define ANALYSERBASE_HH
#include <vector>
#include <memory>
#include "TVirtualPad.h"
#include "TStyle.h"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
#include "mica/CutsBase.hh"
namespace mica {
/** @class AnalyserBase
* Base class for all analysers. Defines a public interface via the Draw and Analyse
* functions. These wrap the private draw and analyse respetively which must be overidden
* in daughter classes (an example of the Non-Virtual Interface idiom).
* Analyse applies any cuts selected prior to passing events to daughter routines.
* An optional Merge function is also provided. Daughter classes which wish to implement this
* should inherit from IAnalyser (a CRTP class), rather than AnalyserBase directly.
* All new daughter classes should be registered with AnalyserFactory::CreateAnalyser.
* @author <NAME>
*/
class AnalyserBase {
public:
AnalyserBase();
virtual ~AnalyserBase();
/** @brief Check the cuts, then if they are passed calls the daughter class analyse method
* @param aReconEvent The recon event
* @param aMCEvent The corresponding MC event
* @return Boolean indicating if the cuts passed and the analysis happened
*/
bool Analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent);
/** @brief Create a new instance of the actual daughter class, returning a base pointer */
// virtual AnalyserBase* Clone() = 0;
/** @brief Wraps draw(std::shared_ptr<TVirtualPad> aPad)
*/
std::shared_ptr<TVirtualPad> Draw();
/** @brief Merge combines the data from a second analyser of the same concrete type into
* into this analyser (generally by calling the Add method of the ROOT histogram members).
*
* Daughter classes should inherit from IAnalyser instead of AnalyserBase directly if they
* implement this method (which provides some wrapping to handle the dynamic_cast from
* AnalyserBase to the specific daughter class).
*
* @param[in] aAnalyser The analyser to add the data from, must be same type as this
* @return Boolean, was the merge sucessful or not
*/
virtual bool Merge(AnalyserBase* aAnalyser) { return false; };
/** @brief Update the plots, with adding or altering the existing canvases */
void Update() { update(); }
/** @brief Add a pad to the list of internal pad pointers */
void AddPad(std::shared_ptr<TVirtualPad> aPad) { mPads.push_back(aPad); }
/** @brief Return all the pads */
std::vector<std::shared_ptr<TVirtualPad>> const GetPads() { return mPads; }
/** @brief Add a cut, only events which pass the cut will be processed
* @param aCut The cut to add
*/
void AddCut(CutsBase* aCut) { mCuts.push_back(aCut); }
/** @brief Return the cuts enter for the analyser */
std::vector<CutsBase*> GetCuts() { return mCuts; }
/** @brief Set the cuts, only events which pass all the cuts will be processed */
void SetCuts(std::vector<CutsBase*>& aCuts) { mCuts = aCuts; }
/** @brief Return a pointer to the ROOT TStyle used
* to set the plotting style for this analyser
* @return pointer to the ROOT TStyle for this analyser
*/
std::shared_ptr<TStyle> GetStyle() { return mStyle; }
private:
/** @brief Analyse the given event, to be overidden by concrete daughter classes
* @param aReconEvent The recon event
* @param aMCEvent The corresponding MC event
* @return Boolean indicating if the cuts passed and the analysis happened
*/
virtual bool analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) = 0;
/** @brief Apply the cuts held by the mCuts members to the event given as arguments, if they
* pass return true, otherwise false - no cuts just causes return true.
* @param aReconEvent The recon event
* @param aMCEvent The corresponding MC event
* @return Boolean indicating if the cuts passed
*/
bool ApplyCuts(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent);
/** @brief After analysing all the events, draw the results,
* to be overidden by concrete daughter classes
* @param aPad ROOT TPad to draw results on
*/
virtual bool draw(std::shared_ptr<TVirtualPad> aPad) = 0;
/** @brief Update the plots, with adding or altering the existing canvases */
virtual void update() {};
std::vector<std::shared_ptr<TVirtualPad>> mPads; ///< The canvas upon which the plots are drawn
std::vector<CutsBase*> mCuts; ///< The cuts to apply before admitting an event for analysis
std::shared_ptr<TStyle> mStyle; ///< The ROOT TStyle to be applied to the canvases
};
} // ~namespace mica
#endif
<file_sep>/include/mica/AnalyserTrackerAngularMomentum.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef ANALYSERTRACKERANGULARMOMENTUM_HH
#define ANALYSERTRACKERANGULARMOMENTUM_HH
#include <vector>
#include "TVirtualPad.h"
#include "TH2.h"
#include "mica/AnalyserBase.hh"
#include "mica/IAnalyser.hh"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
#include "src/common_cpp/DataStructure/SciFiSeed.hh"
#include "src/common_cpp/DataStructure/SciFiTrack.hh"
namespace mica {
/** @class AnalyserTrackerAngularMomentum
* Anayser class which produces plots of ang. mom. vs radius
* @author <NAME>
*/
class AnalyserTrackerAngularMomentum : public IAnalyser<AnalyserTrackerAngularMomentum> {
public:
AnalyserTrackerAngularMomentum();
virtual ~AnalyserTrackerAngularMomentum() {}
/** @brief Return the tracker station at which parameters are evaluated */
int GetAnalysisStation() const { return mAnalysisStation; }
/** @brief Set the tracker station at which parameters are evaluated */
void SetAnalysisStation(int aAnalysisStation) { mAnalysisStation = aAnalysisStation; }
/** @brief Get the tracker plane at which parameters are evaluated */
int GetAnalysisPlane() const { return mAnalysisPlane; }
/** @brief Set the tracker plane at which parameters are evaluated */
void SetAnalysisPlane(int aAnalysisPlane) { mAnalysisPlane = aAnalysisPlane; }
private:
virtual bool analyse(MAUS::ReconEvent* const aReconEvent,
MAUS::MCEvent* const aMCEvent) override;
virtual bool draw(std::shared_ptr<TVirtualPad> aPad) override;
virtual void merge(AnalyserTrackerAngularMomentum* aAnalyser) override;
int mAnalysisStation; ///< The tracker station to calculate all values at (default 1)
int mAnalysisPlane; ///< The tracker plane to calculate all values at (default 0)
TH2D* mHAngMomTKU; ///< Plot of ang. mom. vs radius for TkU
TH2D* mHAngMomTKD; ///< Plot of ang. mom. vs radius for TkD
/** @brief Extract the seed associated with a SciFiTrack. Checks the validity of the pointer.
* @param aTrack Pointer to the track
* @return The seed corresponding to the input track
*/
MAUS::SciFiSeed* ExtractSeed(MAUS::SciFiTrack* aTrack) const;
};
} // ~namespace mica
#endif
<file_sep>/include/mica/IAnalyser.hh
#ifndef IANALYSER_HH
#define IANALYSER_HH
#include "mica/AnalyserBase.hh"
namespace mica {
/** @class IAnalyser Template class inserted between AnalyserBase and the concrete daughter
* classes. The purpose of the class is to enable CRTP, allowing the merge function to be defined.
* We want to make merge virtual void to force the daughter classes implement it, however merge
* requires its argument to be the daughter class type, hence the neccessity of CRTP.
* May also implement a Clone here, easier than doing it in each daughter class (another CRTP use).
*
* @tparam Derived The daughter class type
*/
template <typename Derived>
class IAnalyser : public AnalyserBase {
public:
IAnalyser() {};
virtual ~IAnalyser() {};
/** Converts the AnalyserBase pointer into the derived class pointer and passes this to merge
*
* @param aAnalyser The analyser whose internal data is to be added to the current data
*/
virtual bool Merge(AnalyserBase* aAnalyser) override {
Derived* derivedAnalyser = dynamic_cast<Derived*>(aAnalyser);
if (!derivedAnalyser)
return false;
merge(derivedAnalyser);
return true;
}
private:
/** Add data from the internal data variables of another analyser instance to the internal
* data variables of this analyser instance
*
* @param aAnalyser The analyser whose internal data is to be added to the current data
*/
virtual void merge(Derived* aAnalyser) = 0;
};
} // ~namespace mica
#endif
<file_sep>/include/mica/AnalyserTrackerPREfficiency.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef ANALYSERTRACKERPREFFICIENCY_HH
#define ANALYSERTRACKERPREFFICIENCY_HH
#include <iostream>
#include <fstream>
#include "TVirtualPad.h"
#include "TH2.h"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
#include "src/common_cpp/DataStructure/SciFiEvent.hh"
#include "src/common_cpp/DataStructure/TOFEvent.hh"
#include "mica/AnalyserBase.hh"
namespace mica {
/** @class AnalyserTrackerPREfficiency
* Analyser class which produces tracker pattern recognition
* efficiency results, uses reconstrcuted data only (no MC)
* @author <NAME>
*/
class AnalyserTrackerPREfficiency : public AnalyserBase {
public:
AnalyserTrackerPREfficiency();
virtual ~AnalyserTrackerPREfficiency();
/** @brief Reset the internal counter variables to 0 */
virtual void clear();
/** @brief Return if we are checking time-of-flight between TOF1 and TOF2, overrules
* CheckTOFSpacePoints
*/
bool GetCheckTOF() const { return mCheckTOF; }
/** @brief Set if we are checking time-of-flight between TOF1 and TOF2
* CheckTOFSpacePoints
*/
void SetCheckTOF(bool aBool) { mCheckTOF = aBool; }
/** @brief Return if we are checking TOF spacepoint, will be overruled if CheckTOF is true */
bool GetCheckTOFSpacePoints() const { return mCheckTOFSpacePoints; }
/** @brief Set if we are checking TOF spacepoint, will be overruled if CheckTOF is true */
void SetCheckTOFSpacePoints(bool aBool) { mCheckTOFSpacePoints = aBool; }
/** @brief Return if we allow non-ideal events to be considered */
bool GetAllowMultiHitStations() const { return mAllowMultiHitStations; }
/** @brief Set if we allow non-ideal events to be considered */
void SetAllowMultiHitStations(bool aBool) { mAllowMultiHitStations = aBool; }
/** Return if we are checking TkU criteria at all */
bool GetCheckTkU() const { return mCheckTkU; }
/** Set if we are checking TkU criteria at all */
void SetCheckTkU(bool aBool) { mCheckTkU = aBool; }
/** Return if we are checking TkD criteria at all */
bool GetCheckTkD() const { return mCheckTkD; }
/** Set if we are checking TkD criteria at all */
void SetCheckTkD(bool aBool) { mCheckTkD = aBool; }
private:
virtual bool analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) override;
virtual bool draw(std::shared_ptr<TVirtualPad> aPad) override;
bool mCheckTOF; ///< Should we check time-of-flight between TOF1 and TOF2. Requires 1 and only 1
///< spacepoint in both TOF1 and TOF2, so if set to true it will override
///< mCheckTOFSpacePoints.
bool mCheckTOFSpacePoints; ///< Should we check there is 1 and only 1 spacepoint in both TOF1
///< and TOF2? mCheckTOF being set to true will override this flag,
///< and force it to be a requirement.
bool mAllowMultiHitStations; ///< Should we allow non-ideal events to be considered, that is,
///< events with more than one spacepoint per tracker station for
///< a given tracker. Even when set to true we still require there
///< not be enough spacepoints present to form two distinct tracks.
bool mCheckTkU; ///< Should we check TkU criteria at all, or just pass the event as good? May
///< want to ignore TkU if we wanted to just check TkD for example.
bool mCheckTkD; ///< Should we check TkD criteria at all, or just pass the event as good? May
///< want to ignore TkD if we wanted to just check TkU for example.
int mNEvents; ///< Counter, number of events analysed
int mTkUGoodEvents; ///< Counter, number of events where we expect a track in TkU
int mTkU5ptTracks; ///< Counter, number of 5pt tracks actually reconstructed in TkU
int mTkU4to5ptTracks; ///< Counter, number of 4 or 5pt tracks actually reconstructed in TkU
int mTkDGoodEvents; ///< Counter, number of events where we expect a track in TkD
int mTkD5ptTracks; ///< Counter, number of 5pt tracks actually reconstructed in TkD
int mTkD4to5ptTracks; ///< Counter, number of 4 or 5pt tracks actually reconstructed in TkD
double mLowerTimeCut; ///< Minimum time-of-flight between TOF1 and TOF2 for event to be classed
///< as good, if mCheckTOF is set true
double mUpperTimeCut; ///< Maximum time-of-flight between TOF1 and TOF2 for event to be classed
///< as good, if mCheckTOF is set true
// std::ofstream mOf1; ///< output filestream for efficiency data
/** @brief Check a tracker to see if a single track is expected. Set the input bools to
* say whether a 4pt track or a 5pt track are expected.
* @param[in] evt SciFiEvent containing the spacepoints
* @param[in] trker_num Which tracker to analyse
* @param[out] good4pt Do we expect a 4pt track to be reconstructed, but NOT a 5pt track
* @param[out] good5pt Do we expect a 5pt track to be reconstructed
*/
void check_good_tk_event(MAUS::SciFiEvent* evt, int trker_num, bool& good4pt, bool& good5pt);
/** @brief Check the TOFs to see if the event passes the choosen criteria for a good event
* @return Bool indicating if this is a good event
*/
bool check_good_tof_event(MAUS::TOFEvent* evt);
};
} // ~namespace mica
#endif
<file_sep>/src/AnalyserTrackerKFStats.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "mica/AnalyserTrackerKFStats.hh"
#include "src/common_cpp/DataStructure/SciFiEvent.hh"
#include "src/common_cpp/DataStructure/SciFiSpacePoint.hh"
namespace mica {
AnalyserTrackerKFStats::AnalyserTrackerKFStats() : mHChiSqTKU{nullptr},
mHChiSqTKD{nullptr},
mHPValueTKU{nullptr},
mHPValueTKD{nullptr} {
int nbins = 100;
mHChiSqTKU = new TH1D("hChiSqTKU", "KF #chi^{2}_{\nu} TkU", nbins, 0, 20);
mHChiSqTKU->GetXaxis()->SetTitle("#chi^{2}_{\nu} ");
mHChiSqTKD = new TH1D("hChiSqTKD", "KF #chi^{2}_{\nu} TkD", nbins, 0, 20);
mHChiSqTKD->GetXaxis()->SetTitle("#chi^{2}_{\nu} ");
mHPValueTKU = new TH1D("hPValueTKU", "KF p-value TkU", nbins, 0, 1);
mHPValueTKU->GetXaxis()->SetTitle("p-value");
mHPValueTKD = new TH1D("hPValueTKD", "KF p-value TkD", nbins, 0, 1);
mHPValueTKD->GetXaxis()->SetTitle("p-value");
}
bool AnalyserTrackerKFStats::analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) {
if (!aReconEvent)
return false;
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
if (!sfevt)
return false;
for (auto trk : sfevt->scifitracks()) {
if (trk->tracker() == 0) {
mHChiSqTKU->Fill(trk->chi2() / trk->ndf());
mHPValueTKU->Fill(trk->P_value());
} else if (trk->tracker() == 1) {
mHChiSqTKD->Fill(trk->chi2() / trk->ndf());
mHPValueTKD->Fill(trk->P_value());
}
}
}
bool AnalyserTrackerKFStats::draw(std::shared_ptr<TVirtualPad> aPad) {
GetStyle()->SetOptStat(111111);
GetPads()[0]->Divide(2, 2);
GetPads()[0]->cd(1);
mHChiSqTKU->Draw();
GetPads()[0]->cd(2);
mHPValueTKU->Draw();
GetPads()[0]->cd(3);
mHChiSqTKD->Draw();
GetPads()[0]->cd(4);
mHPValueTKD->Draw();
return true;
}
} // ~namespace mica
<file_sep>/include/mica/AnalyserTrackerMCPurity.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef ANALYSERTRACKERMCPURITY_HH
#define ANALYSERTRACKERMCPURITY_HH
#include <vector>
#include "TVirtualPad.h"
#include "TH1.h"
#include "mica/AnalyserTrackerMC.hh"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
#include "src/common_cpp/DataStructure/SciFiSeed.hh"
#include "src/common_cpp/DataStructure/SciFiTrack.hh"
#include "src/common_cpp/DataStructure/SciFiBasePRTrack.hh"
namespace mica {
/** @class AnalyserTrackerMCPurity
* Analyser class which calculates pattern recognition purity.
* @author <NAME>
*/
class AnalyserTrackerMCPurity : public AnalyserTrackerMC {
public:
AnalyserTrackerMCPurity();
virtual ~AnalyserTrackerMCPurity() {}
private:
virtual bool analyse_recon(MAUS::ReconEvent* const aReconEvent) override;
virtual bool draw(std::shared_ptr<TVirtualPad> aPad) override;
int find_mc_track_id(MAUS::SciFiBasePRTrack* trk);
TH1I* mHTracksMatched;
};
} // ~namespace mica
#endif
<file_sep>/include/mica/AnalyserGroup.hh
#ifndef ANALYSERGROUP_HH
#define ANALYSERGROUP_HH
#include <vector>
#include <memory>
#include "mica/AnalyserBase.hh"
namespace mica {
/** @class AnalyserGroup
* Store a group of MICA analysers in a vector, plus convenience functions.
* @author <NAME>
*/
class AnalyserGroup {
public:
AnalyserGroup() {};
virtual ~AnalyserGroup() {}
/** Return an analyser at a given position of the storage vector */
AnalyserBase* operator [](int i) const { return mAnalysers[i]; }
/** Add an analyser to the group */
void AddAnalyser(AnalyserBase* aAnalyser) { mAnalysers.push_back(aAnalyser); }
/** Call Analyse on each analyser */
bool Analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent);
// AnalyserGroup* Clone();
/** Call Draw on each analyser */
std::vector<std::shared_ptr<TVirtualPad>> Draw();
/** Draw and save the plots to a pdf, ofname specifies the output pdf file name */
void MakePlots(const std::string& ofname);
/** Merge the data from another set of identical analysers into this AnalyserGroup */
bool Merge(AnalyserGroup* aAnalyserGroup);
size_t size() { return mAnalysers.size(); }
private:
std::vector<AnalyserBase*> mAnalysers;
};
} // ~namespace mice
#endif
<file_sep>/src/AnalyserViewerRealSpace.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "mica/AnalyserViewerRealSpace.hh"
#include <algorithm>
#include <cmath>
#include <iomanip>
#include "TRef.h"
#include "TAxis.h"
#include "src/common_cpp/DataStructure/TOFEvent.hh"
#include "src/common_cpp/DataStructure/TOFEventSpacePoint.hh"
#include "src/common_cpp/DataStructure/TOFSpacePoint.hh"
#include "src/common_cpp/DataStructure/SciFiTrack.hh"
#include "src/common_cpp/DataStructure/SciFiTrackPoint.hh"
namespace mica {
AnalyserViewerRealSpace::AnalyserViewerRealSpace() {
// Do nothing
}
bool AnalyserViewerRealSpace::analyse(MAUS::ReconEvent* const aReconEvent,
MAUS::MCEvent* const aMCEvent) {
// Populate position vectors from event spacepoints
if (!aReconEvent) return false;
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
if (!sfevt) return false;
clear_vectors();
for (auto sp : sfevt->spacepoints()) {
if (sp->get_tracker() == 0) {
mXTkU.push_back(sp->get_position().x());
mYTkU.push_back(sp->get_position().y());
mZTkU.push_back(sp->get_position().z());
} else if (sp->get_tracker() == 1) {
mXTkD.push_back(sp->get_position().x());
mYTkD.push_back(sp->get_position().y());
mZTkD.push_back(sp->get_position().z());
}
}
// Populate track fit function vectors
for (auto trk : sfevt->helicalprtracks()) {
double x0 = trk->get_reference_position().x();
double y0 = trk->get_reference_position().y();
double xc = trk->get_circle_x0();
double yc = trk->get_circle_y0();
double rad = trk->get_R();
double dsdz = trk->get_dsdz();
double sz_c = trk->get_line_sz_c();
if (trk->get_tracker() == 0) {
mHtrkXYTkU.push_back(make_helix_xy(xc, yc, rad));
mHtrkZXTkU.push_back(make_helix_xz(-1, xc, rad, dsdz, sz_c, mZMin, mZMax));
mHtrkZYTkU.push_back(make_helix_yz(xc, yc, rad, dsdz, -x0, y0, mZMin, mZMax));
} else if (trk->get_tracker() == 1) {
mHtrkXYTkD.push_back(make_helix_xy(xc, yc, rad));
mHtrkZXTkD.push_back(make_helix_xz(-1, xc, rad, dsdz, sz_c, mZMin, mZMax));
mHtrkZYTkD.push_back(make_helix_yz(xc, yc, rad, dsdz, x0, y0, mZMin, mZMax));
}
print_track_info(trk);
}
return true;
}
bool AnalyserViewerRealSpace::draw(std::shared_ptr<TVirtualPad> aPad) {
GetPads()[0]->Divide(3, 2);
update();
return true;
}
void AnalyserViewerRealSpace::update() {
mGrXYTkU = std::unique_ptr<TGraph>(new TGraph(mXTkU.size(), &(mXTkU[0]), &(mYTkU[0])));
mGrZXTkU = std::unique_ptr<TGraph>(new TGraph(mZTkU.size(), &(mZTkU[0]), &(mXTkU[0])));
mGrZYTkU = std::unique_ptr<TGraph>(new TGraph(mZTkU.size(), &(mZTkU[0]), &(mYTkU[0])));
mGrXYTkD = std::unique_ptr<TGraph>(new TGraph(mXTkD.size(), &(mXTkD[0]), &(mYTkD[0])));
mGrZXTkD = std::unique_ptr<TGraph>(new TGraph(mZTkD.size(), &(mZTkD[0]), &(mXTkD[0])));
mGrZYTkD = std::unique_ptr<TGraph>(new TGraph(mZTkD.size(), &(mZTkD[0]), &(mYTkD[0])));
GetPads()[0]->cd(1);
mGrXYTkU->SetTitle("X-Y Projection TkU");
mGrXYTkU->GetXaxis()->SetTitle("x(mm)");
mGrXYTkU->GetYaxis()->SetTitle("y(mm)");
mGrXYTkU->SetMarkerStyle(20);
mGrXYTkU->SetMarkerColor(kBlack);
mGrXYTkU->Draw("AP same");
for (auto& fit : mHtrkXYTkU) {
fit.Draw("same");
}
GetPads()[0]->cd(2);
mGrZXTkU->SetTitle("Z-X Projection TkU");
mGrZXTkU->GetXaxis()->SetTitle("z(mm)");
mGrZXTkU->GetYaxis()->SetTitle("x(mm)");
mGrZXTkU->SetMarkerStyle(20);
mGrZXTkU->SetMarkerColor(kBlack);
mGrZXTkU->Draw("AP same");
for (auto& fit : mHtrkZXTkU) {
fit.Draw("same");
}
GetPads()[0]->cd(3);
mGrZYTkU->SetTitle("Z-Y Projection TkU");
mGrZYTkU->GetXaxis()->SetTitle("z(mm)");
mGrZYTkU->GetYaxis()->SetTitle("y(mm)");
mGrZYTkU->SetMarkerStyle(20);
mGrZYTkU->SetMarkerColor(kBlack);
mGrZYTkU->Draw("AP same");
for (auto& fit : mHtrkZYTkU) {
fit.Draw("same");
}
GetPads()[0]->cd(4);
mGrXYTkD->SetTitle("X-Y Projection TkD");
mGrXYTkD->GetXaxis()->SetTitle("x(mm)");
mGrXYTkD->GetYaxis()->SetTitle("y(mm)");
mGrXYTkD->SetMarkerStyle(20);
mGrXYTkD->SetMarkerColor(kBlack);
mGrXYTkD->Draw("AP same");
for (auto& fit : mHtrkXYTkD) {
fit.Draw("same");
}
GetPads()[0]->cd(5);
mGrZXTkD->SetTitle("Z-X Projection TkD");
mGrZXTkD->GetXaxis()->SetTitle("z(mm)");
mGrZXTkD->GetYaxis()->SetTitle("x(mm)");
mGrZXTkD->SetMarkerStyle(20);
mGrZXTkD->SetMarkerColor(kBlack);
mGrZXTkD->Draw("AP same");
for (auto& fit : mHtrkZXTkD) {
fit.Draw("same");
}
GetPads()[0]->cd(6);
mGrZYTkD->SetTitle("Z-Y Projection TkD");
mGrZYTkD->GetXaxis()->SetTitle("z(mm)");
mGrZYTkD->GetYaxis()->SetTitle("y(mm)");
mGrZYTkD->SetMarkerStyle(20);
mGrZYTkD->SetMarkerColor(kBlack);
mGrZYTkD->Draw("AP same");
for (auto& fit : mHtrkZYTkD) {
fit.Draw("same");
}
}
void AnalyserViewerRealSpace::clear_vectors() {
mXTkU.resize(0);
mYTkU.resize(0);
mZTkU.resize(0);
mXTkD.resize(0);
mYTkD.resize(0);
mZTkD.resize(0);
mHtrkXYTkU.resize(0);
mHtrkZXTkU.resize(0);
mHtrkZYTkU.resize(0);
mHtrkXYTkD.resize(0);
mHtrkZXTkD.resize(0);
mHtrkZYTkD.resize(0);
}
TArc AnalyserViewerRealSpace::make_helix_xy(double x0, double y0, double rad) {
TArc arc = TArc(x0, y0, rad);
arc.SetFillStyle(0); // 0 - Transparent
arc.SetLineColor(kBlue);
return arc;
};
TF1 AnalyserViewerRealSpace::make_str_track(double c, double m, double zmin, double zmax) {
// Note: in the function expression, x is just the independent variable, which
// in this case is the z coordinate in the tracker coordinate system
TF1 trk = TF1("trk", "[0]+([1]*x)", zmin, zmax);
trk.SetParameters(c, m);
trk.SetLineColor(kRed);
return trk;
};
TF1 AnalyserViewerRealSpace::make_helix_xz(int handness, double circle_x0, double rad, double dsdz,
double sz_c, double zmin, double zmax) {
// The x in the cos term is actually representing z (the indep variable)
TF1 func = TF1("xz_func", "[0]-[4]*([1]*cos((1/[1])*([2]*x+[3])))", zmin, zmax);
func.SetParameter(0, circle_x0);
func.SetParameter(1, rad);
func.SetParameter(2, dsdz);
func.SetParameter(3, sz_c);
func.SetParameter(4, handness);
func.SetLineColor(kBlue);
return func;
};
TF1 AnalyserViewerRealSpace::make_helix_yz(double circle_x0, double circle_y0, double rad, double dsdz,
double x0, double y0, double zmin, double zmax) {
// The x in the cos term is actually representing z (the indep variable)
// TF1 func = TF1("yz_func", "[0]+([1]*sin((1/[1])*([2]*x+[3])))", zmin, zmax);
TF1 func = TF1("yz_func", "[1] + ([5]-[1])*cos((1/[2])*([3]*x)) + ([4]-[0])*sin((1/[2])*[3]*x)", zmin, zmax);
func.SetParameter(0, circle_x0);
func.SetParameter(1, circle_y0);
func.SetParameter(2, rad);
func.SetParameter(3, dsdz);
func.SetParameter(4, x0);
func.SetParameter(5, y0);
func.SetLineColor(kBlue);
return func;
};
void AnalyserViewerRealSpace::print_track_info(const MAUS::SciFiHelicalPRTrack* const trk) {
double rad = trk->get_R();
double pt = rad * mRadToPt;
double pz = pt / trk->get_dsdz();
std::cout << "Tracker " << trk->get_tracker() << + ", ";
std::cout << "Num points " << trk->get_num_points() << ", ";
std::cout << "Charge " << trk->get_charge() << ", ";
std::cout << "R = " << std::setprecision(4) << trk->get_R() << "mm, ";
std::cout << "X0 = " << std::setprecision(4) << trk->get_circle_x0() << "mm, ";
std::cout << "Y0 = " << std::setprecision(4) << trk->get_circle_y0() << "mm,\n";
std::cout << "dsdz " << std::setprecision(4) << trk->get_dsdz() << ", ";
std::cout << "pt = " << std::setprecision(4) << pt << "MeV/c, ";
std::cout << "pz = " << std::setprecision(4) << pz << "MeV/c, ";
std::cout << "xy_chi2 = " << std::setprecision(4) << trk->get_circle_chisq() << ", ";
std::cout << "sz_c = " << std::setprecision(4) << trk->get_line_sz_c() << ", ";
std::cout << "sz_chi2 = " << std::setprecision(4) << trk->get_line_sz_chisq() << "\n";
};
} // ~namespace mica
<file_sep>/src/AnalyserTrackerAngularMomentum.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "TRef.h"
#include "mica/AnalyserTrackerAngularMomentum.hh"
#include "src/common_cpp/DataStructure/SciFiTrackPoint.hh"
#include "src/common_cpp/DataStructure/SciFiHelicalPRTrack.hh"
namespace mica {
AnalyserTrackerAngularMomentum::AnalyserTrackerAngularMomentum() : mAnalysisStation(1),
mAnalysisPlane(0),
mHAngMomTKU(NULL),
mHAngMomTKD(NULL) {
mHAngMomTKU = new TH2D("hAngMomTKU", "PR Canonical AM vs Radius TkU",
200, -4000, 2000, 200, 0, 150);
mHAngMomTKU->GetXaxis()->SetTitle("xPy - yPx (mm MeV/c)");
mHAngMomTKU->GetYaxis()->SetTitle("Radius (mm)");
mHAngMomTKD = new TH2D("hAngMomTKD", "PR Canonical AM vs Radius TkD",
200, -4000, 2000, 200, 0, 150);
mHAngMomTKD->GetXaxis()->SetTitle("xPy - yPx (mm MeV/c)");
mHAngMomTKD->GetYaxis()->SetTitle("Radius (mm)");
}
bool AnalyserTrackerAngularMomentum::analyse(MAUS::ReconEvent* const aReconEvent,
MAUS::MCEvent* const aMCEvent) {
if (!aReconEvent)
return false;
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
if (!sfevt)
return false;
// Loop over all the scifi tracks in this event
for (auto trk : sfevt->scifitracks()) {
// Access the SciFiSeed associate with this track
MAUS::SciFiSeed* seed = ExtractSeed(trk);
if (!seed)
continue;
// Access the PR track from the SciFiSeed in order to extract the radius
TObject* pr_track_obj = seed->getPRTrackTobject();
if (!pr_track_obj) {
// std::cerr << "Empty PR track TObject pointer, skipping track" << std::endl;
continue;
}
MAUS::SciFiHelicalPRTrack* htrk =
dynamic_cast<MAUS::SciFiHelicalPRTrack*>(pr_track_obj); // NOLINT(runtime/rtti)
if (!htrk) {
// std::cerr << "PR track dynamic cast failed, source pointer address "
// << pr_track_obj << std::endl;
continue;
}
double radius = htrk->get_R();
// Pull out the associated trackpoints, get the position and momentum for the selected station
// and plane, and then fill the histograms
for (auto tp : trk->scifitrackpoints()) {
if ((tp->station() == mAnalysisStation) && (tp->plane() == mAnalysisPlane)) {
MAUS::ThreeVector pos = tp->pos();
MAUS::ThreeVector mom = tp->mom();
double am = (pos.x() * mom.y()) - (pos.y() * mom.x());
if (tp->tracker() == 0) {
mHAngMomTKU->Fill(am, radius);
} else if (tp->tracker() == 1) {
mHAngMomTKD->Fill(am, radius);
}
} // ~if on reference plane
} // ~Loop over trackpoints
} // ~Loop over tracks
return true;
}
bool AnalyserTrackerAngularMomentum::draw(std::shared_ptr<TVirtualPad> aPad) {
// If no data, don't bother drawing the canvas
if (mHAngMomTKU->GetEntries() < 1.0 && mHAngMomTKD->GetEntries() < 1.0) {
return false;
}
GetPads()[0]->Divide(2, 1);
GetPads()[0]->cd(1);
mHAngMomTKU->Draw("COLZ");
GetPads()[0]->cd(2);
mHAngMomTKD->Draw("COLZ");
return true;
}
MAUS::SciFiSeed* AnalyserTrackerAngularMomentum::ExtractSeed(MAUS::SciFiTrack* aTrack) const {
MAUS::SciFiSeed* seed = aTrack->scifi_seed();
if (!seed) {
// std::cerr << "Empty seed pointer at: " << seed << std::endl;
}
TObject* seed_obj = aTrack->scifi_seed_tobject();
if (!seed_obj) {
std::cerr << "Empty seed TObject pointer" << std::endl;
}
if (!seed && !seed_obj) {
// std::cerr << "No seed pointer at all" << std::endl;
return NULL;
}
if (!seed && seed_obj) {
seed = dynamic_cast<MAUS::SciFiSeed*>(seed_obj); // NOLINT(runtime/rtti)
if (!seed) {
// std::cerr << "Dynamic cast from SciFiSeed TObject failed" << std::endl;
return NULL;
}
}
return seed;
}
void AnalyserTrackerAngularMomentum::merge(AnalyserTrackerAngularMomentum* aAnalyser) {
mHAngMomTKU->Add(aAnalyser->mHAngMomTKU);
mHAngMomTKD->Add(aAnalyser->mHAngMomTKD);
}
} // ~namespace mica
<file_sep>/src/AnalyserTrackerKFMomentum.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "mica/AnalyserTrackerKFMomentum.hh"
#include <algorithm>
#include <cmath>
#include "TCanvas.h"
#include "TRef.h"
#include "src/common_cpp/DataStructure/SciFiTrack.hh"
#include "src/common_cpp/DataStructure/SciFiTrackPoint.hh"
namespace mica {
AnalyserTrackerKFMomentum::AnalyserTrackerKFMomentum() : mAnalysisStation{1},
mAnalysisPlane{0},
mHPUSDS{nullptr},
mHPtPzTkU{nullptr},
mHPtPzTkD{nullptr} {
int nbins = 100;
mHPUSDS = std::unique_ptr<TH2D>(new TH2D("hPUSDS", "TkU p vs TkD p",
nbins, 0, 300, nbins, 0, 300));
mHPUSDS->GetXaxis()->SetTitle("tku p (MeV/c)");
mHPUSDS->GetYaxis()->SetTitle("tkd p (MeV/c)");
mHPtPzTkU = std::unique_ptr<TH2D>(new TH2D("hPtPzTkU", "Recon pt vs Recon pz TkU",
nbins, 0, 100, nbins, 0, 300));
mHPtPzTkU->GetXaxis()->SetTitle("pt (MeV/c)");
mHPtPzTkU->GetYaxis()->SetTitle("pz (MeV/c)");
mHPtPzTkD = std::unique_ptr<TH2D>(new TH2D("hPtPzTkD", "Recon pt vs Recon pz TkD",
nbins, 0, 100, nbins, 0, 300));
mHPtPzTkD->GetXaxis()->SetTitle("pt (MeV/c)");
mHPtPzTkD->GetYaxis()->SetTitle("pz (MeV/c)");
}
bool AnalyserTrackerKFMomentum::analyse(MAUS::ReconEvent* const aReconEvent,
MAUS::MCEvent* const aMCEvent) {
if (!aReconEvent) return false;
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
if (!sfevt) return false;
// Check and pull out the tracker data
std::vector<MAUS::SciFiTrack*> trks = sfevt->scifitracks();
if (trks.size() != 2) return false;
std::vector<MAUS::SciFiTrack*> tku_trks;
std::vector<MAUS::SciFiTrack*> tkd_trks;
for (auto trk : trks) {
if (trk->tracker() == 0)
tku_trks.push_back(trk);
else if (trk->tracker() == 1)
tkd_trks.push_back(trk);
}
if (tku_trks.size() != 1 && tkd_trks.size() != 1) return false;
// Pull out the associated trackpoints, get the momentum
MAUS::ThreeVector mom_tku;
MAUS::ThreeVector mom_tkd;
bool tku_good = GetMomentum(tku_trks[0], mom_tku);
bool tkd_good = GetMomentum(tkd_trks[0], mom_tkd);
// Fill the histograms
if (tku_good && tkd_good) {
double tku_mag =
sqrt(mom_tku.x()*mom_tku.x() + mom_tku.y()*mom_tku.y() + mom_tku.z()*mom_tku.z());
double tkd_mag =
sqrt(mom_tkd.x()*mom_tkd.x() + mom_tkd.y()*mom_tkd.y() + mom_tkd.z()*mom_tkd.z());
mHPUSDS->Fill(tku_mag, tkd_mag);
}
if (tku_good) mHPtPzTkU->Fill(sqrt(mom_tku.x()*mom_tku.x() + mom_tku.y()*mom_tku.y()), mom_tku.z());
if (tkd_good) mHPtPzTkD->Fill(sqrt(mom_tkd.x()*mom_tkd.x() + mom_tkd.y()*mom_tkd.y()), mom_tkd.z());
return true;
}
bool AnalyserTrackerKFMomentum::draw(std::shared_ptr<TVirtualPad> aPad) {
GetStyle()->SetOptStat(111111);
if (GetPads().size() == 1) {
GetPads()[0]->Divide(2);
GetPads()[0]->Draw();
AddPad(std::shared_ptr<TVirtualPad>(new TCanvas()));
}
update();
return true;
}
void AnalyserTrackerKFMomentum::update() {
auto pads = GetPads();
pads[0]->cd(1);
mHPtPzTkU->Draw("COLZ");
pads[0]->cd(2);
pads[0]->Update();
mHPtPzTkD->Draw("COLZ");
pads[1]->cd();
mHPUSDS->Draw("COLZ");
pads[1]->Update();
}
bool AnalyserTrackerKFMomentum::GetMomentum(const MAUS::SciFiTrack* const trk,
MAUS::ThreeVector& mom) {
MAUS::ThreeVector mom_out;
bool found = false;
for (auto tp : trk->scifitrackpoints()) {
if ((tp->station() == mAnalysisStation) && (tp->plane() == mAnalysisPlane)) {
mom_out = tp->mom();
found = true;
}
}
if (found) mom = mom_out;
return found;
}
} // ~namespace mica
<file_sep>/include/mica/AnalyserTrackerPRStats.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef ANALYSERTRACKERPRSTATS_HH
#define ANALYSERTRACKERPRSTATS_HH
#include <vector>
#include "TVirtualPad.h"
#include "TH2.h"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
#include "mica/AnalyserBase.hh"
namespace mica {
/** @class AnalyserTrackerPRStats
* Calculate the chisq per dof for patrec tracks and plot them
* @author <NAME>
*/
class AnalyserTrackerPRStats : public AnalyserBase {
public:
AnalyserTrackerPRStats();
~AnalyserTrackerPRStats() {}
private:
virtual bool analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) override;
virtual bool draw(std::shared_ptr<TVirtualPad> aPad) override;
TH1D* mHCircleChiSqTKU; ///< mHCircleChiSqTKU Histogram for TkU circle chisq per dof
TH1D* mHCircleChiSqTKD; ///< mHCircleChiSqTKD Histogram for TkD circle chisq per dof
TH1D* mHSZChiSqTKU; ///< mHSZChiSqTKU Histogram for TkU sz chisq per dof
TH1D* mHSZChiSqTKD; ///< mHSZChiSqTKD Histogram for TkD sz chisq per dof
};
} // ~namespace mica
#endif
<file_sep>/include/mica/AnalyserTrackerPRSeedResidual.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef ANALYSERTRACKERPRSEEDRESIDUAL_HH
#define ANALYSERTRACKERPRSEEDRESIDUAL_HH
#include <vector>
#include "TVirtualPad.h"
#include "TH1.h"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
#include "mica/AnalyserBase.hh"
namespace mica {
class AnalyserTrackerPRSeedResidual : public AnalyserBase {
public:
AnalyserTrackerPRSeedResidual();
~AnalyserTrackerPRSeedResidual() {}
/** @brief Return if plots should be a log scale on y axis */
bool getLogScale() const { return mLogScale; }
/** @brief Set if plots should be a log scale on y axis */
void setLogScale(bool aLogScale) { mLogScale = aLogScale; }
private:
virtual bool analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) override;
virtual bool draw(std::shared_ptr<TVirtualPad> aPad) override;
bool mLogScale; ///< Should plots be a log scale on y axis
std::vector<TH1D*> mHResidualsTkU; ///< TkU residuals of seeds from fit
std::vector<TH1D*> mHResidualsTkD; ///< TkD residuals of seeds from fit
};
} // ~namespace mica
#endif
<file_sep>/src/AnalyserTrackerMCPRResiduals.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "mica/AnalyserTrackerMCPRResiduals.hh"
#include <cmath>
#include "TCanvas.h"
#include "TStyle.h"
#include "src/common_cpp/DataStructure/Hit.hh"
#include "src/common_cpp/DataStructure/SciFiSpacePoint.hh"
#include "src/common_cpp/DataStructure/SciFiHelicalPRTrack.hh"
#include "src/common_cpp/DataStructure/SciFiEvent.hh"
namespace mica {
AnalyserTrackerMCPRResiduals::AnalyserTrackerMCPRResiduals() : mHTkUMCPositionX{nullptr},
mHTkUMCPositionY{nullptr},
mHTkUMCMomentumT{nullptr},
mHTkUMCMomentumZ{nullptr},
mHTkURecPositionX{nullptr},
mHTkURecPositionY{nullptr},
mHTkURecMomentumT{nullptr},
mHTkURecMomentumZ{nullptr},
mHTkUPositionResidualsX{nullptr},
mHTkUPositionResidualsY{nullptr},
mHTkUMomentumResidualsT{nullptr},
mHTkUMomentumResidualsZ{nullptr},
mHTkUPtResPt{nullptr},
mHTkUPzResPt{nullptr},
mHTkUPtResPzRec{nullptr},
mHTkUPzResPzRec{nullptr},
mHTkDMCPositionX{nullptr},
mHTkDMCPositionY{nullptr},
mHTkDMCMomentumT{nullptr},
mHTkDMCMomentumZ{nullptr},
mHTkDRecPositionX{nullptr},
mHTkDRecPositionY{nullptr},
mHTkDRecMomentumT{nullptr},
mHTkDRecMomentumZ{nullptr},
mHTkDPositionResidualsX{nullptr},
mHTkDPositionResidualsY{nullptr},
mHTkDMomentumResidualsT{nullptr},
mHTkDMomentumResidualsZ{nullptr},
mHTkDPtResPt{nullptr},
mHTkDPzResPt{nullptr},
mHTkDPtResPzRec{nullptr},
mHTkDPzResPzRec{nullptr} {
mHTkUMCPositionX = new TH1D("hTkUMCPositionX", "TkU MC x ", 100, -170, 170);
mHTkUMCPositionY = new TH1D("hTkUMCPositionY", "TkU MC y ", 100, -170, 170);
mHTkUMCMomentumT = new TH1D("hTkUMCMomentumT", "TkU MC pt ", 100, 0, 100);
mHTkUMCMomentumZ = new TH1D("hTkUMCMomentumZ", "TkU MC pz ", 100, 0, 300);
mHTkURecPositionX = new TH1D("hTkURecPositionX", "TkU Recon x ", 100, -170, 170);
mHTkURecPositionY = new TH1D("hTkURecPositionY", "TkU Recon y ", 100, -170, 170);
mHTkURecMomentumT = new TH1D("hTkURecMomentumT", "TkU Recon pt ", 100, 0, 100);
mHTkURecMomentumZ = new TH1D("hTkURecMomentumZ", "TkU Recon pz ", 100, -300, 300);
mHTkUPositionResidualsX = new TH1D("hTkUPositionResidualsX", "TkU x Residuals", 100, -5, 5);
mHTkUPositionResidualsY = new TH1D("hTkUPositionResidualsY", "TkU y Residuals", 100, -5, 5);
mHTkUMomentumResidualsT = new TH1D("hTkUMomentumResidualsT", "TkU pt Residuals", 100, -20, 20);
mHTkUMomentumResidualsZ = new TH1D("hTkUMomentumResidualsZ", "TkU pz Residuals", 100, -50, 200);
mHTkUPtResPt = new TH2D("hTkUPtResPt", "TkU pt residuals vs ptmc", 100, 0, 100, 100, -20, 20);
mHTkUPzResPt = new TH2D("hTkUPzResPt", "TkU pz residuals vs ptmc", 100, 0, 100, 100, -300, 300);
mHTkUPtResPzRec = new TH2D("hTkUPtResPzRec", "TkU pt residuals vs pzrec", 100, -300, 300, 100, -20, 20);
mHTkUPzResPzRec = new TH2D("hTkUPzResPzRec", "TkU pz residuals vs pzrec", 100, -300, 300, 100, -200, 200);
mHTkDMCPositionX = new TH1D("hTkDMCPositionX", "TkD MC x ", 100, -170, 170);
mHTkDMCPositionY = new TH1D("hTkDMCPositionY", "TkD MC y ", 100, -170, 170);
mHTkDMCMomentumT = new TH1D("hTkDMCMomentumT", "TkD MC pt ", 100, 0, 100);
mHTkDMCMomentumZ = new TH1D("hTkDMCMomentumZ", "TkD MC pz ", 100, 0, 300);
mHTkDRecPositionX = new TH1D("hTkDRecPositionX", "TkU Recon x ", 100, -170, 170);
mHTkDRecPositionY = new TH1D("hTkDRecPositionY", "TkU Recon y ", 100, -170, 170);
mHTkDRecMomentumT = new TH1D("hTkDRecMomentumT", "TkU Recon pt ", 100, 0, 100);
mHTkDRecMomentumZ = new TH1D("hTkDRecMomentumZ", "TkU Recon pz ", 100, -300, 300);
mHTkDPositionResidualsX = new TH1D("hTkDPositionResidualsX", "TkD x Residuals", 100, -5, 5);
mHTkDPositionResidualsY = new TH1D("hTkDPositionResidualsY", "TkD y Residuals", 100, -5, 5);
mHTkDMomentumResidualsT = new TH1D("hTkDMomentumResidualsT", "TkD pt Residuals", 100, -20, 20);
mHTkDMomentumResidualsZ = new TH1D("hTkDMomentumResidualsZ", "TkD pz Residuals", 100, -50, 200);
mHTkDPtResPt = new TH2D("hTkDPtResPt", "TkD pt residuals vs ptmc", 100, 0, 100, 100, -20, 20);
mHTkDPzResPt = new TH2D("hTkDPzResPt", "TkD pz residuals vs ptmc", 100, 0, 100, 100, -300, 300);
mHTkDPtResPzRec = new TH2D("hTkDPtResPzRec", "TkD pt residuals vs pzrec", 100, -300, 300, 100, -20, 20);
mHTkDPzResPzRec = new TH2D("hTkDPzResPzRec", "TkD pz residuals vs pzrec", 100, -300, 300, 100, -200, 200);
}
bool AnalyserTrackerMCPRResiduals::analyse(MAUS::ReconEvent* const aReconEvent,
MAUS::MCEvent* const aMCEvent) {
if (!aReconEvent || !aMCEvent) {
return false;
}
// Find a hit from a muon in the tracker references plane for each tracker
MAUS::SciFiHit* tku_ref_hit = nullptr;
MAUS::SciFiHit* tkd_ref_hit = nullptr;
for (auto&& hitref : *(aMCEvent->GetSciFiHits())) {
MAUS::SciFiHit* hit = &hitref;
int pid = hit->GetParticleId();
if (pid != 13 && pid != -13)
continue;
if (hit->GetChannelId()->GetStationNumber() == 1 && \
hit->GetChannelId()->GetPlaneNumber() == 0) {
if (hit->GetChannelId()->GetTrackerNumber() == 0) {
tku_ref_hit = hit;
} else if (hit->GetChannelId()->GetTrackerNumber() == 1) {
tkd_ref_hit = hit;
}
}
if (tku_ref_hit && tkd_ref_hit)
break;
}
if (!tku_ref_hit || !tkd_ref_hit) {
return false;
}
// Access the SciFi Event
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
if (!sfevt) {
return false;
}
// Loop over all the scifi tracks in this event
int nTkURecTracks = 0;
int nTkDRecTracks = 0;
MAUS::SciFiHelicalPRTrack* tku_trk = nullptr;
MAUS::SciFiHelicalPRTrack* tkd_trk = nullptr;
for (auto trk : sfevt->helicalprtracks()) {
if (trk->get_tracker() == 0) {
++nTkURecTracks;
tku_trk = trk;
} else if (trk->get_tracker() == 1) {
++nTkDRecTracks;
tkd_trk = trk;
}
}
// Require 1 recon track in each tracker
if (nTkURecTracks != 1 || nTkDRecTracks != 1) {
return false;
}
if (tku_trk->get_spacepoints_pointers().size() != 5 ||
tkd_trk->get_spacepoints_pointers().size() != 5) {
return false;
}
// At this point we should an event that is good to analyse
// Calculate the recon postion at the reference station, and the recon momentum (average)
double tku_x = 0.0;
double tku_y = 0.0;
for (auto sp : tku_trk->get_spacepoints_pointers()) {
if (sp->get_station() == 1) {
tku_x = sp->get_global_position().x();
tku_y = sp->get_global_position().y();
}
}
double tkd_x = 0.0;
double tkd_y = 0.0;
for (auto sp : tkd_trk->get_spacepoints_pointers()) {
if (sp->get_station() == 1) {
tkd_x = sp->get_global_position().x();
tkd_y = sp->get_global_position().y();
}
}
double tku_dx = tku_x - tku_ref_hit->GetPosition().x();
double tku_dy = tku_y - tku_ref_hit->GetPosition().y();
double tku_ptmc = sqrt(tku_ref_hit->GetMomentum().x()*tku_ref_hit->GetMomentum().x() +
tku_ref_hit->GetMomentum().y()*tku_ref_hit->GetMomentum().y());
double tku_ptrec = 0.3*mBfield*tku_trk->get_R(); // 0.3 comes from mom being in MeV and rad in mm
double tku_dpt = tku_ptrec - tku_ptmc;
double tku_pzrec = tku_ptrec / tku_trk->get_dsdz();
double tku_dpz = tku_pzrec + tku_ref_hit->GetMomentum().z();
double tkd_dx = tkd_x - tkd_ref_hit->GetPosition().x();
double tkd_dy = tkd_y - tkd_ref_hit->GetPosition().y();
double tkd_ptmc = sqrt(tkd_ref_hit->GetMomentum().x()*tkd_ref_hit->GetMomentum().x() +
tkd_ref_hit->GetMomentum().y()*tkd_ref_hit->GetMomentum().y());
double tkd_ptrec = 0.3*mBfield*tkd_trk->get_R(); // 0.3 comes from mom being in MeV and rad in mm
double tkd_dpt = tkd_ptrec - tkd_ptmc;
double tkd_pzrec = tkd_ptrec / tkd_trk->get_dsdz();
double tkd_dpz = tkd_pzrec + tkd_ref_hit->GetMomentum().z();
// Fill the histograms
mHTkUMCPositionX->Fill(tku_ref_hit->GetPosition().x());
mHTkUMCPositionY->Fill(tku_ref_hit->GetPosition().y());
mHTkUMCMomentumT->Fill(tku_ptmc);
mHTkUMCMomentumZ->Fill(tku_ref_hit->GetMomentum().z());
mHTkURecPositionX->Fill(tku_x);
mHTkURecPositionY->Fill(tku_y);
mHTkURecMomentumT->Fill(tku_ptrec);
mHTkURecMomentumZ->Fill(tku_pzrec);
mHTkUPositionResidualsX->Fill(tku_dx);
mHTkUPositionResidualsY->Fill(tku_dy);
mHTkUMomentumResidualsT->Fill(tku_dpt);
mHTkUMomentumResidualsZ->Fill(tku_dpz);
mHTkUPtResPt->Fill(tku_ptmc, tku_dpt);
mHTkUPzResPt->Fill(tku_ptmc, tku_dpz);
mHTkUPtResPzRec->Fill(tku_pzrec, tku_dpt);
mHTkUPzResPzRec->Fill(tku_pzrec, tku_dpz);
mHTkDMCPositionX->Fill(tkd_ref_hit->GetPosition().x());
mHTkDMCPositionY->Fill(tkd_ref_hit->GetPosition().y());
mHTkDMCMomentumT->Fill(tkd_ptmc);
mHTkDMCMomentumZ->Fill(tkd_ref_hit->GetMomentum().z());
mHTkDRecPositionX->Fill(tkd_x);
mHTkDRecPositionY->Fill(tkd_y);
mHTkDRecMomentumT->Fill(tkd_ptrec);
mHTkDRecMomentumZ->Fill(tkd_pzrec);
mHTkDPositionResidualsX->Fill(tkd_dx);
mHTkDPositionResidualsY->Fill(tkd_dy);
mHTkDMomentumResidualsT->Fill(tkd_dpt);
mHTkDMomentumResidualsZ->Fill(tkd_dpz);
mHTkDPtResPt->Fill(tkd_ptmc, tkd_dpt);
mHTkDPzResPt->Fill(tkd_ptmc, tkd_dpz);
mHTkDPtResPzRec->Fill(tkd_pzrec, tkd_dpt);
mHTkDPzResPzRec->Fill(tkd_pzrec, tkd_dpz);
return true;
}
bool AnalyserTrackerMCPRResiduals::draw(std::shared_ptr<TVirtualPad> aPad) {
GetStyle()->SetOptStat(111111);
// Draw the MC distribution
std::shared_ptr<TVirtualPad> padMC = std::shared_ptr<TVirtualPad>(new TCanvas());
padMC->cd();
padMC->Divide(4, 2);
padMC->cd(1);
mHTkUMCPositionX->Draw();
padMC->cd(2);
mHTkUMCPositionY->Draw();
padMC->cd(3);
mHTkUMCMomentumT->Draw();
padMC->cd(4);
mHTkUMCMomentumZ->Draw();
padMC->cd(5);
mHTkDMCPositionX->Draw();
padMC->cd(6);
mHTkDMCPositionY->Draw();
padMC->cd(7);
mHTkDMCMomentumT->Draw();
padMC->cd(8);
mHTkDMCMomentumZ->Draw();
// Draw the Recon distribution
std::shared_ptr<TVirtualPad> padRec = std::shared_ptr<TVirtualPad>(new TCanvas());
padRec->cd();
padRec->Divide(4, 2);
padRec->cd(1);
mHTkURecPositionX->Draw();
padRec->cd(2);
mHTkURecPositionY->Draw();
padRec->cd(3);
mHTkURecMomentumT->Draw();
padRec->cd(4);
mHTkURecMomentumZ->Draw();
padRec->cd(5);
mHTkDRecPositionX->Draw();
padRec->cd(6);
mHTkDRecPositionY->Draw();
padRec->cd(7);
mHTkDRecMomentumT->Draw();
padRec->cd(8);
mHTkDRecMomentumZ->Draw();
// Draw the residuals with a linear scale
GetPads()[0]->cd();
GetPads()[0]->Divide(4, 2);
GetPads()[0]->cd(1);
mHTkUPositionResidualsX->Draw();
GetPads()[0]->cd(2);
mHTkUPositionResidualsY->Draw();
GetPads()[0]->cd(3);
mHTkUMomentumResidualsT->Draw();
GetPads()[0]->cd(4);
mHTkUMomentumResidualsZ->Draw();
GetPads()[0]->cd(5);
mHTkDPositionResidualsX->Draw();
GetPads()[0]->cd(6);
mHTkDPositionResidualsY->Draw();
GetPads()[0]->cd(7);
mHTkDMomentumResidualsT->Draw();
GetPads()[0]->cd(8);
mHTkDMomentumResidualsZ->Draw();
// Draw the residuals with a log scale
std::shared_ptr<TVirtualPad> pad2 = std::shared_ptr<TVirtualPad>(new TCanvas());
pad2->Divide(4, 2);
pad2->cd(1);
pad2->GetPad(1)->SetLogy(1);
mHTkUPositionResidualsX->Draw();
pad2->cd(2);
pad2->GetPad(2)->SetLogy(1);
mHTkUPositionResidualsY->Draw();
pad2->cd(3);
pad2->GetPad(3)->SetLogy(1);
mHTkUMomentumResidualsT->Draw();
pad2->cd(4);
pad2->GetPad(4)->SetLogy(1);
mHTkUMomentumResidualsZ->Draw();
pad2->cd(5);
pad2->GetPad(5)->SetLogy(1);
mHTkDPositionResidualsX->Draw();
pad2->cd(6);
pad2->GetPad(6)->SetLogy(1);
mHTkDPositionResidualsY->Draw();
pad2->cd(7);
pad2->GetPad(7)->SetLogy(1);
mHTkDMomentumResidualsT->Draw();
pad2->cd(8);
pad2->GetPad(8)->SetLogy(1);
mHTkDMomentumResidualsZ->Draw();
// Draw the graphs
std::shared_ptr<TVirtualPad> pad2d = std::shared_ptr<TVirtualPad>(new TCanvas());
pad2d->Divide(2, 2);
pad2d->cd(1);
mHTkUPtResPt->Draw("COLZ");
pad2d->cd(2);
mHTkUPzResPt->Draw("COLZ");
pad2d->cd(3);
mHTkDPtResPt->Draw("COLZ");
pad2d->cd(4);
mHTkDPzResPt->Draw("COLZ");
std::shared_ptr<TVirtualPad> padResPzRec = std::shared_ptr<TVirtualPad>(new TCanvas());
padResPzRec->Divide(2, 2);
padResPzRec->cd(1);
mHTkUPtResPzRec->Draw("COLZ");
padResPzRec->cd(2);
mHTkUPzResPzRec->Draw("COLZ");
padResPzRec->cd(3);
mHTkDPtResPzRec->Draw("COLZ");
padResPzRec->cd(4);
mHTkDPzResPzRec->Draw("COLZ");
AddPad(padMC);
AddPad(padRec);
AddPad(pad2);
AddPad(pad2d);
AddPad(padResPzRec);
return true;
}
void AnalyserTrackerMCPRResiduals::merge(AnalyserTrackerMCPRResiduals* aAnalyser) {
mHTkUPositionResidualsX->Add(aAnalyser->mHTkUPositionResidualsX);
mHTkUPositionResidualsY->Add(aAnalyser->mHTkUPositionResidualsY);
mHTkUMomentumResidualsT->Add(aAnalyser->mHTkUMomentumResidualsT);
mHTkUMomentumResidualsZ->Add(aAnalyser->mHTkUMomentumResidualsZ);
mHTkDPositionResidualsX->Add(aAnalyser->mHTkDPositionResidualsX);
mHTkDPositionResidualsY->Add(aAnalyser->mHTkDPositionResidualsY);
mHTkDMomentumResidualsT->Add(aAnalyser->mHTkDMomentumResidualsT);
mHTkDMomentumResidualsZ->Add(aAnalyser->mHTkDMomentumResidualsZ);
}
} // ~namespace mica
<file_sep>/include/mica/AnalyserTrackerSpacePointSearchStation.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef ANALYSERTRACKERSPACEPOINTSEARCHSTATION_HH
#define ANALYSERTRACKERSPACEPOINTSEARCHSTTAION_HH
#include <vector>
#include "TVirtualPad.h"
#include "TH2.h"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
#include "mica/AnalyserBase.hh"
namespace mica {
class AnalyserTrackerSpacePointSearchStation : public AnalyserBase {
public:
AnalyserTrackerSpacePointSearchStation();
~AnalyserTrackerSpacePointSearchStation() {}
private:
virtual bool analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) override;
virtual bool draw(std::shared_ptr<TVirtualPad> aPad) override;
std::vector<TH2D*> mHSeeds;
std::vector<TH2D*> mHAddOns;
};
} // ~namespace mica
#endif
<file_sep>/src/AnalyserTrackerSpacePointSearch.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "mica/AnalyserTrackerSpacePointSearch.hh"
namespace mica {
AnalyserTrackerSpacePointSearch::AnalyserTrackerSpacePointSearch() : mHSeeds(NULL), mHAddOns(NULL) {
mHSeeds = new TH2D("hSeeds", "Seed Pull vs NPE", 100, 0, 30, 100, 0, 200);
mHSeeds->GetXaxis()->SetTitle("Pull (mm)");
mHSeeds->GetYaxis()->SetTitle("NPE");
mHAddOns = new TH2D("hAddOns", "Add-On Seed Pull vs NPE", 100, 0, 30, 100, 0, 200);
mHAddOns->GetXaxis()->SetTitle("Pull (mm)");
mHAddOns->GetYaxis()->SetTitle("NPE");
}
bool AnalyserTrackerSpacePointSearch::analyse(MAUS::ReconEvent* const aReconEvent,
MAUS::MCEvent* const aMCEvent) {
if (!aReconEvent)
return false;
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
for (auto trk : sfevt->helicalprtracks()) {
for (auto sp : trk->get_spacepoints_pointers()) {
double npe = sp->get_npe();
double pull = sp->get_prxy_pull();
mHSeeds->Fill(pull, npe);
if (sp->get_add_on()) {
mHAddOns->Fill(pull, npe);
}
} // Loop over seed spacepoints
} // ~Loop over tracks
return true;
}
bool AnalyserTrackerSpacePointSearch::draw(std::shared_ptr<TVirtualPad> aPad) {
GetPads()[0]->Divide(3, 2);
GetPads()[0]->cd(1);
mHSeeds->Draw("COLZ");
GetPads()[0]->cd(2);
mHSeeds->ProjectionX()->Draw();
GetPads()[0]->cd(3);
mHSeeds->ProjectionY()->Draw();
GetPads()[0]->cd(4);
mHAddOns->Draw("COLZ");
GetPads()[0]->cd(5);
mHAddOns->ProjectionX()->Draw();
GetPads()[0]->cd(6);
mHAddOns->ProjectionY()->Draw();
return true;
}
} // ~namespace mica
<file_sep>/app/event-viewer.cc
/** The main application for the Muon Ionization Cooling Analysis (MICA) framework */
// std library headers
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <memory>
// ROOT headers
#include "TApplication.h"
#include "TGClient.h"
#include "TStyle.h"
#include "TFile.h"
#include "TTree.h"
#include "TVirtualPad.h"
// MAUS headers
#include "src/common_cpp/DataStructure/Spill.hh"
#include "src/common_cpp/DataStructure/Data.hh"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
// MICA headers
#include "mica/AnalyserBase.hh"
#include "mica/AnalyserFactory.hh"
#include "mica/AnalyserTrackerPRSeedResidual.hh"
#include "mica/AnalyserTrackerPREfficiency.hh"
int main(int argc, char *argv[]) {
// Instantiate the analysers required
std::vector<std::string> anl_names {"AnalyserTrackerKFMomentum",
"AnalyserTofTracker",
"AnalyserViewerRealSpace"};
std::vector<mica::AnalyserBase*> analysers = mica::AnalyserFactory::CreateAnalysers(anl_names);
// Should we pause between events?
bool bool_pause = true;
// Set up the input and output files using the programme arguments
std::string infile = "";
std::string outfile = "viewer.pdf";
if (argc > 1) {
infile = std::string(argv[1]); // 1st arg to code should be input ROOT file name
} else {
std::cerr << "Please enter the input file name as the first argument and try again\n";
return -1;
}
TApplication theApp("App", &argc, argv); // Set up the ROOT application for live plotting
TFile f1(infile.c_str());
if (!f1.IsOpen()) {
std::cerr << "Failed to find file: " << infile <<std::endl;
return -1;
}
std::cout << "Input file " << infile << std::endl;
if (argc > 2) outfile = std::string(argv[2]);
std::cout << "Output file " << outfile << std::endl;
// Set up access to ROOT data from input file
TTree* T = static_cast<TTree*>(f1.Get("Spill"));
MAUS::Data* data = nullptr; // Don't forget = nullptr or you get a seg fault
T->SetBranchAddress("data", &data); // Yes, this is the *address* of a *pointer*
int nentries = T->GetEntries();
std::cerr << "Found " << nentries << " spills\n";
// Loop over all spills
int spills_processed = 0;
int events_processed = 0;
for (int i = 0; i < nentries; ++i) {
++spills_processed;
T->GetEntry(i);
if (!data) {
std::cout << "Data is NULL\n";
continue;
}
MAUS::Spill* spill = data->GetSpill();
if (spill == nullptr) {
std::cout << "Spill is NULL\n";
continue;
}
if (spill->GetDaqEventType() != "physics_event") {
// std::cout << "Spill is of type " << spill->GetDaqEventType() << ", not a usable spill\n";
continue;
}
// Call the analysers
for (auto an : analysers) {
an->Draw();
}
int event_counter = 0;
for (auto revt : (*(spill->GetReconEvents()))) {
MAUS::MCEvent* mevt = nullptr;
if (event_counter < static_cast<int>(spill->GetMCEvents()->size()))
mevt = spill->GetMCEvents()->at(event_counter);
for (auto an : analysers) {
an->Analyse(revt, mevt);
an->Update();
for (auto pad : an->GetPads()) {
if (pad) {
pad->Update();
}
}
}
if (bool_pause) {
std::cout << "Press Enter to Continue";
std::cin.ignore();
}
++event_counter;
++events_processed;
}
std::cout << "Spills processed: " << spills_processed << " of " << nentries
<< ", events processed: " << events_processed << std::endl;
} // ~Loop over all spills
// Wrap up
for (auto an : analysers) {
delete an;
}
f1.Close();
theApp.Run();
return 0;
}
<file_sep>/src/AnalyserTrackerChannelHits.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include "mica/AnalyserTrackerChannelHits.hh"
#include "TCanvas.h"
#include "src/common_cpp/DataStructure/SciFiEvent.hh"
#include "src/common_cpp/DataStructure/SciFiDigit.hh"
namespace mica {
AnalyserTrackerChannelHits::AnalyserTrackerChannelHits() {
int nChannels = 214;
for (int iStation = 0; iStation < 5; ++iStation) {
for (int iPlane = 0; iPlane < 3; ++iPlane) {
std::string title = "Station " + std::to_string(iStation+1)
+ " Plane " + std::to_string(iPlane);
std::string name = "S" + std::to_string(iStation+1) + "P" + std::to_string(iPlane);
// Set up channel occupancy histograms
std::string tku_title_occ = "TkU Channel Occupancy " + title;
std::string tku_name_occ = "TkUOcc" + name;
std::string tkd_title_occ = "TkD Channel Occupancy " + title;
std::string tkd_name_occ = "TkDOcc" + name;
mTkU.emplace_back(new TH1I(tku_name_occ.c_str(), tku_title_occ.c_str(),
nChannels, 0, nChannels));
mTkD.emplace_back(new TH1I(tkd_name_occ.c_str(), tkd_title_occ.c_str(),
nChannels, 0, nChannels));
mTkU.back()->GetXaxis()->SetTitle("Channel Number");
mTkD.back()->GetXaxis()->SetTitle("Channel Number");
// Set up npe vs channel number plots
std::string tku_title_npe = "TkU Channel vs NPE " + title;
std::string tku_name_npe = "TkUNPE" + name;
std::string tkd_title_npe = "TkD Channel vs NPE " + title;
std::string tkd_name_npe = "TkDNPE" + name;
mNPETkU.emplace_back(new TH2D(tku_name_npe.c_str(), tku_title_npe.c_str(),
nChannels, 0, nChannels, 100, 0, 70));
mNPETkD.emplace_back(new TH2D(tkd_name_npe.c_str(), tkd_title_npe.c_str(),
nChannels, 0, nChannels, 100, 0, 70));
mNPETkU.back()->GetXaxis()->SetTitle("Channel Number");
mNPETkU.back()->GetYaxis()->SetTitle("NPE");
mNPETkD.back()->GetXaxis()->SetTitle("Channel Number");
mNPETkD.back()->GetYaxis()->SetTitle("NPE");
}
}
}
bool AnalyserTrackerChannelHits::analyse(MAUS::ReconEvent* const aReconEvent,
MAUS::MCEvent* const aMCEvent) {
// A few checks
if (!aReconEvent)
return false;
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
if (!sfevt)
return false;
// Populate the plots
for (auto dig : sfevt->digits()) {
int index = 3*(dig->get_station()-1) + dig->get_plane();
if (dig->get_tracker() == 0) {
mTkU[index]->Fill(dig->get_channel());
mNPETkU[index]->Fill(dig->get_channel(), dig->get_npe());
} else if (dig->get_tracker() == 1) {
mTkD[index]->Fill(dig->get_channel());
mNPETkD[index]->Fill(dig->get_channel(), dig->get_npe());
}
}
return true;
}
bool AnalyserTrackerChannelHits::draw(std::shared_ptr<TVirtualPad> aPad) {
GetStyle()->SetOptStat(111111);
int nStations = 5;
int nPlanes = 3;
// Set up the pads
std::vector<std::shared_ptr<TVirtualPad>> pads_occ;
pads_occ.push_back(GetPads()[0]);
std::vector<std::shared_ptr<TVirtualPad>> pads_npe;
pads_npe.push_back(std::shared_ptr<TVirtualPad>(new TCanvas()));
for (int i = 1; i < nStations; ++i) {
pads_occ.push_back(std::shared_ptr<TVirtualPad>(new TCanvas()));
pads_npe.push_back(std::shared_ptr<TVirtualPad>(new TCanvas()));
}
// Draw the plots
for (int iStation = 0; iStation < nStations; ++iStation) {
pads_occ[iStation]->Divide(nPlanes, 2);
pads_npe[iStation]->Divide(nPlanes, 2);
for (int iPlane = 0; iPlane < nPlanes; ++iPlane) {
pads_occ[iStation]->cd(iPlane+1);
int index = 3*iStation + iPlane;
mTkU[index]->Draw();
pads_npe[iStation]->cd(iPlane+1);
mNPETkU[index]->Draw("COLZ");
pads_occ[iStation]->cd(nPlanes + iPlane + 1);
mTkD[index]->Draw();
pads_npe[iStation]->cd(nPlanes + iPlane + 1);
mNPETkD[index]->Draw("COLZ");
}
}
// Add the pads to the analyser internal store
for (int i = 1; i < nStations; ++i) { // 1 as don't want to add default canvas again
AddPad(pads_occ[i]);
}
for (int i = 0; i < nStations; ++i) {
AddPad(pads_npe[i]);
}
return true;
}
} // ~namespace mica
<file_sep>/include/mica/AnalyserTrackerKFStats.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef ANALYSERTRACKERKFSTATS_HH
#define ANALYSERTRACKERKFSTATS_HH
#include <vector>
#include "TVirtualPad.h"
#include "TH2.h"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
#include "mica/AnalyserBase.hh"
namespace mica {
/** @class AnalyserTrackerKFStats
* Calculate the chisq per dof and p-value for kalman fit tracks and plot them
* @author <NAME>
*/
class AnalyserTrackerKFStats : public AnalyserBase {
public:
AnalyserTrackerKFStats();
~AnalyserTrackerKFStats() {}
private:
virtual bool analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent);
virtual bool draw(std::shared_ptr<TVirtualPad> aPad);
TH1D* mHChiSqTKU; ///< mHChiSqTKU Histogram for TkU circle chisq per dof
TH1D* mHChiSqTKD; ///< mHCircleChiSqTKD Histogram for TkD circle chisq per dof
TH1D* mHPValueTKU; ///< mHSZChiSqTKU Histogram for TkU p-value
TH1D* mHPValueTKD; ///< mHSZChiSqTKD Histogram for TkD p-value
};
} // ~namespace mica
#endif
<file_sep>/src/AnalyserTrackerMCPurity.cc
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#include <map>
#include "mica/AnalyserTrackerMCPurity.hh"
#include "TLatex.h"
#include "src/common_cpp/DataStructure/SciFiEvent.hh"
namespace mica {
AnalyserTrackerMCPurity::AnalyserTrackerMCPurity() : mHTracksMatched(nullptr) {
mHTracksMatched = new TH1I("hTracksMatched", "Recon Tracks Matched to MC Track IDs", 13, -3, 10);
}
bool AnalyserTrackerMCPurity::analyse_recon(MAUS::ReconEvent* const aReconEvent) {
// std::cout << "Found " << GetMCDataTkU().size() << " TkU tracks & " << GetMCDataTkD().size() <<
// " TkD tracks\n";
// Loop over pattern recognition helical tracks
MAUS::SciFiEvent* sfevt = aReconEvent->GetSciFiEvent();
for (auto trk : sfevt->helicalprtracks()) {
int track_id = find_mc_track_id(trk);
std::cout << "Found associated mc track id: " << track_id << std::endl;
mHTracksMatched->Fill(track_id);
}
clear_lookup();
clear_mc_data();
return true;
}
bool AnalyserTrackerMCPurity::draw(std::shared_ptr<TVirtualPad> aPad) {
GetPads()[0]->Divide(2);
GetPads()[0]->cd(1);
TLatex tl;
tl.SetTextSize(0.03);
tl.DrawLatex(0.1, 0.8, "PatRec Purity");
GetPads()[0]->cd();
tl.Draw();
GetPads()[0]->Update();
GetPads()[0]->cd(2);
mHTracksMatched->Draw();
GetPads()[0]->Update();
return true;
}
int AnalyserTrackerMCPurity::find_mc_track_id(MAUS::SciFiBasePRTrack* trk) {
std::vector<MAUS::SciFiHit*> all_track_hits;
auto htrk = dynamic_cast<MAUS::SciFiHelicalPRTrack*>(trk); // NOLINT
if (htrk) std::cerr << "Tk" << htrk->get_tracker() << " ";
std::cerr << "Recon track at " << trk << " has " << trk->get_spacepoints_pointers().size()
<< " seed spacepoints\n";
for (auto spnt : trk->get_spacepoints_pointers()) {
for (auto clus : spnt->get_channels_pointers()) {
for (auto dig : clus->get_digits_pointers()) {
// Perform the digits to hits lookup
std::vector<MAUS::SciFiHit*> hits;
bool lkup_result = GetLookup()->get_hits(dig, hits);
if (!lkup_result) {
std::cerr << "WARNING: AnalyserTrackerMCPurity: Lookup failed\n";
continue;
}
std::cerr << "Adding " << hits.size() << " hits, ";
all_track_hits.insert(all_track_hits.end(), hits.begin(), hits.end());
std::cerr << "now have " << all_track_hits.size() << " in total\n";
}
}
}
std::cerr << "Found " << all_track_hits.size() << " hits for this track\n";
if (all_track_hits.size() == 0) return -1;
// Sort track's scifi hits into map from station # to a vector holding the hits for that station
std::map<int, std::vector<MAUS::SciFiHit*> > hit_map;
for (auto hit : all_track_hits) {
hit_map[hit->GetChannelId()->GetStationNumber()].push_back(hit);
}
// Do we have 1 and only 1 mc_track_id which produced hits in >= 3 stations for this rec track
std::map<int, std::vector<int> > hit_stations = calc_stations_hit_by_track(hit_map, 2);
std::vector<int> reconstructible_mc_track_ids;
for (auto mctrack : hit_stations) {
std::cerr << " Track id " << mctrack.first << " hit " << mctrack.second.size() << " stations\n";
if (mctrack.second.size() >= 3) reconstructible_mc_track_ids.push_back(mctrack.first);
}
int mc_track_id = -1;
if (reconstructible_mc_track_ids.size() == 1) {
mc_track_id = reconstructible_mc_track_ids[0];
} else if (reconstructible_mc_track_ids.size() < 1) {
mc_track_id = -2;
} else if (reconstructible_mc_track_ids.size() > 1) {
mc_track_id = -3;
}
return mc_track_id;
}
} // ~namespace mica
<file_sep>/include/mica/AnalyserTrackerSpacePoints.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef ANALYSERTRACKERSPACEPOINTS_HH
#define ANALYSERTRACKERSPACEPOINTS_HH
#include <vector>
#include "TVirtualPad.h"
#include "TH2.h"
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
#include "mica/IAnalyser.hh"
namespace mica {
/** @class AnalyserTrackerSpacePoints
* Anayser class for producing spacepoint level plots for the trackers
* @author <NAME>
*/
class AnalyserTrackerSpacePoints : public IAnalyser<AnalyserTrackerSpacePoints> {
public:
AnalyserTrackerSpacePoints();
virtual ~AnalyserTrackerSpacePoints() {}
private:
virtual bool analyse(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent) override;
virtual bool draw(std::shared_ptr<TVirtualPad> aPad) override;
virtual void merge(AnalyserTrackerSpacePoints* aAnalyser) override;
const int mNStations = 5; ///< The number of tracker stations
std::unique_ptr<TH1D> mHNpeTKU; ///< Spacepoint NPE plot for TkU
std::unique_ptr<TH1D> mHNpeTKD; ///< Spacepoint NPE plot for TkD
std::unique_ptr<TH1D> mHStationNumTKU; ///< spacepoints per station plot for TkU
std::unique_ptr<TH1D> mHStationNumTKD; ///< spacepoints per station plot for TkD
std::unique_ptr<TH2D> mHXYTKU; ///< xy plot for TkU (over all stations)
std::unique_ptr<TH2D> mHXYTKD; ///< xy plot for TkD (over all stations)
std::vector<std::unique_ptr<TH2D> > mXYPerStationTkU; ///< xy plots for TkU, order by station
std::vector<std::unique_ptr<TH2D> > mXYPerStationTkD; ///< xy plots for TkD, order by station
std::vector<std::unique_ptr<TH2D> > mXYPerStationTripletsTkU; ///< xy plots for TkU triplets
std::vector<std::unique_ptr<TH2D> > mXYPerStationTripletsTkD; ///< xy plots for TkD triplets
std::vector<std::unique_ptr<TH2D> > mXYPerStationDoubletsTkU; ///< xy plots for TkU triplets
std::vector<std::unique_ptr<TH2D> > mXYPerStationDoubletsTkD; ///< xy plots for TkD triplets
};
} // ~namespace mica
#endif
<file_sep>/scripts/multithread.py
#!/usr/bin/env python
""" Run a program on multiple maus output files on multiple threads """
import sys
import os
import string
import argparse
import subprocess
import math
import threading
def launch_exe(files, namespace):
""" Worker thread function. Run an executable on a set of MAUS output files """
print threading.currentThread().getName(), ' starting'
for i, f in enumerate(files):
print threading.currentThread().getName(), ' analysing ' + f,
print ', file ' + str(i+1) + ' of ' + str(len(files))
# Extract the run number from the filename to set the output file name
loc, fname = os.path.split(f)
index = str.find(namespace.input_file, '#')
if index == -1:
print 'Could not extract run number from ' + fname + ', skipping'
continue
run_number = fname[index:index+namespace.pad]
ofile = string.replace(namespace.output_file, '#', str(run_number))
# Call the executable
subprocess.call([namespace.executable, f, ofile])
print threading.currentThread().getName(), ' exiting'
def run(namespace):
""" Loop over input root files, send each file for processing """
print 'Number of threads to run on: ' + str(namespace.nthreads)
print 'Executable: ' + namespace.executable
print 'Input directory: ' + namespace.input_dir
print 'Input file format: ' + namespace.input_file
print 'Output file format: ' + namespace.output_file
# Loop over run numbers and generate file names
ifilenames = []
for i in range(namespace.istart, namespace.istop, namespace.istep):
ifile = string.replace(namespace.input_file, '#', str(i).zfill(namespace.pad))
ifilenames.append(ifile)
print 'Number of input files requested: ' + str(len(ifilenames))
# Search the input directory recursively for files in
matches = []
lfiles = ifilenames[:]
for root, dirnames, filenames in os.walk(namespace.input_dir):
print 'Parsing directory: ' + root
# matches = matches + [os.path.join(root, f) for f in filenames if f in ifilenames]
for f in filenames:
if f in lfiles:
matches.append(os.path.join(root, f))
print 'Found ' + os.path.join(root, f)
del lfiles[lfiles.index(f)]
# print 'Files left: '
# print lfiles
if len(lfiles) == 0:
break
if len(lfiles) == 0:
break
print 'Number of matched input files found in data directory: ' + str(len(matches))
# Split the file set found into chunks to distribute to the threads
nfiles = len(matches)
chunk_size = int(math.ceil(float(nfiles) / float(namespace.nthreads)))
chunks = [matches[i:i + chunk_size] for i in xrange(0, len(matches), chunk_size)]
print 'Chunk size: ' + str(chunk_size)
# Set up the threads to process the chunks
threads = []
for i in range(namespace.nthreads):
if i > (len(chunks) - 1):
break
t = threading.Thread(target=launch_exe, args=(chunks[i], namespace))
threads.append(t)
t.start()
for t in threads:
t.join()
if __name__ == "__main__" :
parser = argparse.ArgumentParser( description='Multithread processing ' +\
'of MAUS output files' )
parser.add_argument( '-n', '--nthreads', type=int, default=1, \
help='Number of processor threads to use')
parser.add_argument( '-b', '--istart', type=int, default=0, \
help='Starting number of run range')
parser.add_argument( '-e', '--istop', type=int, default=1, \
help='Stop number of run range')
parser.add_argument( '-i', '--istep', type=int, default=1, \
help='Run range increment')
parser.add_argument( '-x', '--executable', type=str, default='mica', \
help='Location of the executable to run')
parser.add_argument( '-p', '--pad', type=int, default=5, \
help='Number of digits in run number format')
parser.add_argument( '-d', '--input_dir', type=str, default='.', \
help='Input directory path')
parser.add_argument( '-f', '--input_file', type=str, default='#_recon.root', \
help='Input file name, # will be substituted for run number')
parser.add_argument( '-o', '--output_file', type=str, default='analysis_#.pdf', \
help='Output file name, # will be substituted for run number')
try :
namespace = parser.parse_args()
except :
raise
else :
run(namespace)
print "Complete"
<file_sep>/include/mica/CutsTOFTime.hh
/* This file is part of the MICA (Muon Ionization Cooling Analysis) package.
* Author: <NAME>
*/
#ifndef CUTSTOFTIME_HH
#define CUTSTOFTIME_HH
#include "src/common_cpp/DataStructure/ReconEvent.hh"
#include "src/common_cpp/DataStructure/MCEvent.hh"
#include "mica/CutsBase.hh"
namespace mica {
class CutsTOFTime : public CutsBase {
public:
CutsTOFTime();
virtual ~CutsTOFTime() {}
virtual bool Cut(MAUS::ReconEvent* const aReconEvent, MAUS::MCEvent* const aMCEvent);
private:
double mLowerTimeCut;
double mUpperTimeCut;
};
} // ~namespace mica
#endif
| 2c6850e1f9cc10941fe6458c362e8682d0963c71 | [
"Markdown",
"C++",
"Python",
"CMake"
] | 45 | Markdown | ajdobbs/mica | 37e82fbf22b55615b7b8f83566ee0278cd7eaa45 | 4c9cd1fb2c9d34f9170514f020fc13fa63303a6b |
refs/heads/master | <file_sep># Simple Stupid Weather
| a7f464899f65a1a4b14b220d7dd5a988d835d9b1 | [
"Markdown"
] | 1 | Markdown | adithyakreddy/stupidlysimpleweather | 34f0c5eb10900759a019d99cd60c50e6c806808c | c083e3d2e3e73ea3444aef5a3fe3787d75b578d1 |
refs/heads/master | <repo_name>LilSebastian5000/aurelia-webpack4-karma-interpolation-failure<file_sep>/src/app.js
import {inject} from 'aurelia-framework';
import {AppLocalization} from './localizations/app-localization';
@inject(AppLocalization)
export class App {
constructor(appLocalization) {
this.appLocalization = appLocalization;
}
activate() {
console.log(this.appLocalization.HELLO_WORLD);
}
}
<file_sep>/README.md
# aurelia-webpack4-karma-interpolation-failure
A reproducible issue for the aurelia team to show an issue where karma tests are unable to find the value of an element which uses string interpolation via dependency injection
<file_sep>/src/localizations/app-localization.js
/**
* Screen specific strings the main app component
*/
export class AppLocalization {
/**
* Constructor for app localization strings
*/
constructor() {
this.HELLO_WORLD = 'Hello World!';
}
}
| 55f2a23b0a5ce114e2cfa8c4142a3b6cac0cdb17 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | LilSebastian5000/aurelia-webpack4-karma-interpolation-failure | ff2f07fc23796bf02fe508d1224adf7505627ed1 | 755bdc9f2619f5ebc737a2c1f7b954823180b290 |
refs/heads/master | <file_sep># Test
Just a test
Testing the test
| 04afa2672e243c8f518cf2ef6348cbf9f449c421 | [
"Markdown"
] | 1 | Markdown | VSS14/Test | d7030346d93582ba50885aa066e8a4fd24862ef8 | f9eb686a31b11509074c38a8501369fe26535f7b |
refs/heads/master | <file_sep>(function ($) {
"use strict";
/* preloader */
$(window).on('load', function() {
$('#jhilmil-loader').fadeOut('slow');;
});
jQuery( document ).ready(function() {
jQuery('.height-product, .single-from-blog, .equal_height').matchHeight();
jQuery('.from-blog-img a').addClass('border-hover');
// product description tab activator
jQuery(".description-tab-menu ul li").first().addClass("active");
jQuery(".product-description-tab .tab-content .tab-pane").first().addClass("active");
/*----------------------------
client owl active
------------------------------ */
jQuery(".client-owl").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 6,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1399,5],
itemsDesktopSmall : [980,4],
itemsTablet: [768,3],
itemsMobile : [479,1],
});
/*----------------------------
trend owl active
------------------------------ */
jQuery(".trend-item-slider, .tab-item-slider-two").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 3,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,2],
itemsDesktopSmall : [980,2],
itemsTablet: [768,2],
itemsMobile : [479,1],
});
/*----------------------------
product thaumbnail owl active
------------------------------ */
jQuery(".p-details-slider, .product-slider").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 3,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1199,3],
itemsDesktopSmall : [980,3],
itemsTablet: [768,3],
itemsMobile : [479,2],
});
/*----------------------------
related owl active
------------------------------ */
jQuery(".related-product-wrapper").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 4,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1399,4],
itemsDesktopSmall : [980,3],
itemsTablet: [768,2],
itemsMobile : [479,1],
});
/*----------------------------
testimonial owl active
------------------------------ */
jQuery(".testimonial-owl-wrap").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 1,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1399,1],
itemsDesktopSmall : [980,1],
itemsTablet: [768,1],
itemsMobile : [479,1],
});
jQuery(".menu-carou, .menu-pro-carou").owlCarousel({
autoPlay: true,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 1,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1399,1],
itemsDesktopSmall : [980,1],
itemsTablet: [768,1],
itemsMobile : [479,1],
});
jQuery(".woman_carousel").owlCarousel({
autoPlay: true,
slideSpeed:2000,
pagination:false,
navigation:true,
items : 4,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1399,4],
itemsDesktopSmall : [980,3],
itemsTablet: [768,2],
itemsMobile : [479,1],
});
jQuery(".timing-pro-carosel").owlCarousel({
autoPlay: false,
slideSpeed:2000,
pagination:false,
navigation:false,
items : 1,
/* transitionStyle : "fade", */ /* [This code for animation ] */
navigationText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"],
itemsDesktop : [1399,1],
itemsDesktopSmall : [980,1],
itemsTablet: [768,1],
itemsMobile : [479,1],
singleItem : true,
transitionStyle : "fade"
});
//---------------------------------------------
//Nivo slider
//---------------------------------------------
jQuery('#nivoslider').nivoSlider({
effect: 'random',
animSpeed: 500,
pauseTime: 5000,
startSlide: 0,
directionNav: true,
controlNavThumbs: true,
pauseOnHover: true,
manualAdvance: false,
prevText: 'Pr <br /> ev',
nextText: 'Ne <br /> xt',
});
/*--------------------------
Countdown
---------------------------- */
$('[data-countdown]').each(function() {
var $this = $(this), finalDate = $(this).data('countdown');
$this.countdown(finalDate, function(event) {
$this.html(event.strftime('<div class="cdown days"><span class="counting">%-D</span>days</div><div class="cdown hours"><span class="counting">%-H</span>hrs</div><div class="cdown minutes"><span class="counting">%M</span>mins</div><div class="cdown seconds"><span class="counting">%S</span>secs</div>'));
});
});
/*----------------------------------------------
Personal Address toggle function
-----------------------------------------------*/
$("#add-new-address").on('click', function(){
$("#add-new-address-info").slideToggle();
});
$("#transfer").on('click', function(){
$("#transfer-info").slideToggle();
});
$("#payment").on('click', function(){
$("#payment-info").slideToggle();
});
$("#paypal").on('click', function(){
$("#paypal-info").slideToggle();
});
/*----------------------------
jQuery MeanMenu
------------------------------ */
jQuery('nav#dropdown').meanmenu();
/*--------------------------
scrollUp
---------------------------- */
jQuery.scrollUp({
scrollText: '<i class="fa fa-angle-up"></i>',
easingType: 'linear',
scrollSpeed: 900,
animation: 'fade'
});
/*----------------------------
Elevate Zoom active
------------------------------ */
jQuery(".zoom1").elevateZoom({
gallery:'ProductThumbs',
cursor: 'move',
galleryActiveClass: 'active',
imageCrossfade: false,
zoomWindowFadeIn: 300,
zoomWindowFadeOut: 300,
lensFadeIn: 300,
lensFadeOut: 300,
easing : true,
zoomWindowWidth: 400,
zoomWindowHeight: 400,
borderSize: 1,
borderColour: "#dddddd",
scrollZoom: false,
lensBorderColour: "#dddddd",
lensShape: "square",
zoomType: "window" //window is default, also "lens" available -
});
//pass the images to Fancybox
jQuery(".zoom1").on("click", function(e) {
var ez = $('.zoom1').data('elevateZoom');
$.fancybox(ez.getGalleryList());
return false;
});
jQuery(".product-video-link").fancybox();
});
})(jQuery); <file_sep><!DOCTYPE html>
<html lang="en-US">
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
<link rel="shortcut icon" href="media/favicon.ico" type="image/x-icon">
<title>Duncan Technologies</title>
<meta name="Language" content="en" />
<meta name="author" content="Duncan Technologies.">
<link rel="canonical" href="index-2.html">
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="Rating" content="General">
<meta content="index,follow" name="robots" />
<link rel="stylesheet" id="font-awesome-css-css" href="css/font-awesome.css" type="text/css" media="all">
<link rel="stylesheet" id="icon-pin-css-css" href="css/style.css" type="text/css" media="all">
<link rel="stylesheet" id="contact-form-7-css" href="css/styles.css" type="text/css" media="all">
<link rel="stylesheet" id="bootstrap-css" href="css/bootstrap.css" type="text/css" media="all">
<link rel="stylesheet" id="font-awesome-css" href="css/font-awesome.min.css" type="text/css" media="all">
<link rel="stylesheet" id="custom-style-css" href="css/style(1).css" type="text/css" media="all">
<link rel="stylesheet" href="css/css(1).html">
<link rel="stylesheet" id="custom-color2-css" href="css/responsive.css" type="text/css" media="all">
<link rel="stylesheet" id="Solitaire-css" href="css/style(2).css" type="text/css" media="all">
<link rel="stylesheet" href="css/theme.css">
<link rel="stylesheet" type="text/css" href="css/demo.css" />
<link rel='stylesheet' id='' href='css/accord.css' type='text/css' media='all' />
<script type="text/javascript" src="js/jquery.js"></script>
<script type='text/javascript' src='takethemes.net/wp/xshop/rummers/wp-includes/js/imagesloaded.min55a055a0.html?ver=3.2.0'></script>
<script type='text/javascript' src='takethemes.net/wp/xshop/rummers/wp-includes/js/masonry.mind617d617.html?ver=3.3.2'></script>
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz" rel="stylesheet">
<script src="../ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="../maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="css/animate.css" rel="stylesheet">
<script type="text/javascript" src="js2/wow.min.js"></script>
<script type="text/javascript" src="js/bin.js"></script>
<script>
new WOW().init();
</script>
<style>
@media only screen and (max-width: 450px) {
.mdForm {
padding: 17px 18px 27px;
}
#h3{
font-size: 15px;
}
#h1{
font-size: 26px;
}
.btn{
border-radius: 0px;
}
}
@media only screen and (min-width: 450px) {
.mdForm {
padding: 37px 95px 50px;
}
.btn{
border-radius: 0px;
}
}
.catColor{
background-color: #fff;
}
h2 {
font-size:20px;
margin-top:5px;
}
</style>
</head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-127576126-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-127576126-1');
</script>
<body class="home page page-id-144 page-template-default classic-view solitaire wpb-js-composer js-comp-ver-4.12.1 vc_responsive">
<div class="top">
<div class="container">
<div class="row">
<div class="col-md-9 col-xs-12">
<div class="site-option">
<marquee scrollamount="4" onMouseOver="this . stop();" onMouseOut="this . start();" class="mqsa wow fadeInUp ppp" style="">
DUNCAN TECHNOLOGIES |
SOFTWARE SOLUTIONS , HARDWARE SOLUTIONS, NETWORKING . </marquee>
</div>
</div>
<div class="col-md-3 col-xs-12 right hidden-xs">
<div class="site-option">
<ul class="" >
<li style="font-size: 27px"><a href="https://www.facebook.com/" target="_blank"><i class="fa fa-facebook-square social-media-f" aria-hidden="true"></i></a></li>
<li style="font-size: 27px"> <a href="https://plus.google.com/" target="_blank"><i class="fa fa-google-plus-square social-media-g" aria-hidden="true"></i></a></li>
<li style="font-size: 27px"> <a href="https://in.pinterest.com/" target="_blank"><i class="fa fa-pinterest" aria-hidden="true"></i></a></li>
<li style="font-size: 27px"> <a href="https://twitter.com/"><i class="fa fa-twitter-square social-media-t" aria-hidden="true"></i></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="logo-top">
<div class="">
<div class="container">
<div class="row">
<div class="col-md-5">
<a href="index-2.html" class="logo-branding">
<!-- <img src="images/logo.png" height="57" class="img-responsive" alt="">-->
<img src="media/director/duncan.jpg" class="img-thumbnail" width="15%" padding-style="center" padding-left="37px"style="
margin-left: 12%;
" />
<h2 class="text-uppercase">Duncan Technologies</h2>
</a>
</div>
<div class="col-md-2">
<div class="upper-column info-box">
<div class="icon-box">
<span class="flaticon-clock-2"><i class="fa fa-phone"></i></span>
</div>
CALL US
<div class="light-text"> +91 9555555546</div>
</div>
</div>
<!-- <div class="col-md-2">
<div class="upper-column info-box">
<div class="icon-box">
<span class="flaticon-clock-2"><i class="fa fa-phone"></i></span>
</div>
CALL US
<div class="light-text"> +(91)-9899770509</div>
</div>
</div> -->
<div class="col-md-2">
<div class="upper-column info-box">
<div class="icon-box">
<span class="flaticon-clock-2"><i class="fa fa-envelope"></i></span>
</div>
E-MAIL
<div class="light-text"><EMAIL></div>
</div>
</div>
<!-- <div class="col-md-3">
<div class="upper-column info-box pp" style="">
<div class="icon-box">
<span class="flaticon-clock-2"><i class="fa fa-clock-o"></i></span>
</div>
WORKING HOURS
<div class="light-text"> Daily, 10.00am to 05.30pm</div>
</div>
</div>-->
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="header5 rummer-home">
<div class="home2-ticker top-strip">
<div class="container">
<div class="row">
<div class="col-md-12">
<style>
/* CSS Document */
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
@import url(https://fonts.googleapis.com/css?family=Bree+Serif);
body {
margin: 0;
padding: 0;
word-wrap:break-word !important;
}
.toggle,
[id^=drop] {
display: none;
}
/* Giving a background-color to the nav container. */
nav {
margin:0;
padding: 0;
background-color: unset;
}
/* Since we'll have the "ul li" "float:left"
* we need to add a clear after the container. */
nav:after {
content:"";
display:table;
clear:both;
}
/* Removing padding, margin and "list-style" from the "ul",
* and adding "position:reltive" */
nav ul {
/*float: right;*/
padding:0;
margin:0;
list-style: none;
position: relative;
}
/* Positioning the navigation items inline */
nav ul li {
margin: 0px;
display:inline-block;
float: left;
background-color: #3bb5eb;
}
/* Styling the links */
nav a {
display:block;
padding:14px 20px;
color:#FFF;
font-size:15px;
text-decoration:none;
}
nav ul li ul li:hover { background: #000000; }
/* Background color change on Hover */
nav a:hover {
background-color: #feda1f;
}
/* Hide Dropdowns by Default
* and giving it a position of absolute */
nav ul ul {
display: none;
position: absolute;
/* has to be the same number as the "line-height" of "nav a" */
top: 49px;
}
/* Display Dropdowns on Hover */
nav ul li:hover > ul {
display:inherit;
}
/* Fisrt Tier Dropdown */
nav ul ul li {
width:200px;
float:none;
display:list-item;
position: relative;
}
/* Second, Third and more Tiers
* We move the 2nd and 3rd etc tier dropdowns to the left
* by the amount of the width of the first tier.
*/
nav ul ul ul li {
position: relative;
top:-60px;
/* has to be the same number as the "width" of "nav ul ul li" */
left:170px;
}
/* Change ' +' in order to change the Dropdown symbol */
/*li > a:after { content: ' +'; }*/
/*li > a:only-child:after { content: ''; }*/
/* Media Queries
--------------------------------------------- */
@media all and (max-width : 768px) {
#logo {
display: block;
padding: 0;
width: 100%;
text-align: center;
float: none;
}
label {
font-family: inherit;
}
nav {
margin: 0;
}
a:hover, a:focus {
color: #fff;
}
/* Hide the navigation menu by default */
/* Also hide the */
.toggle + a,
.menu {
display: none;
}
/* Stylinf the toggle lable */
.toggle {
display: block;
background-color: #3bb5eb;
padding:14px 20px;
color:#FFF;
font-size:15px;
text-decoration:none;
border:none;
}
.toggle:hover {
background-color: #feda1f;
}
/* Display Dropdown when clicked on Parent Lable */
[id^=drop]:checked + ul {
display: block;
}
/* Change menu item's width to 100% */
nav ul li {
display: block;
width: 100%;
}
nav ul ul .toggle,
nav ul ul a {
padding: 0 40px;
}
nav ul ul ul a {
padding: 0 80px;
}
nav a:hover,
nav ul ul ul a {
background-color: #feda1f;
}
nav ul li ul li .toggle,
nav ul ul a,
nav ul ul ul a{
padding:14px 20px;
color:#FFF;
font-size:15px;
}
nav ul li ul li .toggle,
nav ul ul a {
background-color: #212121;
}
/* Hide Dropdowns by Default */
nav ul ul {
float: none;
position:static;
color: #ffffff;
/* has to be the same number as the "line-height" of "nav a" */
}
/* Hide menus on hover */
nav ul ul li:hover > ul,
nav ul li:hover > ul {
display: none;
}
/* Fisrt Tier Dropdown */
nav ul ul li {
display: block;
width: 100%;
}
nav ul ul ul li {
position: static;
/* has to be the same number as the "width" of "nav ul ul li" */
}
}
@media all and (min-width : 1000px) {
#get-hide{
visibility: hidden;
}
}
@media all and (max-width : 330px) {
nav ul li {
display:block;
width: 94%;
}
#get-hide{
visibility: visible;
}
}
.custColor a {
font-size: 12px;
}
/* Below css for modal*/
.close {
opacity: inherit;
}
</style>
<nav>
<!-- <div id="logo">Your Logo here</div> -->
<label for="drop" class="toggle">Menu</label>
<input type="checkbox" id="drop" />
<ul class="menu" style="z-index: 100">
<li><a href="index-2.html">HOME</a></li>
<li>
<!-- First Tier Drop Down -->
<label for="drop-1" class="toggle">ABOUT US +</label>
<a href="#">ABOUT US</a>
<input type="checkbox" id="drop-1"/>
<ul>
<li class="custColor"><a href="about.html" class="text-left">ABOUT US</a></li>
<li class="custColor"><a href="director.html" class="text-left">DIRECTOR</a></li>
</ul>
</li>
<li>
<!-- First Tier Drop Down -->
<label for="drop-2" class="toggle">PRODUCTS +</label>
<a href="#">PRODUCTS/SERVICES</a>
<input type="checkbox" id="drop-2"/>
<ul>
<li class="custColor">
<a class="text-left" href="softwaresolutions.html">
<!-- <i class="fa fa-dot-circle-o" ></i> -->
SOFTWARE SOLUTIONS </a>
</li>
<li class="custColor">
<a class="text-left" href="hardwaresolutions.html">
<!-- <i class="fa fa-dot-circle-o" ></i> -->
HARDWARE SOLUTIONS </a>
</li>
<li class="custColor">
<a class="text-left" href="networking.html">
<!-- <i class="fa fa-dot-circle-o" ></i> -->
NETWORKING </a>
</li>
</ul>
</li>
<li>
<li><a href="ourteam.html">OUR TEAM</a></li>
<li><a href="clients.html">CLIENTS</a></li>
<li><a href="gallery.html">GALLERY</a></li>
<li><a href="contact.html">CONTACT US</a></li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
<!--------------------------------CLOSE HEADER---------------------------------->
<div class=" header5 product_content_wrapper" id="blog-page-title">
<div class="page-title-overlay"></div>
<div class="page-title-content container">
<div class="col-sm-6">
<div class="home2-breadcram">
<ul class="clearfix">
<li><a href="index-2.html">Home</a></li>
<li><a href="#">Product</a></li>
<li>Networking</li>
</ul>
</div>
</div>
<div class="col-sm-6 right">
<h4 class="text-capitalize">Networking Products</h4>
</div>
</div>
</div>
<!---------------------------------------------------------------------------->
<div class="section-contianer">
<div class="post-content">
<div class="row_inner clearfix container padding-top-30 padding-bottom-30">
<div class="col-md-3">
<div class="categories_title">
<div class="anav-left"><i class="fa fa-bars"></i></div>
<span>Our Brands</span>
</div>
<div id="outer-wrap">
<nav class="mainNav accordion-nav sticky">
<ul class="tumaccor">
<li class="catColor" style=""><a href=""><h4 class="cate">Samsung</h4></a>
</li>
<li class="catColor" style="position: relative;"><a href=""><h4 class="cate">Microsoft</h4></a>
</li>
<li class="catColor" style="position: relative;"><a href=""><h4 class="cate">Sony</h4></a>
</li>
<li class="catColor" style="position: relative;"><a href=""><h4 class="cate">Intel</h4></a>
</li>
<li class="catColor" style="position: relative;"><a href=""><h4 class="cate">D-Link</h4></a>
</li>
<li class="catColor" style="position: relative;"><a href=""><h4 class="cate">Toshiba</h4></a>
</li>
<li class="catColor" style="position: relative;"><a href=""><h4 class="cate">LG</h4></a>
</li>
<li class="catColor" style="position: relative;"><a href=""><h4 class="cate">Symantec</h4></a>
</li>
<li class="catColor" style="position: relative;"><a href=""><h4 class="cate">IBM</h4></a>
</li>
<li class="catColor" style="position: relative;"><a href=""><h4 class="cate">HP</h4></a>
</li>
</ul>
</nav>
</div>
</div>
<div class=" col-md-9">
<div class="vc_column-inner vc_custom_1476102063657">
<div class="wpb_wrapper">
<div role="form" class="wpcf7 form2" id="wpcf7-f486-p820-o1" lang="en-US" dir="ltr">
<h4 class="heading"><span>NETWORKING PRODUCTS</span></h4>
<div class="col-md-12" style="padding:0px;">
<div style="margin-bottom:10px; padding: 15px;border: 1px solid #210e0e38; border-radius: 10px;" class="col-md-12 player-article imageGallery1">
<div class="">
<h3>STRUCTURED CABLINGS NETWORK</h3>
<div class="col-md-4 wow rollIn" style="width:201px;height: 201px">
<img src="media/networking/cable.jpg" class="" style="width: 100%;height: 90%" />
</div>
<div class="col-md-8 wow lightSpeedIn" style="margin-top:10px;">
<p class="text-justify ">
At Duncan Technologies we provide state of art Structured Cablings Networking Solutions.
A data cable is any media that allows baseband transmissions (binary 1,0s) from a transmitter to a receiver.
Networking Media
Ethernet Cables (Cat5, Cat5e, Cat6, Cat6a)
Token Ring Cables (Cat4)
Coaxial cable is sometimes used as a baseband digital data cable, such as in serial digital interface and thicknet and thinnet.
Optical fiber cable; see fiber-optic communication
Serial cable
Telecommunications Cable (Cat2 or telephone cord)
Media devices
USB cable
</p>
</div>
</div>
</div>
<div style="margin-bottom:10px; padding: 15px;border: 1px solid #210e0e38; border-radius: 10px;" class="col-md-12 player-article imageGallery1">
<div class="">
<h3>HUBS NETWORKING SOLUTIONS</h3>
<div class="col-md-4 wow rollIn" style="width:201px;height: 201px">
<img src="media/networking/hubsNetwork.jpg" class="" style="width: 100%;height: 90%" />
</div>
<div class="col-md-8 wow lightSpeedIn" style="margin-top:10px;">
<p class="text-justify ">
At Duncan Technologies we provide state of art Hubs Networking Solutions.
A data hub is a collection of data from multiple sources organized for distribution, sharing, and often subsetting and sharing. Generally this data distribution is in the form of a hub and spoke architecture.
A data hub differs from a data warehouse in that it is generally unintegrated and often at different grains. It differs from an operational data store because a data hub does not need to be limited to operational data.
A data hub differs from a data lake by homogenizing data and possibly serving data in multiple desired formats, rather than simply storing it in one place, and by adding other value to the data such as de-duplication, quality, security, and a standardized set of query services.
</p>
</div>
</div>
</div>
<div style="margin-bottom:10px; padding: 15px;border: 1px solid #210e0e38; border-radius: 10px;" class="col-md-12 player-article imageGallery1">
<div class="">
<h3>SWITCHES NETWORKING SOLUTIONS</h3>
<div class="col-md-4 wow rollIn" style="width:201px;height: 201px">
<img src="media/networking/switchNet.jpg" class="" style="width: 100%;height: 90%" />
</div>
<div class="col-md-8 wow lightSpeedIn" style="margin-top:10px;">
<p class="text-justify ">
At Duncan Technologies we provide state of art Switches Networking Solutions.
A data monitoring switch is a networking hardware appliance that provides a pool of monitoring tools with access to traffic from a large number of network links. It provides a combination of functionality that may include aggregating monitoring traffic from multiple links, regenerating traffic to multiple tools, pre-filtering traffic to offload tools, and directing traffic according to one-to-one and many-to-many port mappings.
Data monitoring switches enable organizations to use their monitoring tools more efficiently, to centralize traffic monitoring functions, and to share tools and traffic access between groups. Some of these devices also provide functionality that helps justify tool purchases and simplify deployment and management of the device itself.
</p>
</div>
</div>
</div>
<div style="margin-bottom:10px; padding: 15px;border: 1px solid #210e0e38; border-radius: 10px;" class="col-md-12 player-article imageGallery1">
<div class="">
<h3>ROUTERS NETWORKING SOLUTIONS</h3>
<div class="col-md-4 wow rollIn" style="width:201px;height: 201px">
<img src="media/networking/routersNet.jpg" class="" style="width: 100%;height: 90%" />
</div>
<div class="col-md-8 wow lightSpeedIn" style="margin-top:10px;">
<p class="text-justify ">
At Duncan Technologies we provide state of art Routers Networking Solutions.
When multiple routers are used in interconnected networks, the routers can exchange information about destination addresses using a routing protocol. Each router builds up a routing table listing the preferred routes between any two systems on the interconnected networks.
A router has two types of network element components organized onto separate planes:
Control plane: A router maintains a routing table that lists which route should be used to forward a data packet, and through which physical interface connection. It does this using internal preconfigured directives, called static routes, or by learning routes dynamically using a routing protocol. Static and dynamic routes are stored in the routing table. The control-plane logic then strips non-essential directives from the table and builds a forwarding information base (FIB) to be used by the forwarding plane.
</p>
</div>
</div>
</div>
<div style="margin-bottom:10px; padding: 15px;border: 1px solid #210e0e38; border-radius: 10px;" class="col-md-12 player-article imageGallery1">
<div class="">
<h3>RJ45 NETWORKING SOLUTIONS</h3>
<div class="col-md-4 wow rollIn" style="width:201px;height: 201px">
<img src="media/networking/rj45.jpg" class="" style="width: 100%;height: 90%" />
</div>
<div class="col-md-8 wow lightSpeedIn" style="margin-top:10px;">
<p class="text-justify ">
At Duncan Technologies we provide state of art RJ45 Networking Solutions.
Network computer devices that originate, route and terminate the data are called network nodes.[1] Nodes are identified by network addresses and can include hosts such as personal computers, phones, servers as well as networking hardware. Two such devices can be said to be networked together when one device is able to exchange information with the other device, whether or not they have a direct connection to each other. In most cases, application-specific communications protocols are layered (i.e. carried as payload) over other more general communications protocols. This formidable collection of information technology requires skilled network management to keep it all running reliably.
</p>
</div>
</div>
</div>
<div style="margin-bottom:10px; padding: 15px;border: 1px solid #210e0e38; border-radius: 10px;" class="col-md-12 player-article imageGallery1">
<div class="">
<h3>WIFI NETWORKING SOLUTIONS</h3>
<div class="col-md-4 wow rollIn" style="width:201px;height: 201px">
<img src="media/networking/wifi.jpg" class="" style="width: 100%;height: 90%" />
</div>
<div class="col-md-8 wow lightSpeedIn" style="margin-top:10px;">
<p class="text-justify ">
At Duncan Technologies we provide state of art Wifi Networking Solutions.
Wi-Fi is technology for radio wireless local area networking of devices based on the IEEE 802.11 standards. Wi‑Fi is a trademark of the Wi-Fi Alliance, which restricts the use of the term Wi-Fi Certified to products that successfully complete interoperability certification testing.[2] Devices that can use Wi-Fi technologies include desktops and laptops, video game consoles, smartphones and tablets, smart TVs, digital audio players, cars and modern printers. Wi-Fi compatible devices can connect to the Internet via a WLAN and a wireless access point.
</p>
</div>
</div>
</div>
<div style="margin-bottom:10px; padding: 15px;border: 1px solid #210e0e38; border-radius: 10px;" class="col-md-12 player-article imageGallery1">
<div class="">
<h3>WAN NETWORKING SOLUTIONS</h3>
<div class="col-md-4 wow rollIn" style="width:201px;height: 201px">
<img src="media/networking/wan.jpg" class="" style="width: 100%;height: 90%" />
</div>
<div class="col-md-8 wow lightSpeedIn" style="margin-top:10px;">
<p class="text-justify ">
At Duncan Technologies we provide state of art WAN Networking Solutions.
A wide area network (WAN) is a telecommunications network or computer network that extends over a large geographical distance place. Wide area networks are often established with leased telecommunication circuits.
Business, education and government entities use wide area networks to relay data to staff, students, clients, buyers, and suppliers from various locations across the world. In essence, this mode of telecommunication allows a business to effectively carry out its daily function regardless of location. The Internet may be considered a WAN
</p>
</div>
</div>
</div>
<div style="margin-bottom:10px; padding: 15px;border: 1px solid #210e0e38; border-radius: 10px;" class="col-md-12 player-article imageGallery1">
<div class="">
<h3>LAN NETWORKING SOLUTIONS</h3>
<div class="col-md-4 wow rollIn" style="width:201px;height: 201px">
<img src="media/networking/lan.jpg" class="" style="width: 100%;height: 90%" />
</div>
<div class="col-md-8 wow lightSpeedIn" style="margin-top:10px;">
<p class="text-justify ">
At Duncan Technologies we provide state of art LAN Networking Solutions.
A local area network (LAN) is a computer network that interconnects computers within a limited area such as a residence, school, laboratory, university campus or office building.[1] By contrast, a wide area network (WAN) not only covers a larger geographic distance, but also generally involves leased telecommunication circuits.
Ethernet and Wi-Fi are the two most common technologies in use for local area networks. Historical technologies include ARCNET, Token ring.
</p>
</div>
</div>
</div>
<div style="margin-bottom:10px; padding: 15px;border: 1px solid #210e0e38; border-radius: 10px;" class="col-md-12 player-article imageGallery1">
<div class="">
<h3>DISTRIBUTED PROCESSING NETWORK</h3>
<div class="col-md-4 wow rollIn" style="width:201px;height: 201px">
<img src="media/networking/distributedProcessing.jpg" class="" style="width: 100%;height: 90%" />
</div>
<div class="col-md-8 wow lightSpeedIn" style="margin-top:10px;">
<p class="text-justify ">
At Duncan Technologies we provide state of art Distributed Processing Networking Solutions.
Distributed Processing Technology (DPT) was founded in 1977, in Maitland, Florida. DPT was an early pioneer in computer storage technology, popularizing the use of disk caching in the 1980s and 1990s. DPT was the first company to design, manufacture and sell microprocessor-based intelligent caching disk controllers to the OEM computer market. Prior to DPT, disk caching technology had been implemented in proprietary hardware in mainframe computing to improve the speed of disk access.
</p>
</div>
</div>
</div>
<div style="margin-bottom:10px; padding: 15px;border: 1px solid #210e0e38; border-radius: 10px;" class="col-md-12 player-article imageGallery1">
<div class="">
<h3>REPEATERS NETWORKING SOLUTIONS</h3>
<div class="col-md-4 wow rollIn" style="width:201px;height: 201px">
<img src="media/networking/repeater.jpg" class="" style="width: 100%;height: 90%" />
</div>
<div class="col-md-8 wow lightSpeedIn" style="margin-top:10px;">
<p class="text-justify ">
At Duncan Technologies we provide state of art Repeaters Networking Solutions.
In telecommunications, a repeater is an electronic device that receives a signal and retransmits it. Repeaters are used to extend transmissions so that the signal can cover longer distances or be received on the other side of an obstruction. Some types of repeaters broadcast an identical signal, but alter its method of transmission, for example, on another frequency or baud rate. There are several different types of repeaters; a telephone repeater is an amplifier in a telephone line, an optical repeater is an optoelectronic circuit that amplifies the light beam in an optical fiber cable; and a radio repeater is a radio receiver and transmitter that retransmits a radio signal.
</p>
</div>
</div>
</div>
<div style="margin-bottom:10px; padding: 15px;border: 1px solid #210e0e38; border-radius: 10px;" class="col-md-12 player-article imageGallery1">
<div class="">
<h3>FIREWALL NETWORKING SOLUTIONS</h3>
<div class="col-md-4 wow rollIn" style="width:201px;height: 201px">
<img src="media/networking/firewallNetworking.jpg" class="" style="width: 100%;height: 90%" />
</div>
<div class="col-md-8 wow lightSpeedIn" style="margin-top:10px;">
<p class="text-justify ">
At Duncan Technologies we provide state of art Firewall Networking Solutions.
In computing, a firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules.[1] A firewall typically establishes a barrier between a trusted internal network and untrusted external network, such as the Internet.
Firewalls are often categorized as either network firewalls or host-based firewalls. Network firewalls filter traffic between two or more networks and run on network hardware. Host-based firewalls run on host computers and control network traffic in and out of those machines.
</p>
</div>
</div>
</div>
<div style="margin-bottom:10px; padding: 15px;border: 1px solid #210e0e38; border-radius: 10px;" class="col-md-12 player-article imageGallery1">
<div class="">
<h3>INTERFACE CARDS NETWORKING</h3>
<div class="col-md-4 wow rollIn" style="width:201px;height: 201px">
<img src="media/networking/interfaceCards.jpg" class="" style="width: 100%;height: 90%" />
</div>
<div class="col-md-8 wow lightSpeedIn" style="margin-top:10px;">
<p class="text-justify ">
At Duncan Technologies we provide state of art Interface Cards Networking Solutions.
A Network interface card (also known as a NIC, network card, or network interface controller) is an electronic device that connects a computer to a computer network, usually a LAN. It is considered a piece of computer hardware. Most modern computers support an internal network interface controller embedded in the motherboard directly rather than provided as an external component.
Network cards let a computer exchange data with a network. To achieve the connection, network cards use a suitable protocol, for example CSMA/CD. Network cards usually implement the first two layers of the OSI model, that is the physical layer, and the data link layer. There are older network protocols such as ARCNET, introduced in 1977, LocalTalk or Token Ring, but today, most network cards use Ethernet.
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!------------------------------ Start Modal ------------------------------->
<div class="modal fade" id="myEnquiry" role="dialog" >
<div class="modal-dialog" >
<!-- Modal content-->
<div class="modal-content" style="background-image: linear-gradient(to bottom, #3c8ea2, #007ba4, #0066a3, #1d4d9a, #472e85);color: #fff">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><i class="fa fa-times-circle" style="color:#fff;font-size:35px"></i></button>
<h4 class="text-center" id="h1" style="margin-top:10px" >Contact Us</h4>
</div>
<div class="modal-body">
<h3 class="text-center" id="h3">Got a question? We'd love to hear from you. Send us a message and we'll respond as soon as possible.</h3>
<div class="text-center" id="error" style="color:#ff0000;background-color: #ffff00"></div>
<form id="proEnquiry" class="mdForm" >
<input type="hidden" name='id' value="1">
<input type="hidden" name='proid' value="11">
<input type="hidden" name='protitle' value="Fruit Basket">
<div class="form-group">
<label for="email">Name<sup style="color:red">*</sup></label>
<input type="text" class="form-control" id="email" placeholder="Enter Name" name="name">
</div>
<div class="form-group">
<label for="pwd">Mobile No.<sup style="color:red">*</sup></label>
<input type="tel" maxlength="10" class="form-control" id="pwd" placeholder="Enter Contact Number" name="phone">
</div>
<div class="form-group">
<label for="pwd">Email<sup style="color:red"></sup></label>
<input type="email" class="form-control" id="pwd" placeholder="Enter Email Address" name="email">
</div>
<div class="form-group">
<label for="pwd">Message</label>
<textarea class="form-control" name="message" cols="30" rows="6" ></textarea>
</div>
<button type="submit" class="btn btn-default" style="background-color:#0085d0;width:100%;color:#fff">Submit</button>
<!--<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>-->
</form>
</div>
</div>
</div>
</div>
<!------------------------------ Ends Modal ------------------------------->
<!------------------------------ Start Footer ------------------------------->
<section id="home6-footer" class="6th-footer">
<div class="footer-widgets-area">
<div class="container">
<div class="row">
<aside class="col-md-3 sidebar-widgets wow fadeInLeft animated animated animated animated" data-wow-duration="0.2s" data-wow-delay="0.2s" style="visibility: visible; animation-duration: 0.2s; animation-delay: 0.2s; animation-name: fadeInLeft;">
<h4 style="color:#ffffff;">About Us</h4>
<div class="title-line color"></div>
<p class="text-justify">Founded in 2004 as a small company with a big vision. Maintained a phenomenal growth over Time. Achieved total financial stability since inception and grown solely based on internally generated funds.</p>
<div class="home2-info-section-socials">
<a href="" target="_blank"><i class="fa fa-facebook-square social-media-f" aria-hidden="true"></i></a>
<a href="" target="_blank"><i class="fa fa-instagram social-media-i" aria-hidden="true"></i></a>
<a href="" target="_blank"><i class="fa fa-twitter-square social-media-t" aria-hidden="true"></i></a>
<a href="" target="_blank"><i class="fa fa-google-plus-square social-media-g" aria-hidden="true"></i></a>
</div>
</aside>
<aside class="col-md-3 sidebar-widgets widget_nav_menu wow fadeInLeft animated animated animated animated" data-wow-duration="0.4s" data-wow-delay="0.4s" style="visibility: visible; animation-duration: 0.4s; animation-delay: 0.4s; animation-name: fadeInLeft;">
<h4 style="color:#ffffff;">Quick Link</h4>
<div class="title-line color"></div>
<div class="menu-footer-menu-1-container">
<!-- <ul id="menu-footer-menu-1" class="menu">-->
<ul id="menu-footer-menu-1" class="">
<li class="menu-item menu-item-type-post_type "><a href="index-2.html"> Home </a></li>
<li class="menu-item menu-item-type-post_type "><a href="about.html">About Us </a></li>
<li class="menu-item menu-item-type-post_type "><a href="director.html"> Our Team </a></li>
<li class="menu-item menu-item-type-post_type "><a href="gallery.html"> Clients </a></li>
<li class="menu-item menu-item-type-post_type "><a href="contact.html"> Gallery </a></li> </ul>
</div>
</aside>
<aside class="col-md-3 sidebar-widgets widget_nav_menu wow fadeInLeft animated animated animated animated" data-wow-duration="0.6s" data-wow-delay="0.6s" style="visibility: visible; animation-duration: 0.6s; animation-delay: 0.6s; animation-name: fadeInLeft;">
<h4 style="color:#ffffff;">Our Products Collection</h4>
<div class="title-line color"></div>
<div class="menu-footer-menu-1-container">
<!-- <ul id="menu-footer-menu-1" class="menu">-->
<ul id="menu-footer-menu-1" class="put-list">
<li class="menu-item menu-item-type-post_type "><a href="softwaresolutions.html">SOFTWARE SOLUTIONS</a></li>
<li class="menu-item menu-item-type-post_type "><a href="hardwaresolutions.html">HARDWARE SOLUTIONS</a></li>
<li class="menu-item menu-item-type-post_type "><a href="networking.html">NETWORKING</a></li>
<li class="menu-item menu-item-type-post_type " id="get-hide"><a href="sub-product-list0055.html?id=11">View More...</a></li>
</ul>
</div>
</aside>
<!-- <aside class="col-md-3 sidebar-widgets widget_nav_menu wow fadeInLeft animated animated animated animated" data-wow-duration="0.6s" data-wow-delay="0.6s" style="visibility: visible; animation-duration: 0.6s; animation-delay: 0.6s; animation-name: fadeInLeft;">
<h1 style="color:#000">.</h1>
<div class="title-line color" style="background-color: #000;"></div>
<div class="menu-footer-menu-1-container" id="get">
<ul id="menu-footer-menu-1" class="menu">
<ul id="menu-footer-menu-1" class="menu">
<li class="menu-item menu-item-type-post_type "><a href="sub-product-list.php?id=11">FRUIT BASKET</a></li>
</ul>
</div>
</aside>-->
<aside class="col-md-3 sidebar-widgets wow fadeInLeft animated animated animated animated" data-wow-duration="0.2s" data-wow-delay="0.2s" style="visibility: visible; animation-duration: 0.2s; animation-delay: 0.2s; animation-name: fadeInLeft;">
<h4 style="color:#ffffff;">Address</h4>
<div class="title-line color"></div>
<ul>
<p><i class="fa fa-map-marker"></i> G-6 , Amrapali Corporate Hub IMT Manesar, Gurgaon -122050, India.</p>
<p><i class="fa fa-phone"></i>+91 9555555546</p>
<p><i class="fa fa-envelope"></i> <EMAIL></p>
<p><i class="fa fa-envelope"></i> <EMAIL></p>
</ul>
</aside>
</div>
</div>
</div>
<div class="home3-footer-wrapper text-center home2-footer-area">
<div class="container">
<div class="row">
<div class="copyright">
<p>Copyright © duncanindia.com, 2019. All rights reserved.</p>
</div>
<div class="home2-paymet">
Powered By :<a href="http://www.miraclehuntservices.com/" target="_blank" style="color:#fff"> Miracle Hunt Services </a>
</div>
</div>
</div>
</div>
</section>
<!------------------------------------------------------------------------------------------->
<script src="js2/lightbox-plus-jquery.min.js"></script>
<script src="js/navAccordion.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery('.mainNav').navAccordion({
expandButtonText: '<i class="fa fa-plus"></i>',
collapseButtonText: '<i class="fa fa-minus"></i>'
},
function(){
console.log('Callback')
});
});
jQuery.noConflict();
</script>
<script type='text/javascript' src='takethemes.net/wp/xshop/rummers/wp-includes/js/jquery/jquery.masonry.minef70ef70.html?ver=3.1.2b'></script>
<script type='text/javascript' src='takethemes.net/wp/xshop/rummers/wp-content/themes/xshop/assets/js/custom83b683b6.html?ver=4.6.2'></script>
<script type='text/javascript' src='takethemes.net/wp/xshop/rummers/wp-content/themes/xshop/assets/js/bootstrap-select83b683b6.html?ver=4.6.2'></script>
<script type='text/javascript' src='takethemes.net/wp/xshop/rummers/wp-content/themes/xshop/assets/css/slick/slick.min83b683b6.html?ver=4.6.2'></script>
<script src="maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.html" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep>$(document).ready(function (e){
$("#contactUs").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "include/contact.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
if(data == 'true'){
alert("Thank you for contacting us one of our colleague will get back to you soon.");
document.getElementById('error').value='';
document.getElementById('contactUs').value='';
location.reload();
}else{
document.getElementById('error').innerHTML = data;
}
},
error: function(){}
});
}));
$("#proEnquiry").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "include/pro-enquiry.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
if(data == 'true'){
alert("Thank you for contacting us one of our colleague will get back to you soon.");
document.getElementById('error').value='';
document.getElementById('proEnquiry').value='';
location.reload();
}else{
document.getElementById('error').innerHTML = data;
}
},
error: function(){}
});
}));
$("#galleryEnquiry").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "include/pro-enquiry.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
if(data == 'true'){
alert("Thank you for contacting us one of our colleague will get back to you soon.");
document.getElementById('g-error').value='';
document.getElementById('galleryEnquiry').value='';
location.reload();
}else{
document.getElementById('g-error').innerHTML = data;
}
},
error: function(){}
});
}));
$("#distEnquiry").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "include/dist-enquiry.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
if(data == 'true'){
alert("Thank you for contacting us one of our colleague will get back to you soon.");
document.getElementById('error').value='';
document.getElementById('distEnquiry').value='';
location.reload();
}else{
document.getElementById('error').innerHTML = data;
}
},
error: function(){}
});
}));
}); | e0337a3646c109c92a8accde529c1e56b4e26774 | [
"HTML",
"JavaScript"
] | 3 | HTML | nikhil141/DuncanNew | 1158ce5f73e31af88229d23d0a15e29794fcc8ba | 8790b13c8fb9357c74dfe7fb7201dddb409affac |
refs/heads/master | <repo_name>atmonello/omnistack-9-frontend<file_sep>/README.md
# omnistack-9-frontend
Frontend da Semana Omnistack #9
| 4fb91bcd8c1ecc096facda2878a2bfc532110ebc | [
"Markdown"
] | 1 | Markdown | atmonello/omnistack-9-frontend | b06d1294d08439270edcf8a5a0ce98de85b08be9 | 69980e3bba4a522c21feeb603f44dd600f4e28d4 |
refs/heads/master | <repo_name>Bastiantheone/MajorAdvisement<file_sep>/app/src/main/java/engineering/software/gsu/majoradvisement/GM.java
package engineering.software.gsu.majoradvisement;
import android.content.Context;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by Kwame on 3/26/2017.
*/
//Responsible for instantion of the questions
// Also holds the score, if we use a database save system we'll likely load up an 'instance'
//of the GM (or Game master) class
//the 'fun' value is what we'll use to determine at what step in the chain will certain questions
//pop up
public class GM {
public static int globalScore, globalCsScore, globalITScore, globalISScore, globalCEScore;
public static int funValue;
public static String username;
protected static String password;
private static GM Alpha;
public List<Question> questCS = new ArrayList<Question>();
public List<Question> questIT = new ArrayList<Question>();
public List<Question> questIS = new ArrayList<Question>();
public List<Question> questCE = new ArrayList<Question>();
public static Question currentQuestion;
private static final String TAG = "Game Master";
//Use it to pull the next Question from the Array lists, uses combination of 2 methods
//
public static GM initialize(Context context){
if(Alpha == null){
Alpha = new GM();
Alpha.loadQuestions(context);
}
else{
return Alpha;
}
return Alpha;
}
private GM(){};
public Question nextQuestion(){
funValue+=1;
int total = globalCsScore + globalITScore + globalISScore + globalCEScore;
List<Question> focus = new ArrayList<Question>();
Random random = new Random();
int randomNum = random.nextInt(total+1);
Log.d(TAG, "nextQuestion: "+randomNum+" and total "+total);
if (randomNum <= globalCsScore){
focus = questCS;
Log.d(TAG, "nextQuestion: CS Focus");
}
else if(randomNum < (globalCsScore + globalITScore)){
focus = questIT;
}
else if(randomNum < (globalCsScore + globalITScore + globalISScore)){
focus = questIS;
}
else if(randomNum <= (globalCsScore + globalITScore + globalISScore + globalCEScore)){
focus = questCE;
}
Question Selection = fetchQuestion(focus, funValue);
return Selection;
}
public Question fetchQuestion(List<Question> focus, int fun){
// enough fun, time for the score activity
// FIXME decide on a good fun value to take a break. Needs more questions for this
if(fun == 20)
return null;
List<Question>possibleQuestions = new ArrayList<>();
for(int i = 0; i < focus.size(); i++){
if(fun == focus.get(i).FunValue){
Question dummy = focus.get(i);
possibleQuestions.add(dummy);
}
}
Log.d(TAG, "fetchQuestion: possible Questions:"+possibleQuestions.size());
if(possibleQuestions.size()==0)return null;
Random random = new Random();
int r = random.nextInt(possibleQuestions.size());
Question q = possibleQuestions.get(r);
currentQuestion = q;
return q;
}
//This is where some sort of 'loading' method will go, will create a hardcode example to run this
//section of the code
public void loadQuestions(Context context){
// Method for loading would go in here, you'd create an array list of questions and answers and feed them into each other and then
//make the master list and edit the individual questions based on format
//the usage of it after the method is completed would be in the MyApplication.java class in order to allow us to edit it on initialization
DbConnect dbConnect = DbConnect.get(context);
questCS = dbConnect.getQuestion(1);
questCE = dbConnect.getQuestion(2);
questIT = dbConnect.getQuestion(3);
questIS = dbConnect.getQuestion(4);
}
}
<file_sep>/app/src/main/java/engineering/software/gsu/majoradvisement/GMHolder.java
package engineering.software.gsu.majoradvisement;
import android.content.Context;
/**
* Created by <NAME> on 4/13/2017.
*/
public class GMHolder {
public int score, cs, ce, it, is, fun;
public String username;
protected String password;
public GMHolder(int score, int cs, int ce, int it, int is, int fun, String username, String password){
this.score = score;
this.cs = cs;
this.ce = ce;
this.it = it;
this.is = is;
this.fun = fun;
this.username = username;
this.password = <PASSWORD>;
}
public GM initializeGM(String password, Context context){
if(this.password.equals(password)){
GM.globalScore = score;
GM.globalISScore = is;
GM.globalCEScore = ce;
GM.globalCsScore = cs;
GM.globalITScore = it;
GM.funValue = fun;
GM.username=username;
GM.password=<PASSWORD>;
return GM.initialize(context);
}else{
return null;
}
}
}
<file_sep>/app/src/main/java/engineering/software/gsu/majoradvisement/Question.java
package engineering.software.gsu.majoradvisement;
import android.app.Activity;
import android.content.Context;
import java.io.Serializable;
/**
* Created by Kwame on 4/1/2017.
*/
public class Question{
int FunValue;
int id;
public void display(Activity activity){
this.display(activity);
}
}
<file_sep>/app/src/main/java/engineering/software/gsu/majoradvisement/Image.java
package engineering.software.gsu.majoradvisement;
/**
* Created by <NAME> on 3/11/2017.
*/
//left is when the image is swipped to the left, right is for the right
// code was slightly redudant, changed it into a child of the Answer class for simplicity sake
public class Image {
private int imgID;
private Answer leftAnswer;
private Answer rightAnswer;
public Image(int imgID, int leftScore, int leftCSRating, int leftITRating, int leftISRating, int leftCERating,
int rightScore, int rightCSRating, int rightITRating, int rightISRating, int rightCERating){
this.imgID = imgID;
this.leftAnswer = new Answer(imgID + "", leftScore, leftCSRating, leftITRating, leftISRating, leftCERating);
this.rightAnswer= new Answer(imgID + "", rightScore, rightCSRating, rightITRating, rightISRating, rightCERating);
}
public int getImgID(){
return imgID;
}
public int getLeftScore() {
return leftAnswer.getScore();
}
public int getLeftCSRating() {
return leftAnswer.getCsRating();
}
public int getLeftITRating() {
return leftAnswer.getItRating();
}
public int getLeftISRating() {
return leftAnswer.getIsRating();
}
public int getLeftCERating() {
return leftAnswer.getCeRating();
}
public int getRightScore() {
return rightAnswer.getScore();
}
public int getRightCSRating() {
return rightAnswer.getCsRating();
}
public int getRightITRating() {
return rightAnswer.getItRating();
}
public int getRightISRating() {
return rightAnswer.getIsRating();
}
public int getRightCERating() {
return rightAnswer.getCeRating();
}
}
<file_sep>/app/src/main/java/engineering/software/gsu/majoradvisement/ScoreActivity.java
package engineering.software.gsu.majoradvisement;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.ValueDependentColor;
import com.jjoe64.graphview.helper.StaticLabelsFormatter;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint;
public class ScoreActivity extends AppCompatActivity {
private GraphView graph;
private TextView scoreTextView;
private TextView linkTextView;
private Button logoutButton;
private Button continueButton;
private Button startOverButton;
private GM gm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
gm = GM.initialize(this);
DbConnect.get(this).updateGameMaster(gm);
scoreTextView = (TextView)findViewById(R.id.score_text_view);
String text = "Score: "+gm.globalScore ;
scoreTextView.setText(text);
logoutButton=(Button)findViewById(R.id.logout_button);
logoutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ScoreActivity.this,LoginActivity.class);
startActivity(intent);
}
});
// start over but skip the initial which major question
continueButton=(Button)findViewById(R.id.continue_button);
continueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// FIXME instead of setting it back to 0 just continue. Needs more questions to have this
gm.funValue = 0;
Question q = gm.nextQuestion();
if(q!=null)
q.display(ScoreActivity.this);
}
});
// reset everything
startOverButton = (Button)findViewById(R.id.start_over_button);
startOverButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
gm.funValue = -1;
gm.globalCEScore = 0;
gm.globalITScore = 0;
gm.globalISScore = 0;
gm.globalCsScore = 0;
gm.globalScore = 0;
Question q = gm.nextQuestion();
if(q!=null)
q.display(ScoreActivity.this);
}
});
linkTextView = (TextView)findViewById(R.id.link_to_major_view);
linkTextView.setMovementMethod(LinkMovementMethod.getInstance());
if(gm.globalCsScore > gm.globalCEScore){
if(gm.globalISScore > gm.globalITScore){
if(gm.globalCsScore > gm.globalISScore)
linkTextView.setText(R.string.cs_link);
else
linkTextView.setText(R.string.is_link);
}else{
if(gm.globalCsScore > gm.globalITScore)
linkTextView.setText(R.string.cs_link);
else
linkTextView.setText(R.string.it_link);
}
}else{
if(gm.globalISScore > gm.globalITScore){
if(gm.globalCEScore > gm.globalISScore)
linkTextView.setText(R.string.ce_link);
else
linkTextView.setText(R.string.is_link);
}else{
if(gm.globalITScore > gm.globalCEScore)
linkTextView.setText(R.string.it_link);
else
linkTextView.setText(R.string.ce_link);
}
}
graph = (GraphView)findViewById(R.id.graph);
BarGraphSeries<DataPoint> series = new BarGraphSeries<>(new DataPoint[]{
new DataPoint(1,gm.globalCsScore),
new DataPoint(2,gm.globalCEScore),
new DataPoint(3,gm.globalITScore),
new DataPoint(4,gm.globalISScore)
});
graph.addSeries(series);
// set Color depending on the height and position
series.setValueDependentColor(new ValueDependentColor<DataPoint>() {
@Override
public int get(DataPoint data) {
return Color.rgb((int) data.getX()*255/4, (int) Math.abs(data.getY()*255/6),100);
}
});
series.setSpacing(50);
// add numbers on top
series.setDrawValuesOnTop(true);
series.setValuesOnTopColor(Color.RED);
// add labels
StaticLabelsFormatter staticLabelsFormatter = new StaticLabelsFormatter(graph);
staticLabelsFormatter.setHorizontalLabels(new String[]{"CS","CE","IT","IS"});
graph.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter);
}
@Override
public void onBackPressed(){
//do nothing
}
}
<file_sep>/README.md
# MajorAdvisement
An App that helps students find the right computing major
<file_sep>/app/src/main/java/engineering/software/gsu/majoradvisement/RateActivity.java
package engineering.software.gsu.majoradvisement;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class RateActivity extends AppCompatActivity {
private static final String TAG = "RateActivity";
private Button nextButton;
private RatingBar ratingBar;
private TextView textView;
private RateQuestion rateQuestion;
private int increase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rate);
nextButton = (Button)findViewById(R.id.next_button);
ratingBar = (RatingBar)findViewById(R.id.rating_bar);
textView = (TextView)findViewById(R.id.question_text);
rateQuestion = (RateQuestion)GM.currentQuestion;
increase = 0;
textView.setText(rateQuestion.getText());
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
float rating = ratingBar.getRating();
increase += rateQuestion.getScore();
GM.globalScore+=rateQuestion.getScore();
GM.globalCsScore+=calcScore(rateQuestion.getCs(),rating);
GM.globalITScore+=calcScore(rateQuestion.getIt(),rating);
GM.globalISScore+=calcScore(rateQuestion.getIs(),rating);
GM.globalCEScore+=calcScore(rateQuestion.getCe(),rating);
Log.d(TAG, "onClick: Cs:"+calcScore(rateQuestion.getCs(),rating)+ " IT: "+calcScore(rateQuestion.getIt(),rating));
next();
}
});
}
public int calcScore(int score, float rating){
float a = Math.abs(score-rating*2);
return (int)(10-a);
}
public void next(){
Toast.makeText(this,"+ "+increase+" pts",Toast.LENGTH_SHORT).show();
Question q = GM.initialize(this).nextQuestion();
if(q!=null)
q.display(this);
else{
Intent intent = new Intent(this,ScoreActivity.class);
startActivity(intent);
}
}
@Override
public void onBackPressed(){
//do nothing
}
@Override
public void onPause(){
super.onPause();
DbConnect.get(this).updateGameMaster(GM.initialize(this));
}
}
<file_sep>/app/src/main/java/engineering/software/gsu/majoradvisement/SwipeActivity.java
package engineering.software.gsu.majoradvisement;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class SwipeActivity extends AppCompatActivity {
private ImageView lowerImage, upperImage;
private TextView leftText, centerText, rightText;
private Button nextButton;
private int increase;
private List<Image> images;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe);
leftText = (TextView)findViewById(R.id.text_left);
centerText = (TextView)findViewById(R.id.text_center);
rightText = (TextView)findViewById(R.id.text_right);
upperImage = (ImageView)findViewById(R.id.upper_image);
upperImage.setContentDescription("Middle");
lowerImage = (ImageView)findViewById(R.id.lower_image);
lowerImage.setContentDescription("Middle");
nextButton = (Button)findViewById(R.id.next_button);
upperImage.setOnTouchListener(new OnSwipeListener(getBaseContext()));
lowerImage.setOnTouchListener(new OnSwipeListener(getBaseContext()));
SwipeQuestion question = (SwipeQuestion)GM.currentQuestion;
images = question.getImages();
upperImage.setImageResource(images.get(0).getImgID());
lowerImage.setImageResource(images.get(1).getImgID());
leftText.setText(question.getTextLeft());
rightText.setText(question.getTextRight());
increase = 0;
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(upperImage.getContentDescription().equals("Right")){
increase += images.get(0).getRightScore();
GM.globalScore+=images.get(0).getRightScore();
GM.globalCsScore+=images.get(0).getRightCSRating();
GM.globalITScore+=images.get(0).getRightITRating();
GM.globalISScore+=images.get(0).getRightISRating();
GM.globalCEScore+=images.get(0).getRightCERating();
}
else if(upperImage.getContentDescription().equals("Left")){
increase += images.get(0).getLeftScore();
GM.globalScore+=images.get(0).getLeftScore();
GM.globalCsScore+=images.get(0).getLeftCSRating();
GM.globalITScore+=images.get(0).getLeftITRating();
GM.globalISScore+=images.get(0).getLeftISRating();
GM.globalCEScore+=images.get(0).getLeftCERating();
}
if(lowerImage.getContentDescription().equals("Right")){
increase += images.get(1).getRightScore();
GM.globalScore+=images.get(1).getRightScore();
GM.globalCsScore+=images.get(1).getRightCSRating();
GM.globalITScore+=images.get(1).getRightITRating();
GM.globalISScore+=images.get(1).getRightISRating();
GM.globalCEScore+=images.get(1).getRightCERating();
}
else if(lowerImage.getContentDescription().equals("Left")){
increase += images.get(1).getLeftScore();
GM.globalScore+=images.get(1).getLeftScore();
GM.globalCsScore+=images.get(1).getLeftCSRating();
GM.globalITScore+=images.get(1).getLeftITRating();
GM.globalISScore+=images.get(1).getLeftISRating();
GM.globalCEScore+=images.get(1).getLeftCERating();
}
next();
}
});
}
public void next(){
Toast.makeText(this,"+ "+increase+" pts",Toast.LENGTH_SHORT).show();
Question q = GM.initialize(this).nextQuestion();
if(q!=null)
q.display(this);
else{
Intent intent = new Intent(this,ScoreActivity.class);
startActivity(intent);
}
}
@Override
public void onBackPressed(){
//do nothing
}
@Override
public void onPause(){
super.onPause();
DbConnect.get(this).updateGameMaster(GM.initialize(this));
}
}
<file_sep>/app/src/main/java/engineering/software/gsu/majoradvisement/QuestionWrapper.java
package engineering.software.gsu.majoradvisement;
import android.database.Cursor;
import android.database.CursorWrapper;
public class QuestionWrapper extends CursorWrapper {
public QuestionWrapper(Cursor cursor) {
super(cursor);
}
public Answer getAnswer() {
String text = getString(getColumnIndex(QuestionDbSchema.gamemaster_Table.answer_cols.text));
int score = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.answer_cols.score));
int csRating = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.answer_cols.csRating));
int itRating = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.answer_cols.itRating));
int isRating = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.answer_cols.isRating));
int ceRating = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.answer_cols.ceRating));
Answer answer1 = new Answer(text, score, csRating, itRating, isRating, ceRating);
return answer1;
}
public GMHolder getGameMaster() {
String user_name = getString(getColumnIndex(QuestionDbSchema.gamemaster_Table.GameMasterCols.user_name));
String password = getString(getColumnIndex(QuestionDbSchema.gamemaster_Table.GameMasterCols.password));
int fun = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.GameMasterCols.fun));
int global_score = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.GameMasterCols.global_score));
int global_cs_score = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.GameMasterCols.global_cs_score));
int global_it_score = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.GameMasterCols.global_it_score));
int global_is_score = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.GameMasterCols.global_is_score));
int global_ce_score = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.GameMasterCols.global_ce_score));
return new GMHolder(global_score,global_cs_score,global_ce_score,global_it_score,global_is_score,fun,user_name,password);
}
public Image images() {
int imgIDs = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.image_cols.imgID));
int leftScore = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.image_cols.leftAnswer));
int leftCSRating = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.image_cols.leftCSRating));
int leftITRating = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.image_cols.leftITRating));
int leftISRating = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.image_cols.leftISRating));
int leftCERating = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.image_cols.leftCERating));
int rightScore = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.image_cols.rightAnswer));
int rightCSRating = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.image_cols.rightCSRating));
int rightITRating = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.image_cols.rightITRating));
int rightISRating = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.image_cols.rightISRating));
int rightCERating = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.image_cols.rightCERating));
Image images1 = new Image(imgIDs, leftScore, leftCSRating, leftITRating, leftISRating, leftCERating,
rightScore, rightCSRating, rightITRating, rightISRating, rightCERating);
return images1;
}
public SwipeQuestion swipey() {
String text_left = getString(getColumnIndex(QuestionDbSchema.gamemaster_Table.swipe_cols.textLeft));
String text_right = getString(getColumnIndex(QuestionDbSchema.gamemaster_Table.swipe_cols.textRight));
int id = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.swipe_cols.answers_id));
int fun = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.swipe_cols.fun));
//SwipeQuestion swipey1 = new SwipeQuestion(text_left,text_right);
//swipey1.getTextLeft();
//swipey1.getTextRight();
SwipeQuestion swipey1 = new SwipeQuestion(text_left,text_right,id,fun);
return swipey1;
}
public RateQuestion ratey() {
String text_rate = getString(getColumnIndex(QuestionDbSchema.gamemaster_Table.ratequestion_cols.text));
int score = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.ratequestion_cols.score));
int cs = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.ratequestion_cols.cs));
int it = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.ratequestion_cols.it));
int is = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.ratequestion_cols.is));
int ce = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.ratequestion_cols.ce));
int fun = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.ratequestion_cols.fun));
RateQuestion ratey1 = new RateQuestion(text_rate, score, cs, it, is, ce, fun);
return ratey1;
}
public TextQuestion texty() {
String text_text = getString(getColumnIndex(QuestionDbSchema.gamemaster_Table.textquestion_cols.text));
int fun = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.textquestion_cols.fun));
int answer_id = getInt(getColumnIndex(QuestionDbSchema.gamemaster_Table.textquestion_cols.answer_id));
TextQuestion texty1 = new TextQuestion(text_text, fun, answer_id);
return texty1;
}
}
<file_sep>/app/src/main/java/engineering/software/gsu/majoradvisement/AboutScreenActivity.java
package engineering.software.gsu.majoradvisement;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.net.Uri;
import android.widget.TextView;
public class AboutScreenActivity extends AppCompatActivity {
private Button back;
private Button GSULink;
private TextView abouttxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about_screen);
GSULink = (Button)(findViewById(R.id.GSUButton));
abouttxt = (TextView) (findViewById(R.id.about_txt));
abouttxt.setText("This is the Georgia Southern computing advisement app. Here you can take a questionnaire to see what major you might be best suited for. The questionnaire will try and ask you questions that you should be asking yourself when choosing a computing major. The results from the questionnaire are not final, and you can go into any major you want. The results will just show you what major you might like, based on how you answer the questionnaire. ");
GSULink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Uri uriUril = Uri.parse("http://www.georgiasouthern.edu/");
Intent LB = new Intent(Intent.ACTION_VIEW, uriUril);
startActivity(LB);
}
});
}
}
| 25f53436391acd6cf1087b6fc0c4ef40e13e59f7 | [
"Java",
"Markdown"
] | 10 | Java | Bastiantheone/MajorAdvisement | 3f0e945beb6e5a8b69aaac3a5f04c141ac839c67 | c7684ef9048b3b3dcb1a37b7df4ab7b6f228c632 |
refs/heads/master | <file_sep>/**
* Created by moshaobu on 2017/4/12.
*/
require.config({
baseUrl:'../resources/views/requireJs/app',
paths:{
'jquery':'../lib/jquery-3.1.0',
'angular':'../lib/angular.min',
'bootstrap':'../lib/bootstrap.min',
'css':'../lib/css.min',
'router':'../lib/angular-ui-router.min',
},
shim:{
'bootstrap':{
'deps':['jquery','css!../css/bootstrap.min.css']
},
}
});<file_sep><div class="container-fluid home" ng-controller="homeController">
<div class="row">
<div class="col-md-4">
左边
</div>
<div class="col-md-7">
<h3>最新动态</h3>
<hr/>
<div class="item-list">
<div class="item clearfix" ng-repeat="(k,v) in home.data track by $index">
<div ng-if="v.question_id" class="vote">
<span ng-click="home.vote({id:v.id,vote:1})" class="up">赞 [:v.upvote_count:]</span>
<span ng-click="home.vote({id:v.id,vote:2})" class="down">踩 [:v.downvote_count:]</span>
</div>
<div class="item-content">
<div ng-if="v.question_id" class="content-act">
[:v.user.username:]添加了回答
</div>
<div ng-if="!v.question_id" class="content-act">
[:v.user.username:]添加了提问
</div>
<div class="title" ng-if="!v.question_id"
ui-sref="question.detail({id:v.id})">
[:v.title:]
</div>
<div class="title" ng-if="v.question_id"
ui-sref="question.detail({id:v.question.id})">
[:v.question.title:]
</div>
<div class="owner"><a href="#" ui-sref="user({id:v.user.id})">[:v.user.username:]</a>
<span class="desc" >[:v.user.intro:]</span>
</div>
<div class="content-main"
ui-sref="question.detail({id:v.id})"
ng-if="!v.question_id">
[:v.desc:]
</div>
<div class="content-main"
ui-sref="question.detail({id:v.question.id,answer_id:v.id})"
ng-if="v.question_id">
[:v.content:]
</div>
<div class="action_set">
<div class="comment" data-toggle="collapse" data-target="#comentCollapse[:k:]">评论</div>
</div>
<div class="collapse conmen-block" id="comentCollapse[:k:]">
<hr/>
<div class="comment-item-set">
<span class="owncaret"></span>
<div class="comment-item">
<div class="comment-user"><a href="#"> mohaobu:</a></div>
<p class="comment-content">这个学校很垃圾这个学校很垃圾这个学校很垃圾这个学校很垃圾这个学校很垃圾这个学校很垃圾这个学校很垃圾</p>
</div>
<div class="comment-item">
<div class="comment-user"><a href="#"> mohaobu:</a></div>
<p class="comment-content">这个学校很垃圾这个学校很垃圾这个学校很垃圾这个学校很垃圾这个学校很垃圾这个学校很垃圾这个学校很垃圾</p>
</div>
<div class="comment-item">
<div class="comment-user"><a href="#"> mohaobu:</a></div>
<p class="comment-content">这个学校很垃圾这个学校很垃圾这个学校很垃圾这个学校很垃圾这个学校很垃圾这个学校很垃圾这个学校很垃圾</p>
</div>
</div>
</div>
</div>
</div>
<div class="socur" ng-if="!home.socurces_have">加载更多</div>
<div class="socur" ng-if="home.socurces_have">没有更多资源啦</div>
</div>
</div>
</div>
</div><file_sep>define(['main'],function(model){
model.factory('loginService',['$http','$state',function ($http,$state) {
var obj={};
obj.login_data={};
obj.logined=false;
obj.login=function(){
$http.post('api/login',{
username:obj.login_data.username,
password:obj.login_data.password
}).then(function (data) {
if(data.status&&data.data.status) {
obj.logined=true;
$state.go('home');
obj.login_data={};
}
else {
alert('登录失败');
}
},function (error) {
alert('服务器错误')
})
};
obj.logout=function () {
$http.post('api/logout').then(function (data) {
if(data.data.status){
obj.logined=false;
$state.go('login');
}
},function (err) {
console.error('service error')
})
}
return obj;
}]);
model.controller('loginController',['$scope','loginService',function ($scope,loginService) {
$scope.userLogin=loginService;
}]);
});<file_sep><?php
/**
* Created by PhpStorm.
* User: moshaobu
* Date: 2017/4/8
* Time: 13:15
*/
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Http\Requests\Request;
class Answer extends Model{
public $timestamps=true;
protected function getDateFormat()
{
return time();
}
protected function asDateTime($value)
{
return parent::asDateTime($value); // TODO: Change the autogenerated stub
}
public function add(){
if(!user_ins()->login_or_out())
return ['status'=>0,'msg'=>'login required'];
if(!rq('question_id'))
return ['status'=>0,'msg'=>'need question id'];
if(!rq('content')){
return ['status'=>0,'msg'=>'need content can do action'];
}
$answered=$this
->where(['user_id'=>session('user_id'),'question_id'=>rq('question_id')])
->count();
if($answered)
return ['status'=>0,'msg'=>'you have answerd'];
$answer=$this;
$answer->question_id=rq('question_id');
$answer->user_id=session('user_id');
$answer->content=rq('content');
return $answer->save()?
['status'=>1,'id'=>$this->id]:
['status'=>0,'msg'=>'add answer failed'];
}
public function change(){
if(!user_ins()->login_or_out())
return ['status'=>0,'msg'=>'login required'];
if(!rq('id')||!rq('content'))
return ['status'=>0,'msg'=>'id ang content require'];
$answer=$this->find(rq('id'));
if(!$answer)
return ['status'=>0,'msg'=>'question no exists'];
if($answer->user_id!=session('user_id'))
return ['status'=>0,'msg'=>'have no prossiom'];
$answer->content=rq('content');
return $answer->save()?
['status'=>1,'msg'=>'update answer success']:
['status'=>0,'msg'=>'update answer failed'];
}
public function remove(){
if(!rq('id'))
return ['status'=>0,'msg'=>'id require'];
$answer=$this->find(rq('id'));
if(!$answer)
return ['status'=>0,'msg'=>'answer not found'];
$answer->users()
->newPivotStatement()//就是引用了vote库
->whereRaw('answer_id=?',[rq('id')])
->delete();
return $answer->delete()?
['status'=>1]:
['status'=>0,'msg'=>'service error'];
}
public function read(){
if(!rq('id')&&!rq('question_id')&&!rq('user_id'))
return ['status'=>0,'msg'=>'id,user_id and question_d require'];
/*
* 读取用户所有的回答
* */
if(rq('user_id')) {
$user_id = rq('user_id') == 'self' ? session('user_id') : rq('user_id');
$user_answers = $this
->with('question')
->with('users')
->where('user_id','=',$user_id)
->get()
->keyBy('id');
//$time=$user_answers->toArray();
foreach ($user_answers as $answer1){
$time = $answer1->created_at;
$answer1->time=$time;
}
if (!$user_answers) {
return ['status'=>0,'msg'=>'null answers'];
}else{
return ['status'=>1,'data'=>$user_answers->toArray()];
}
}
/*
* 查找回答,,以及他的回答者的信息和点赞的用户
* */
if(rq('id')) {
$answer=$this
->with('user')
->with('question')
->with('users')
->find(rq('id'));
if(!$answer)
return ['status'=>0,'msg'=>'data not fond'];
//这是问题详情页,每次读取的时候刷新点赞数
$upvote_count=0;
$downvote_count=0;
foreach($answer->users as $user){
if($user->pivot->vote==1)
$upvote_count++;
else if($user->pivot->vote==2)
$downvote_count++;
$answer->upvote_count=$upvote_count;
$answer->downvote_count=$downvote_count;
}
//当没有点赞数据的时候也记录为0
if(sizeof($answer->users)==0){//或者用count
$answer->upvote_count=0;
$answer->downvote_count=0;
}
$time=$answer->created_at;
$answer->time=$time;
return ['status'=>1,'data'=>$answer->toArray()];
}
if(!question_ins()->find(rq('question_id')))
return ['status'=>0,'msg'=>'question not found'];;
$question=$this
->where('question_id',rq('question_id'))
->get()
->keyBy('id');
if(!$question)
return ['status'=>0,'msg'=>'question not found'];
return ['status'=>1,'data'=>$question];
}
/*
* 点赞
* */
public function vote(){
if(!user_ins()->login_or_out())
return ['status'=>0,'msg'=>'you login require','login'=>2];
if(!rq('id')&&!rq('vote'))
return ['status'=>0,'msg'=>'id and vote reqiure'];
$answer=$this->find(rq('id'));
if(!$answer)
return ['status'=>0,'msg'=>'answer not find'];
/*
* 查看是否已经vote过
* */
$vote=rq('vote');
if($vote!=1&&$vote!=2&&$vote!=3)
return ['status'=>0,'msg'=>'invalid vote'];
$answer->users()
->newPivotStatement()//就是引用了vote库
->whereRaw('user_id=? and answer_id=?',[session('user_id'),rq('id')])
->delete();
if($vote==3)
return ['status'=>1];
$answer->users()
->attach(session('user_id'),['vote'=>$vote]);//就是用user_id把这张表连起来,第二各参数就存入数据
return ['status'=>1];
}
public function user(){
return $this->
belongsTo('App\User');
}
public function users(){
return $this
->belongsToMany('App\User')
->withPivot('vote')
->withTimestamps();
}
public function question(){//记住这里如果是一对多就用复苏,一对一就用单数
return $this->belongsTo('App\Question');
}
}<file_sep>/**
* 主页模块
*/
define(['angular','router'],function () {
var model=angular.module('xiaohu',['ui.router']);
model.config(['$interpolateProvider',
'$stateProvider',
'$urlRouterProvider',
'$locationProvider',
function($interpolateProvider,$stateProvider,$urlRouterProvider,$locationProvider){
$locationProvider.hashPrefix('');
$interpolateProvider.startSymbol('[:');
$interpolateProvider.endSymbol(':]');
$urlRouterProvider.otherwise('/home');
$stateProvider.state('home',{
url:'/home',
templateUrl:'tpl/page/home'
})
.state('login',{
url:'/login',
templateUrl:'tpl/page/login'
})
.state('signup',{
url:'/signup',
templateUrl:'tpl/page/signup'
})
.state('question',{
abstract:true,//这样在地址栏输入的时候不会显示这个模块,把他隐藏
url:'/question',
template:"<div ui-view></div>",
controller:'questionController'
})
.state('question.add',{
url:'/add',
templateUrl:'tpl/page/question_add',
//controller:'questionAddController'
})
.state('question.detail',{//也可以是/:answer_id但必须要有answer_id,不然会掉到首页
url:'/detail/:id?answer_id',
templateUrl:'tpl/page/question_detail',
//controller:'questionDetailController'
})
.state('user',{
url:'/user/:id',
templateUrl:'tpl/page/user'
})
.state('user.question',{
url:'/question',
templateUrl:'tpl/user/question'
})
.state('user.answer',{
url:'/answer',
templateUrl:'tpl/user/answer'
})
.state('user.desc',{
url:'/desc',
templateUrl:'tpl/user/desc'
});
}]);
return model;
});<file_sep><div class="container" id="questionadd">
<form name="questionForm" ng-controller="questionAddController" ng-submit="question.question_submit()">
<div class="form-group">
<h4 class="control-label">问题标题</h4>
<input placehodler="2-160个字符"
name="title"
ng-model="question.question_data.title"
ng-minlength="2"
maxlength="160"
required
class="form-control"/>
<p class="error" ng-if="questionForm.title.$touched&&
questionForm.title.$error.required">标题不能为空</p>
<p class="error" ng-if="questionForm.title.$touched&&
(questionForm.title.$error.minlength||
questionForm.title.$error.maxlength)">标标题应在2-160之间</p>
</div>
<div class="form-group">
<h4 class="control-label">问题描述</h4>
<textarea class="form-control" name="desc"
ng-model="question.question_data.desc"
placehodler="输入问题的描述">
</textarea>
</div>
<div class="form-group">
<button class="btn btn-primary"
type="submit"
ng-disabled="!questionForm.$valid">提问</button>
</div>
</form>
</div><file_sep>#后台api v 1.0
##常用api调用原则
####所有api都已localhost/momo/public/....
####所有api都有两个部分localhost/momo/public/part_1/part_2
######第一部part_1分为模型 如question
######第er部part_2分为行为如 read
###CRUD
####
#####增删改查
######每个四个方法......
<file_sep><div class="container login" id="login" ng-controller="loginController" >
<h4>登录</h4>
<form ng-submit="userLogin.login()" name="loginForm">
<div class="form-group" ng-class="{'has-success':loginForm.username.$valid}">
<label class="control-label">用户名</label>
<input type="text" name="username"
class="form-control"
ng-model="userLogin.login_data.username"
required
placehodler="用户名/手机/邮箱"/>
<p class="error" ng-if="loginForm.username.$touched&&
loginForm.username.$error.required">用户名不能为空</p>
</div>
<div class="form-group" ng-class="{'has-success':loginForm.password.$valid}">
<label class="control-label">密 码</label>
<input type="<PASSWORD>"
class="form-control"
ng-model="userLogin.login_data.password"
required
name="password"/>
<p class="error" ng-if="loginForm.password.$touched&&
loginForm.password.$error.required">密码不能为空</p>
</div>
<div class="form-group">
<input type="submit"
class="btn btn-default"
ng-disabled="!loginForm.$valid"
value="登录"/>
</div>
</form>
</div><file_sep><div class="item-list" id="user_question">
<div ng-if="user_answers_data.user_answers|answered" class="answer_alert">
还没有回答任何问题哦,赶快去回答吧
</div>
<div class="item clearfix" ng-repeat="(key,value) in user_answers_data.user_answers">
<div class="vote">
<span ng-click="user_self_data.user_answer_vote({id:key,vote:1})" class="up">赞 [:value.upvote_count:]</span>
<span ng-click="user_self_data.user_answer_vote({id:key,vote:2})" class="down">踩 [:value.downvote_count:]</span>
</div>
<div class="item-content">
<div class="title" ui-sref="question.detail({id:value.question.id})">问题标题:<a href="#">[:value.question.title:]</a></div>
<div class="content-main" ui-sref="question.detail({id:value.question.id,answer_id:value.id})">
回答内容:
[:value.content:]
</div>
<div class="action_set clearfix">
<div class="comment pull-left" data-toggle="collapse"
data-target="#comentCollapse[:key:]"
ng-if="value.question.desc"> 查看问题内容</div>
<div class="pull-right create_time">发布时间:[:value.time.date:]</div>
</div>
<div class="collapse conmen-block" id="comentCollapse[:key:]" ng-if="value.question.desc">
<hr/>
<p>[:value.question.desc:]</p>
</div>
</div>
</div>
</div><file_sep><?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Hash;
use Request;
class User extends Authenticatable
{
public $timestamps=true;
protected function getDateFormat(){
return time();
}
/*protected function asDateTime($value)
{
return $value; // TODO: Change the autogenerated stub
}*/
public function check_username_password(){
$username=rq('username');
$password=rq('<PASSWORD>');
if($username&&$password)
return [$username,$password];
else
return false;
}
public function signup(){
$user_data=$this->check_username_password();
if(!$user_data)
return ['status'=>0,'msg'=>'用户名和密码不能为空'];
$username=$user_data[0];
$password=$user_data[1];
/*检查用户名是否存在*/
$username_exists=$this
->where('username',$username)
->exists();
if($username_exists)
return ['status'=>0,'msg'=>"用户名已存在"];
/*加密密码*/
$password_hash=bcrypt($password);//和Hash::make()一样;
if(rq('phone'))
$phone_exists=$this->where('phone','=',rq('phone'))->first();
if($phone_exists)
return ['status'=>0,'msg'=>'phone exitst'];
if(rq('email'))
$email_exists=$this->where('email','=',rq('email'))->first();
if($email_exists)
return ['status'=>0,'msg'=>'email exitst'];
/*存入数据库*/
$user=$this;
$user->email=rq('email');
$user->phone=rq('phone');
$user->password=$<PASSWORD>;
$user->username=$username;
$save_ok=$user->save();
if($save_ok)
return ['status' => 1, 'id'=>$user->id];
return ['status'=>0,'msg'=>'insert bd failed'];
}
/*
* 获取用户信息api
* */
public function read(){
if(!rq('id'))
return ['status'=>0,'msg'=>'user id require'];
/*判断是否是当前用户在获取信息
* */
$id=rq('id')=='self'? session('user_id'):rq('id');
/*if($id!=session('user_id'))
return ['status'=>3,'msg'=>'you have no promission'];*/
$get=['id','username','intro','avatar_url','created_at'];
$user=$this->find($id,$get);
if(!$user)
return ['status'=>0,'msg'=>'user not exists'];
$answer_count=answer_ins()->where('id',rq('id'))->count();
$question_count=question_ins()->where('id',rq('id'))->count();
$user=$user->toArray();//本来user是对象,要把数据放在里面就把它转化成数组
$user['answer_count']=$answer_count;
$user['question_count']=$question_count;
return ['status'=>1,'data'=>$user];
}
/*登陆api*/
public function login(){
/*半段用户名密码是否存在*/
$user_data=$this->check_username_password();
if(!$user_data)
return ['status'=>0,'meg'=>'用户名和密码不能为空'];
$username=$user_data[0];
$password=$user_data[1];
/*判断用户是否存在*/
$user=$this->where('username',$username)->first();
if(!$user)
return ['status'=>0,'meg'=>'用户不存在'];
$password_db=$user->password;
/*判断用户s信息*/
if(!Hash::check($password,$password_db))
return ['status'=>0,'meg'=>'密码错误'];
/*session*/
session()->put('username',$username);
session()->put('user_id',$user->id);
return ['status'=>1,'msg'=>'登录成功'];
}
/*检查是否登录*/
public function login_or_out(){
if(session('user_id'))
return session('user_id');
return false;
}
/*登出*/
public function logout(){
if($this->login_or_out()) {
//session()->set('person.name','mo');//这样可以嵌套存
//SESSION()->set('person.name.a','nimabi');
//session()->flush();//就是把所有的sesseion删除;
//session()->pull('username');就是把username从session剪切掉;
session()->forget('username');
session()->forget('user_id');
//return redirect('/');//跳转到首页;
return ['status'=>1];
}
}
/*
* 修改密码
* */
public function change_password(){
if(!$this->login_or_out())
return ['status'=>0,'msg'=>'login require'];
if(!rq('old_password')||!rq('new_password'))
return ['status'=>0,'msg'=>'new and old password require'];
$user=$this->find(session('user_id'));
if(!Hash::check(rq('old_password'),$user->password))
return ['status'=>0,'msg'=>'old password is wrong'];
$password=bcrypt(rq('new_password'));
$user->password=$password;
return $user->save()?
['status'=>1,'msg'=>'change password success']:
['status'=>0,'msg'=>'change failed'];
}
/*
* 找回密码
* */
public function reset_password(){
/*
* 检查是否频繁调用接口
* */
if($this->is_roobt())
return ['status'=>0,'msg'=>'require to munck'];
/*
* 查看是否有号码
* */
if(!rq('phone'))
return ['status'=>0,'msg'=>'phone require'];
/*
* cha查看电话号码的用户
* */
$user=$this->where([
'phone'=>rq('phone'),
])
->first();
/*查看号码用户是否存在
* */
if(!$user)
return ['status'=>0,'msg'=>'phone noy found'];
$phone_captcha=$this->gerenel_captcha();
$user->phone_captcha=$phone_captcha;
if($user->save()){
$this->phone_sms();
/*为下一次机器人条用做准备
* */
session('last_sms_time',time());
return ['status'=>1];
}
return ['status'=>0,'msg'=>'db fail'];
}
/*
* 发送短信
* */
public function phone_sms(){
return true;
}
/*判断是否是机器人
* */
public function is_roobt($timeDufault=10){
/*查看接口是否被调用过
* */
if(!session('last_sms_time'))
return false;
$time=time();
$last_sms_time=session('last_sms_time');
$active_time=$time-$last_sms_time;
return !($active_time>$timeDufault);
}
/*
* 实验生成验证码
* */
public function gerenel_captcha(){
return rand(11111,99999);
}
/*
* 验证找回密码
* */
public function validate_reset_password(){
/*
* 查看是否是机器人
* */
if($this->is_roobt(3))
return ['status'=>0,'msg'=>'require to munck'];
/*
* 判断新密码,手机,手机验证码是否提交
* */
if(!rq('phone')||!rq('phone_captcha')||!rq('new_password'))
return ['status'=>0,'msg'=>'phone,phone_captcha,new_password require'];
/*匹配信息是否正确
* */
$user=$this->where([
'phone'=>rq('phone'),
'phone_captcha'=>rq('phone_captcha')
])->first();
if(!$user)
return ['status'=>0,'msg'=>'phone or captcha is wrong'];
/*
* 存入信号吗
* */
$user->password=<PASSWORD>(rq('<PASSWORD>'));
session()->put('last_sms_time',time());//在laravel不能直接用session(‘a’,'ja')之类的原生保存数据
return $user->save()?
['status'=>1]:
['status'=>0,'msg'=>'db failed'];
}
public function answers(){
return $this
->belongsToMany('App\Answer')
->withPivot('vote')
->withTimestamps();
}
public function userExists(){
$user=$this->where(rq())->count();
if(!$user)
return ['status'=>0,'msg'=>'not found'];
return ['status'=>1,'msg'=>'user exists'];
}
public function phone_exists(){
$user=$this->where(rq())->first();
if(!$user)
return ['status'=>0,'msg'=>'phone not found'];
return ['status'=>1,'msg'=>'phone exists'];
}
public function email_exists(){
$user=$this->where(rq())->first();
if(!$user)
return ['status'=>0,'msg'=>'email not found'];
return ['status'=>1,'msg'=>'email exists'];
}
}
<file_sep>define(['main'],function(model){
model.service('questionService',[
'$state',
'$http',
'answerService',
function($state,$http,answerService){
var me=this;
me.question_data={};
me.add_question=function () {
$state.go('question.add');
};
/*读取用户所有的问题或者读取某个问题*/
me.read=function (param) {
return $http.post('api/question/read',param).then(function (suc) {
if(suc.status&&suc.data.status) {
/*me.question_detail为问题详情页*/
me.question_detail=suc.data.data;
/*获取所有点赞或踩的数据*/
me.it_answers=suc.data.data.get_question_user_answers||[];
me.it_answers=answerService.getVote(me.it_answers);
return suc.data.data;
}
return false;
},function (error) {
console.log('service error')
})
}
/*
* 用户详情页的回答点赞功能
* conf({id:,vote:1})
* id为回答id
* */
me.vote=function (conf) {
//判断用户是否是取消点赞
me.check_invote(conf);
answerService.vote(conf).then(function (vote_success) {
if(vote_success){
/*获取该回答的所有内容和点赞书进行比较,赋值改变点赞的值*/
answerService.read(conf).then(function (data) {
for(var i=0; i < me.it_answers.length; i++){
if(conf.id==me.it_answers[i].id){
me.it_answers[i]=data;
}
}
},function () {
console.log('service error')
})
}
},function () {
console.log('service error')
})
}
/*
* 判断用户是否是取消点赞
* */
me.check_invote=function (conf) {
for(var i=0; i < me.it_answers.length; i++){
if(conf.id==me.it_answers[i].id){
var current_answer=me.it_answers[i];
break;
}
}
for(var i=0; i<current_answer.users.length; i++){
if (current_answer.users[i].id==user.id){
if(current_answer.users[i].pivot.vote==conf.vote){
conf.vote=3;
}
}
}
}
/*问题提交*/
me.question_submit=function () {
$http.post('api/question/add',me.question_data).then(function (data) {
console.log(data);
if(data.status&&data.data.status==2){
alert('请先登录');
$state.go('login');
}else if(data.status&&data.data.status==1){
$state.go('home');
me.question_data={};
}
},function (error) {})
};
}]);
model.controller('questionController',[
'$scope',
'questionService',
'answerService',
function($scope,questionService,answerService){
$scope.question=questionService;
$scope.answer=answerService;
}]);
model.controller('questionAddController',[
'$scope',
'questionService',
function($scope,questionService){
}])
model.controller('questionDetailController',[
'$scope',
'$stateParams',
'questionService',
'answerService',
function ($scope,$stateParams,questionService,answerService) {
answerService.answer_form={};
if($stateParams.answer_id)
questionService.answer_curent_id=$stateParams.answer_id;
else
questionService.answer_curent_id=null;
questionService.read($stateParams).then(function (data) {
})
}])
//回答评论.里面的scope只是控制该域
model.directive('commentBlock',[
'$http',
'answerService',
function ($http,answerService) {
var obj={};
obj.restrict='AE';
obj.templateUrl="comment.tpl";
obj.scope={
'answer_id':'=answerId'
}
obj.link=function (scope,elem,attr,con) {
scope.answer=answerService;
scope.comment_action={};
scope.data={};
function get_comment_data() {
$http.post('api/comment/read',{answer_id:scope.answer_id}).then(function (success) {
if(success.data.status)
scope.data=angular.merge({},scope.data,success.data.data);
},function () {
console.error('service error')
});
}
if(scope.answer_id)
get_comment_data();
scope.comment_action.comment_submit=function () {
answerService.comment_text.answer_id=scope.answer_id;
answerService.comment_submit().then(function (status) {
if(status) {
answerService.comment_text = {};
get_comment_data();
}
},function (err) {
console.log(err);
})
}
//判断data是否为空
scope.comment_data=function(data) {
var comment_data_arr=Object.keys(data);
return comment_data_arr.length;
}
scope.user_id=user.id;
scope.comment_delete=function (comment_id) {
$http.post('api/comment/remove',{id:comment_id}).then(function (success) {
if(success.data.status){
get_comment_data();
}
},function (err) {
console.error('service error')
})
}
};
return obj;
}]);
});<file_sep>define(['main'],function (model) {
model.filter('answered',function(){
return function(data){
if (angular.isArray(data)&&!data.length)
return true;
return false;
}
})
model.factory('userService',[
'$http',
'$state',
'answerService',
function ($http,$state,answerService) {
var userObj={};
userObj.read=function (userParam) {
$http({
method:'post',
url:'api/user/read',
data:$.param(userParam),
headers:{'content-type':'application/x-www-form-urlencoded'}
}).then(function (success) {
if(success.status&&success.data.status==3){
$state.go('home');
}
else if (success.status&&success.data.status)
userObj.user_data=success.data.data;
},function (error) {
console.log(error);
})
};
//个人主页的点赞模块
userObj.user_answer_vote=function (conf) {
userObj.check_vote(conf);
answerService.vote(conf).then(function (data) {
if(data)
answerService.read({id:conf.id}).then(function (success) {
answerService.user_answers[conf.id]=success;
console.log(success)
},function (error) {
console.error('service error')
})
},function () {
console.error('service error')
})
};
//判断是否取消点赞
userObj.check_vote=function (conf) {
var current_answer=answerService.user_answers[conf.id];
for(var i=0; i<current_answer.users.length; i++){
if(current_answer.users[i].id == user.id){
if(current_answer.users[i].pivot.vote==conf.vote){
conf.vote=3;
}
}
}
}
return userObj;
}]);
model.controller('userController',[
'$scope',
'answerService',
'$stateParams',
'questionService',
'userService',
function ($scope,
answerService,
$stateParams,
questionService,
userService) {
userService.read($stateParams);
$scope.user_self_data=userService;
$scope.user_questions=questionService;
$scope.user_answers_data=answerService;
answerService.read({user_id:$stateParams.id})
.then(function (data) {
//data不是数组,先转化成数组
console.log(data)
var answers=[];
var index=0;
for(var attr in data){
answers[index]=data[attr];
index++;
}
answerService.getVote(answers);
answerService.user_answers=data;
});
questionService.read({user_id:$stateParams.id})
.then(function (data) {
questionService.user_questions=data;
})
}]);
});<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="/momo/resources/views/requireJs/require.js"></script>
<script src="/momo/resources\views\requireJs\base.js"></script>
<link rel="stylesheet" href="\momo\resources\views\requireJs\css\main.css"/>
</head>
<body ng-app="xiaohu" user_id="{{session('user_id')}}" ng-controller="baseController">
<div class="navbar navbar-default" id="headerNav">
<div class="container">
<div class="navbar-header">
<a href="#" class="navbar-brand">小呼</a>
</div>
<form class="navbar-form navbar-left" id="navbar-form" ng-controller="questionController" ng-submit="question.add_question()" >
<div class="input-group">
<input type="text" placeholder="输入问题" ng-model="question.question_data.title" class="form-control"/>
<span class="input-group-btn">
<button type="submit" class="btn btn-default">提问</button>
</span>
</div>
</form>
<ul class="nav navbar-nav navbar-right">
<li class="nav-active"><a href="#" ui-sref="home">首页</a> </li>
@if(!session('user_id'))
<li ng-if="!base.logined" ><a href="#" class="" ui-sref="login">登录</a> </li>
<li ng-if="!base.logined"><a href="#" ui-sref="signup">注册</a> </li>
@else
<li ng-if="base.logined" ng-click="base.logout()"><a href="#">退出</a> </li>
<li class="date-target-self" ng-if="base.logined"><a href="#"
ui-sref="user({id:'self'})">个人中心</a> </li>
@endif
</ul>
</div>
</div>
<div ui-view></div>
<script>
require(['bootstrap','signup','login','question','home','user']);
</script>
</body>
</html>
<script type="text/ng-template" id="comment.tpl">
<hr/>
<div class="comment-item-set">
<span class="owncaret"></span>
<div class="comment_none" ng-if="!comment_data(data)">暂无评论</div>
<div ng-if="comment_data(data)" class="comment-item" ng-repeat="comment in data">
<div class="comment-user"><span class="comment_user_id" ui-sref="user({id:comment.user.id})">[:comment.user.username:]</span></div>
<p class="comment-content">: [:comment.content:]</p>
<div class="comment_do_list">
<span ng-click="comment_delete(comment.id)" ng-if="comment.user.id==user_id">删除</span>
</div>
</div>
</div>
<div>
<form name="comment_form" ng-submit="comment_action.comment_submit()">
<div class="input-group">
<input
placeholder="说点什么吧......"
type="text"
name="content"
required
ng-model="answer.comment_text.content"
class="form-control comment-text">
<div class="input-group-btn">
<input
type="submit"
ng-disabled="!comment_form.$valid"
class="btn btn-primary"
value="评论">
</div>
</form>
</div>
</script><file_sep><div class="item-list" ng-controller="questionDetailController" id="questionDetail">
<div class="item clearfix">
<div class="item-content">
<div class="title" >[:question.question_detail.title:]</div>
<div class="owner">
<a href="#" ui-sref="user({id:question.question_detail.user.id})">[:question.question_detail.user.username:]</a>
<span class="desc" >[:question.question_detail.intro:]</span>
</div>
<div class="content-main">
[:question.question_detail.desc:]
</div>
<h4 class="answer_count">
<span>回答数:[:question.question_detail.get_question_user_answers.length:]</span>
</h4>
<hr ng-if="question.question_detail.get_question_user_answers.length">
<div class="answer_block"
ng-if="!question.answer_curent_id || question.answer_curent_id==v.id"
ng-repeat="(k,v) in question.question_detail.get_question_user_answers">
<div class="vote">
<span ng-click="question.vote({id:v.id,vote:1})" class="up">赞 [:v.upvote_count:]</span>
<span ng-click="question.vote({id:v.id,vote:2})" class="down">踩 [:v.downvote_count:]</span>
</div>
<div class="answer-item">
<h6 class="answer_username">
<a href="#" ui-sref="user({id:[:v.user.id:]})">
[:v.user.username:]
</a>
</h6>
<div class="answer_content">
[:v.content:]
<span ng-if="user_id==v.user.id" class="answer_reset">
<span href="#"
ng-click="answer.answer_form=v">编辑</span>
<span ng-click="answer.delete({id:v.id})">删除</span>
</span>
</div>
</div>
<div class="action_set">
<div class="comment" data-toggle="collapse" data-target="#comentCollapse[:k:]">评论</div>
</div>
<div class="collapse conmen-block" comment-block answer-id="v.id" id="comentCollapse[:k:]">
</div>
<hr>
</div>
<form name="answer_form"
{{--ng-init="question.answer_form.id=question.question_detail.id"
每次提交的时候这和语句才实行,从服务器去慢啦--}}
ng-submit="answer.answer_add_update(question.question_detail.id)">
<div class="form-group">
<textarea
name="content"
ng-minlength="5"
ng-maxlength="400"
ng-model="answer.answer_form.content"
required
class="answer_form_text"></textarea>
</div>
<div class="form-group">
<input ng-disabled="answer_form.$invalid"
class="btn btn-default btn-sm"
type="submit" value="提交"/>
</div>
</form>
</div>
</div>
</div>
<file_sep><?php
/**
* Created by PhpStorm.
* User: moshaobu
* Date: 2017/4/8
* Time: 15:37
*/
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Http\Requests\Request;
class Comment extends Model{
public $timestamps=true;
protected function getDateFormat()
{
return time();
}
/*添加评论api*/
public function add(){
if(!user_ins()->login_or_out())
return ['status'=>0,'msg'=>'login require'];
/*
* 检查是否id
* */
if(!rq('question_id')&&!rq('answer_id'))
return ['status'=>0,'msg'=>'question_id or answer_id need'];
/*
*检查是否question_id和answer_id都存在
* */
if(rq('question_id')&&rq('answer_id'))
return ['status'=>0,'msg'=>'answer_id and question_id not to all set'];
/*
* 查找question或answer是否存在且写如数据
* */
if(rq('question_id')){
$question=question_ins()->find(rq('question_id'));
if(!$question)
return ['status'=>0,'msg'=>'question not found'];
$this->question_id=rq('question_id');
}else{
$answer=answer_ins()->find(rq('answer_id'));
if(!$answer)
return ['status'=>0,'msg'=>'answer not found'];
$this->answer_id=rq('answer_id');
}
/*
* 检查content的存在
* */
if(!rq('content'))
return ['status'=>0,'msg'=>'content required'];
$this->content=rq('content');
/*
* 是否是回复api
* */
if(rq('reply_to')){
$target=$this->find(rq('reply_to'));
if(!$target)
return ['status'=>0,'msg'=>'target not exists'];
/*
* 用户本身不能回复自己
* */
if($target->user_id==session('user_id'))
return ['status'=>0,'msg'=>'cannot reply yurself'];
$this->reply_to=rq('reply_to');
}
$this->user_id=session('user_id');
/*
* 保存数据
* */
return $this->save()?
['status'=>1,'id'=>$this->id]:
['status'=>0,'msg'=>'save failed'];
}
/*
* 删除api
* */
public function read(){
/*
* 判断查看的问题question_id或answer_id是否存在
* */
if(!rq('question_id')&&!rq('answer_id'))
return ['status'=>0,'msg'=>'question_id or answer_id all need'];
/*
*对数据处理
* */
if(rq('question_id')){
/*查看问题是否存在
* */
$question=question_ins()->find(rq('question_id'));
if(!$question)
return ['status'=>0,'msg'=>'question not exists'];
/*找出问题的所有评论
* */
$data=$this
->with('user')
->where('question_id',rq('question_id'))
->get();
}else{
$answer=answer_ins()->find(rq('answer_id'));
if(!$answer)
return ['status'=>0,'msg'=>'answer is not extists'];
$data=$this
->with('user')
->where('answer_id',rq('answer_id'))
->get();
}
return ['status'=>1,'data'=>$data];
}
/*
* 删除评论
* */
public function remove(){
if(!user_ins()->login_or_out())
return ['status'=>0,'msg'=>'login required'];
if(!rq('id'))
return ['status'=>0,'msg'=>'id required'];
/*查该数据是否存在
* */
$comment=$this->find(rq('id'));
if(!$comment)
return ['status'=>0,'mag'=>'comment not exitsts'];
if($comment->user_id!=session('user_id'))
return ['status'=>0,'msg'=>'you no promission'];
/*删除
* */
$this->where('reply_to',rq('id'))->delete();
return $comment->delete()?
['status'=>1,'msg'=>'delete success']:
['status'=>0,'mag'=>'delete failed'];
}
public function user(){
return $this->belongsTo('App\User');
}
}<file_sep><?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTableTest extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('test',function(Blueprint $table){
//$table->unsignedInteger('id')->autoIncrement();这句等于
$table->increments('id');
$table->string('cat')->unllable();
$table->text('article')->nullable()->comment('文章');//hou后umianshi数据表的注释
$table->string('username',60)->unique();
});
Schema::rename('test','test_1');//就就是把表明改成test_1
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('test_1');
}
}
<file_sep><div class="home container" id="signup">
<div>
<h3>注册</h3>
<form name="signupForm" class="form-horizontal has-feedback" ng-submit="userSignup.signup()" ng-controller="signupController">
<div class="form-group" ng-class="{'has-success':signupForm.username.$valid&&!userSignup.usernameexists}">
<label class="col-sm-3 control-label">
用户名:
</label>
<div class="col-sm-9">
<input name="username"
placeholder="手机/邮箱/用户名"
ng-minlength="2"
ng-maxlength="26"
required="required"
ng-model="userSignup.signup_data.username"
ng-model-options="{updateOn:'default blur',debounce:{default:400,blur:0}}"
class="form-control"
/>
<p class="error" ng-if="signupForm.username.$touched&&
(signupForm.username.$error.minlength||
signupForm.username.$error.maxlength)">用户名应在3-30之间</p>
<p class="error" ng-if="signupForm.username.$touched&&
signupForm.username.$error.required">用户名不能为空</p>
<p class="error" ng-if="signupForm.username.$valid&&
userSignup.usernameexists">用户名已存在</p>
</div>
</div>
<div class="form-group" ng-class="{'has-success':signupForm.email.$valid&&!userSignup.emailexists}">
<label class="col-sm-3 control-label">
邮箱:
</label>
<div class="col-sm-9">
<input type="email"
name="email"
placeholder="输入邮箱"
required="required"
ng-model-options="{debounce:300}"
ng-model="userSignup.signup_data.email"
class="form-control"/>
<p class="error" ng-if="signupForm.email.$touched&&
signupForm.email.$error.email">邮箱格式错误</p>
<p class="error" ng-if="signupForm.email.$touched&&
signupForm.email.$error.required">邮箱不能为空</p>
<p class="error" ng-if="signupForm.email.$valid&&userSignup.emailexists">邮箱码已存在</p>
</div>
</div>
<div class="form-group" ng-class="{'has-success':signupForm.phone.$valid&&!userSignup.phoneexists}">
<label class="col-sm-3 control-label">
电话:
</label>
<div class="col-sm-9">
<div class="input-group">
<span class="input-group-addon">186+</span>
<input name="phone"
placeholder="输入电话"
ng-model="userSignup.signup_data.phone"
ng-model-options="{debounce:300}"
ng-pattern="/^[1]{1}[3,5,7,8]{1}[0-9]{9}$/"
required="required"
class="form-control"/>
</div>
<p class="error" ng-if="signupForm.phone.$touched&&
signupForm.phone.$error.required">电话不能为空</p>
<p class="error" ng-if="signupForm.phone.$touched&&
signupForm.phone.$error.pattern">电话格式不对</p>
<p class="error" ng-if="signupForm.phone.$valid&&userSignup.phoneexists">电话号码已存在</p>
</div>
</div>
<div class="form-group" ng-class="{'has-success':signupForm.password.$valid}">
<label class="col-sm-3 control-label">
密码:
</label>
<div class="col-sm-9">
<input name="password"
type="<PASSWORD>"
ng-minlength="6"
ng-maxlength="60"
required="required"
ng-model="userSignup.signup_data.password"
class="form-control"/>
<p class="error" ng-if="signupForm.password.$touched&&
(signupForm.password.$error.minlength||
signupForm.password.$error.maxlength)">密码应在3-30之间</p>
<p class="error" ng-if="signupForm.password.$touched&&
signupForm.password.$error.required">用户名不能为空</p>
</div>
</div>
<div class="form-group" ng-class="{'has-success':signupForm.password2.$valid}">
<label class="col-sm-3 control-label">
确认密码:
</label>
<div class="col-sm-9">
<input name="password2"
type="<PASSWORD>"
required="required"
ng-model="userSignup.signup_data.password2"
compare="userSignup.signup_data.password"
class="form-control"/>
<p class="error" ng-if="signupForm.password2.$touched&&
signupForm.password2.$error.compare">两次密码不一致</p>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary center-block" ng-disabled="!signupForm.$valid||
userSignup.usernameexists||userSignup.phoneexists||userSignup.emailexists">注册</button>
</div>
</form>
</div>
</div><file_sep><?php
/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
*/
Route::get('/',function(){
return view('index');
});
/*user路由*/
function paginate($page,$limit=null){
$limit=$limit?:15;
$skip=($page? $page-1:0)*$limit;
return [$limit,$skip];
}
function rq($key=null,$default=null){
if(!$key) return Request::all();
return Request::get($key,$default);
}
function user_ins(){
return new App\User();
}
Route::any('api/signup',function (){
return user_ins()->signup();
});
Route::any('api/login',function(){
return user_ins()->login();
});
Route::any('api/logout',function(){
return user_ins()->logout();
});
/*获取用户信息
* */
Route::any('api/user/read',function(){
return user_ins()->read();
});
/*
* 查看用户是否存在
* */
Route::any('api/user/username_exists',function (){
return user_ins()->userExists();
});
Route::any('api/user/phone_exists',function (){
return user_ins()->phone_exists();
});
Route::any('api/user/email_exists',function (){
return user_ins()->email_exists();
});
/*
* 修改密码
* */
Route::any('api/user/change_password',function(){
return user_ins()->change_password();
});
/*
*
* 找回密码
*
*(1)发验证码
*(10验证)
* */
Route::any('api/user/reset_password',function (){
return user_ins()->reset_password();
});
Route::any('api/user/validate_reset_password',function(){
return user_ins()->validate_reset_password();
});
/*问题路由*/
function question_ins(){
return new App\Question();
}
Route::any('api/question/add',function(){
return question_ins()->add();
});
Route::any('api/question/update',function() {
return question_ins()->change();
});
Route::any('api/question/read',function(){
return question_ins()->read();
});
Route::any('api/question/remove',function(){
return question_ins()->remove();
});
/*问题回答路由*/
function answer_ins(){
return new App\Answer();
}
Route::any('api/answer/add',function(){
return answer_ins()->add();
});
Route::any('api/answer/update',function(){
return answer_ins()->change();
});
Route::any('api/answer/read',function(){
return answer_ins()->read();
});
Route::any('api/answer/remove',function(){
return answer_ins()->remove();
});
/*评论路由*/
function comment_ins(){
return new App\Comment();
}
Route::any('api/comment/add',function(){
return comment_ins()->add();
});
Route::any('api/comment/read',function(){
return comment_ins()->read();
});
Route::any('api/comment/remove',function(){
return comment_ins()->remove();
});
/*
* 点赞路有
* */
Route::any('api/answer/vote',function(){
return answer_ins()->vote();
});
Route::any('api/timeline','CommonController@timeline');
//前端路由
Route::any('tpl/page/home',function (){
return view('page.home');
});
Route::any('tpl/page/signup',function (){
return view('page.signup');
});
Route::any('tpl/page/question_add',function (){
return view('page.question_add');
});
Route::any('tpl/page/login',function (){
return view('page.login');
});
Route::any('tpl/page/user',function (){
return view('page.user');
});
Route::any('tpl/user/question',function (){
return view('page.user_question');
});
Route::any('tpl/user/answer',function (){
return view('page.user_answer');
});
Route::any('tpl/user/desc',function (){
return view('page.user_desc');
});
Route::any('tpl/page/question_detail',function (){
return view('page.question_detail');
});
<file_sep>
define([],function () {
return {
checkExists:function(scope,service){
scope.$watch(function(){
return service.signup_data.username;
},function (v,o) {//signup_data.username只有满足条件$valid为true的时候才会有值,但刚刷新的时候为undefine,会触发这个¥watch方法
if(v)
service.chech_or_exitsts('username');
},true)
scope.$watch(function () {
return service.signup_data.phone;
},function (v,o) {
if(v)
service.chech_or_exitsts('phone');
})
scope.$watch('userSignup.signup_data.email',function (v,o) {
if(v)
service.chech_or_exitsts('email');
})
},
signup_user_phone_email_exists:function (http,service) {
return function (name) {
var userData=service.signup_data[name];
var obj={};
obj[name]=userData;
/*http.post('api/user/'+name+'_exists',obj)
.then(function(data){
console.log(data);
if(data.data.status&&data.status)
service[name+'exists']=true;
else
service[name+'exists']=false;
},function(data){
});*///这两个方法都可以
http({
method:'post',
url:'api/user/'+name+'_exists',
data:$.param(obj),
headers:{'content-type':'application/x-www-form-urlencoded'}
}).then(function(data){
console.log(data);
if(data.data.status&&data.status)
service[name+'exists']=true;
else
service[name+'exists']=false;
},function(data){
});
}
}
}
})<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Question extends Model
{
public $timestamps=true;
protected function getDateFormat(){
return time();
}
public function add(){
if(!user_ins()->login_or_out())
return ['status'=>2,'msg'=>'login required'];
if(!rq('title'))
return ['status'=>1,'meg'=>'title required'];
$this->title=rq('title');
if(rq('desc'))
$this->desc=rq('desc');
$this->user_id=session('user_id');
$save_ok=$this->save();
if(!$save_ok)
return ['status'=>0,'id'=>$this->id];
return ['status'=>1,'msg'=>'save ok'];
}
/*更新问题api*/
public function change(){
/*检查是否登陆*/
if(!user_ins()->login_or_out())
return ['status'=>0,'msg'=>'you have no login'];
$id=rq('id');
$question=$this->find($id);
if(!$question)
return ['status'=>0,'msg'=>'date not find'];
if($question->user_id!=session('user_id'))
return ['status'=>0,'msg'=>'you have no promiss to change'];
if(rq('title'))
$question->title=rq('title');
if(rq('desc'))
$question->desc=rq('desc');
/*保存数据*/
return $question->save()?
['status'=>1,'msg'=>'update data success']:
['status'=>0,'msg'=>'update date failed'];
}
/*查看数据*/
public function read(){
/*
* 查询单个问题详情
* */
if(rq('id')) {
$oneData = $this
->with('user')
->with('get_question_user_answers')
->find(rq('id'));
if(!$oneData)
return ['status' => 0, 'msg' =>'no found question'];
return ['status' => 1, 'data' => $oneData];
}
//查看用户提出的问题
if(rq('user_id')) {
$user_id = rq('user_id') == 'self' ? session('user_id') : rq('user_id');
$question_user = $this->where('user_id','=',$user_id)->get()->keyBy('id');
if (!$question_user) {
return ['stat'=>0,'msg'=>'null answers'];
}else{
return ['status'=>1,'data'=>$question_user->toArray()];
}
}
/*
* 读取所有的问题
* */
list($article_limit,$skip)=paginate(rq('page'),rq('limit'));
$data=$this
->orderBy('created_at','desc')
->limit($article_limit)
->skip($skip)
->select('title','id','created_at','desc','user_id')//这个也可以用get(['title','id','created_at','desc','user_id']);代替
->get()
->keyBy('id');
if(!$data)
return ['status'=>0,'have no data'];
return array('status' => '1', 'data' => $data);
}
/*
* 查看用户提出的问题
* */
/*public function read_question_by_user_id(){
if(!rq('user_id'))
return ['status'=>0,'msg'=>'user_id required'];
if(rq('user_id')) {
$user_id = rq('user_id') == 'self' ? session('user_id') : rq('user_id');
$question_user = $this->where('user_id','=',$user_id)->get()->keyBy('id');
if (!$question_user) {
return ['stat'=>0,'msg'=>'null answers'];
}else{
return ['status'=>1,'data'=>$question_user];
}
}
}*/
/*
* 删除问题api*/
public function remove(){
if(!user_ins()->login_or_out())
return ['status'=>0,'msg'=>'you not logined'];
if(!rq('id'))
return ['status'=>0,'msg'=>'not id'];
$question=$this->find(rq('id'));
if(!$question)
return ['status'=>0,'msg'=>'no question'];
if(session('user_id')!=$question->user_id)
return ['status'=>0,'msg'=>'not prossion'];
return $question->delete()?
['status'=>1,'msg'=>'delete data success']:
['status'=>0,'msg'=>'delete failed'];
}
public function user(){
return $this->belongsTo('App\User');
}
public function answers(){
return $this->hasMany('App\Answer');
}
public function get_question_user_answers(){
return $this
->answers()
->with('users')//会从App\answer下面找到users
->with('user');
}
}
<file_sep>
<div ng-controller="userController" class="clearfix" id="user">
<div class="header">
<div class="header-left">
<h2>[:user_self_data.user_data.username:]</h2>
<p>[:user_self_data.user_data.intro||'主人很懒,还没有个人签名哦':]</p>
</div>
<div class="header-right">
<ul>
<li>
<a href="#">2</a>
<span>关注</span>
</li>
<li>
<a href="#">100</a>
<span>粉丝</span>
</li>
</ul>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<ul class="nav nav-static user_nav">
<li class="active"><a href="#">主页</a></li>
<li><a href="#" ui-sref="user.question"><i class=""></i>提问</a></li>
<li><a href="#" ui-sref="user.answer">回答</a></li>
<li><a href="#" ui-sref="user.desc">个人资料</a></li>
</ul>
</div>
<div class="col-sm-9">
<div ui-view></div>
</div>
</div>
</div><file_sep>#headerNav a:focus{
outline: none;
}
.myserf{
width: 30%;
height:30%;
position: absolute;
right: 2%;
-webkit-box-shadow: 0 0 6px #cccccc ;
-moz-box-shadow: 0 0 6px #cccccc ;
box-shadow: 0 0 6px #cccccc ;
margin-top:10px;
background: #fff;
z-index: 10;
display: none;
}
.myserf .selfcaret{
width:0;
height:0;
border-right: 10px solid transparent;
border-left: 10px solid transparent;
border-bottom:10px solid #c1e2b3;
position: absolute;
top: -10px;
right:25%;
}
.nav-active{
background: #c1e2b3;
}
#headerNav{ margin-bottom:0;}
/*主页*/
.home h3{
font-size:18px;
font-weight: 400;
color: #46b8da;
}
.item-list{
-webkit-box-shadow: 0 0 3px #46b8da;
-moz-box-shadow: 0 0 3px #46b8da;
box-shadow: 0 0 3px #46b8da;
line-height:1.5;
padding: 10px;
width:70%;
background: rgba(0,0,0,0.01);
}
.conmen-block{
background: #fff;
}
.item{
margin-bottom: 20px;
border-bottom: 1px solid #cccccc;
}
.content-act{
font-size: 14px;
color: #999;
}
.title{
cursor: pointer;
color: #000;
font-size: 15px;
font-weight: 500;
}
.owner{
color: #222;
font-size: 12px;
cursor: pointer;
}
.owner .desc{
color: #aaaaaa;
}
.content-main{
color: #666;
font-size: 13px;
cursor: pointer;
}
.comment-item-set{
background: #fff;
margin: 5px;
}
.comment-item{
overflow: hidden;
zoom: 1;
}
.comment,.create_time{
font-size: 12px;
color: #999;
}
.comment{
cursor: pointer;
}
.owncaret{
position: relative;
top:-13px;
display: inline-block;
width: 0;
height: 0;
border-left:6px solid transparent;
border-right:6px solid transparent;
border-bottom: 6px solid #999999;
}
.comment-item .comment-user{
float: left;
color: #46b8da;
}
.comment-item .comment-content{
overflow: hidden;
padding-left: 5px;
font-size: 13px;
color: #666666;
}
.item hr{
margin:6px 0;
}
.socur{
height: 28px;
font-style: italic;
font-size: 13px;
line-height: 28px;
text-align: center;
background: #46b8da;
}
.item .vote{
width: 8%;
float: left;
margin-right: 2%;
padding-top:1%;
}
.item .vote span{
display: block;
margin-top:5%;
text-align: center;
background: #cccccc;
font-size: 12px;
cursor: pointer;
color: #333;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
color: #46b8da;
}
.item .vote .up{
background: rgba(200,0,0,0.2);
cursor: pointer;
}
.item .vote .up:hover{
background: #a10;
color: #FFFFFF;
}
.item .vote .down:hover{
background: #999999;
color: #FFFFFF;
}
.item .item-content{
width:90%;
float: left;
}
#navbar-form input{ width: 300px}
#signup{
width:38%;
box-shadow: 0 0 6px #999;
border-radius: 4px;
}
.error{
color: red;
padding-top:10px;
margin:0;
}
/*登录css*/
#login{
width: 30%;
-webkit-box-shadow: 0 0 5px #666;
-moz-box-shadow: 0 0 5px #666 ;
box-shadow: 0 0 5px #666;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
#login h4{
font-weight: bold;
padding-top:10px;
color: blue;
}
/*问题*/
#questionadd {
width: 45%;
-webkit-box-shadow: 0 0 5px #46b8da ;
-moz-box-shadow: 0 0 5px #46b8da ;
box-shadow: 0 0 5px #46b8da ;
padding-top: 10px;
-webkit-border-radius:5px;
-moz-border-radius:5px;
border-radius:5px;
font-weight: bold;
color: #46b8da;
}
/*
主页
*/
#user .header{
background-image: url("/momo/resources/views/image/temp1.jpg");
height: 150px;
background-size: 100% 100%;
}
#user .header .header-left{
float: left;
width:40%;
margin-left:10%;
}
#user .header .header-left h2{
color: #FFFFFF;
margin-top:10%;
}
#user .header .header-left p{
color: #FFFFFF;
font-size: 13px;
}
#user .header .header-right{
float: right;
position: relative;
right:10%;
top:50%;
}
#user .header .header-right li{
float: left;
padding-right:30px;
}
#user .header .header-right li a,
#user .header .header-right li span{
display: block;
text-align: center;
}
#user .header .header-right li a{
color: #fff;
}
#user .header .header-right li span{
color: #cccccc;
}
#user .user_nav li{
text-align: center;
background: #46b8da;
margin-top:2px;
}
#user .user_nav li a{
color: #aa1100;
}
#user .user_nav li a:hover{
background: #1b6d85;
}
#user_question{
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
width: 80%;
}
#user_question .answer_alert{
width:100%;
-webkit-box-shadow: 0 0 10px #eeeeee ;
-moz-box-shadow: 0 0 5px #666666 ;
box-shadow: 0 0 5px #666666 ;
height: 150px;
text-align: center;
line-height: 150px;
font-size: 22px;
color: #46b8da;
margin: 0 auto;
}
#user_question .title{
font-size: 13px;
}
/*
问题详情页*/
#questionDetail{
margin-left: 10px;
}
#questionDetail .answer_count{
font-size: 14px;
color: #999999;
}
#questionDetail .item{
padding-left: 5%;
}
#questionDetail.item-list{
margin-top: 20px;
}
#questionDetail .item{
margin-bottom: 0px;
border-bottom: 0px solid #cccccc;
}
#questionDetail .content-main{
font-size: 12px;
}
#questionDetail .answer_username{
cursor: pointer;
color: #5bc0de;
}
#questionDetail .vote{
padding-top: 0;
}
#questionDetail .answer_form_text{
width:100%;
resize: none;
border:0px solid #cccccc;
-webkit-box-shadow: 0 0 2px #cccccc ;
-moz-box-shadow: 0 0 2px #cccccc ;
box-shadow: 0 0 2px #cccccc ;
text-align: left;
margin-top: 10px;
padding: 10px;
text-indent:0;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
color: #999;
font-size: 12px;
}
#questionDetail .answer_form_text:focus,
.comment-text:focus{
outline: none;
-webkit-box-shadow: 0 0 5px #cccccc ;
-moz-box-shadow: 0 0 5px #cccccc ;
box-shadow: 0 0 5px #cccccc ;
}
#questionDetail .answer_content{
position: relative;
}
#questionDetail .answer_reset {
color: #999;
position: absolute;
bttom: 0;
right: 0;
font-size: 13px;
cursor: pointer;
}
#questionDetail .answer-item{
overflow: hidden;
}
#questionDetail .answer-item h6{
margin-top:0;
padding-top:0;
}
.comment_user_id{
cursor: pointer;
}
.comment_none{
color: #cccccc;
font-size: 13px;
text-align: center;
font-weight: bold;
padding-bottom: 4px;
}
.comment_do_list{
padding-right:1%;
color: #5bc0de;
cursor: pointer;
}
.comment_do_list span{
float: right;
font-size: 12px;
}
<file_sep>define(['main'],function (model) {
model.service('answerService',[
'$http',
'$state',
function ($http,$state) {
var me=this;
me.data=[];//对数据重新读取,跟从新替换之前旧数据的选项
me.up_down_data={};//获取回答的数据,便判断取消赞
me.answer_form={};
window.user={
'id':parseInt($('body').attr('user_id'))
};
/*总和点赞和踩的数据
* */
me.getVote=function (answers) {
for (var i=0; i<answers.length; i++){
var votes, answer=answers[i];
if(!answers[i].question_id)
continue;
me.up_down_data[answer.id]=answer;
answer.upvote_count=0;
answer.downvote_count=0;
votes=answer['users'];
for (var j=0; j<votes.length; j++){
if(votes[j].pivot.vote==1){
answer.upvote_count++;
}else if(votes[j].pivot.vote==2){
answer.downvote_count++;
}
}
}
return answers;
};
/*
* 点赞功能,看点赞是否成功
* conf={id:}id表示对那条回答进行点赞
* */
me.vote=function (conf) {
if(!conf.id||!conf.vote)
return;
/*
* 判断vote和数据库的vote是否一样,一样的花就取消d点赞
* */
var answers=me.up_down_data[conf.id],
users=answers.users;
for(var i=0; i<users.length; i++){
if(user.id == users[i].id&&conf.vote == users[i].pivot.vote)
conf.vote=3;
}
return $http.post('api/answer/vote',conf).then(function (success) {
if(success.data.status&&success.status)
return true;
else if(success.data.login==2)
$state.go('login');
else
return false;
},function (error) {
console.log('error');
return false;
});
};
/*
*查看用户回答过的问题
* param {user_id:}
* */
me.read=function (param) {
return $http({
method:'post',
url:'api/answer/read',
data:$.param(param),
headers:{'content-type':'application/x-www-form-urlencoded'}
}).then(function (success) {
if (success.status&&success.data.status)
return success.data.data;
return false;
},function (error) {
console.log('service error')
})
}
/*
* 点赞成功后对数据从新读取,为以后的点赞完直接改变前端数据
* */
me.answer_update=function(id){
$http.post('api/answer/read',{id:id}).then(function (success) {
me.data[id]=success.data.data;
},function (err) {
console.log(err);
});
}
//问题回答的提交和更新
me.answer_add_update=function (question_id) {
me.answer_form.question_id=question_id;
if(me.answer_form.id){
$http.post('api/answer/update',me.answer_form).then(function (success) {
if (success.status&&
success.data.status){
me.answer_form={};
$state.reload();
}
},function () {
console.error('service error')
})
}else {
$http.post('api/answer/add',me.answer_form).then(function (success) {
console.log(success)
if (success.status&&
success.data.status===0 &&
success.data.msg=='you have answerd'){
alert('你已经回答过了');
}else if(success.status&&success.data.status){
me.answer_form={};
$state.reload();
}
},function () {
console.error('service error')
})
}
}
me.delete=function (conf) {
$http.post('api/answer/remove',conf).then(function (success) {
if(success.data.status){
$state.reload();
}
},function () {
console.log('service error')
})
}
me.comment_text={};
me.comment_submit=function () {
return $http.post('api/comment/add',me.comment_text).then(function (success) {
if(!success.data.status&&success.data.msg=='login require')
$state.go('login');
if(success.data.status)
return true;
return false;
},function () {
console.log('service error')
})
}
}])
})
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class CommonController extends Controller
{
public function timeline(){
list($limit,$skip)=paginate(rq('page',rq('limit')));
/*
* 获取问题数据
* */
$question=question_ins()
->with('user')
->limit($limit)
->skip($skip)
->orderBy('created_at','desc')
->get();
/*
* 获取回答数据
* */
$answer=answer_ins()
->with('user')
->with('question')
->with('users')
->limit($limit)
->skip($skip)
->orderBy('created_at','desc')
->get();
//dd($question->toArray());
//dd($answer->toArray());
/*
* 数据合并
* */
$data=$question->merge($answer);
/*
* 数据【排序
* */
$data=$data->sortByDesc(function($item){
return $item->created_at;
});
/*
* 讲数据全部都索引去掉
* */
$data=$data->values()->all();
return ['status'=>1,'data'=>$data];
}
}
| d036aa7f759decf38ef1adebeadb2d0725813e4b | [
"Markdown",
"JavaScript",
"PHP",
"Blade",
"CSS"
] | 24 | Markdown | moaiqin/angular-zhihu | 31247ea1bdb0a586a4d30a066a60a60fc6bb5857 | 1f7c45ee0da8bf3d5b6ccc8113d2b523874c37b2 |
refs/heads/master | <file_sep>import nv from 'nvd3'
import ChartMixin from './mixins/chart'
import TooltipModel from './models/tooltip'
import AxisModel from './models/axis'
export default {
name: 'BarChart',
mixins: [
ChartMixin,
TooltipModel,
AxisModel
],
props: {
data: {
type: Array,
required: true
},
color: {
type: [Array, Function]
},
forceY: {
type: Array
},
showXAxis: {
type: Boolean,
default: true
},
showYAxis: {
type: Boolean,
default: true
},
showValues: {
type: Boolean,
default: false
},
valueFormat: {
type: Function
},
x: {
type: Function
},
y: {
type: Function
},
staggerLabels: {
type: Boolean,
default: false
},
showLegend: {
type: Boolean,
default: true
}
},
mounted() {
nv.addGraph(() => {
let model = nv.models.discreteBarChart
let chart = model()
chart.staggerLabels(this.staggerLabels)
.showValues(this.showValues)
.showLegend(this.showLegend)
.duration(this.duration)
if (!this.x) {
chart.x(function(d) { return d.label })
} else {
chart.x(this.x)
}
if (!this.y) {
chart.y(function(d) { return d.value })
} else {
chart.y(this.y)
}
if (this.tooltip) {
chart = this._applyTooltipModel(chart, this.tooltip)
}
if (this.xAxis) {
chart = this._applyAxisXModel(chart, this.xAxis)
}
if (this.yAxis) {
chart = this._applyAxisYModel(chart, this.yAxis)
}
if (this.valueFormat) {
chart.valueFormat(this.valueFormat)
}
this.$el.chart = chart
this._initEvents()
this.renderChart()
nv.utils.windowResize(chart.update);
chart.update()
return chart;
});
}
}<file_sep># vue-nvd3-charts
> NVD3 wrapper for Vue.js
## Build Setup
``` bash
# Installing with npm
npm install vue-nvd3-charts
```
Fully import
``` javascript
import Vue from 'vue'
import VueNvd3 from 'vue-nvd3-charts'
Vue.use(VueNvd3)
```
On demand
``` javascript
import { BarChart, LineChart, PieChart } from 'vue-nvd3-charts'
...
new Vue({
components: {
BarChart,
LineChart,
PieChart
}
})
```
<file_sep><template>
<div id="app">
<div class="chart-tools">
Legend Position:
<select v-model="legendPosition">
<option value="top">Top</option>
<option value="bottom">Bottom</option>
</select>
Donut: <input type="checkbox" v-model="donut">
Use Interactive Guideline <input type="checkbox" v-model="useInteractiveGuideline">
</div>
<div class="chart-panel">
<BarChart :data="data.barChart" :legendPosition="legendPosition" />
</div>
<div class="chart-panel">
<LineChart :data="data.lineChart"
:legendPosition="legendPosition"
:useInteractiveGuideline="useInteractiveGuideline"
:xAxis="chartAxisX"
:yAxis="chartAxisY"
/>
</div>
<div class="chart-panel">
<PieChart :data="data.pieChart" :legendPosition="legendPosition" :donut="donut" />
</div>
</div>
</template>
<script>
import Vue from "vue";
import Nvd3Charts from './charts'
import SampleData from './data'
Vue.use(Nvd3Charts)
export default {
data() {
return {
data: SampleData,
legendPosition: 'top',
useInteractiveGuideline: true,
donut: true,
xAxis: {
axisLabel: 'Dân số Việt Nam'
},
chartAxisX: {
axisLabel: "Time (s)",
tickFormat: d3.format(',.1f'),
staggerLabels: true
},
chartAxisY: {
axisLabel: 'Voltage (v)',
tickFormat(d) {
if (d == null) {
return 'N/A';
}
return d3.format(',.2f')(d);
}
}
}
},
methods: {
formatX(item) {
return d3.time.format("%d/%m")(d3.time.format("%Y-%m-%d").parse(item.label))
},
valueFormat(value) {
return d3.format(',.0f')(value);
}
}
}
</script>
<style>
.chart-panel {
width: 49%;
display: inline-block;
}
textarea {
width: 100%;
height: 200px;
}
</style><file_sep>import nv from 'nvd3'
import ChartMixin from './mixins/chart'
import TooltipModel from './models/tooltip'
import AxisModel from './models/axis'
export default {
name: 'LineChart',
mixins: [
ChartMixin,
TooltipModel,
AxisModel
],
props: {
data: {
type: Array,
required: true
},
useInteractiveGuideline: {
type: Boolean,
default: false
},
legendPosition: {
type: String,
default: 'top',
validator: function (value) {
return ['top', 'bottom'].indexOf(value) !== -1
}
},
x: {
type: Function
},
y: {
type: Function
},
},
mounted() {
nv.addGraph(() => {
let model = nv.models.lineChart
let chart = model()
chart.duration(this.duration)
.useInteractiveGuideline(this.useInteractiveGuideline)
.legendPosition(this.legendPosition)
if (this.x) {
chart.x(this.x)
}
if (this.y) {
chart.y(this.y)
}
if (this.tooltip) {
chart = this._applyTooltipModel(chart, this.tooltip)
}
if (this.xAxis) {
chart = this._applyAxisXModel(chart, this.xAxis)
}
if (this.yAxis) {
chart = this._applyAxisYModel(chart, this.yAxis)
}
this.$el.chart = chart
this._initEvents()
this.renderChart()
nv.utils.windowResize(chart.update);
return chart;
});
},
watch: {
legendPosition(val) {
if (this.$el.chart) {
this.$el.chart.legendPosition(val);
this.$el.chart.update()
}
},
useInteractiveGuideline(val) {
if (this.$el.chart) {
this.$el.chart.useInteractiveGuideline(val);
this.$el.chart.update()
}
}
}
}<file_sep>const keys = [
'chartContainer',
'classes',
'contentGenerator',
'data',
'distance',
'duration',
'enabled',
'fixedTop',
'gravity',
'headerEnabled',
'headerFormatter',
'hidden',
'hideDelay',
'id',
'keyFormatter',
'node',
'offset',
'position',
'snapDistance',
'valueFormatter'
]
export default {
props: {
tooltip: {
type: Object
}
},
methods: {
_applyTooltipModel(chart, options) {
for (let key in options) {
if (keys.indexOf(key) !== -1) {
chart['tooltip'][key].call(this, options[key])
}
}
return chart
}
}
}<file_sep>import d3 from 'd3'
import BarChart from './BarChart'
import LineChart from './LineChart'
import PieChart from './PieChart'
import 'nvd3/build/nv.d3.css'
export {
BarChart,
LineChart,
PieChart
}
export default {
install(Vue, options) {
Vue.component(BarChart.name, BarChart)
Vue.component(LineChart.name, LineChart)
Vue.component(PieChart.name, PieChart)
}
} | 220a6455bd292f226b349a229e11dbf5d797b848 | [
"Markdown",
"Vue",
"JavaScript"
] | 6 | Markdown | daofresh/vue-nvd3-charts | e7eaab31cff4caaeadb73f2908e9424d8802ca07 | 68792bc48db151030eeac78e0dd569ace5848791 |
refs/heads/master | <repo_name>ameba-proteus/triton-client<file_sep>/src/main/java/com/amebame/triton/client/TritonClient.java
package com.amebame.triton.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.nio.channels.NotYetConnectedException;
import com.amebame.triton.entity.TritonCall;
import com.amebame.triton.entity.TritonFuture;
import com.amebame.triton.exception.TritonClientClosedException;
import com.amebame.triton.exception.TritonClientConnectException;
import com.amebame.triton.exception.TritonClientException;
import com.amebame.triton.exception.TritonClientTimeoutException;
import com.amebame.triton.exception.TritonErrors;
import com.amebame.triton.exception.TritonRuntimeException;
import com.amebame.triton.json.Json;
import com.amebame.triton.protocol.TritonMessage;
import com.amebame.triton.util.NamedThreadFactory;
import com.fasterxml.jackson.databind.JsonNode;
public class TritonClient {
private TritonClientContext context;
private Bootstrap bootstrap;
private Channel channel;
private EventLoopGroup group;
private static final JsonNode EMPTY_NODE = Json.object();
/**
* Create triton client with default configuraiton.
*/
public TritonClient() {
this(new TritonClientConfiguration());
}
/**
* Create triton client with the custom configuration.
* @param config
*/
public TritonClient(TritonClientConfiguration config) {
context = new TritonClientContext(config);
group = new NioEventLoopGroup(config.getWorker(), new NamedThreadFactory("triton-client-"));
try {
bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new TritonClientChannelInitializer(context))
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, context.getConfig().getConnectTimeout())
;
} catch (Exception e) {
throw new TritonRuntimeException(TritonErrors.client_error, e.getMessage(), e);
}
}
/**
* Opening connection to the server
* @param host
* @throws TritonClientConnectException
*/
public void open(String host) throws TritonClientConnectException {
open(host, 4848);
}
/**
* Opening connection to the server
* @param host
* @param port
* @throws TritonClientConnectException
*/
public void open(String host, int port) throws TritonClientConnectException {
try {
channel = bootstrap.connect(host, port)
.sync()
.channel();
} catch (InterruptedException e) {
}
}
/**
* Check client status.
* @return
*/
public boolean isOpen() {
return channel != null && channel.isActive();
}
private void checkOpen() throws TritonClientClosedException {
if (channel == null || !channel.isActive()) {
throw new TritonClientClosedException();
}
}
private void write(TritonCall call) throws TritonClientClosedException {
try {
channel.writeAndFlush(call.build());
} catch (NotYetConnectedException e) {
throw new TritonClientClosedException();
}
}
/**
* send data to the server and not wait for reply.
* @param name
* @param data
*/
public void sendAsyncFully(String name, Object data) throws TritonClientException {
checkOpen();
TritonCall call = new TritonCall(name, data, true);
write(call);
}
/**
* Send data to the server and reply future object.
* Use future object can to wait for the reply from the server.
* @param name
* @param data
* @return
*/
public TritonFuture sendAsync(String name, Object data) throws TritonClientException {
checkOpen();
TritonCall call = new TritonCall(name, data);
TritonFuture future = new TritonFuture(call, context.getConfig().getCommandTimeout());
context.addFuture(future);
// send message to the server
write(call);
return future;
}
/**
* send only method to the server with future object.
* future will be invoked when server send reply
* @param name
* @param data
* @return
*/
public TritonFuture sendAsync(String name) throws TritonClientException {
return sendAsync(name, EMPTY_NODE);
}
/**
* send data to the server with annotated object instance.
* object class should have {@link TritonMethodData} annotation.
* @param command
* @return
*/
public TritonFuture sendAsync(Object data) throws TritonClientException {
TritonMethodData methodData = data.getClass().getAnnotation(TritonMethodData.class);
if (methodData == null) {
throw new TritonRuntimeException(TritonErrors.client_error, "method data must annotated with TritonMethodData");
}
return sendAsync(methodData.value(), data);
}
/**
* Send data to the server and waiting for reply.
* @param data
* @return
*/
public JsonNode send(Object data) throws TritonClientException {
TritonMethodData methodData = data.getClass().getAnnotation(TritonMethodData.class);
if (methodData == null) {
throw new TritonRuntimeException(TritonErrors.client_error, "method data must annotated with TritonMethodData");
}
return send(methodData.value(), data);
}
/**
* Send data to the server and waiting for reply.
* @param data
* @return
*/
public <E> E send(Object data, Class<E> resultClass) throws TritonClientException {
TritonMethodData methodData = data.getClass().getAnnotation(TritonMethodData.class);
if (methodData == null) {
throw new TritonRuntimeException(TritonErrors.client_error, "method data must annotated with TritonMethodData");
}
JsonNode result = send(methodData.value(), data);
return Json.convert(result, resultClass);
}
/**
* send data to the server and waiting for reply.
* @param name
* @param data
* @return
* @throws TritonClientException throws if server replies error result
*/
public JsonNode send(String name, Object data) throws TritonClientException {
TritonFuture future = sendAsync(name, data);
TritonMessage message = future.getResult();
if (message == null) {
throw new TritonClientTimeoutException("method " + name + " has been timed out");
}
if (message.isError()) {
if (message.hasBody()) {
JsonNode body = message.getBodyJson();
JsonNode messageNode = body.get("message");
String errorMessage = messageNode == null ? "" : messageNode.asText();
JsonNode codeNode = body.get("code");
int errorCode = codeNode == null ? 500 : codeNode.asInt();
throw new TritonClientException(TritonErrors.codeOf(errorCode), errorMessage);
} else {
throw new TritonClientException(TritonErrors.server_error, "unknown exception caused at server");
}
}
return message.getBodyJson();
}
/**
* sent data to the server and wait the reply.
* this method coverts result data to specified class.
*
* @param name
* @param data
* @param resultClass
* @return
* @throws TritonClientException
*/
public <E> E send(String name, Object data, Class<E> resultClass) throws TritonClientException {
JsonNode result = send(name, data);
return Json.convert(result, resultClass);
}
/**
* Close the client connection
*/
public void close() {
if (channel != null && channel.isOpen()) {
try {
channel.close().await(5000L);
} catch (InterruptedException e) {
}
}
group.shutdownGracefully();
}
}
<file_sep>/src/main/java/com/amebame/triton/client/cassandra/method/RemoveColumns.java
package com.amebame.triton.client.cassandra.method;
import java.util.Arrays;
import java.util.List;
import com.amebame.triton.client.TritonMethodData;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
@TritonMethodData("cassandra.column.remove")
@JsonInclude(Include.NON_NULL)
public class RemoveColumns {
private String cluster;
private String keyspace;
private String table;
private List<String> keys;
private List<String> columns;
// Map<String, Map<String, JsonNode>>
private JsonNode rows;
private Consistency consistency;
public RemoveColumns() {
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getKeyspace() {
return keyspace;
}
public void setKeyspace(String keyspace) {
this.keyspace = keyspace;
}
public String getTable() {
return table;
}
public void setTable(String table) {
this.table = table;
}
public boolean hasRows() {
return rows != null && rows.size() > 0;
}
public JsonNode getRows() {
return rows;
}
public void setRows(JsonNode rows) {
this.rows = rows;
}
public Consistency getConsistency() {
return consistency;
}
public void setConsistency(Consistency consistency) {
this.consistency = consistency;
}
public boolean hasKeys() {
return keys != null && keys.size() > 0;
}
public List<String> getKeys() {
return keys;
}
public void setKeys(List<String> keys) {
this.keys = keys;
}
public void setKey(String key) {
this.keys = Arrays.asList(key);
}
public boolean hasColumns() {
return columns != null && columns.size() > 0;
}
public List<String> getColumns() {
return columns;
}
public void setColumns(List<String> columns) {
this.columns = columns;
}
public void setColumn(String column) {
this.columns = Arrays.asList(column);
}
}
<file_sep>/src/main/java/com/amebame/triton/exception/TritonClientTimeoutException.java
package com.amebame.triton.exception;
public class TritonClientTimeoutException extends TritonClientException {
private static final long serialVersionUID = -7740109050086234544L;
public TritonClientTimeoutException(String message) {
super(TritonErrors.client_timeout, message);
}
}
<file_sep>/src/main/java/com/amebame/triton/client/cassandra/entity/TritonCassandraTable.java
package com.amebame.triton.client.cassandra.entity;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
@JsonInclude(Include.NON_NULL)
public class TritonCassandraTable {
private String name;
private String keyType;
private String columnType;
private JsonNode options;
public TritonCassandraTable() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public JsonNode getOptions() {
return options;
}
public void setOptions(JsonNode options) {
this.options = options;
}
public String getKeyType() {
return keyType;
}
public String getColumnType() {
return columnType;
}
public void setColumnType(String columnType) {
this.columnType = columnType;
}
public void setKeyType(String keyType) {
this.keyType = keyType;
}
}
<file_sep>/src/main/java/com/amebame/triton/client/memcached/method/GetCache.java
package com.amebame.triton.client.memcached.method;
import java.util.List;
import com.amebame.triton.client.TritonMethodData;
@TritonMethodData("memcached.get")
public class GetCache {
// cluster
private String cluster;
// cache key
private String key;
// cache keys
private List<String> keys;
// expires for get and touch if set.
private Integer expire;
public GetCache() {
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getKey() {
return key;
}
public List<String> getKeys() {
return keys;
}
public void setKey(String key) {
this.key = key;
}
public void setKeys(List<String> keys) {
this.keys = keys;
}
public Integer getExpire() {
return expire;
}
public void setExpire(Integer expire) {
this.expire = expire;
}
}
<file_sep>/src/main/java/com/amebame/triton/protocol/TritonProtocolEncoder.java
package com.amebame.triton.protocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* Triton Protocol Encoder
* to encode data to TritonMesasge
*
*/
public class TritonProtocolEncoder extends MessageToByteEncoder<TritonMessage> {
@Override
protected void encode(
ChannelHandlerContext ctx,
TritonMessage msg,
ByteBuf out) throws Exception {
// write to message
msg.writeTo(out);
}
}
<file_sep>/src/main/java/com/amebame/triton/client/lock/method/LockRelease.java
package com.amebame.triton.client.lock.method;
import com.amebame.triton.client.TritonMethodData;
@TritonMethodData("lock.release")
public class LockRelease {
private String key;
private int ownerId;
public LockRelease() {
}
public LockRelease(String key, int ownerId) {
this.key = key;
this.ownerId = ownerId;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public int getOwnerId() {
return ownerId;
}
public void setOwnerId(int ownerId) {
this.ownerId = ownerId;
}
}
<file_sep>/src/main/java/com/amebame/triton/exception/TritonException.java
package com.amebame.triton.exception;
public class TritonException extends Exception {
private static final long serialVersionUID = 6884306643710263861L;
private TritonErrors error;
public TritonException(TritonErrors error, String message) {
super(message);
this.error = error;
}
public TritonException(TritonErrors error, Throwable cause) {
super(cause.getMessage(), cause);
this.error = error;
}
public TritonException(TritonErrors error, String message, Throwable cause) {
super(message, cause);
this.error = error;
}
public TritonErrors getError() {
return error;
}
}
<file_sep>/src/main/java/com/amebame/triton/client/TritonClientChannelInitializer.java
package com.amebame.triton.client;
import com.amebame.triton.protocol.TritonProtocolDecoder;
import com.amebame.triton.protocol.TritonProtocolEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
public class TritonClientChannelInitializer extends ChannelInitializer<SocketChannel> {
private TritonClientContext context;
public TritonClientChannelInitializer(TritonClientContext context) {
this.context = context;
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("encoder", new TritonProtocolEncoder());
pipeline.addLast("decoder", new TritonProtocolDecoder());
pipeline.addLast("handler", new TritonClientHandler(context));
}
}
<file_sep>/README.md
# Triton Client for Java
Triton client for java enable to interact with Triton Data Access Gateway.
# License
BSD<file_sep>/src/main/java/com/amebame/triton/json/UUIDDeserializer.java
package com.amebame.triton.json;
import java.io.IOException;
import java.util.UUID;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
public class UUIDDeserializer extends StdScalarDeserializer<UUID> {
private static final long serialVersionUID = -6186423319849754786L;
public UUIDDeserializer() {
super(UUID.class);
}
@Override
public UUID deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
String text = jp.getValueAsString();
if (text == null) {
return null;
}
return UUID.fromString(text);
}
}
<file_sep>/src/main/java/com/amebame/triton/exception/TritonRuntimeException.java
package com.amebame.triton.exception;
public class TritonRuntimeException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 7958464770082357800L;
private TritonErrors error;
public TritonRuntimeException() {
super();
this.error = TritonErrors.server_error;
}
public TritonRuntimeException(TritonErrors error) {
super();
this.error = error;
}
public TritonRuntimeException(TritonErrors error, String message, Throwable cause) {
super(message, cause);
this.error = error;
}
public TritonRuntimeException(TritonErrors error, String message) {
super(message);
this.error = error;
}
public TritonRuntimeException(TritonErrors error, Throwable cause) {
super(cause.getMessage(), cause);
this.error = error;
}
public TritonErrors getError() {
return error;
}
}
<file_sep>/src/main/java/com/amebame/triton/client/TritonClientHandler.java
package com.amebame.triton.client;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import com.amebame.triton.entity.TritonFuture;
import com.amebame.triton.protocol.TritonMessage;
public class TritonClientHandler extends ChannelInboundHandlerAdapter {
private TritonClientContext context;
public TritonClientHandler(TritonClientContext context) {
this.context = context;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
TritonMessage message = (TritonMessage) msg;
if (message.isReply() || message.isError()) {
TritonFuture future = context.removeFuture(message.getCallId());
if (future != null) {
future.setResult(message);
}
}
}
}
<file_sep>/src/main/java/com/amebame/triton/client/memcached/method/SetCache.java
package com.amebame.triton.client.memcached.method;
import com.amebame.triton.client.TritonMethodData;
import com.fasterxml.jackson.databind.JsonNode;
@TritonMethodData("memcached.set")
public class SetCache {
// cluster
private String cluster;
// cache key
private String key;
// seconds to expire (max 30 days)
private int expire;
// cache value
private JsonNode value;
public SetCache() {
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public int getExpire() {
return expire;
}
public void setExpire(int expire) {
this.expire = expire;
}
public JsonNode getValue() {
return value;
}
public void setValue(JsonNode value) {
this.value = value;
}
}
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.amebame.triton</groupId>
<artifactId>triton-client</artifactId>
<version>1.1.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>triton-client</name>
<url>http://maven.apache.org</url>
<properties>
<netty.version>4.0.9.Final</netty.version>
<jackson.version>2.2.3</jackson.version>
<junit.version>4.11</junit.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<scm>
<url>http://github.com/ameba-proteus/triton-client.git</url>
<connection>scm:git:https://github.com/ameba-proteus/triton-client.git</connection>
</scm>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.13</version>
<configuration>
<includes>
<include>**/Test*.java</include>
</includes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Netty -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
<file_sep>/src/main/java/com/amebame/triton/client/cassandra/method/ListKeyspace.java
package com.amebame.triton.client.cassandra.method;
import com.amebame.triton.client.TritonMethodData;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
* Create a keyspace
*/
@TritonMethodData("cassandra.keyspace.list")
@JsonInclude(Include.NON_NULL)
public class ListKeyspace {
// cluster name
private String cluster;
public ListKeyspace() {
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
}
<file_sep>/src/main/java/com/amebame/triton/client/elasticsearch/method/GetDocument.java
package com.amebame.triton.client.elasticsearch.method;
import com.amebame.triton.client.TritonMethodData;
@TritonMethodData("elasticsearch.get")
public class GetDocument {
private String cluster;
private String index;
private String type;
private String id;
private String routing;
private long timeout;
public GetDocument() {
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public long getTimeout() {
return timeout;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
public String getRouting() {
return routing;
}
public void setRouting(String routing) {
this.routing = routing;
}
}
<file_sep>/src/main/java/com/amebame/triton/client/elasticsearch/method/SearchDocumentHit.java
package com.amebame.triton.client.elasticsearch.method;
import com.fasterxml.jackson.databind.JsonNode;
public class SearchDocumentHit {
private String id;
private String index;
private String type;
private JsonNode source;
private float score;
public SearchDocumentHit() {
}
public String getId() {
return id;
}
public String getIndex() {
return index;
}
public JsonNode getSource() {
return source;
}
public String getType() {
return type;
}
public float getScore() {
return score;
}
public void setId(String id) {
this.id = id;
}
public void setIndex(String index) {
this.index = index;
}
public void setSource(JsonNode source) {
this.source = source;
}
public void setType(String type) {
this.type = type;
}
public void setScore(float score) {
this.score = score;
}
}
<file_sep>/src/main/java/com/amebame/triton/client/cassandra/entity/TritonCassandraKeyspace.java
package com.amebame.triton.client.cassandra.entity;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonInclude(Include.NON_NULL)
public class TritonCassandraKeyspace {
private String name;
private Map<String, String> replication;
private List<TritonCassandraTable> tables;
public TritonCassandraKeyspace() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getReplication() {
return replication;
}
public void setReplication(Map<String, String> replication) {
this.replication = replication;
}
public void setTables(List<TritonCassandraTable> tables) {
this.tables = tables;
}
public List<TritonCassandraTable> getTables() {
return tables;
}
}
<file_sep>/src/main/java/com/amebame/triton/exception/TritonClientConnectException.java
package com.amebame.triton.exception;
public class TritonClientConnectException extends TritonClientException {
private static final long serialVersionUID = 6361241566200424L;
public TritonClientConnectException(String message) {
super(TritonErrors.not_connected, message);
}
public TritonClientConnectException(Throwable cause) {
super(TritonErrors.not_connected, cause.getMessage(), cause);
}
public TritonClientConnectException(String message, Throwable cause) {
super(TritonErrors.not_connected, message, cause);
}
}
<file_sep>/src/main/java/com/amebame/triton/exception/TritonJsonException.java
package com.amebame.triton.exception;
public class TritonJsonException extends TritonRuntimeException {
private static final long serialVersionUID = -5916693574413964335L;
public TritonJsonException() {
super(TritonErrors.json_format);
}
public TritonJsonException(String message, Throwable cause) {
super(TritonErrors.json_format, message, cause);
}
public TritonJsonException(String message) {
super(TritonErrors.json_format, message);
}
public TritonJsonException(Throwable cause) {
super(TritonErrors.json_format, cause.getMessage(), cause);
}
}
<file_sep>/src/main/java/com/amebame/triton/entity/TritonFuture.java
package com.amebame.triton.entity;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.amebame.triton.protocol.TritonMessage;
/**
* TritonFuture
*/
public class TritonFuture {
private TritonCall call;
private TritonMessage result;
private CountDownLatch latch;
private long defaultTimeout;
private long expired;
public TritonFuture(TritonCall call, long defaultTimeout) {
this.call = call;
this.latch = new CountDownLatch(1);
this.defaultTimeout = defaultTimeout;
this.expired = System.currentTimeMillis() + defaultTimeout;
}
/**
* Get the callID of the call which sent to the server.
* @return
*/
public int getCallId() {
return call.getCallId();
}
/**
* Waiting the server response with default timeout.
*/
public void await() {
await(defaultTimeout);
}
/**
* Waiting the server response.
* @param timeout
* @throws InterruptedException
*/
public void await(long timeout) {
try {
latch.await(timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
}
}
/**
* Set result
* @param result
*/
public void setResult(TritonMessage result) {
this.result = result;
latch.countDown();
}
/**
* Get the result with default timeout
* @return
*/
public TritonMessage getResult() {
return getResult(defaultTimeout);
}
/**
* Get the result
* @return
*/
public TritonMessage getResult(long timeout) {
await(timeout);
return result;
}
/**
* Check expired or not
* @param now
* @return true if expired
*/
public boolean isExpired(long now) {
return now > expired;
}
}
| 7fa9f76077fa36b784f5789ec73e75f90389b871 | [
"Java",
"Markdown",
"Maven POM"
] | 22 | Java | ameba-proteus/triton-client | f66b9776f5153e853f78bfb8f1700676b1fa8770 | e0425a1464f2b83ddf019ed42463927b6ea68165 |
refs/heads/master | <file_sep>from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine
Base = declarative_base()
# Write your classes here :
class Product(Base):
__tablename__ = 'product'
id= Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
year = Column (Integer)
alive = Column(Boolean)
<file_sep>from model import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///lecture.db')
Base.metadata.create_all(engine)
DBSession = sessionmaker(bind=engine)
session = DBSession()
def add_product(first_name, last_name, year, alive):
product = Product(
first_name=first_name,
last_name=last_name,
year=year,
alive=alive)
session.add(product)
session.commit()
# Write your functions to interact with the database here :
def create_product():
#TODO: complete the functions (you will need to change the function's inputs)
pass
def update_product():
#TODO: complete the functions (you will need to change the function's inputs)
pass
def delete_product(id):
pass
def get_product(id):
pass
| 7ffff19202e4df84fe5fc02ca85527d567e60332 | [
"Python"
] | 2 | Python | noor19-meet/y2l-databases | ad51c9ea295cadce308cd66711f48b725039105f | 0e33308df594514bea5f88458c5f3eef16a69ddb |
refs/heads/master | <file_sep># hello-world
Lavanya's personalspace
Completely new to coding hoping to learn something new.
| b48e8a00a08086e3adafe20e71d83f1970bd48db | [
"Markdown"
] | 1 | Markdown | lavan22in/hello-world | 26f576457976ec229a9ef8b5ffb8685413fdc6fd | 54594539167b810c805088a1e3c6b7277c5fb8ec |
refs/heads/master | <repo_name>carbonvisuals/accor-hotels<file_sep>/js/index.js
var index = {
}
index.conversion_lookup = {
mass: [
{unit: "g", m: 1000},
{unit: "kg", m: 1},
{unit: "t", m: 0.001},
],
length: [
{unit: "mm", m: 1000},
{unit: "cm", m: 100},
{unit: "m", m: 1},
{unit: "km", m: 0.001},
],
volume: [
{unit: "cm<sup>3</sup>", m: 1000000},
{unit: "m<sup>3</sup>", m: 1},
{unit: "km<sup>3</sup>", m: 0.000001},
],
power: [
{unit: "W", m: 1000},
{unit: "kW", m: 1},
{unit: "MW", m: 0.001},
{unit: "TW", m: 0.000000001},
],
energy: [
{unit: "Wh", m: 1000},
{unit: "kWh", m: 1},
{unit: "MWh", m: 0.001},
{unit: "TWh", m: 0.000000001},
],
}
index.Converter = function (_type, _value, _unit) {
var value = null;
var converstion_type = null;
var conversion_lookup = null;
var construct = function (_type, _value, _unit) {
if (debug.sentinel(_type, "Empty converstion type value passed to Converter.") ||
debug.sentinel(index.conversion_lookup.hasOwnProperty(_type), "Invalid conversion type '"+_type+"' passed to Converter.") ||
debug.sentinel(utility.check_numeric(_value), "Invalid (non-numerical) value passed to Converter.")) {
//debug.sentinel(index.conversion_lookup[_type].hasOwnProperty(_value), "Invalid unit '"+_unit+"' passed to Converter.")) {
return;
}
conversion_type = _type;
conversion_lookup = index.conversion_lookup[_type];
var C = conversion_lookup.filter(function (a) {
return a.unit == _unit;
})[0];
value = C ? _value/C.m : _value;
}
this.get_result = function (_unit) {
var C;
if (_unit) {
C = conversion_lookup.filter(function (a) {
return a.unit == _unit;
})[0];
}
if (!C) {
C = conversion_lookup[0];
conversion_lookup.forEach(function (a) {
if (value*a.m >= 0.1) {
C = a;
}
})
}
return {
value: value*C.m,
unit: C.unit
}
}
this.get_result_string = function (_unit) {
var result = this.get_result(_unit);
return utility.add_commas(utility.round(result.value, 2))+" "+result.unit;
}
construct (_type, _value, _unit);
}
index.Three_scene = function (_wrapper) {
var set = false;
var wrapper;
var scene;
var camera;
var renderer;
var lights = {}
var groups = {}
var materials = {}
var fonts = {}
var w = 100;
function construct (_wrapper) {
if (debug.sentinel(utility.is_element(_wrapper), "Failed to initialise scene as wrapper is not a valid DOM object.")) {
return;
}
wrapper = _wrapper;
set_scene();
set_renderer();
wrapper.appendChild(renderer.domElement);
}
function set_scene () {
scene = new THREE.Scene();
}
function set_renderer () {
renderer = new THREE.WebGLRenderer({preserveDrawingBuffer: true, antialias: true });
renderer.setClearColor(new THREE.Color(0xeeeeee));
renderer.setSize(wrapper.offsetWidth, wrapper.offsetHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
check_if_set();
}
this.set_light = function (_type) {
if (debug.sentinel(typeof(THREE[_type]) == "function", "Failed to initialise light of nonexistant type "+_type+".")) {
return;
}
light = new THREE[_type](0xffffff);
light.position.set(100, 100, 0);
light.castShadow = true;
lights[_type] = light;
scene.add(light);
}
this.get_light = function (_type) {
if (debug.sentinel(lights.hasOwnProperty(_type), "Light of type '"+_type+"' has not been initialised.")) {
return;
}
return lights[_type];
}
function check_if_set () {
if (camera && renderer && scene) {
set = true;
}
}
this.set_camera = function (_type, _w) {
if (debug.sentinel(typeof(THREE[_type]) == "function", "Failed to initialise camera of nonexistant type "+_type+".")) {
return;
}
var aspect_ratio = wrapper.offsetWidth / wrapper.offsetHeight;
switch (_type) {
case "OrthographicCamera":
if (_w && utility.check_positive_number(_w)) {
w = _w;
}
camera = new THREE[_type](w/2, -w/2, w/(2*aspect_ratio), -w/(2*aspect_ratio), 1, 1000);
break;
default:
camera = new THREE[_type](30, aspect_ratio, 0.1, 10000000);
}
camera.position.x = 50;
camera.position.y = 10;
camera.position.z = 50;
camera.lookAt(new THREE.Vector3(0, 0, 0))
scene.add(camera);
check_if_set();
}
this.update_size = function () {
if (!camera) {return}
var type = camera.type;
var aspect_ratio = wrapper.offsetWidth / wrapper.offsetHeight;
renderer.setSize(wrapper.offsetWidth, wrapper.offsetHeight);
switch (type) {
case "OrthographicCamera":
camera.top = w/(2*aspect_ratio);
camera.bottom = -w/(2*aspect_ratio);
break;
default:
camera.aspect = aspect_ratio;
}
}
this.get_camera = function () {return camera};
this.get_renderer = function () {return renderer};
this.add = function (_obj, _add_to) {
if (debug.sentinel(_obj instanceof THREE.Object3D, "Could not add object as it is not a valid instance of Object3D.")) {
return;
}
if (!_add_to ||
debug.sentinel(groups[_add_to], "Could not add object to nonexistant group "+_add_to+". Adding to scene instead")) {
scene.add(_obj);
return;
}
groups[_add_to].add(_obj);
return;
}
this.get_material = function (_name) {
if (debug.sentinel(materials[_name], "Failed to get material. No existing material by the name of "+_name+".")) {
return;
}
return materials[_name];
}
this.set_material = function (_name, _material) {
if (debug.sentinel(_material instanceof THREE.Material, "Failed to assign an invalid material to name "+_name+".")) {
return;
}
debug.sentinel(!materials[_name], "Overwriting existing material by the name of "+_name+".")
materials[_name] = _material;
}
this.set_group = function (_name, _group, _parent) {
if (debug.sentinel(_group instanceof THREE.Object3D, "Failed to assign an invalid group to name "+_name+".")) {
return;
}
if (debug.sentinel(groups[_parent], "Failed to add group to invalid wrapper "+_parent+". Adding to scene instead.")) {
scene.add(_group);
}
else {
groups[_parent].add(group);
}
debug.sentinel(!groups[_name], "Overwriting existing group by the name of "+_name+".");
groups[_name] = _group;
}
this.get_group = function (_name) {
if (debug.sentinel(groups[_name], "Failed to get group. No existing group by the name of "+_name+".")) {
return;
}
return groups[_name];
}
this.clear_group = function (_name, _all_but) {
if (debug.sentinel(groups[_name], "Failed to get group. No existing group by the name of "+_name+".")) {
return;
}
if (debug.sentinel(!isNaN(_all_but) && _all_but >= 0, "Invalid or non-existant all_but value passed. Default value '0' used instead.")) {
_all_but = 0;
}
var _group = groups[_name];
while (_group.children.length > _all_but) {
_group.remove(_group.children[_all_but]);
}
}
this.set_font = function (_name, _font) {
if (debug.sentinel(_font instanceof THREE.Font, "Failed to assign an invalid font to name "+_name+".")) {
return;
}
debug.sentinel(!fonts[_name], "Overwriting existing font by the name of "+_name+".")
fonts[_name] = _font;
}
this.get_font = function (_name) {
if (debug.sentinel(fonts[_name], "Failed to get font. No existing font by the name of "+_name+".")) {
return;
}
return fonts[_name];
}
this.render = function () {
renderer.render(scene, camera);
}
construct(_wrapper)
}
index.Stack = function (_quantity_kg, _density_kg_m3) {
var density_kg_m3 = null;
var stack = {
kg: null,
m3: null,
base: null,
height: null,
sphere_count: null
}
var sphere = {
kg: null,
m3: null,
r_m: null
}
var set = false;
var construct = function (_quantity_kg, _density_kg_m3) {
_quantity_kg = parseFloat(_quantity_kg);
_density_kg_m3 = parseFloat(_density_kg_m3);
if (debug.sentinel(!isNaN(_quantity_kg), "Invalid non-numerical quantity value passed.") ||
debug.sentinel(_quantity_kg >= 0, "Invalid negative quantity value passed.") ||
debug.sentinel(!isNaN(_density_kg_m3), "Invalid non-numerical density value passed.") ||
debug.sentinel(_density_kg_m3 >= 0, "Invalid negative density value passed.")
) {
return;
}
density_kg_m3 = _density_kg_m3
stack.kg = _quantity_kg;
stack.m3 = stack.kg/density_kg_m3;
}
function calculate_sphere () {
var sphere_kg = 0.001;
var spheres_per_stack_limit = stack.base*stack.base*stack.height;
while (stack.kg/sphere_kg > spheres_per_stack_limit) {
sphere_kg *= 10;
}
sphere.kg = sphere_kg;
sphere.m3 = sphere.kg/density_kg_m3;
sphere.r_m = sphere.r_m = Math.cbrt((3*sphere.m3)/(4*Math.PI));
stack.sphere_count = Math.round(stack.kg/sphere.kg);
}
this.set_stack_parameters = function (_base, _height) {
_base = parseInt(_base);
_height = parseInt(_height);
if (debug.sentinel(!isNaN(_base), "Invalid non-numerical base value passed.") ||
debug.sentinel(_base >= 0, "Invalid negative base value passed.") ||
debug.sentinel(!isNaN(_height), "Invalid non-numerical height value passed.") ||
debug.sentinel(_height >= 0, "Invalid negative height value passed.")
) {
return;
}
stack.base = _base;
stack.height = _height;
calculate_sphere();
}
this.get_sphere_position = function (i) {
i = parseInt(i);
if (debug.sentinel(!isNaN(i), "Invalid non-numerical index value passed.") ||
debug.sentinel(i >= 0, "Invalid negative index value passed.") ||
debug.sentinel(i < stack.sphere_count, "Index value cannot be greater than the total sphere count.")
) {
return;
}
return {
x: ((i%stack.base)*(sphere.r_m*2)) - (stack.base*sphere.r_m),
y: (Math.floor(i/Math.pow(stack.base, 2))*(sphere.r_m*2))+sphere.r_m,
z: ((Math.floor(i/stack.base)%stack.base)*(sphere.r_m*2)) - (stack.base*sphere.r_m)
}
}
this.get_sphere = function () {
return sphere;
}
this.get_stack = function () {
return stack;
}
construct (_quantity_kg, _density_kg_m3);
}
index.Rate = function (_rate_kg_s, _density_kg_m3) {
var density_kg_m3;
var rate = {
kg_s: null,
m3_s: null,
}
var sphere = {
kg: null,
m3: null,
r_m: null,
per_s: null,
s_per: null,
}
var set = false;
var construct = function (_rate_kg_s, _density_kg_m3) {
_rate_kg_s = parseFloat(_rate_kg_s);
_density_kg_m3 = parseFloat(_density_kg_m3);
if (debug.sentinel(!isNaN(_rate_kg_s), "Invalid non-numerical rate value passed.") ||
debug.sentinel(_rate_kg_s >= 0, "Invalid negative rate value passed.") ||
debug.sentinel(!isNaN(_density_kg_m3), "Invalid non-numerical density value passed.") ||
debug.sentinel(_density_kg_m3 >= 0, "Invalid negative density value passed.")
) {
return;
}
density_kg_m3 = _density_kg_m3
rate.kg_s = _rate_kg_s;
rate.m3_s = rate.kg_s/density_kg_m3;
calculate_sphere ();
}
var calculate_sphere = function () {
//setup starting sphere weight, then increase it in a loop until no more than 30 spheres per second are needed.
var sphere_kg = 0.001;
var spheres_per_s_limit = 20
while (rate.kg_s/sphere_kg > spheres_per_s_limit) {
sphere_kg *= 10;
}
sphere.kg = sphere_kg;
sphere.m3 = sphere.kg/density_kg_m3;
sphere.r_m = Math.cbrt((3*sphere.m3)/(4*Math.PI));
sphere.per_s = rate.kg_s/sphere.kg;
sphere.s_per = 1/sphere.per_s;
}
this.get_sphere = function () {
return sphere;
}
this.get_rate = function () {
return rate;
}
this.get_density_kg_m3 = function () {
return density_kg_m3;
}
construct(_rate_kg_s, _density_kg_m3);
}
<file_sep>/js/modules/select_handler.js
function select_handler (sb) {
var brand_select = document.getElementById("brand-select");
var hotel_select = document.getElementById("hotel-select");
var hotel_options = hotel_select.getElementsByTagName("option");
function INIT () {
sb.addEvent(brand_select, "change", toggle_hotel_visibility)
}
function toggle_hotel_visibility (d) {
var brand = brand_select.options[brand_select.selectedIndex].value;
var brand_hyphenated = brand.replace(' ', '-');
var i;
var l = hotel_options.length;
if (brand == "0") {
for (i=1; i<l; i++) {
utility.addClass(hotel_options[i], "active")
}
return;
};
for (i=1; i<l; i++) {
var hotel = hotel_options[i];
if (utility.containsClass(hotel, brand_hyphenated)) {
utility.addClass(hotel_options[i], "active")
} else {
utility.removeClass(hotel_options[i], "active")
}
}
}
function DESTROY () {
sb.unlisten(this.moduleID)
notify = null;
}
return {
init : INIT,
destroy : DESTROY
};
}<file_sep>/js/modules/ready.js
function ready (sb) {
/*
This module's entire function is to send out a 'ready' notification meaning that all other
modules have been initialised and are ready to receive notifications.
*/
function INIT () {
/*
'ready' notification means that all modules have been loaded and initialised, and are ready to be run.
*/
sb.notify({
type : "ready",
data: null
});
}
function DESTROY () {
sb.unlisten(this.moduleID)
notify = null;
}
return {
init : INIT,
destroy : DESTROY
};
}<file_sep>/home.php
<?php
$settings_location = "settings.json";
$settings = json_decode(file_get_contents($settings_location));
require "php/data_wrapper.php";
$dw = new data_wrapper($settings->data_location);
if (array_key_exists('brand', $_GET) &&
array_key_exists('hotel', $_GET)) {
$rate = $dw->seek_rate_for($_GET['brand'], $_GET['hotel']);
$hotel_name = $_GET['hotel'] ? $_GET['hotel'] : "all hotels";
$brand_name = $_GET['brand'] ? $_GET['brand'] : "all brands";
}
/*$brands = $dw->get_brands();
foreach ($brands as $brand) {
print_r($brand);
echo "</br>";
$hotels = $dw->get_hotels($brand);
print_r($hotels);
echo "</br>";
echo "</br>";
}
exit()*/
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>
Hotel emissions
</title>
<?php
require "php/head_include_handler.php";
?>
</head>
<body>
<div id = "mother">
<div id = "form-container">
<form>
<p>Select a brand</p>
<select id = "brand-select" name="brand">
<option value=0>All brands</option>
<?php
$brands = $dw->get_brands();
foreach ($brands as $brand) {
echo "<option value = '{$brand}'>{$brand}</option>";
}
?>
</select>
<p>Select a hotel</p>
<select id = "hotel-select" name="hotel">
<option class = 'active' value=0>All hotels</option>
<?php
foreach ($brands as $brand) {
$hotels = $dw->get_hotels($brand);
$brand_hyphenated = str_replace(' ', '-', $brand);
foreach ($hotels as $hotel) {
echo "<option class ='{$brand_hyphenated} active' value = '{$hotel}'>{$hotel}</option>";
}
}
?>
</select>
<p><input type="submit" value="Submit"></p>
</form>
</div>
<div id = "vis-container">
<?php
if ($rate) {
if ($hotel_name != "all hotels") {
echo "<h1>Emissions rate of {$hotel_name}</h1>";
} else {
echo "<h1>Emissions rate of {$hotel_name} belonging to {$brand_name}</h1>";
}
echo "<iframe id = 'iframe' src ='http://192.168.3.11/realtime-vis/home.html?gas=carbon dioxide&rate={$rate}'></iframe>";
}
?>
</div>
</body>
</html><file_sep>/php/data_wrapper.php
<?php
class data_wrapper {
private $data = array();
function __construct ($data_location) {
ini_set("auto_detect_line_endings", true);
$this->load_data($data_location);
}
public function get_brands () {
$brands = array();
foreach ($this->data as $data_point) {
if (!in_array($data_point['brand'], $brands)) {
array_push($brands, $data_point['brand']);
}
}
print_r($brands);
return $brands;
}
public function get_hotels ($brand) {
$hotels = array();
foreach ($this->data as $data_point) {
if ($data_point['brand'] == $brand) {
array_push($hotels, $data_point['hotel']);
}
}
return $hotels;
}
public function seek_rate_for ($brand, $hotel) {
$data = $this->seek_data_for($brand, $hotel);
$total = 0;
foreach ($data as $data_point) {
$total += $data_point['kg_co2_s'];
}
return $total;
}
public function seek_data_for ($brand, $hotel) {
$data = $this->filter_data_by_brand($this->data, $brand);
$data = $this->filter_data_by_hotel($data, $hotel);
return $data;
}
private function load_data ($data_location) {
$file = fopen($data_location, "r");
$column_headings = fgetcsv($file);
while(($row = fgetcsv($file)) != FALSE) {
array_push($this->data, array(
$column_headings[0] => $row[0],
$column_headings[1] => $row[1],
$column_headings[2] => $row[2],
));
}
fclose($file);
}
private function filter_data_by_brand ($data, $brand) {
if (!$brand) {return $data;}
foreach ($data as $data_point) {
if ($data_point['brand'] != $brand) {
$key = array_search($data_point, $data);
unset($data[$key]);
}
}
return $data;
}
private function filter_data_by_hotel ($data, $hotel) {
if (!$hotel) {return $data;}
foreach ($data as $data_point) {
if ($data_point['hotel'] != $hotel) {
$key = array_search($data_point, $data);
unset($data[$key]);
}
}
return $data;
}
}
?>
<file_sep>/php/share_buttons_handler.php
<?php
foreach ($visualiser_config['share_buttons'] as $share_button) {
$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$img = "<img src ='{$share_button['icon_path']}' class = 'share-icon' id = '{$share_button['name']}-share-icon'>";
$a = "<a id = '{$share_button['name']}-share-link' class = 'share-link' target = '_blank' href = '{$share_button['share_link']}?{$share_button['text_key']}={$url}'>{$img}</a>";
echo $a;
}
?> | 7f0f6dc69b567e90cd26a8779e0904653988410f | [
"JavaScript",
"PHP"
] | 6 | JavaScript | carbonvisuals/accor-hotels | 9555bc93f2af961d231e168e9fc50a6bd6471e98 | 6febe340827503f33958b6d8f5c9336ce1341102 |
refs/heads/master | <file_sep>package main
import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
"code.cloudfoundry.org/cli/cf/trace"
"code.cloudfoundry.org/cli/plugin/models"
"github.com/cloudfoundry/cli/cf/terminal"
"github.com/cloudfoundry/cli/plugin"
"github.com/simonleung8/flags"
)
/*
* This is the struct implementing the interface defined by the core CLI. It can
* be found at "github.com/cloudfoundry/cli/plugin/plugin.go"
*
*/
type DoctorPlugin struct {
ui terminal.UI
}
/*
* This function must be implemented by any plugin because it is part of the
* plugin interface defined by the core CLI.
*
* Run(....) is the entry point when the core CLI is invoking a command defined
* by a plugin. The first parameter, plugin.CliConnection, is a struct that can
* be used to invoke cli commands. The second paramter, args, is a slice of
* strings. args[0] will be the name of the command, and will be followed by
* any additional arguments a cli user typed in.
*
* Any error handling should be handled with the plugin itself (this means printing
* user facing errors). The CLI will exit 0 if the plugin exits 0 and will exit
* 1 should the plugin exits nonzero.
*/
func (c *DoctorPlugin) Run(cliConnection plugin.CliConnection, args []string) {
fmt.Printf("\n\n")
var allSpacesRun bool
var spaces []string
traceLogger := trace.NewLogger(os.Stdout, true, os.Getenv("CF_TRACE"), "")
c.ui = terminal.NewUI(os.Stdin, os.Stdout, terminal.NewTeePrinter(os.Stdout), traceLogger)
// set flag for all spaces
fc := flags.New()
fc.NewBoolFlag("all-spaces", "as", "bool all-spaces flag")
err := fc.Parse(args[1:]...)
if err != nil {
c.ui.Failed(err.Error())
}
// check if the user asked for a all-spaces run or not
if fc.IsSet("all-spaces") {
allSpacesRun = fc.Bool("all-spaces")
}
c.ui.Say(terminal.WarningColor("doctor: time to triage cloudfoundry"))
fmt.Printf("\n")
c.CFMainChecks(cliConnection)
if allSpacesRun {
spaces = c.getAllSpacesInCurrentOrg(cliConnection)
// get current space so we can restore it for a better ux
cliCurrentSpace, err := cliConnection.GetCurrentSpace()
if err != nil {
c.ui.Failed(err.Error())
}
for _, s := range spaces {
c.ui.Say(terminal.WarningColor("TRIAGE SPACE: " + s))
_, err = cliConnection.CliCommandWithoutTerminalOutput("target", "-s", s)
if err != nil {
c.ui.Failed(err.Error())
}
c.triageSpace(cliConnection)
}
_, err = cliConnection.CliCommandWithoutTerminalOutput("target", "-s", cliCurrentSpace.Name)
if err != nil {
c.ui.Failed(err.Error())
}
} else {
c.triageSpace(cliConnection)
}
}
func (c *DoctorPlugin) triageSpace(cliConnection plugin.CliConnection) {
var triageApps []string
var triageRoutes []string
var triageServices []string
var totalNumberOfApps int
var totalNumberOfRunningApps int
listOfRunningApps := c.AppsStateRunning(cliConnection)
listOfStoppedApps := c.AppsStateStopped(cliConnection)
triageApps = c.CheckUpApps(cliConnection, triageApps, listOfRunningApps, listOfStoppedApps)
triageRoutes = c.CheckUpRoutes(cliConnection, triageRoutes)
triageServices = c.CheckUpServices(cliConnection, triageServices)
if len(triageApps) == 0 && len(triageRoutes) == 0 && len(triageServices) == 0 {
c.ui.Say(terminal.SuccessColor("doctor: Everything looks OK!"))
return
}
// doctor run results
if len(triageApps) > 0 {
c.ui.Say(terminal.WarningColor("Detected triage points for apps: "))
for _, v := range triageApps {
c.ui.Say(terminal.LogStderrColor(strings.Split(v, "___")[0]+" <---> ") + terminal.LogStderrColor(strings.Split(v, "___")[1]))
}
}
c.ui.Say(" ")
if len(triageRoutes) > 0 {
c.ui.Say(terminal.WarningColor("Following routes do not have any app bound to them:"))
for _, y := range triageRoutes {
c.ui.Say(terminal.LogStderrColor(y))
}
}
fmt.Printf("\n")
if len(triageServices) > 0 {
c.ui.Say(terminal.WarningColor("Following services do not have any app bound to them:"))
for _, y := range triageServices {
c.ui.Say(terminal.LogStderrColor(y))
}
}
fmt.Printf("\n")
results, err := cliConnection.GetApps()
if err != nil {
c.ui.Failed(err.Error())
}
for _, app := range results {
if app.State == "started" {
totalNumberOfApps++
totalNumberOfRunningApps++
} else {
totalNumberOfApps++
}
}
c.ui.Say(terminal.WarningColor("Total Number of Apps: " + strconv.Itoa(totalNumberOfApps)))
c.ui.Say(terminal.WarningColor("Total Number of Running Apps: " + strconv.Itoa(totalNumberOfRunningApps)))
fmt.Printf("\n")
}
// CheckUpRoutes performs checkup on currently defined routes in cloudfoundry
func (c *DoctorPlugin) CheckUpRoutes(cliConnection plugin.CliConnection, triageRoutes []string) []string {
const NO_ROUTES = "No routes found"
results, err := cliConnection.CliCommandWithoutTerminalOutput("routes")
if err != nil {
c.ui.Failed(err.Error())
}
for _, line := range results {
if line == NO_ROUTES {
return triageRoutes
}
}
for _, line := range results {
// regex to match cf routes output and see if there are unbound routes
match, _ := regexp.MatchString("^[a-zA-Z]*\\s*\\S*\\s*\\S*\\s*", line)
if match {
parts := strings.Fields(line)
if len(parts) == 3 {
triageRoutes = append(triageRoutes, "Host: "+parts[1]+" <---> Domain: "+parts[2])
}
}
}
return triageRoutes
}
// CheckUpServices performs checkup on currently defined services in cloudfoundry
func (c *DoctorPlugin) CheckUpServices(cliConnection plugin.CliConnection, triageServices []string) []string {
results, err := cliConnection.CliCommandWithoutTerminalOutput("services")
if err != nil {
c.ui.Failed(err.Error())
}
for _, line := range results {
// regex to match cf services output and see if there are unbound services
match, _ := regexp.MatchString("^\\S*\\s*\\S*\\s*\\D*\\s*create succeeded", line)
if match {
parts := strings.Fields(line)
if len(parts) == 5 || len(parts) == 7 {
triageServices = append(triageServices, "Service: "+parts[1]+" <---> Name: "+parts[0])
}
}
}
return triageServices
}
// CheckUpApps performs checkup on applications and adds the result to triage map
func (c *DoctorPlugin) CheckUpApps(cliConnection plugin.CliConnection, triage []string, listOfRunningApps []plugin_models.GetAppsModel, listOfStoppedApps []plugin_models.GetAppsModel) []string {
const alarmCPU float64 = 85.0
for _, i := range listOfRunningApps {
app, err := cliConnection.GetApp(i.Name)
if err != nil {
triage = append(triage, i.Name+" ___ failed to get app: "+err.Error())
}
if len(app.StagingFailedReason) > 0 {
triage = append(triage, i.Name+" ___ StagingFailedReason: "+app.StagingFailedReason)
}
insts := app.Instances
for _, ins := range insts {
if ins.CpuUsage > alarmCPU {
triage = append(triage, i.Name+" ___ CPU usage over %85 percent!")
}
if float64(ins.DiskUsage) > float64(ins.DiskQuota)*0.80 {
triage = append(triage, i.Name+" ___ DiskUsage over %80 percent of DiskQuota")
}
if float64(ins.MemUsage) > float64(ins.MemQuota)*0.80 {
triage = append(triage, i.Name+" ___ MemUsage over %80 percent of MemQuota")
}
if float64(ins.MemUsage) < float64(ins.MemQuota)*0.15 {
triage = append(triage, i.Name+" ___ MemUsage lower than %15 percent of MemQuota, scaledown is an option.")
}
if len(insts) > 1 && float64(ins.MemUsage) < float64(ins.MemQuota)*0.15 && ins.CpuUsage < 10.0 {
triage = append(triage, i.Name+" ___ app has more than one instance running with very low resource consumption. candidate for scaling down.")
}
}
routes := app.Routes
if len(routes) == 0 {
triage = append(triage, i.Name+" ___ You have a running application that does not have a route!")
}
}
for _, y := range listOfStoppedApps {
app, err := cliConnection.GetApp(y.Name)
if err != nil {
c.ui.Failed(err.Error())
}
if len(app.StagingFailedReason) > 0 {
triage = append(triage, y.Name+" ___ StagingFailedReason: "+app.StagingFailedReason)
}
}
return triage
}
// AppsStateRunning will return a list of app whose state is running
func (c *DoctorPlugin) AppsStateRunning(cliConnection plugin.CliConnection) []plugin_models.GetAppsModel {
var res []plugin_models.GetAppsModel
appsListing, err := cliConnection.GetApps()
if err != nil {
c.ui.Failed(err.Error())
}
for _, app := range appsListing {
if app.State == "started" {
res = append(res, app)
}
}
return res
}
// AppsStateStopped will return a list of app whose state is running
func (c *DoctorPlugin) AppsStateStopped(cliConnection plugin.CliConnection) []plugin_models.GetAppsModel {
var res []plugin_models.GetAppsModel
appsListing, err := cliConnection.GetApps()
if err != nil {
c.ui.Failed(err.Error())
}
for _, app := range appsListing {
if app.State == "stopped" {
res = append(res, app)
}
}
return res
}
func (c *DoctorPlugin) getAllSpacesInCurrentOrg(cliConnection plugin.CliConnection) []string {
var spaces []string
cliSpaces, err := cliConnection.GetSpaces()
if err != nil {
c.ui.Failed(err.Error())
}
for _, v := range cliSpaces {
spaces = append(spaces, v.Name)
}
return spaces
}
// CFMainChecks is responsible if the environment is okay for running doctor
func (c *DoctorPlugin) CFMainChecks(cliConnection plugin.CliConnection) {
cliLogged, err := cliConnection.IsLoggedIn()
if err != nil {
c.ui.Failed(err.Error())
}
cliHasOrg, err := cliConnection.HasOrganization()
if err != nil {
c.ui.Failed(err.Error())
}
cliHasSpace, err := cliConnection.HasSpace()
if err != nil {
c.ui.Failed(err.Error())
}
if cliLogged == false {
panic("doctor cannot work without being logged in to CF")
}
if cliHasOrg == false || cliHasSpace == false {
c.ui.Warn("WARN: It seems that your cloudfoundry cli has no target space or org...")
}
}
/*
* This function must be implemented as part of the plugin interface
* defined by the core CLI.
*
* GetMetadata() returns a PluginMetadata struct. The first field, Name,
* determines the name of the plugin which should generally be without spaces.
* If there are spaces in the name a user will need to properly quote the name
* during uninstall otherwise the name will be treated as seperate arguments.
* The second value is a slice of Command structs. Our slice only contains one
* Command Struct, but could contain any number of them. The first field Name
* defines the command `cf basic-plugin-command` once installed into the CLI. The
* second field, HelpText, is used by the core CLI to display help information
* to the user in the core commands `cf help`, `cf`, or `cf -h`.
*/
func (c *DoctorPlugin) GetMetadata() plugin.PluginMetadata {
return plugin.PluginMetadata{
Name: "DoctorPlugin",
Version: plugin.VersionType{
Major: 1,
Minor: 0,
Build: 3,
},
MinCliVersion: plugin.VersionType{
Major: 6,
Minor: 7,
Build: 0,
},
Commands: []plugin.Command{
plugin.Command{
Name: "doctor",
HelpText: "doctor is responsible for scanning and reporting about anomalies present in your cloudfoundry.",
// UsageDetails is optional
// It is used to show help of usage of each command
UsageDetails: plugin.Usage{
Usage: "cf doctor\n",
Options: map[string]string{
"all-spaces": "--all-spaces, doctor runs for the all spaces in the current org",
},
},
},
},
}
}
/*
* Unlike most Go programs, the `Main()` function will not be used to run all of the
* commands provided in your plugin. Main will be used to initialize the plugin
* process, as well as any dependencies you might require for your
* plugin.
*/
func main() {
plugin.Start(new(DoctorPlugin))
}
func (c *DoctorPlugin) showUsage(args []string) {
for _, cmd := range c.GetMetadata().Commands {
if cmd.Name == args[0] {
fmt.Println("Invalid Usage: \n", cmd.UsageDetails.Usage)
}
}
}
<file_sep># CloudFoundry CLI Plugin - Doctor
This plugin is obviously inspired from [brew](http://brew.sh/) doctor :) It will scan your currently `target`ed cloudfoundry space to see if there are anomalies or useful action points that it can report back to you. Current functionality is only focused on apps and routes..
This plugin does *not* change any state or configuration, it merely just scans and gathers information than reports back anomalies.
## Installation
Install pre-built plugin from <https://plugins.cloudfoundry.org>:
```plain
cf install-plugin -r CF-Community "doctor"
```
Alternatively, build and install from source:
```plain
go get github.com/cloudfoundry/cli
go get github.com/emirozer/cf-doctor-plugin
cd $GOPATH/src/github.com/emirozer/cf-doctor-plugin
go build
cf install-plugin cf-doctor-plugin
```
## Usage
To triage the current space:
```plain
cf doctor
```
To triage all available spaces in current org:
```plain
cf doctor --all-spaces
```
## Sample output
![Screenshot](https://raw.github.com/emirozer/cf-doctor-plugin/master/docs/ndoc.png)
<file_sep>#!/bin/bash
if [[ "$(which gox)X" == "X" ]]; then
echo "Please install gox. https://github.com/mitchellh/gox#readme"
exit 1
fi
rm -f doctor_plugin*
gox -os linux -os windows -arch 386 --output="doctor_plugin_{{.OS}}_{{.Arch}}"
gox -os darwin -os linux -os windows -arch amd64 --output="doctor_plugin_{{.OS}}_{{.Arch}}"
rm -rf out
mkdir -p out
mv doctor_plugin* out/
<file_sep>#!/bin/bash
set -e
(cf uninstall-plugin "DoctorPlugin" || true) && go build -o doctor-plugin main.go && cf install-plugin doctor-plugin
| 4cbb9391991c48acd98581bee95a5f5c263a5405 | [
"Markdown",
"Shell",
"Go"
] | 4 | Markdown | emirozer/cf-doctor-plugin | a27e1835119c7ea8f36dcd6b64d3d9794de6befe | 2d62447fad0a49ca9801d27c847740847e81509f |
refs/heads/master | <repo_name>Ritu16Rughwani/School-website-portal<file_sep>/README.md
# School-website-portal
It is a frontend code for school website made with html , css , javascript , jquery , bootstrap.
| 2951345d1fe9b7c0d3bba3fe49df787b74f9cd63 | [
"Markdown"
] | 1 | Markdown | Ritu16Rughwani/School-website-portal | b5bbe5614cd276ed18597968437548adb6cfd2f7 | 3f55b5dd319582f9ae100ca5a430754080356cf3 |
refs/heads/master | <repo_name>dellik2004/autoconfig<file_sep>/src/main/resources/application.yml
logging.level.org.springframework: DEBUG
springbootex:
autoconfig:
configserver:
uri: "http://localhost:8080/"<file_sep>/README.md
# autoconfig
Load configuration while starting server
| ba2d79786b60dae3963d8b6e7d4249d8618d1a95 | [
"Markdown",
"YAML"
] | 2 | Markdown | dellik2004/autoconfig | 497b861dccd70925616f0d2a13b84b70c675c560 | c77c2b5ef230b185abd703c117065a4043c98b7f |
refs/heads/master | <file_sep>package norobo
import (
"encoding/csv"
"fmt"
"os"
"strings"
"time"
"github.com/dgnorton/norobo/hayes"
)
// Call represents the current in-progress call.
type Call struct {
*hayes.Call
FilterResult *FilterResult
}
// CallEntry represents a completed (ended) call log entry.
type CallEntry struct {
Time time.Time `json:"time"`
Name string `json:"name"`
Number string `json:"number"`
Action string `json:"action"`
Filter string `json:"filter"`
Reason string `json:"reason"`
}
// CallLog represents a list of completed (ended) calls.
type CallLog struct {
Calls []*CallEntry `json:"calls"`
}
// LastTime returns the time of the last call in the log.
func (l *CallLog) LastTime() time.Time {
return l.Calls[len(l.Calls)-1].Time
}
// LoadCallLog loads a call log from file.
func LoadCallLog(filename string) (*CallLog, error) {
f, err := os.Open(filename)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
return &CallLog{
Calls: make([]*CallEntry, 0),
}, nil
}
records, err := csv.NewReader(f).ReadAll()
if err != nil {
return nil, err
}
calls := &CallLog{
Calls: make([]*CallEntry, 0, len(records)),
}
for _, r := range records {
if len(r) != 6 {
return nil, fmt.Errorf("expected 6 fields but got %d: %s", len(r), strings.Join(r, ","))
}
t, err := time.Parse(time.RFC3339Nano, r[0])
if err != nil {
return nil, err
}
call := &CallEntry{
Time: t,
Name: r[1],
Number: r[2],
Action: r[3],
Filter: r[4],
Reason: r[5],
}
calls.Calls = append(calls.Calls, call)
}
return calls, nil
}
<file_sep>package norobo
import (
"fmt"
"sync"
)
type Filter interface {
// Check runs a call through the filter. Results are returned through the
// result channel. The caller can stop the filter by closing the cancel
// channel. The filter will signal the done wait group when it has finished.
Check(c *Call, result chan *FilterResult, cancel chan struct{}, done *sync.WaitGroup)
// Action returns the action to be taken when a call matches the filter.
Action() Action
// Description returns a description of the filter.
Description() string
}
type Action string
func (a Action) String() string { return string(a) }
func ParseAction(s string) (Action, error) {
switch s {
case Allow.String():
return Allow, nil
case Block.String():
return Block, nil
default:
return Allow, fmt.Errorf("unrecognized action: %s", s)
}
}
const (
Allow = Action("allow")
Block = Action("block")
)
type FilterResult struct {
Err error
Match bool
Action Action
Filter Filter
Description string
}
func (r *FilterResult) FilterDescription() string {
if r.Filter != nil {
return r.Filter.Description()
}
return ""
}
type Filters []Filter
func (a Filters) Run(call *Call) *FilterResult {
// Check filters with Allow action first.
if result := a.RunAction(Allow, call); result.Match {
return result
}
// Check filters with Block action.
return a.RunAction(Block, call)
}
func (a Filters) RunAction(action Action, call *Call) *FilterResult {
results, cancel, done := a.run(action, call)
for {
select {
case <-done:
return &FilterResult{Match: false, Action: Allow}
case result := <-results:
if result.Match {
close(cancel)
return result
}
}
}
}
func (a Filters) run(action Action, call *Call) (<-chan *FilterResult, chan struct{}, chan struct{}) {
//func (a Filters) run(action Action, call *Call) (<-chan *FilterResult, int, chan struct{}, *sync.WaitGroup) {
results := make(chan *FilterResult)
cancel := make(chan struct{})
done := make(chan struct{})
wg := &sync.WaitGroup{}
for _, filter := range a {
if filter.Action() != action {
continue
}
wg.Add(1)
go filter.Check(call, results, cancel, wg)
}
// When all filters are finished, signal the caller.
go func() { wg.Wait(); close(done) }()
return results, cancel, done
}
<file_sep>package filter
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"sync"
"github.com/dgnorton/norobo"
"github.com/dgnorton/norobo/filters/twilio/addons"
"github.com/dgnorton/norobo/filters/twilio/addons/whitepagespro"
)
type Twilio struct {
sid string
token string
minSpamConfidence float64
}
func NewTwilio(sid, token string) *Twilio {
return &Twilio{
sid: sid,
token: token,
minSpamConfidence: 40.0,
}
}
func (t *Twilio) Check(c *norobo.Call, result chan *norobo.FilterResult, cancel chan struct{}, done *sync.WaitGroup) {
go func() {
defer done.Done()
// Build the HTTP request to Twilio's Lookup service.
url := fmt.Sprintf("https://lookups.twilio.com/v1/PhoneNumbers/%s?AddOns=whitepages_pro_phone_rep", c.Number)
fmt.Println(url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
result <- &norobo.FilterResult{Err: err, Action: norobo.Allow}
return
}
req.SetBasicAuth(t.sid, t.token)
// Make the request.
resp, err := http.DefaultClient.Do(req)
if err != nil {
result <- &norobo.FilterResult{Err: err, Action: norobo.Allow}
return
}
defer resp.Body.Close()
// Decode the JSON response.
twloResp := &Response{}
if err := json.NewDecoder(resp.Body).Decode(twloResp); err != nil {
result <- &norobo.FilterResult{Err: err, Action: norobo.Allow}
return
}
// Get results from Twilio addons.
results := twloResp.AddOnsResults()
if len(results) == 0 {
result <- &norobo.FilterResult{Err: errors.New("no response from Twilio Whitepages Pro Phone Rep"), Action: norobo.Allow}
return
}
// See if any of the addons think this caller is spam.
for _, r := range results {
if r.SpamConfidence() >= t.minSpamConfidence {
result <- &norobo.FilterResult{Match: true, Action: t.Action(), Filter: t, Description: r.SpamDescription()}
return
}
}
// Addons think this caller is legitimate.
result <- &norobo.FilterResult{Action: norobo.Allow}
}()
}
func (f *Twilio) Action() norobo.Action { return norobo.Block }
func (f *Twilio) Description() string { return "Twilio (White Pages Pro Phone Reputation)" }
type Response struct {
CallerName string `json:"caller_name"`
Carrier string `json:"carrier"`
CountryCode string `json:"country_code"`
NationalFormat string `json:"national_format"`
PhoneNumber string `json:"phone_number"`
URL string `json:"url"`
AddOns *AddOnsResponse `json:"add_ons"`
}
type AddOnsResponse struct {
Code string `json:"code"`
Message string `json:"message"`
Status string `json:"status"`
Results Results `json:"results"`
}
type Results struct {
WhitePagesProPhoneRep *whitepagespro.Response `json:"whitepages_pro_phone_rep"`
}
func (r *Response) AddOnsResults() []addon.Result {
results := []addon.Result{}
if r.AddOns == nil {
return results
}
ar := r.AddOns.Results
if ar.WhitePagesProPhoneRep != nil {
results = append(results, ar.WhitePagesProPhoneRep)
}
return results
}
<file_sep>package filter
import (
"bytes"
"encoding/json"
"testing"
)
func TestTwilio(t *testing.T) {
t.Parallel()
twloResp := &Response{}
buf := bytes.NewBuffer(response())
if err := json.NewDecoder(buf).Decode(twloResp); err != nil {
t.Fatal(err)
}
results := twloResp.AddOnsResults()
if len(results) != 1 {
t.Fatalf("exp: 1, got: %d", len(results))
}
if results[0].SpamConfidence() != 1.0 {
t.Fatalf("exp: 1.0, got %f", results[0].SpamConfidence())
}
}
func response() []byte {
return []byte(`{
"caller_name": null,
"country_code": "US",
"phone_number": "+12022831710",
"national_format": "(202) 283-1710",
"carrier": null,
"add_ons": {
"status": "successful",
"message": null,
"code": null,
"results": {
"whitepages_pro_phone_rep": {
"request_sid": "XR1234567890THISISABOGUSSIDAAAAAAA",
"status": "successful",
"message": null,
"code": null,
"result": {
"id": "Phone.abcdefef-a1bc-a45b-fed6-abcd1234ef56.Durable",
"phone_number": "2022831710",
"reputation_level": 1,
"reputation_details": {
"score": 1,
"type": "UncertainType",
"category": null
},
"volume_score": 1,
"report_count": 4,
"error": null,
"warnings": [ ]
}
}
}
},
"url": "https://lookups.twilio.com/v1/PhoneNumbers/+12022831710"
}`)
}
<file_sep>package local
import (
"bytes"
"encoding/csv"
"fmt"
"io"
"os"
"regexp"
"strings"
"sync"
"unicode"
"github.com/dgnorton/norobo"
)
type Rule struct {
Description string
name *regexp.Regexp
number *regexp.Regexp
fn func(*norobo.Call) bool
}
func NewRule(description, name, number string, fn func(*norobo.Call) bool) (r *Rule, err error) {
r = &Rule{}
r.Description = description
if name != "" {
if r.name, err = regexp.Compile(name); err != nil {
return
}
}
if number != "" {
r.number, err = regexp.Compile(number)
}
r.fn = fn
return
}
func (r *Rule) Match(call *norobo.Call) bool {
if r.name != nil && r.name.MatchString(call.Name) ||
r.number != nil && r.number.MatchString(call.Number) {
return true
}
if r.fn != nil {
return r.fn(call)
}
return false
}
type LocalFilter struct {
description string
action norobo.Action
Rules []*Rule
}
func NewLocalFilter(description string, action norobo.Action) *LocalFilter {
return &LocalFilter{
description: description,
action: action,
}
}
func LoadFilterFile(filepath string, action norobo.Action) (*LocalFilter, error) {
f, err := os.Open(filepath)
if err != nil {
return nil, err
}
bl := NewLocalFilter(filepath, action)
r := csv.NewReader(f)
for {
record, err := r.Read()
if err == io.EOF {
break
} else if err != nil {
return nil, err
} else if len(record) != 4 {
return nil, fmt.Errorf("expected 4 fields but found %d", len(record))
}
var fn func(*norobo.Call) bool
if record[3] != "" {
fn, err = lookupRuleFunc(record[3])
if err != nil {
return nil, err
}
}
bl.Add(record[0], record[1], record[2], fn)
}
return bl, nil
}
func (l *LocalFilter) Add(description, name, number string, fn func(*norobo.Call) bool) error {
c, err := NewRule(description, name, number, fn)
if err != nil {
return err
}
l.Rules = append(l.Rules, c)
return nil
}
func (f *LocalFilter) Check(c *norobo.Call, result chan *norobo.FilterResult, cancel chan struct{}, done *sync.WaitGroup) {
go func() {
defer done.Done()
for _, rule := range f.Rules {
if rule.Match(c) {
select {
case <-cancel:
return
case result <- &norobo.FilterResult{Match: true, Action: f.action, Filter: f, Description: rule.Description}:
return
}
}
}
select {
case <-cancel:
return
case result <- &norobo.FilterResult{Match: false, Action: norobo.Allow, Filter: f}:
return
}
}()
}
func (f *LocalFilter) Description() string { return f.description }
func (f *LocalFilter) Action() norobo.Action { return f.action }
// alphas returns a new string containing only the alpha-numeric characters.
func alphas(s string) string {
var b bytes.Buffer
for _, r := range s {
if unicode.IsLetter(r) || unicode.IsNumber(r) {
b.WriteRune(r)
}
}
return b.String()
}
// nameContainsNumber returns true if the caller's name contains their phone number.
// Non alpha-numeric chars are stripped from both strings before testing.
func nameContainsNumber(c *norobo.Call) bool {
name, number := alphas(c.Name), alphas(c.Number)
return strings.Contains(name, number)
}
// numberContainsName returns true if the caller's phone number sontains their name.
// Non alpha-numeric chars are stripped from both strings before testing.
func numberContainsName(c *norobo.Call) bool {
name, number := alphas(c.Name), alphas(c.Number)
return strings.Contains(number, name)
}
// lookupRuleFunc returns a function given the name of the function.
func lookupRuleFunc(name string) (func(*norobo.Call) bool, error) {
switch name {
case "NameContainsNumber":
return nameContainsNumber, nil
case "NumberContainsName":
return numberContainsName, nil
default:
return nil, fmt.Errorf("unrecognized rule function: %s", name)
}
}
<file_sep>package addon
type Result interface {
Name() string
Error() error
SpamConfidence() float64
SpamDescription() string
}
<file_sep>//go:generate statik -src=web
//go:generate go fmt statik/statik.go
package main
import (
"encoding/csv"
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"sync"
"time"
"github.com/dgnorton/norobo"
"github.com/dgnorton/norobo/filters/exec"
"github.com/dgnorton/norobo/filters/local"
"github.com/dgnorton/norobo/filters/twilio"
"github.com/dgnorton/norobo/hayes"
"github.com/rakyll/statik/fs"
_ "github.com/dgnorton/norobo/cmd/norobod/statik"
)
func main() {
var (
connstr string
blockFile string
allowFile string
callLogFile string
twloAccountSID string
twloToken string
execCommand string
execArgs string
httpAddr string
)
flag.StringVar(&connstr, "c", "/dev/ttyACM0,19200,n,8,1", "serial port connect string (port,baud,handshake,data-bits,stop-bits)")
flag.StringVar(&blockFile, "block", "", "path to file containing patterns to block")
flag.StringVar(&allowFile, "allow", "", "path to file containing patterns to allow")
flag.StringVar(&callLogFile, "call-log", "", "path to call log file")
flag.StringVar(&twloAccountSID, "twlo-sid", "", "Twilio account SID")
flag.StringVar(&twloToken, "twlo-token", "", "Twilio token")
flag.StringVar(&execCommand, "exec", "", "Command gets executed for every call")
flag.StringVar(&execArgs, "exec-args", "-n {{.Number}}", "Arguments for exec command; uses text/template; availible vars are (Number, Name, Time)")
flag.StringVar(&httpAddr, "bind", "localhost:7080", "HTTP IP and port")
flag.Parse()
modem, err := hayes.Open(connstr)
check(err)
callHandler := newCallHandler(modem, blockFile, allowFile, twloAccountSID, twloToken, callLogFile, execCommand, execArgs)
modem.SetCallHandler(callHandler)
modem.EnableSoftwareCache(false)
check(modem.Reset())
infos, err := modem.Info()
check(err)
println("Modem info:")
for _, info := range infos {
println(info)
}
fcs, err := modem.FaxClasses()
check(err)
println("Fax classes:")
for _, fc := range fcs {
println(fc)
}
fc, err := modem.FaxClass()
check(err)
fmt.Printf("fax class: %s\n", fc)
check(modem.SetFaxClass(hayes.FaxClass2))
fc, err = modem.FaxClass()
check(err)
fmt.Printf("fax class: %s\n", fc)
cidModes, err := modem.CallerIDModes()
check(err)
println("Caller ID modes:")
for _, m := range cidModes {
println(m)
}
cidMode, err := modem.CallerIDMode()
check(err)
fmt.Printf("caller ID mode: %s\n", cidMode)
check(modem.SetCallerIDMode(hayes.CallerIDOn))
cidMode, err = modem.CallerIDMode()
check(err)
fmt.Printf("caller ID mode: %s\n", cidMode)
// Start call log web server.
s := &http.Server{
Addr: httpAddr,
Handler: newWebHandler(callHandler),
}
check(s.ListenAndServe())
modem.Close()
}
type webHandler struct {
mux *http.ServeMux
callHandler *callHandler
}
func newWebHandler(h *callHandler) *webHandler {
handler := &webHandler{
mux: http.NewServeMux(),
callHandler: h,
}
statikFS, err := fs.New()
if err != nil {
panic(err)
}
handler.mux.Handle("/", http.FileServer(statikFS))
handler.mux.HandleFunc("/calls", handler.serveCalls)
return handler
}
func (h *webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.mux.ServeHTTP(w, r)
}
func (h *webHandler) serveCalls(w http.ResponseWriter, r *http.Request) {
//<-h.callHandler.CallLogChanged(time.Now())
log := h.callHandler.CallLog()
b, err := json.Marshal(log)
if err != nil {
panic(err)
}
w.Header().Add("content-type", "application/json")
w.Write(b)
}
type callHandler struct {
modem *hayes.Modem
filters norobo.Filters
callLogFile string
mu sync.RWMutex
callLog *norobo.CallLog
callLogChanged chan struct{}
}
func newCallHandler(m *hayes.Modem, blockFile, allowFile, twloAccountSID, twloToken, callLogFile, execCommand, execArgs string) *callHandler {
filters := norobo.Filters{}
if blockFile != "" {
block, err := local.LoadFilterFile(blockFile, norobo.Block)
if err != nil {
panic(err)
}
filters = append(filters, block)
}
if allowFile != "" {
allow, err := local.LoadFilterFile(allowFile, norobo.Allow)
if err != nil {
panic(err)
}
filters = append(filters, allow)
}
if twloAccountSID != "" && twloToken != "" {
filters = append(filters, filter.NewTwilio(twloAccountSID, twloToken))
}
// Adds external cammand exec to filter list if command exists in flags
if execCommand != "" {
filters = append(filters, exec.NewFilter(execCommand, execArgs))
}
callLog, err := norobo.LoadCallLog(callLogFile)
if err != nil {
panic(err)
}
h := &callHandler{
modem: m,
filters: filters,
callLogFile: callLogFile,
callLog: callLog,
callLogChanged: make(chan struct{}),
}
return h
}
func (h *callHandler) Handle(c *hayes.Call) {
call := &norobo.Call{Call: c}
call.FilterResult = h.filters.Run(call)
if call.FilterResult.Action == norobo.Block {
call.Block()
}
h.log(call)
}
func (h *callHandler) CallLog() *norobo.CallLog {
h.mu.RLock()
defer h.mu.RUnlock()
return h.callLog
}
func (h *callHandler) CallLogChanged(after time.Time) chan struct{} {
h.mu.RLock()
defer h.mu.RUnlock()
changedCh := make(chan struct{})
ch := h.callLogChanged
go func() {
for {
<-ch
h.mu.RLock()
changed := h.callLog.LastTime().After(after)
if changed {
close(changedCh)
h.mu.RUnlock()
return
}
ch = h.callLogChanged
h.mu.RUnlock()
}
}()
return changedCh
}
func (h *callHandler) log(c *norobo.Call) {
f, err := os.OpenFile(h.callLogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0770)
if err != nil {
println(err)
return
}
defer f.Close()
r := c.FilterResult
w := csv.NewWriter(f)
msg := []string{c.Time.Format(time.RFC3339Nano), c.Name, c.Number, r.Action.String(), r.FilterDescription(), r.Description}
h.mu.Lock()
call := &norobo.CallEntry{
Time: c.Time,
Name: c.Name,
Number: c.Number,
Action: r.Action.String(),
Filter: r.FilterDescription(),
Reason: r.Description,
}
h.callLog.Calls = append(h.callLog.Calls, call)
close(h.callLogChanged)
h.callLogChanged = make(chan struct{})
h.mu.Unlock()
if err := w.Write(msg); err != nil {
println(err)
}
w.Flush()
fmt.Println(call)
}
func check(err error) {
if err != nil {
println(err.Error())
os.Exit(1)
}
}
<file_sep>package hayes
import (
"errors"
"fmt"
"io"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/tarm/serial"
)
type Cmd string
const (
ResetCmd Cmd = "ATZ"
InfoCmd = "ATI%d"
VolumnCmd = "ATL%d"
FaxClassesCmd = "AT+FCLASS=?"
FaxClassCmd = "AT+FCLASS?"
SetFaxClassCmd = "AT+FCLASS=%s"
CallerIDModesCmd = "AT+VCID=?"
CallerIDCmd = "AT+VCID?"
SetCallerIDCmd = "AT+VCID=%s"
AnswerCmd = "ATA"
HangupCmd = "ATH0"
)
func FmtCmd(c Cmd, a ...interface{}) Cmd {
return Cmd(fmt.Sprintf(string(c), a...))
}
type Request struct {
Cmd Cmd
Response chan *Response
}
func NewRequest(c Cmd) *Request {
return &Request{
Cmd: c,
Response: make(chan *Response),
}
}
func NewRequestFmt(c Cmd, a ...interface{}) *Request {
return NewRequest(FmtCmd(c, a...))
}
type Response struct {
Data string
Err error
}
type CallHandler interface {
Handle(c *Call)
}
type Modem struct {
tx chan *Request
stop chan struct{}
stopped sync.WaitGroup
cfg *config
port *serial.Port
portCfg *serial.Config
callerIDMode CallerIDMode
mu sync.RWMutex
cache map[string]interface{}
cacheEnabled bool
callHandler CallHandler
}
func Open(conn string) (*Modem, error) {
cfg, err := parseConfig(conn)
if err != nil {
return nil, err
}
portCfg := &serial.Config{
Name: cfg.port,
Baud: cfg.baud,
ReadTimeout: 50 * time.Millisecond,
}
port, err := serial.OpenPort(portCfg)
if err != nil {
return nil, err
}
m := &Modem{
tx: make(chan *Request),
stop: make(chan struct{}),
cfg: cfg,
portCfg: portCfg,
port: port,
callerIDMode: CallerIDOff,
cache: make(map[string]interface{}),
cacheEnabled: true,
}
m.stopped.Add(1)
go m.run()
return m, nil
}
func (m *Modem) Close() {
m.stop <- struct{}{}
m.stopped.Wait()
}
func (m *Modem) Answer() error {
rx := make(chan *Response)
m.tx <- &Request{Cmd: AnswerCmd, Response: rx}
resp := <-rx
return resp.Err
}
func (m *Modem) Hangup() error {
rx := make(chan *Response)
m.tx <- &Request{Cmd: HangupCmd, Response: rx}
resp := <-rx
return resp.Err
}
func (m *Modem) EnableSoftwareCache(v bool) {
m.cacheEnabled = v
}
func (m *Modem) SetCallHandler(ch CallHandler) {
m.mu.Lock()
defer m.mu.Unlock()
m.callHandler = ch
}
func (m *Modem) handleCall(c *Call) {
m.mu.Lock()
defer m.mu.Unlock()
if m.callHandler != nil {
go m.callHandler.Handle(c)
}
}
func (m *Modem) Reset() error {
rx := make(chan *Response)
m.tx <- &Request{Cmd: ResetCmd, Response: rx}
resp := <-rx
return resp.Err
}
func (m *Modem) Info() ([]string, error) {
if v, ok := m.readCache("info"); ok {
return v.([]string), nil
}
infos := []string{}
for n := 0; n < 10; n++ {
req := NewRequestFmt(InfoCmd, n)
m.tx <- req
resp := <-req.Response
if resp.Err != nil {
return nil, resp.Err
} else if resp.Data == "ERROR" {
break
} else if resp.Data == "OK" {
continue
}
infos = append(infos, resp.Data)
}
m.writeCache("info", infos)
return infos, nil
}
type FaxClass string
const (
FaxClass0 FaxClass = "0"
FaxClass1 = "1"
FaxClass1_0 = "1.0"
FaxClass2 = "2"
FaxClass8 = "8"
)
// ParseFaxClass parses a string and returns a FaxClass.
func ParseFaxClass(s string) (FaxClass, error) {
switch s {
case "0":
return FaxClass0, nil
case "1":
return FaxClass1, nil
case "1.0":
return FaxClass1_0, nil
case "2":
return FaxClass2, nil
case "8":
return FaxClass8, nil
default:
return FaxClass0, fmt.Errorf("unrecognized FaxClass: %s", s)
}
}
// FaxClasses returns the supported fax service classes.
func (m *Modem) FaxClasses() ([]FaxClass, error) {
if v, ok := m.readCache("faxClasses"); ok {
return v.([]FaxClass), nil
}
req := NewRequest(FaxClassesCmd)
m.tx <- req
resp := <-req.Response
if resp.Err != nil {
return nil, resp.Err
}
a := strings.Split(resp.Data, ",")
fcs := make([]FaxClass, 0, len(a))
for _, s := range a {
fc, err := ParseFaxClass(s)
if err != nil {
return nil, err
}
fcs = append(fcs, fc)
}
m.writeCache("faxClasses", fcs)
return fcs, nil
}
// FaxClass returns the current fax class.
func (m *Modem) FaxClass() (FaxClass, error) {
if v, ok := m.readCache("faxClass"); ok {
return v.(FaxClass), nil
}
req := NewRequest(FaxClassCmd)
m.tx <- req
resp := <-req.Response
if resp.Err != nil {
return FaxClass0, resp.Err
}
class, err := ParseFaxClass(resp.Data)
if err != nil {
return FaxClass0, err
}
m.writeCache("faxClass", class)
return class, nil
}
// SetFaxClass sets the current fax class.
func (m *Modem) SetFaxClass(fc FaxClass) error {
if v, ok := m.readCache("faxClass"); ok && v.(FaxClass) == fc {
return nil
}
req := NewRequestFmt(SetFaxClassCmd, fc)
m.tx <- req
resp := <-req.Response
if resp.Err == nil {
m.writeCache("faxClass", fc)
}
return resp.Err
}
type CallerIDMode string
const (
CallerIDOff CallerIDMode = "0"
CallerIDOn = "1"
CallerIDUnformatted = "2"
)
// ParseCallerIDMode parses a string and returns a CallerIDMode.
func ParseCallerIDMode(s string) (CallerIDMode, error) {
switch s {
case "0":
return CallerIDOff, nil
case "1":
return CallerIDOn, nil
case "2":
return CallerIDUnformatted, nil
default:
return CallerIDOff, fmt.Errorf("unrecognized caller ID mode: %s", s)
}
}
// CallerIDModes returns the supported caller ID modes.
func (m *Modem) CallerIDModes() ([]CallerIDMode, error) {
req := NewRequest(CallerIDModesCmd)
m.tx <- req
resp := <-req.Response
if resp.Err != nil {
return nil, resp.Err
}
// Match lower & upper range. Eg, From "(0-2)", capture the "0" and "2".
a := regexp.MustCompile("([0-9]*)-([0-9]*)").FindAllStringSubmatch(resp.Data, -1)
if len(a) != 1 || len(a[0]) != 3 {
return nil, fmt.Errorf("can't parse(1): %s", resp.Data)
}
lower, err := strconv.Atoi(a[0][1])
if err != nil {
return nil, fmt.Errorf("can't parse(2): %s", resp.Data)
}
upper, err := strconv.Atoi(a[0][2])
if err != nil {
return nil, fmt.Errorf("can't parse(3): %s", resp.Data)
}
modes := []CallerIDMode{}
for n := lower; n <= upper; n++ {
m, err := ParseCallerIDMode(fmt.Sprintf("%d", n))
if err != nil {
return nil, err
}
modes = append(modes, m)
}
return modes, nil
}
// CallerIDMode returns the current caller ID mode.
func (m *Modem) CallerIDMode() (CallerIDMode, error) {
req := NewRequest(CallerIDCmd)
m.tx <- req
resp := <-req.Response
if resp.Err != nil {
return CallerIDOff, resp.Err
}
var err error
m.callerIDMode, err = ParseCallerIDMode(resp.Data)
return m.callerIDMode, err
}
// SetCallerIDMode sets the caller ID mode.
func (m *Modem) SetCallerIDMode(mode CallerIDMode) error {
req := NewRequestFmt(SetCallerIDCmd, mode)
m.tx <- req
resp := <-req.Response
if resp.Err != nil {
return resp.Err
}
m.callerIDMode = mode
return nil
}
// SetVolume sets the modem's speaker volume, if it has one.
// n must be 0 - 3
func (m *Modem) SetVolume(n int) error {
req := NewRequestFmt(VolumnCmd, n)
m.tx <- req
resp := <-req.Response
return resp.Err
}
func (m *Modem) Send(req *Request) error {
panic("not implemented")
}
func initModem(p *serial.Port) error {
if _, err := writeRead(p, "AT Z S0=0 E1 V1 Q0"); err != nil {
return err
}
if _, err := writeRead(p, "ATI3"); err != nil {
return err
}
return nil
}
func (m *Modem) run() {
// Clear modem's buffered responses.
for {
r := m.readResponse()
if r == nil || r.Err != nil {
break
}
}
var call *Call
var callSent *Call
for {
select {
case <-m.stop:
m.stopped.Done()
return
case req := <-m.tx:
// Send command to modem.
if err := write(m.port, string(req.Cmd)); err != nil {
req.Response <- &Response{Err: err}
}
// Read the echoed command from modem.
if r := m.readResponse(); r == nil {
req.Response <- &Response{Err: errors.New("no command echo")}
continue
} else if r.Data != string(req.Cmd) {
req.Response <- &Response{Err: fmt.Errorf("expected %s, got %s", string(req.Cmd), r.Data)}
continue
}
// Read the response from modem.
r := m.readResponse()
if r == nil {
req.Response <- &Response{Err: errors.New("no response")}
continue
}
// Send response to requester.
req.Response <- r
default:
}
// Read modem initiated events (RINGS, etc.).
if r := m.readResponse(); r != nil {
if r.Err != nil {
// TODO: handle error
continue
}
println(r.Data)
if r.Data == "RING" {
if call == nil && callSent == nil {
call = m.newCall()
if m.callerIDMode == CallerIDOff {
// Not waiting on caller ID so send the call.
m.handleCall(call)
callSent = call
call = nil
continue
}
}
} else if strings.Contains(r.Data, "NAME = ") {
if call == nil {
call = m.newCall()
}
a := strings.Split(r.Data, "=")
if len(a) == 2 {
call.Name = strings.TrimSpace(a[1])
m.handleCall(call)
callSent = call
call = nil
}
} else if strings.Contains(r.Data, "NMBR = ") {
if call == nil {
call = m.newCall()
}
a := strings.Split(r.Data, "=")
if len(a) == 2 {
call.Number = strings.TrimSpace(a[1])
}
} else if strings.Contains(r.Data, "DATE = ") {
// ignore it for now
} else if strings.Contains(r.Data, "TIME = ") {
// ignore it for now
}
} else if r == nil {
if call != nil && time.Now().Sub(call.Time) > (20*time.Second) {
// Call was answered, caller hung up early, etc.
m.handleCall(call)
call = nil
callSent = nil
} else if callSent != nil && time.Now().Sub(callSent.Time) > (20*time.Second) {
call = nil
callSent = nil
}
continue
}
}
}
func (m *Modem) newCall() *Call {
return &Call{modem: m, Time: time.Now()}
}
type Call struct {
modem *Modem
Time time.Time
Name string
Number string
}
func (c *Call) Block() error {
if err := c.modem.Answer(); err != nil {
return err
} else if err = c.modem.Hangup(); err != nil {
return err
}
return nil
}
func (m *Modem) readResponse() *Response {
buf := make([]byte, 0, 1024)
b := []byte{0}
for {
n, err := m.port.Read(b)
if err != nil && err != io.EOF {
return &Response{Err: err}
} else if n == 0 {
return nil
}
switch b[0] {
case 13: // CR
if s := string(buf); s != "" {
return &Response{Data: string(buf)}
}
buf = buf[:0]
case 10: // LF
default:
buf = append(buf, b[0])
}
}
}
func (m *Modem) readCache(key string) (interface{}, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
if !m.cacheEnabled {
return nil, false
}
v, ok := m.cache[key]
return v, ok
}
func (m *Modem) writeCache(key string, v interface{}) {
m.mu.Lock()
defer m.mu.Unlock()
if !m.cacheEnabled {
return
}
m.cache[key] = v
}
func writeRead(p *serial.Port, s string) (string, error) {
if err := write(p, s); err != nil {
return "", err
}
time.Sleep(1000 * time.Millisecond)
s, err := read(p)
if err != nil {
return "", err
}
return s, nil
}
func write(p *serial.Port, s string) error {
cmd := []byte(fmt.Sprintf("%s\r\n", s))
n, err := p.Write(cmd)
if err != nil {
return err
}
if n != len(s)+2 {
return fmt.Errorf("only wrote %d of %d bytes", n, len(s)+2)
}
return nil
}
func read(p *serial.Port) (string, error) {
buf := make([]byte, 1024)
n, err := p.Read(buf)
if err != nil {
return "", err
}
s := string(buf[:n])
fields := strings.Split(s, "\n")
if len(fields) != 4 {
return "", fmt.Errorf("invalid response: expected 4 fields, got %d\n", len(fields))
}
resp := strings.TrimSpace(fields[2])
return resp, nil
}
type config struct {
port string
baud int
}
func parseConfig(s string) (*config, error) {
a := strings.Split(s, ",")
if len(a) != 5 {
return nil, fmt.Errorf("expected 5 parameters, got %d", len(a))
}
baud, err := strconv.Atoi(a[1])
if err != nil {
return nil, err
}
cfg := &config{
port: a[0],
baud: baud,
}
return cfg, nil
}
<file_sep>#!/bin/bash
set -e
OPTIND=1
while getopts "n:" opt; do
case "$opt" in
n)
number="$OPTARG"
;;
esac
done
shift $((OPTIND-1))
if [ "$number" -eq "1234567890" ]; then
printf "block\n"
else
printf "allow\n"
fi
<file_sep>#!/bin/bash
set -e
socatPID=0
tmpdir="/tmp/norobo"
session="norobo"
# Parse command line arguments.
while :; do
case "$1" in
-k|--kill)
# Kill socat if it's running and exit this script.
socatPID="$(pidof socat)"
if [ "$socatPID" -gt 1 ]; then
kill -s TERM $socatPID
fi
exit 0
;;
*)
break
esac
shift
done
# Make sure socat is installed.
if [ -z "$(which socat)" ]; then
echo "error: socat must be installed for this script to run"
exit 1
fi
# Delete old tmp work dir if it exists.
if [ -d "$tmpdir" ]; then
rm -rf $tmpdir
fi
# Create working dir.
mkdir $tmpdir
# Copy binaries and config files to working dir.
cp $GOPATH/bin/modem $tmpdir
cp $GOPATH/bin/norobod $tmpdir
#cp -r /home/dgnorton/go/src/github.com/dgnorton/norobo/cmd/norobod/web $tmpdir
cp $GOPATH/src/github.com/dgnorton/norobo/filters/local/block.csv $tmpdir
cp $GOPATH/src/github.com/dgnorton/norobo/filters/exec/exec_example.sh $tmpdir
# Change to the tmp working dir.
cd $tmpdir
# Setup tmux session with three panes: 1 for modem sim, 1 for norobod, and 1 for user interaction.
tmux new-session -d -s $session
tmux split-window -h -t $session -p 50
tmux select-pane -t $session:0.0
tmux split-window -v -t $session -p 25
# Create pair of linked TTYs / serial ports.
tmux send-keys -t $session:0.0 "socat -d -d pty,raw,echo=0 pty,raw,echo=0 > $tmpdir/socat.out 2>&1 &" C-m
sleep 1
# Parse TTY names from socat's output.
modemTTY="$(cat $tmpdir/socat.out | head -1 | awk '{print $NF }')"
norobodTTY="$(cat $tmpdir/socat.out | head -2 | tail -1 | awk '{print $NF }')"
# Start the modem simulator and wait for it to initialize.
tmux send-keys -t $session:0.0 "$tmpdir/modem -c \"$modemTTY,19200,n,8,1\"" C-m
sleep 1
# Start norobod so that it uses the modem simulator.
tmux send-keys -t $session:0.2 "$tmpdir/norobod -c \"$norobodTTY,19200,n,8,1\" -block $tmpdir/block.csv -call-log $tmpdir/call.log -exec $tmpdir/exec_example.sh $@" C-m
# Set the active tmux pane to the one for user interaction.
tmux select-pane -t $session:0.1
tmux send-keys -t $session:0.1 "curl -X POST \"localhost:8087/call?name=JohnDoe&number=1234567890\""
# Attach to the newly configured tmux session.
tmux -2 attach-session -t $session
<file_sep>module github.com/dgnorton/norobo
go 1.13
require (
github.com/rakyll/statik v0.1.6
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e // indirect
)
<file_sep># norobo
Norobo is a spam phone call blocker for land lines. It uses a modem (remember those old things?) connected to a PC, RPi, etc. and plugged into any phone jack in your house.
### Motivation
Spam / robo calling is an epidemic and relativly little has been done to stop it. There are some great services available like Nomorobo but unfortunately not all carriers offer the simulring feature it requires. There are also features I want that that type of service may not offer. E.g., temporarily block a number if it calls more than once in a minute, simultaneously check multiple online blacklist services, web interface for the call log, etc.
### How it works
When a call comes in, your phone rings once, `norobod` gets the caller ID from the modem, runs the caller's info through the filters, and hangs up if the filters flag it as spam. You feel immediate pleasure from hearing the single ring, knowing `norobod` just hung up on a sleezy spammer.
### Compatibility
It has been tested on *Linux* using a *Zoom 3095 USB Mini External Modem*. It can be run on an RPi or other small ARM based computers capable of running Linux & Go apps. It should also (in theory) work with any Hayes compatible modem that supports caller ID. It may also work on Windows and OS X.
### Install
Currently, it must be built from source. You'll need the [Go tools](https://golang.org/doc/install), if you don't already have them installed. Then clone this repo and build the code in `cmd/norobod`.
### How call filters work
`norobod` currently supports three filters: local, exec, Twilio.
#### Local
Local filters run locally and do not send incoming call info out to external services to perform filtering. There are two types of local filters: `allow` and `block`. Both are optional. `Allow` filters are special in that they run first and not concurrently with any other filters. If a call matches an allow filter, it is allowed through immediately with no further filtering. `Block` filters run concurrently with the Twilio filter, if configured. If a call matches a `block` filter, `norobod` will answer the call, immediately hangup, and cancel any other concurrent filters that are running.
#### Twilio
The Twilio filter is optional and requires a [Twilio](https://www.twilio.com) account. Creating an account is easy and only takes a few minutes. There is a charge for each lookup but it is minimal ($0.005 per lookup at the time of this writing). Once you've set up an account, go to the [Lookup Add-ons](https://www.twilio.com/console/lookup/add-ons) page, select the *Whitepages Pro Phone Reputation* add-on, and install it (Note: it installs on your Twilio account, not your local PC).
#### Exec
The exec filter allows users to create their own filters(addon) to run when a call comes in. Configuration notes are down below.
### Filter Configuration
#### Local
Local `allow` and `block` filters are configured using a simple CSV format. The fields are (in order): `description`, `name`, `number`, `function`. All fields are strings. The `name` and `number` fields are [regular expressions](https://golang.org/pkg/regexp/syntax/). The `function` field must be either an empty string or one of the built in filter functions:
- `NameContainsNumber` matches any call where the caller's name contains the caller's number. All symbols are stripped from both before the comparison is made.
- `NumberContainsName` is the opposite of the previous rule. It matches any call where the caller's number contains the caller's name. All symbols are stripped from both before the comparison is made.
See `filter/block.csv` for examples.
The same format is used for `allow` and `block` filter files. Create a file for one or both as desired. Use the `-allow` and `-block` command line options to enable them. E.g.,
```
norobod -allow path/to/allow.csv -block path/to/block.csv <other options>
```
#### Exec Commands
Allows users to execute external commands as a filter. Users can create an executable add-on that sends either `block` or `allow` to std.out to block or allow a call.
To use this feature define the command to run with `-exec` and the command args with `-exec-args`. Exec-args uses the Go text/template format. E.g. `"-n {{.Number}}"`
```
./norobod -exec testFilter -exec-args "-n {{.Number}} -name {{.Name}} -t {{.Time}}"
```
#### Twilio
There are no configuration files for the `Twilio` filter. To enable it, run `norobod` with the `-twlo-sid` and `-twlo-token` command line arguments. E.g.,
```
norobod <other options> -twlo-sid <your Twilio SID> -twlo-token <your Twilio token>
```
Your Twilio `Account SID` and `Auth Token` can be found by logging into your Twilio account and looking on the home tab.
### Running
On Linux:
- Plug the modem in to the PC
- `ls /dev` to find the modem's name. It's `/dev/ttyACM0` for me.
- `./norobod -c "/dev/ttyACM0,19200,n,8,1"`
If it exits immediately with `permission denied`, you probably need to add yourself to the `dialout` group. Check who owns the modem and what group it belongs to first:
```
$ ls -l /dev/ttyACM0
crw-rw---- 1 root dialout 166, 0 Dec 30 21:52 /dev/ttyACM0
```
Then confirm our suspicion that your user is not in the modem's group:
```
$ groups dgnorton
dgnorton : dgnorton adm cdrom sudo
```
Then add yourself to the `dialout` group:
```
$ usermod -a -G dialout dgnorton
```
### Running as a daemon
There is an example init script in `etc/norobo` that may work for you if you're running Linux.
- Copy `etc/norobo` from the source to `/etc/init.d/`
- Open the init script in a text editor and make sure the `cmd=` line is starting `norobod` with the command line options you want
- `sudo chmod +x /etc/init.d/norobo`
- `sudo update-rc.d norobo defaults`
- `sudo service norobo start`
- To make sure it's running, `tail /var/log/norobo.log`
### Call log
Use the `-call-log path/to/call_log.csv` command line option to specify a call log file. The file is a comma separated value format. The fields are (in order): `time`, `caller name`, `caller number`, `action taken`, `filter name`, `rule description`. The call log can also be viewed by web browser on port `7080`.
### Desktop notifications
If you happen to be running it on a Ubuntu Desktop machine and would like desktop notifications, this shell script one-liner will work.
```
while inotifywait -e close_write call_log.csv; do notify-send "Call From..." "`tail -n1 call_log.csv | awk -F, '{ print $2 " at " $3 }'`"; done
```
### Dev notes
On Linux / Unix, use `socat` to create a pair of connected virtual serial ports for development and debug. There's a hacky little modem simulator in `cmd/modem`. `norobod` will talk to it and think it's talking to a modem. The modem simulator has a simple HTTP API for simulating inbound calls. The `norobo/etc/norobosim.sh` bash script can be used to automate the process of starting up `socat`, `modem`, and `norobod`. It starts `socat` in the background and uses `tmux` (terminal mux) to display `modem` & `norobod` output in separate panes. It also creates a third pane for the dev to run `curl` commands to post simulated inbound calls to `modem`. You may need to tweak the `norobosim.sh` script to suit your environment / needs.
Manually running `socat`, `modem`, and `norobod`...
Create a pair of connected virtual serial ports:
```
$ socat -d -d pty,raw,echo=0 pty,raw,echo=0
2015/12/30 20:22:20 socat[9498] N PTY is /dev/pts/30
2015/12/30 20:22:20 socat[9498] N PTY is /dev/pts/31
```
It will tell you the ports it created. In the example above it's `/dev/pts/30` and `/dev/pts/31`. Pass one of those to the connect string when starting the modem simulator and the other in the connect string to `norobod`.
Simulate a call
```
curl -X POST http://localhost:8087/call --data "name=John+Doe&number=111-222-3333"
```
<file_sep>package exec
import (
"bytes"
"errors"
"fmt"
"os/exec"
"strings"
"sync"
"text/template"
"time"
"github.com/dgnorton/norobo"
)
type Filter struct {
cmd string
args string
}
func NewFilter(cmd, args string) *Filter {
return &Filter{
cmd: cmd,
args: args,
}
}
func (e *Filter) Check(c *norobo.Call, result chan *norobo.FilterResult, cancel chan struct{}, done *sync.WaitGroup) {
go func() {
defer done.Done()
var cmdArgs bytes.Buffer
tmpl, err := template.New("args").Parse(e.args)
if err != nil {
panic(err)
}
err = tmpl.Execute(&cmdArgs, c)
if err != nil {
panic(err)
}
// Create command
cmd := exec.Command(e.cmd, strings.Split(cmdArgs.String(), " ")...)
stdout, err := cmd.StdoutPipe()
if err != nil {
result <- &norobo.FilterResult{Err: err, Action: norobo.Allow}
return
}
fmt.Printf("running exec filter: %s %s\n", e.cmd, cmdArgs.String())
if err := cmd.Start(); err != nil {
println(err.Error())
result <- &norobo.FilterResult{Err: err, Action: norobo.Allow}
return
}
out := make([]byte, 5)
defer stdout.Close()
if _, err := stdout.Read(out); err != nil {
result <- &norobo.FilterResult{Err: err, Action: norobo.Allow}
return
}
done := make(chan error)
go func() { done <- cmd.Wait() }()
select {
case err := <-done:
if err != nil {
result <- &norobo.FilterResult{Err: err, Action: norobo.Allow}
return
}
fmt.Printf("exec filter returned: %s\n", string(out[:]))
if string(out[:]) == "block" {
result <- &norobo.FilterResult{Match: true, Action: e.Action(), Filter: e, Description: "command returned: block"}
} else {
result <- &norobo.FilterResult{Match: false, Action: norobo.Allow, Filter: e, Description: ""}
}
return
case <-cancel:
println("exec filter canceled")
return
case <-time.After(10 * time.Second):
println("exec filter timed out")
result <- &norobo.FilterResult{Err: errors.New("exec command timed out"), Action: norobo.Allow, Filter: e, Description: "exec command timed out"}
return
}
}()
}
func (e *Filter) Action() norobo.Action { return norobo.Block }
func (e *Filter) Description() string {
return fmt.Sprintf("%s %s", e.cmd, e.args)
}
<file_sep>package whitepagespro
import "fmt"
// Example resoponse JSON for one of the IRS' phone numbers.
// (SID and result id have been changed to bogus values.)
//{
// caller_name: null,
// country_code: "US",
// phone_number: "+12022831710",
// national_format: "(202) 283-1710",
// carrier: null,
// add_ons: {
// status: "successful",
// message: null,
// code: null,
// results: {
// whitepages_pro_phone_rep: {
// request_sid: "XR1234567890THISISABOGUSSIDAAAAAAA",
// status: "successful",
// message: null,
// code: null,
// result: {
// id: "Phone.abcdefef-a1bc-a45b-fed6-abcd1234ef56.Durable",
// phone_number: "2022831710",
// reputation_level: 1,
// reputation_details: {
// score: 1,
// type: "UncertainType",
// category: null
// },
// volume_score: 1,
// report_count: 4,
// error: null,
// warnings: [ ]
// }
// }
// }
// },
// url: "https://lookups.twilio.com/v1/PhoneNumbers/+12022831710"
//}
type Response struct {
RequestSID string `json:"request_sid"`
Status string `json:"status"`
Message string `json:"message"`
Code string `json:"code"`
Result Result `json:"result"`
}
type Result struct {
ID string `json:"id"`
PhoneNumber string `json:"phone_number"`
ReputationLevel int `json:"reputation_level"`
VolumeScore int `json:"volume_score"`
ReportCount int `json:"report_count"`
Error *ResultError `json:"error"`
Warnings []string `json:"warnings"`
ReputationDetails ReputationDetails `json:"reputation_details"`
}
type ReputationDetails struct {
Score int `json:"score"`
Type string `json:"type"`
Category string `json:"category"`
}
type ResultError struct {
Name string `json:"name"`
Message string `json:"message"`
}
func (r *Response) Name() string {
return "White Pages Pro Phone Reputation"
}
func (r *Response) Error() error {
if r.Result.Error == nil {
return nil
}
return fmt.Errorf("%s: %s", r.Result.Error.Name, r.Result.Error.Message)
}
func (r *Response) SpamConfidence() float64 {
return float64(r.Result.ReputationDetails.Score)
}
func (r *Response) SpamDescription() string {
rd := r.Result.ReputationDetails
return fmt.Sprintf("%s: %s", rd.Type, rd.Category)
}
<file_sep>package main
import (
"bufio"
"flag"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"time"
"unicode"
"github.com/tarm/serial"
)
var port *serial.Port
func main() {
var connstr string
flag.StringVar(&connstr, "c", "/dev/ptyp5,19200,n,8,1", "serial port connect string (port,baud,handshake,data-bits,stop-bits)")
flag.Parse()
cfg, err := parseConfig(connstr)
check(err)
portCfg := &serial.Config{
Name: cfg.port,
Baud: cfg.baud,
ReadTimeout: 100 * time.Millisecond,
}
port, err = serial.OpenPort(portCfg)
check(err)
fmt.Printf("modem port: %s\n", connstr)
var (
fclass = "1"
vcid = "0"
)
r := bufio.NewReader(port)
go func() {
for {
discardWhitespace(r)
s, err := r.ReadString('\r')
if err != nil {
continue
}
s = strings.TrimSpace(s)
fmt.Printf("-> %s\n", s)
port.Write([]byte(s))
port.Write([]byte("\r\n"))
if s == "ATI3" {
write(port, "NOROBO MODEM SIMULATOR\r\n")
} else if s == "AT+FCLASS=?" {
write(port, "1,2,1.0,8\r\n")
} else if s == "AT+FCLASS?" {
write(port, fmt.Sprintf("%s\r\n", fclass))
} else if strings.Contains(s, "AT+FCLASS=") {
fclass = s[10:]
write(port, "OK\r\n")
} else if s == "AT+VCID=?" {
write(port, "(0-2)\r\n")
} else if s == "AT+VCID?" {
write(port, fmt.Sprintf("%s\r\n", vcid))
} else if strings.Contains(s, "AT+VCID=") {
vcid = s[8:]
write(port, "OK\r\n")
} else {
write(port, "OK\r\n")
}
}
}()
fmt.Printf("\nCalls can be simulated using curl. E.g.,\ncurl -X POST \"localhost:8087/call?name=JohnDoe&number=1234567890\"\n\n")
http.HandleFunc("/call", serveCall)
http.ListenAndServe(":8087", nil)
}
func serveCall(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "/call only accepts POST", http.StatusBadRequest)
return
}
q := r.URL.Query()
name := q.Get("name")
number := q.Get("number")
fmt.Printf("call from %s at %s\n", name, number)
t := time.Now()
write(port, "RING\r\n")
time.Sleep(500 * time.Millisecond)
write(port, fmt.Sprintf("DATE = %s\r\n", t.Format("0102")))
write(port, fmt.Sprintf("TIME = %s\r\n", t.Format("1504")))
write(port, fmt.Sprintf("NMBR = %s\r\n", number))
write(port, fmt.Sprintf("NAME = %s\r\n", name))
write(port, "RING\r\n")
time.Sleep(500 * time.Millisecond)
write(port, "RING\r\n")
time.Sleep(500 * time.Millisecond)
}
func httpError(err error, w http.ResponseWriter, status int) {
if err != nil {
fmt.Println(err)
}
http.Error(w, "", status)
}
func write(p *serial.Port, s string) {
if _, err := p.Write([]byte(s)); err != nil {
println(err)
return
}
fmt.Printf("<- %s\n", strings.TrimSpace(s))
}
func discardWhitespace(r *bufio.Reader) {
c, _, err := r.ReadRune()
if err != nil || !unicode.IsSpace(c) {
r.UnreadRune()
r.UnreadRune()
}
}
type config struct {
port string
baud int
}
func parseConfig(s string) (*config, error) {
a := strings.Split(s, ",")
if len(a) != 5 {
return nil, fmt.Errorf("expected 5 parameters, got %d", len(a))
}
baud, err := strconv.Atoi(a[1])
if err != nil {
return nil, err
}
cfg := &config{
port: a[0],
baud: baud,
}
return cfg, nil
}
func check(err error) {
if err != nil {
println(err.Error())
os.Exit(1)
}
}
| 0de69369a9d69b6eb0e930dfa66be8b4b9e5999d | [
"Go Module",
"Markdown",
"Shell",
"Go"
] | 15 | Go Module | dgnorton/norobo | 5372b766b09e18e7a6fda6d09a16a04577c8d11b | 6a7ac9f37b5276827543c71bde2b2a95e677a10d |
refs/heads/master | <file_sep>
require 'garfio/git'
require 'garfio/git/rugged'
require 'garfio/git/bash'
module Garfio
class Hook
include Utils
attr_writer :working_dir
attr_writer :working_branch
def initialize
@linters = []
@runners = []
end
def lint(cmd, pattern, desc = nil)
@linters << lambda do |file|
if File.fnmatch(pattern, file)
print_info("running #{desc || cmd} over #{file}")
run("#{cmd} #{file}")
end
false
end
end
def run_if(pattern, &block)
@runners << lambda do |file|
if File.fnmatch(pattern, file)
instance_exec(file, &block)
return true
end
false
end
end
def exec(&block)
return false if working_dir_required
instance_exec(&block) if block_given?
git.changed_files.each do |file|
@linters.each do |lint|
instance_exec(file, &lint)
end
@runners.each do |runner|
next if instance_exec(file, &runner)
end
end
end
def git
@git ||= begin
if load_rugged
Rugged.new
else
Bash.new
end
end
end
def load_rugged
require 'rugged'
rescue LoadError
print "install rugged gem to improve performance\n"
end
private
def working_dir_required
if @working_dir
return true unless git.sync_with(@working_dir, @working_branch)
Dir.chdir(@working_dir)
elsif git.bare?
out = 'This is a repository bare,'
out << 'You have to define a working directory'
print_error(out)
return true
end
false
end
end
end
<file_sep>#!/usr/bin/ruby
require 'garfio'
print "pre-commit\n"
hook = Garfio::Hook.new
hook.exec do
lint('ruby -c', '*.rb')
lint('rubocop --lint --no-color --format o', '*.rb')
end
<file_sep>require 'open3'
require 'pry'
module Garfio
module Utils
def run(cmd, silent = false)
out = ''
Open3.popen3(cmd) do |_, stdout, stderr, wait_thr|
if wait_thr.value.success?
out = stdout.read
print_success(out) unless silent
else
print_error(stderr.read)
end
end
out
end
def print_info(msg)
print "\033[01;34m#{msg}\e[0m\n"
end
def print_success(msg)
print "\e[1m\e[32m#{msg}\e[0m\n"
end
def print_error(msg)
print "\e[1m\e[31m#{msg}\e[0m\n"
end
def print_warn(msg)
print "\e[1m\e[33m#{msg}\e[0m\n"
end
end
end
<file_sep>#!/usr/bin/ruby
require 'garfio'
print "post-commit\n"
hook = Garfio::Hook.new
hook.exec do
run_if('dummy.rb') do
run "ls"
end
end
<file_sep>$:.unshift File.expand_path('../../lib', __FILE__)
require 'garfio'
require 'fileutils'
def cleanup
%w(dummy dummy_copy dummy_bare dummy_working_directory).each do |dir|
FileUtils.rm_r("/tmp/#{dir}") if File.exist? "/tmp/#{dir}"
end
end
cleanup
FileUtils.mkdir_p('/tmp/dummy')
begin
File.open('/tmp/dummy/dummy.rb', 'w') do |f|
f << 'print "garfio rules"'
end
Dir.chdir('/tmp/dummy') do
print "init dummy repository\n"
system('git init > /dev/null')
system('git add . > /dev/null')
print 'make first commit\n'
system("git commit -m 'first commit' > /dev/null")
end
print "Install pre-commit\n"
FileUtils.cp(
File.join(Dir.pwd, 'examples/pre-commit'),
'/tmp/dummy/.git/hooks/pre-commit'
)
FileUtils.cp(
File.join(Dir.pwd, 'examples/post-commit'),
'/tmp/dummy/.git/hooks/post-commit'
)
Dir.chdir('/tmp/dummy') do
print "Install change file\n"
File.open('/tmp/dummy/dummy.rb', 'w+') do |f|
f << 'print :('
end
print "Attempt commit\n"
system("git commit -am 'with pre-commit' > /dev/null")
print "File error\n"
File.open('/tmp/dummy/dummy.rb', 'w+') do |f|
f << 'print ":)"'
end
print "commit successfully\n"
system("git commit -am 'with pre-commit' > /dev/null")
end
FileUtils.mkdir_p('/tmp/dummy_bare')
Dir.chdir('/tmp/dummy_bare') do
system('git init --bare > /dev/null')
end
FileUtils.cp(
File.join(Dir.pwd, 'examples/post-receive'),
'/tmp/dummy_bare/hooks/post-receive'
)
FileUtils.chdir('/tmp/dummy') do
system('git remote add deploy /tmp/dummy_bare > /dev/null')
system('git push deploy master > /dev/null')
File.open('/tmp/dummy/dummy.rb', 'w+') do |f|
f << 'print ":|"'
end
system("git commit -am 'with post-receive' > /dev/null")
system('git push deploy master > /dev/null')
system('git checkout -b copy > /dev/null')
system('git push deploy copy > /dev/null')
end
ensure
cleanup
end
<file_sep>require 'garfio/utils'
module Garfio
class Git
include Utils
def sync_with(dir, branch = nil)
changed_files
return false unless check_branch(branch)
check_directory(dir)
checkout_to(dir)
true
end
def context
@context ||= begin
r = {}
ENV.each do |var, value|
next unless var.start_with? 'GIT_'
r[var.gsub('GIT_', '').downcase] = value
end
r
end
end
def pushed?(branch)
@branches = []
pushed = false
STDIN.each do |line|
(_, _, ref_name) = line.split
ref_name = ref_name.split('/').last
@branches << ref_name
pushed ||= (branch == ref_name)
end
pushed
end
def checkout_to(dir)
run("git --work-tree=#{dir} checkout -f")
end
def bare?
run('git rev-parse --is-bare-repository', true).chomp == 'true'
end
private
def check_directory(dir)
unless File.exist? dir
FileUtils.mkdir_p(dir)
print_warn("sync_with: #{dir} did not exist, we created it for you")
end
return if ENV['GIT_INDEX_FILE'] &&
File.exist?(File.join(dir, ENV['GIT_INDEX_FILE']))
ENV['GIT_INDEX_FILE'] = nil
end
def check_branch(branch)
return true if !branch || pushed?(branch)
if @branches.empty?
print_warn("sync_with: branch checking doesn't work in this hook")
else
print_error("sync_with: the branch #{branch} was not pushed")
return false
end
true
end
end
end
<file_sep>= garfio
Gem to help write git-hooks focused in automate deployment tasks and committing-workflow hooks
== Usage
gem install garfio
==== Automate deployment
Paste the following code to your post-receive hook(.git/hooks/post-receive)
#!/usr/bin/ruby
require 'garfio'
hook = Garfio::Hook.new
# select the path where deployed code will live
# this is mandatory for bare repositories
hook.working_dir = '~/backend'
# select your stable branch
hook.working_branch = 'master'
hook.exec do
run_if('Gemfile') do
run 'bundle install'
end
run_if('bower.json') do
run 'bower install'
end
run_if('app/assets/**/*') do
run 'rake assets:precompile'
end
end
==== Check code
Paste the following code to your pre-commit hook(.git/hooks/pre-commit)
#!/usr/bin/ruby
require 'garfio'
print "post-receive\n"
hook = Garfio::Hook.new
hook.exec do
lint('ruby -c', '*.rb')
lint('jshint', '*.js')
lint('haml --check , '*.haml')
lint('sass --check , '*.scss')
end
== Contributing to garfio
* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
* Fork the project.
* Start a feature/bugfix branch.
* Commit and push until you are happy with your contribution.
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
== Copyright
Copyright (c) 2015 <NAME>. See LICENSE.txt for
further details.
<file_sep>#!/usr/bin/ruby
require 'garfio'
print "post-receive\n"
hook = Garfio::Hook.new
hook.working_dir = '/tmp/dummy_working_directory'
hook.working_branch = 'master'
hook.exec do
run_if('dummy.rb') do
run 'pwd'
run 'cat dummy.rb'
end
end
<file_sep>
require 'garfio/hook'
<file_sep>
module Garfio
class Rugged < Git
def changed_files
@changed_files ||= begin
::Rugged::Repository.new(Dir.pwd).index.map { |f| f[:path] }
end
end
end
end
<file_sep>
module Garfio
class Bash < Git
def changed_files
@changed_files ||= begin
data = run('git diff --cached --name-only --diff-filter=AM HEAD', true)
data.split("\n").map(&:chomp)
end
end
end
end
| bc44cd155c86e83c1c2989db622164c90db7a21a | [
"RDoc",
"Ruby"
] | 11 | RDoc | kuadrosx/garfio | 45224998a05f3351db2c2279acd8481314cd37f7 | 6fa47dcfa2b87dd0f9c8afa46a8fc6843f322395 |
refs/heads/master | <repo_name>chingu-voyage5/Toucans-Team-0<file_sep>/README.md
# Toucans-Team-0
Add-project-description-here | Voyage-5 | chingu.io
| 4e91fbf978ad7c0e22cc71920f127eecc39b3f84 | [
"Markdown"
] | 1 | Markdown | chingu-voyage5/Toucans-Team-0 | a22e9d9766487f61117c408a04290a62b36eaa30 | 0acd2e5aa3e1ecdd63f1e0590025439806273f47 |
refs/heads/master | <repo_name>jmalciv/worldwide<file_sep>/README.md
# worldwide
Demo Global Site
| ee0804deba96d2862e58ad8d3fd196b725a49d8d | [
"Markdown"
] | 1 | Markdown | jmalciv/worldwide | 326291b522a3efaec6232fc4fd9e02713f55fbc6 | 226400b2ff1298165d4e121bb1a2e8537633f029 |
refs/heads/master | <repo_name>oluwatosinolamilekanitiot/portfolio<file_sep>/portfolio/solar.css
.planet:after,.star:after {
content:"";
position:absolute;
width:15px;
height:15px;
border-radius:50%;
transform-origin:center;
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
}
.planet,.star{
position:absolute;
}
#sun {
transform-origin:center center;
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
}
#sun:after {
transform-origin:center center;
background: radial-gradient(circle, #FCFC14, #FF7700);
box-shadow: 0px 0px 40px #FF7700;
margin:auto;
width:70px;
height:70px;
top:0;
bottom:0;
left:0;
right:0;
}
#mercury {
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
animation:planetMove 4s linear infinite;
}
#mercury:after {
top:100px;
left:100px;
background: radial-gradient(circle, #E86E17, #BA5711);
}
.Orbit {
margin:auto;
top:0;
left:0;
right:0;
bottom:0;
position:absolute;
border-left: 4px solid white;
border-top : 4px solid white;
border-right : 2px solid white;
border-bottom : 2px solid white;
border-radius: 50%;
}
#venus {
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
animation:planetMove 8s linear infinite;
}
#venus:after {
top:150px;
left:150px;
background: radial-gradient(circle, #DB9969, #69462E);
}
#earth {
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
animation:planetMove 16s linear infinite;
}
#earth:after {
top:200px;
left:200px;
background: radial-gradient(circle, #5DF505, #114FFA);
}
#mars {
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
animation:planetMove 20s linear infinite;
}
#mars:after {
top:250px;
left:250px;
background: radial-gradient(circle, #FA9911, #69410A);
}
#jupiter {
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
animation:planetMove 29s linear infinite;
}
#jupiter:after {
top:300px;
left:300px;
background: radial-gradient(circle, #917041, #5C421D);
}
#saturn {
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
animation:planetMove 35s linear infinite;
}
#saturn:after {
top:350px;
left:350px;
background: radial-gradient(circle, #E08D19, #EBAC54);
}
#uranus {
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
animation:planetMove 40s linear infinite;
}
#uranus:after {
top:400px;
left:400px;
background: radial-gradient(circle, #0780E3, #062C9C);
}
#neptune {
margin:auto;
top:0;
bottom:0;
left:0;
right:0;
animation:planetMove 49s linear infinite;
}
#neptune:after {
top:450px;
left:450px;
background: radial-gradient(circle, #0541F5, #4105F5);
}
#mercuryOrbit {
width: 140px;
height: 140px;
animation:spinnerRotate 4s linear infinite;
animation:spinnerRotate 4s linear infinite;
}
#venusOrbit {
width: 210px;
height: 210px;
animation:spinnerRotate 8s linear infinite;
animation:spinnerRotate 8s linear infinite;
}
#earthOrbit {
width: 280px;
height: 280px;
animation:spinnerRotate 16s linear infinite;
animation:spinnerRotate 16s linear infinite;
}
#marsOrbit {
width: 350px;
height: 350px;
animation:spinnerRotate 20s linear infinite;
animation:spinnerRotate 20s linear infinite;
}
#jupiterOrbit {
width: 420px;
height: 420px;
animation:spinnerRotate 29s linear infinite;
animation:spinnerRotate 29s linear infinite;
}
#saturnOrbit {
width: 490px;
height: 490px;
animation:spinnerRotate 35s linear infinite;
animation:spinnerRotate 35s linear infinite;
}
#uranusOrbit {
width: 560px;
height: 560px;
animation:spinnerRotate 40s linear infinite;
animation:spinnerRotate 40s linear infinite;
}
#neptuneOrbit {
width: 630px;
height: 630px;
animation:spinnerRotate 49s linear infinite;
animation:spinnerRotate 49s linear infinite;
}
@keyframes planetMove {
from {transform:rotate(0deg);}
to {transform:rotate(360deg);}
}
@keyframes spinnerRotate {
0% {transform : rotate(0deg)}
100% {transform : rotate(360deg)}
}
body {
background:#222;
} | f992adaa2ed1ad819f4deabff191e34418c6bd29 | [
"CSS"
] | 1 | CSS | oluwatosinolamilekanitiot/portfolio | 2eb3a9716b9b867cc2aafb19327aff7039b09c27 | a2dcaae90867b9b022893f88af74a69c0ed0880f |
refs/heads/main | <repo_name>gichey/jqcz<file_sep>/README.md
# 极奇公众号h5网页倒计时
极奇公司成长计划,公众号h5网页。可以设定公司或者工作室成立日期,带微信分享功能,演示地址:关注公众号:极奇 ,在成长计划打开查看
| bd6c2426acf2a2e4ff96c4e7c25acdf5b57b81a6 | [
"Markdown"
] | 1 | Markdown | gichey/jqcz | 35449327521116329f036a4876907a70e1914012 | 40dfdf1d653a8901d405d59334d7e9f05d2b2ee3 |
refs/heads/master | <file_sep># node.js
my programs on node.js
Node.js is an open source server environment,this uses javascript on the server
features of Node.js
1.event driven
2.single threaded
3.Asynchronous
4.No buffering
| bed721df5e8fa65d8cd21fad87e9918a785dce10 | [
"Markdown"
] | 1 | Markdown | Aaditrii/node.js | dab574ace0797e9a595ab6ab987c933bc4480bc0 | 2ec194d0272464e416c5ede274a6da6555f7f70a |
refs/heads/master | <repo_name>kylerosenmeyer/psychic-game<file_sep>/assets/javascript/game.js
// Variables: Computer Choice Array
var computerChoices = ["a", "b", "c", "d", "e", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "x", "y", "z"];
//Variables: Guesses Letter Array
var guessedLetters = [];
// Variables: Game Tallies
var Win = 0;
var Loss = 0;
var Guesses = 9;
// Variables: HTML References
var uGuess = document.getElementById("userGuess");
var wTally = document.getElementById("winsTally");
var lTally = document.getElementById("lossesTally");
var gLeft = document.getElementById("guessesLeft");
var cGuess = document.getElementById("computerGuess");
// Variables: The Computer's Guess
var cpGuess = computerChoices[Math.floor(Math.random() * computerChoices.length)]
// Variables: Convert the Computer's Guess to a keycode
var cpKey = cpGuess.which || cpGuess.keycode;
// Function: Refresh the Computer's choice
function cpRefresh() {
cpGuess = computerChoices[Math.floor(Math.random() * computerChoices.length)];
};
// Function: Empty the User guess array
function guessRefresh() {
guessedLetters= [];
};
// This is the User's Guess
document.onkeyup = function(event) {
var usGuess = event.key;
//Function: Grab the Keycode for the user Guess
var key = event.which || event.keycode;
// First, Check if usGuess is a lowercase letter
if ( (key >= 65 ) && (key <= 90 ) ) {
//Then, check to see if the user guess matches the computer's guess
if ( usGuess === cpGuess ) {
Win++,
Guesses = 9,
cpRefresh(),
guessRefresh();
//Then, see if the user guess is in the guessedLetters array. If not, add it and subract a guess.
} else if ( guessedLetters.indexOf(" " + usGuess + " ") === -1 ) {
guessedLetters.push(" " + usGuess + " "),
Guesses--;
}
};
// When the guesses get down to Zero, add 1 to the Losses, and reset the Guess fields.
if ( Guesses === 0 ) {
Loss++,
Guesses = 9,
cpRefresh(),
guessRefresh();
};
var guessR = guessedLetters.toString();
// This is the display of the results
uGuess.innerText = "Your Guesses So Far: " + guessR;
wTally.textContent = "Wins: " + Win;
lTally.textContent = "Losses: " + Loss;
gLeft.textContent = "Guesses Left: " + Guesses;
// Cheat (Show the Computer's Guess)
cGuess.textContent = "Cheat: " + cpGuess;
// console.log("this is a text log");
// console.log(key);
// console.log(guessR);
};<file_sep>/README.md
# psychic-game
Coding Bootcamp HW3 by <NAME>
**Psychic Game** is a letter guessing game in which
the user attempts to guess the random letter chosen by the computer.
This game is useful to learn the principals of javascript *arrays, functions, statements, and
loops*. It is also useful to begin learning about the power of objects.
This project is not available for additional contribution from the github community, however
<NAME> may be contacted through his website for help or questions
regarding the project.
More information:
See the [Live Project Here.](https://kylerosenmeyer.github.io/psychic-game/)
See [Under the Hood Here.](https://github.com/kylerosenmeyer/psychic-game)
See **<NAME>'s** [website and entire portfolio here.](https://kylerosenmeyer.github.io/hw2-bootstrap-portfolio/)
| 805198fd2c1cacec2e79be8c4cc39b1249dcf36a | [
"Markdown",
"JavaScript"
] | 2 | Markdown | kylerosenmeyer/psychic-game | 173b5e7e7e08dd01dc2662fb54d51ec079fd26d8 | 252954e474d0e9fe473d700b11b3ecd2f6efaaee |
refs/heads/master | <repo_name>mucahitseba/PHP_Spor_Haberleri_Sitesi<file_sep>/proje/footer.php
<tr>
<td height="42" colspan="3" align="center" bgcolor="#3a3a39">
<img src="images/face.png" width="43" height="42" />
<img src="images/twit.png" width="43" height="42" />
<img src="images/insta.png" width="43" height="42" /></td>
<td bgcolor="#3a3a39"><a href="cikis.php"><b><p style="color:red">ÇIKIŞ</p></b></a></td>
</tr><file_sep>/proje/index.php
<?php require_once("include/veritabaniayari.php")?>
<?php include("header.php") ?>
<html>
<head>
</head>
<body>
<?php
$alınan=@$_GET["sayfa"];
if($alınan=="anasayfa")
{
include("anasayfa.php");
}
else if($alınan=="futbol")
{
include("futbol.php");
}
?>
</body>
</html>
<file_sep>/proje/b1.php
<?php include("include/veritabaniayari.php") ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MSpor Basketbol</title>
<link href='http://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,500,700,800' rel='stylesheet' type='text/css'>
<style>
body {
font-family: "Roboto", Helvetica, Arial, sans-serif;
font-size: 18px;
line-height: 1.42857143;
color: #555555;
}
h1{
text-align:center;
margin-top:-20px;
}
</style>
</head>
<body>
<table width="1251" height="1095" align="center" border="3">
<?php include("header.php") ?>
<tr>
<td height="39" colspan="4"><img src="images/bb.JPG" width="1265" height="35" /></td>
</tr>
<tr>
<td height="645" colspan="3">
<?php
$id = null;
if ( isset($_GET['id'])) {
$id = htmlentities($_REQUEST['id'], ENT_QUOTES);
}?>
<?php
$veri=$vt->query("select * from basketbol where id=$id")->fetchAll(PDO::FETCH_ASSOC);
foreach($veri as $row){
echo '</br><h1>';print_r($row["haberbaslik"]);echo '</h1>';
echo '<center><img src="';print_r($row["resimyolu"]);
echo '" alt="" style="width:900px;height:450px;margin-top: 10px;"></center>';
}
?>
</td>
<td align="center"><img src="images/bfoto.JPG" width="316" height="647" /></td>
</tr>
<tr>
<td colspan="3">
<blockquote>
<?php
$veri=$vt->query("select * from basketbol where id=$id")->fetchAll(PDO::FETCH_ASSOC);
foreach($veri as $row){
echo '</br><p>';print_r($row["icerik"]);echo '</p>';
echo '</br><p style="text-align: -webkit-right;">';print_r($row["yazan"]);echo '</p>';
}
?>
</blockquote>
</td>
<td><img src="images/bpuan.JPG" width="315" height="409" /></td>
</tr>
<tr>
<td height="89" colspan="4">
<?php
$veri=$vt->query("select * from yorumlar where haberid=$id and habertipi='basketbol'")->fetchAll(PDO::FETCH_ASSOC);
foreach($veri as $row){
echo "<br/> ";
echo '<b>';print_r($row["kuladi"]); echo'</b>';
echo "<br/>";
print_r($row["yorum"]);
echo "<hr>";
}
?>
<div class="icerik">
<center>
<form action="" method="post" enctype="multipart/form-data">
<table cellpadding="5" cellspacing="5" >
<tr>
<td >
</td>
</tr>
<tr>
<td>Kullanici Adı</td>
<td><input type="text" name="kadi" /></td>
</tr>
<tr>
<td>Yorum</td>
<td><textarea rows="5" cols="40" name="yorum"></textarea> </td>
</tr>
<tr>
<td><input type="submit" value="Gonder" /></td>
</tr>
</table>
</form>
</center>
</div>
</td>
</tr>
<tr>
<?php include("footer.php") ?>
</tr>
</table>
</body>
</html>
<?php
if($_POST){
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$id = null;
if ( isset($_GET['id'])) {
$id = htmlentities($_REQUEST['id'], ENT_QUOTES);
}
$habertipi="basketbol";
$yazan=$_POST["kadi"];
$yorum=$_POST["yorum"];
//veritabanına ekleme
if(!empty($yazan) &&!empty($yorum)&&!empty($id)&&!empty($id)){
$kayit= $vt->prepare("insert into yorumlar set kuladi=?,yorum=?,haberid=?,habertipi=?");
$kayit->execute(array($yazan,$yorum,$id,$habertipi));
header("Location:b1.php?id=$id");
}
}else{
}
?><file_sep>/proje/basketbol.php
<?php include("include/veritabaniayari.php") ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MSpor Basketbol</title>
<style>
p.thick{font-weight: bold;}
a{
color:black;
}
</style>
</head>
<body>
<table width="1251" height="1070" align="center" cellpadding="3" cellspacing="3" border="3">
<?php include("header.php") ?>
<tr>
<td height="43" colspan="4"><img src="images/b.JPG" width="1298" height="35" /></td>
</tr>
<tr>
<?php
$veri=$vt->query("select * from basketbol")->fetchAll(PDO::FETCH_ASSOC);
$sayac=0;
foreach($veri as $row){
echo '<td>';
echo '<a href="b1.php?id='.$row["id"].'"><img src="';print_r($row["resimyolu"]);
echo '" alt="" style="width:312px;height:250px;margin-top: 0px;">';
echo '</br><p class="thick">';print_r($row["haberbaslik"]);echo '</p>';
echo '</td>';
$sayac++;
if($sayac%4==0)
{
echo '</tr><tr>';
}
}
?>
</tr>
<tr>
<td height="50" colspan="4"><img src="images/basketboltakimlari.png" width="1296" height="89" /></td>
</tr>
<?php include("footer.php") ?>
</table>
</body>
</html><file_sep>/proje/include/sayfa_silme.php
<?php include("veritabaniayari.php") ?>
<?php include("admin_nav.php") ?>
<?php
$secim = null;
if ( isset($_GET['secim'])) {
$secim = htmlentities($_REQUEST['secim'], ENT_QUOTES);
$_SESSION["secim"]=$secim;
}?>
<?php
session_start();
if(!isset($_SESSION['kadi'])){
echo "<script>location.href='giris.php'</script>";
}
require 'veri.php';
$id = 0;
if ( isset($_GET['id'])) {
$id = htmlentities($_REQUEST['id'], ENT_QUOTES);
}
if ( !empty($_POST)) {
$id = $_POST['id'];
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql="";
if($_SESSION["secim"]==1){
$sql = "delete from futbol WHERE id = ?";
}else if($_SESSION["secim"]==2){
$sql = "delete from voleybol WHERE id = ?";
}else if($_SESSION["secim"]==3){
$sql = "delete from basketbol WHERE id = ?";
}
$q = $pdo->prepare($sql);
$q->execute(array($id));
Database::disconnect();
header("Location: sayfa_silme.php");
}
?>
<style type="text/css">
</style>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Paneli</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="<KEY>" crossorigin="anonymous">
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
</style>
</head>
<body>
<div class="container">
<form class="form-horizontal" action="sayfa_silme.php?id=<?php echo $id;?>" method="post">
<input type="hidden" name="id" value="<?php echo $id;?>"/>
<?php if(!empty($_GET['id'])==0):
echo '';
else:
echo '<p class="alert alert-error">Silmek istediğinize eminmisiniz?</p>
<div class="form-actions">
<button type="submit">Evet</button>
<a href="sayfa_silme.php">Hayır</a>
</div>';
endif;
?>
</form>
<div class="dropdown">
<button class="dropbtn">Haber Türü</button>
<div class="dropdown-content">
<a href="?secim=1">Futbol</a>
<a href="?secim=2">Voleybol</a>
<a href="?secim=3">Basketbol</a>
</div>
</div>
</br>
<?php
if($secim==1){
$veri=$vt->query("select * from futbol")->fetchAll(PDO::FETCH_ASSOC);
}else if($secim==2){
$veri=$vt->query("select * from voleybol")->fetchAll(PDO::FETCH_ASSOC);
}else if($secim==3){
$veri=$vt->query("select * from basketbol")->fetchAll(PDO::FETCH_ASSOC);
}
if($secim<4 && $secim>0)
foreach($veri as $row){
print_r($row["haberbaslik"]);
echo "<br/> ";
print_r($row["icerik"]);
echo "<br/>";
print_r($row["yazan"]);
echo "<br/>";
echo '<td><img src="../'.$row["resimyolu"].'" width="75" height="75"/></td>';
echo '<td>'.$row["aciklama"].'</td>';
echo "<br/>";
echo '</tr>';
echo '</table>';
echo '<a href="sayfa_silme.php?id='.$row["id"].'">sil</a>';
echo "<hr>";
}
?>
</div>
</body>
</html><file_sep>/proje/tmp.php
<?php
include("include/veritabaniayari.php");
session_start();
include("header.php");
if(isset($_POST["kadi"])){
$kadi=$_POST["kadi"];
$sifre=$_POST["sifre"];
$bul = $vt->prepare("select * from kullanicikayit WHERE kadi =? and sifre=? ");
$bul->execute(array("$kadi" , "$sifre" ));
$bul->fetch();
if($bul->rowCount() > 0){
echo "giriş başarılı!";
$_SESSION["durum"]=1;
$_SESSION["kadi"]=$kadi;
$_SESSION["sifre"]=$sifre;
}
else{
echo "giriş başarısız";
header("Location:kullanicigirisi.php");
}
}else{
header("Location:kullanicigirisi.php");
}
?>
<?php
if(isset($_SESSION["durum"])){
echo 'Hoşgeldin '. $_SESSION["kadi"];
}
?>
<a href="anasayfa.php">anasayfa</a><file_sep>/proje/include/yeni_haber.php
<?php include("admin_nav.php") ?>
<?php
session_start();
if(!isset($_SESSION["kadi"])){
header("Location:giris.php");
}
$kadi = $_SESSION["kadi"];
$yazan=$_SESSION["yazan"];
?>
<?php @include("veritabaniayari.php")?>
<?php
$secim = null;
if ( isset($_GET['secim'])) {
$secim = htmlentities($_REQUEST['secim'], ENT_QUOTES);
}?>
<!doctype html>
<html>
<head>
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
</style>
</head>
<body>
<div>
<?php
if($_POST){
$yazan=$_POST["yazan"];
$baslik=$_POST["baslik"];
$icerik=$_POST["icerik"];
//dosya ekleme
if(isset($_FILES['dosya'])) {
if($_FILES['dosya']['name']){
$resimyolu="images/".$_FILES['dosya']['name'];
copy($_FILES['dosya']['tmp_name'],'../images/'.$_FILES['dosya']['name']);
}
}else {
echo 'Lütfen bir resim gönderin';
}
//veritabanına ekleme
if(!empty($yazan) &&!empty($baslik)&&!empty($icerik)){
if($secim==1){
$kayit= $vt->prepare("insert into futbol set haberbaslik=?,resimyolu=?,icerik=?,yazan=?");
$kayit->execute(array($baslik,$resimyolu,$icerik,$yazan));
header("Location:yeni_haber.php");
}else if($secim==2){
$kayit= $vt->prepare("insert into voleybol set haberbaslik=?,resimyolu=?,icerik=?,yazan=?");
$kayit->execute(array($baslik,$resimyolu,$icerik,$yazan));
header("Location:yeni_haber.php");
}else if($secim==3){
$kayit= $vt->prepare("insert into basketbol set haberbaslik=?,resimyolu=?,icerik=?,yazan=?");
$kayit->execute(array($baslik,$resimyolu,$icerik,$yazan));
header("Location:yeni_haber.php");
}
}
}else{
?>
<div class="icerik">
<center>
<form action="" method="post" enctype="multipart/form-data">
<table cellpadding="5" cellspacing="5" >
<tr>
<td ><div class="dropdown">
<button class="dropbtn">Haber Türü</button>
<div class="dropdown-content">
<a href="?secim=1">Futbol</a>
<a href="?secim=2">Voleybol</a>
<a href="?secim=3">Basketbol</a>
</div>
</div>
</td>
</tr>
<tr>
<td>Ad Soyad</td>
<td><input type="text" name="yazan" value="<?php echo $yazan ?>" /></td>
</tr>
<tr>
<td>Başlık</td>
<td><input type="text" name="baslik" /> </td>
</tr>
<tr>
<td>İçerik</td>
<td><textarea rows="5" cols="40" name="icerik"></textarea> </td>
</tr>
<td><td><input type="file" name="dosya"/></td></td>
<tr>
<td><input type="submit" value="Gonder" /></td>
</tr>
</table>
</form>
</center>
</div>
</div>
<?php }?>
</body>
</html>
<file_sep>/proje/include/giris.php
<?php include("veritabaniayari.php") ?>
<head>
<style>
p.thick{font-weight:bold;}
a{
color:black;
}
input[type=text] {
width: 80%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
border: 3px solid #ccc;
-webkit-transition: 0.5s;
transition: 0.5s;
outline: none;
}
input[type=password] {
width: 80%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
border: 3px solid #ccc;
-webkit-transition: 0.5s;
transition: 0.5s;
outline: none;
}
input[type=text]:focus {
border: 3px solid #555;
}
input[type=password]:focus {
border: 3px solid #555;
}
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 20px;
margin: 4px 2px;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
cursor: pointer;
}
p {font-size: 20px;}
.button1 {
background-color: white;
color: black;
border: 2px solid #4CAF50;
}
.button1:hover{
background-color: #4CAF50;
color:white;
}
</style>
</head>
<body>
<div align="center">
<table width="500" height="100" border="0" align="center">
<form action="admin.php" method="post">
<tr>
<td><label for="kadi"><p>Kullanıcı Adı</p></label></td>
<td><input type="text" name="kadi" ></td>
</tr>
<tr>
<td> <label for="sifre"><p>Şifre</p></label></td>
<td><input type="password" name="<PASSWORD>"></td>
</tr>
<tr>
<td></td>
<td><button type="submit" class="button button1">Giriş</button></td>
</tr>
</form>
</table>
</div>
</body>
<file_sep>/proje/include/admin_nav.php
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
session_start();
if(!isset($_SESSION["kadi"])){
header("Location:giris.php");
}
$kadi = $_SESSION["kadi"];
?>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Paneli</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="<KEY>" crossorigin="anonymous">
<style>
.yonetim_menu li {
float:left;
margin-left: 0px;
padding: 0;
list-style-type: none;
padding: 10px;
background-color: #f1f1f1;
}
.yonetim_menu li a {
display: block;
color: #039;
padding: 8px 16px;
text-decoration: none;
}
.yonetim_menu li a:hover {
background-color: #0CF;
}
</style>
</head>
<body>
<center>
<div class="nav" style="
margin-left: 500px;
">
<div class="yonetim_menu">
<ul>
<li><a href="yeni_haber.php">Yeni Haber Ekle</a> </li>
<li><a href="sayfa_silme.php">Haber silme</a> </li>
<li><a href="adminekle.php" >Admin Ekle </a> </li>
<li><a href="cikis.php">Çıkış </a> </li>
</ul>
</br>
</div>
</div>
</center>
</body>
</html><file_sep>/proje/giris.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Başlıksız Belge</title>
</head>
<body>
<div align="center">
<table width="500" height="400" border="0">
<tr>
<td width="256" bgcolor="#666666"><p><a href="include/giris.php"><img src="yoneticigirisi.png" width="234" height="220" /></a></p>
<p align="center"><em><strong>YÖNETİCİ GİRİŞİ</strong></em></p></td>
<td width="256" bgcolor="#666666"><p><a href="kullanicigirisi.php"><img src="uyegirisi.png" width="219" height="225" /></a></p>
<p align="center"><strong><em>ÜYE GİRİŞİ</em></strong></p></td>
</tr>
</table>
</div>
</body>
</html>
<file_sep>/proje/include/admin.php
<?php include("admin_nav.php") ?>
<div class="container">
<?php
include("veritabaniayari.php");
session_start();
$kadi=$_POST["kadi"];
$sifre=$_POST["sifre"];
$bul = $vt->prepare("select * from admin WHERE kadi =? and sifre=? ");
$bul->execute(array("$kadi" , "$sifre" ));
$bul->fetch();
if($bul->rowCount() > 0){
echo "</br><p>giriş başarılı!</p>";
$_SESSION["durum"]=1;
$_SESSION["kadi"]=$kadi;
$_SESSION["sifre"]=$sifre;
foreach($bul as $row)
{
$_SESSION["yazan"]=$bul["yazan"];
break;
}
}
else{
header("Location:giris.php");
}
?>
<?php
if(isset($_SESSION["durum"])){
echo 'Hoşgeldin '. $_SESSION["kadi"];
}
?>
</div>
<file_sep>/proje/kullanicikayit.php
<?php include("include/veritabaniayari.php") ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Başlıksız Belge</title>
</head>
<body>
<div class="container" style="margin-top: 50px;">
<center>
<form action=" " method="post">
<table cellpadding="5" cellspacing="5" >
<tr>
<td>Ad</td>
<td><input type="text" name="ad" /></td>
</tr>
<tr>
<td>Soyad</td>
<td><input type="text" name="soyad" /></td>
</tr>
<tr>
<td>E-Mail</td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td>Kullanıcı Adı</td>
<td><input type="text" name="kadi" /></td>
</tr>
<tr>
<td>Şifre</td>
<td><input type="text" name="sifre" /> </td>
</tr>
<tr>
<td>Şifre Tekrar</td>
<td><input type="text" name="sifret" /> </td>
</tr>
<td></td>
<td><input type="submit" value="Gonder" /></td>
</tr>
</table>
</form>
</center>
</div>
</body>
</html>
<?php
if($_POST){
$ad=$_POST["ad"];
$soyad=$_POST["soyad"];
$email=$_POST["email"];
$kadi=$_POST["kadi"];
$sifre=$_POST["sifre"];
$sifret=$_POST["sifret"];
if($sifre==$sifret){
$kayit=$vt->prepare("insert into kullanicikayit set ad=?,soyad=?,email=?,kadi=?,sifre=?");
$kayit->execute(array($ad,$soyad,$email,$kadi,$sifre));
if($kayit){
echo "<font color='green' > KAYIT BAŞARILI</font>";
header("refresh:10;url=anasayfa.php");
die('10 sn sonra yönlendirileceksiniz. Beklememek için <a href="anasayfa.php">tıklayın</a>');
;
}else{
echo "<font color='red' > KAYIT BAŞARISIZ</font>"; }
}
}
?><file_sep>/proje/anasayfa.php
<?php
include("include/veritabaniayari.php");
session_start();
if(isset($_POST["kadi"])|| isset($_SESSION['kadi'])){
if(!isset($_SESSION['kadi'])){
$kadi=$_POST["kadi"];
$sifre=$_POST["sifre"];
$bul = $vt->prepare("select * from kullanicikayit WHERE kadi =? and sifre=? ");
$bul->execute(array("$kadi" , "$sifre" ));
$bul->fetch();
if($bul->rowCount() > 0){
$_SESSION["durum"]=1;
$_SESSION["kadi"]=$kadi;
$_SESSION["sifre"]=$sifre;
}
else{
header("Location:kullanicigirisi.php");
}
}
}else{
header("Location:kullanicigirisi.php");
}
?><head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<style>
.mySlides {display:none}
.w3-left, .w3-right, .w3-badge {cursor:pointer}
.w3-badge {height:13px;width:13px;padding:0}
p.thick{font-weight:bold;}
a{
color:black;
}
input[type=text] {
width: 80%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
border: 3px solid #ccc;
-webkit-transition: 0.5s;
transition: 0.5s;
outline: none;
}
input[type=password] {
width: 80%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
border: 3px solid #ccc;
-webkit-transition: 0.5s;
transition: 0.5s;
outline: none;
}
input[type=text]:focus {
border: 3px solid #555;
}
input[type=password]:focus {
border: 3px solid #555;
}
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 20px;
margin: 4px 2px;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
cursor: pointer;
}
p {font-size: 20px;}
.button1 {
background-color: white;
color: black;
border: 2px solid #4CAF50;
}
.button1:hover{
background-color: #4CAF50;
color:white;
}
</style>
</head>
<body>
<table width="1251" height="1285" align="center" cellpadding="3" cellspacing="3" border="3" >
<?php include("header.php") ?>
<tr>
<td height="43" colspan="4" align="center"><img src="images/anaresim.JPG" width="1278" height="35" /></td>
</tr>
<tr>
<td height="379" colspan="4">
<div class="w3-container">
</div>
<div class="w3-content" style="max-width:1200px">
<a href="f1.php?id=1"><img class="mySlides" src="images/s1.jpg" style="width:100%"></a>
<a href="f1.php?id=2"><img class="mySlides" src="images/s2.jpg" style="width:100%"></a>
<a href="f1.php?id=3"><img class="mySlides" src="images/s4.jpg" style="width:100%"></a>
<a href="f1.php?id=4"><img class="mySlides" src="images/s5.jpg" style="width:100%"></a>
<div class="w3-row-padding w3-section">
<div class="w3-col s3">
<img class="demo w3-opacity w3-hover-opacity-off" src="images/s1.jpg" style="width:100%" onclick="currentDiv(1)">
</div>
<div class="w3-col s3">
<img class="demo w3-opacity w3-hover-opacity-off" src="images/s2.jpg" style="width:100%" onclick="currentDiv(2)">
</div>
<div class="w3-col s3">
<img class="demo w3-opacity w3-hover-opacity-off" src="images/s4.jpg" style="width:100%" onclick="currentDiv(3)">
</div>
<div class="w3-col s3">
<img class="demo w3-opacity w3-hover-opacity-off" src="images/s5.jpg" style="width:100%" onclick="currentDiv(4)">
</div>
</div>
</div>
</td>
</tr>
<tr>
<?php
$veri=$vt->query("select * from futbol")->fetchAll(PDO::FETCH_ASSOC);
$sayac=0;
foreach($veri as $row)
{
echo '<td>';
echo '<a href="f1.php?id='.$row["id"].'"><img src="';print_r($row["resimyolu"]);
echo '" alt="" style="width:312px;height:250px;">';
echo '</br><p >';print_r($row["haberbaslik"]);echo '</p></a>';
echo '</td>';
$sayac++;
if($sayac==2)
{
break;
}
}
$veri=$vt->query("select * from basketbol")->fetchAll(PDO::FETCH_ASSOC);
foreach($veri as $row)
{
echo '<td>';
echo '<a href="b1.php?id='.$row["id"].'"><img src="';print_r($row["resimyolu"]);
echo '" alt="" style="width:312px;height:250px;">';
echo '</br><p >';print_r($row["haberbaslik"]);echo '</p></a>';
echo '</td>';
$sayac++;
if($sayac%4==0)
{
echo '</tr><tr>';
}
if($sayac==5)
{
break;
}
}
$veri=$vt->query("select * from voleybol")->fetchAll(PDO::FETCH_ASSOC);
foreach($veri as $row)
{
echo '<td>';
echo '<a href="v1.php?id='.$row["id"].'"><img src="';print_r($row["resimyolu"]);
echo '" alt="" style="width:312px;height:250px;">';
echo '</br><p >';print_r($row["haberbaslik"]);echo '</p></a>';
echo '</td>';
$sayac++;
if($sayac==8)
{
break;
}
}
?>
</tr>
<tr>
<td height="43" colspan="4"><img src="images/anaresim.JPG" width="1278" height="35" /></td>
</tr>
<?php include("footer.php") ?>
</table>
<script>
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function currentDiv(n) {
showDivs(slideIndex = n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("demo");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" w3-opacity-off", "");
}
x[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " w3-opacity-off";
}
</script>
</body><file_sep>/proje/header.php
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
session_start();
if(!isset($_SESSION['kadi'])){
echo "<script>location.href='giris.php'</script>";
}?>
<tr>
<td height="134"><a href="anasayfa.php"><img src="images/logo.jpg" width="312" height="122" /></a></td>
<td><a href="futbol.php"><img src="images/futbolbuton.jpg" width="312" height="122" /></a></td>
<td><a href="basketbol.php"><img src="images/basketbolbuton.jpg" width="312" height="122" /></a></td>
<td><a href="voleybol.php"><img src="images/voleybolbuton.jpg" width="312" height="122" /></a></td>
</tr>
<file_sep>/proje/include/veritabaniayari.php
<?php
try{
$vt=new PDO("mysql:host=127.0.0.1;dbname=spor;charset=utf8","root","");
}catch(PDOException $hata){
echo $hata->getMessage();
}
?><file_sep>/proje/include/adminekle.php
<?php include("veritabaniayari.php") ?>
<?php include("admin_nav.php") ?>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Paneli</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 50px;">
<?php
if($_POST){
$kadi=$_POST["ad"];
$sifre=$_POST["sifre"];
$sifret=$_POST["sifret"];
if($sifre==$sifret){
$kayit= $vt->prepare("insert into admin set kadi=?,sifre=?");
$kayit->execute(array($kadi,$sifre));
if($kayit){
echo "<font color='green' > basarı ile eklendi</font>";
;
}else{
echo "<font color='red' > eklenmedi</font>"; }
}
}
?>
<center>
<form action=" " method="post">
<table cellpadding="5" cellspacing="5" >
<tr>
<td>Kullanıcı Adı</td>
<td><input type="text" name="ad" /></td>
</tr>
<tr>
<td>Şifre</td>
<td><input type="text" name="sifre" /> </td>
</tr>
<tr>
<td>Şifre Tekrar</td>
<td><input type="text" name="sifret" /> </td>
</tr>
<td></td>
<td><input type="submit" value="Gonder" /></td>
</tr>
</table>
</form>
</center>
</div>
</body>
</html> | bf09f0dd825308aede4dbc6d94ce0b4c47347055 | [
"Hack",
"PHP"
] | 16 | Hack | mucahitseba/PHP_Spor_Haberleri_Sitesi | c2b34ca997232608a54905f197a8d2a1f3452833 | f140d7ff1dca746ea7eb105a4b37a55c13ae356a |
refs/heads/master | <repo_name>johannam999/order-form<file_sep>/js/app.js
'use strict';
var allProducts=[];
var chosenProducts =[];
var clientInfo =[];
var pictureNames = ['bag', 'banana', 'bathroom', 'boots', 'breakfast', 'bubblegum', 'chair', 'cthulhu',
'dog-duck', 'dragon', 'pen', 'pet-sweep', 'scissors', 'shark', 'sweep', 'tauntaun', 'unicorn', 'usb', 'water-can', 'wine-glass'];
function Product(name) {
this.name = name;
this.path = 'img/' + name + '.jpg';
this.title = name;
allProducts.push(this);
}
Product.prototype.productSelection = function(){
var selectProd = document.getElementById('box');
var pics = document.createElement('img');
pics.src = this.path;
pics.title = this.title;
selectProd.appendChild(pics);
};
function createProducts(){
for (var i = 0; i < pictureNames.length; i++) {
var product = new Product(pictureNames[i]);
product.productSelection();
}
}
createProducts();
function createList(){
var items = document.getElementById('products');
for (var i = 0; i <pictureNames.length; i++){
var options = document.createElement('option');
options.textContent = pictureNames[i];
items.appendChild(options);
}
}
createList();
var add = document.getElementById('storeData-form');
add.addEventListener('submit', addToCart);
function addToCart(event){
event.preventDefault();
var item = event.target.products.value;
var total = event.target.amount.value;
chosenProducts.push({ item, total});
add.reset();
localStorage.savedProducts = JSON.stringify(chosenProducts);
}
var goCart = document.getElementById('client');
goCart.addEventListener('submit', goToCart);
function goToCart(event){
event.preventDefault();
var name = event.target.name.value;
var street = event.target.street.value;
var city = event.target.city.value;
var zipCode = event.target.zipCode.value;
var phoneNo = event.target.phoneNo.value;
clientInfo.push({name,street,city,zipCode, phoneNo});
event.target.reset();
localStorage.savedProducts = JSON.stringify(clientInfo);
} | 2d812bea20209c9504aeded1aebaea1852f64443 | [
"JavaScript"
] | 1 | JavaScript | johannam999/order-form | f959968c5bd7375e01b4feb45ab27211afb02724 | f863144eadbb5b612df5bb13d7f57207f9f091c0 |
refs/heads/master | <file_sep>package com.ust.magetnotest;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.*;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.IOException;
public class BaseTest {
WebDriver driver;
WebDriverWait wait;
@BeforeClass
public void openBrowser()
{
ChromeOptions opt =new ChromeOptions();
opt.addArguments("--headless");
driver =new ChromeDriver(opt);
wait=new WebDriverWait(driver, 57);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
}
@Test
public void magentoTest() throws IOException {
driver.get("https://magento.com/");
WebElement myAccEle= driver.findElement(By.xpath("//span[text()='Account']/ancestor::a"));
myAccEle.click();
//wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//input[@type='text']")));
//wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//input[@type='text']"))));
driver.findElement(By.xpath("//input[@type='text']")).sendKeys("<EMAIL>");
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("<PASSWORD>");
driver.findElement(By.xpath("//input[@type='<PASSWORD>']")).submit();
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//a[contains(text(),'Out')]")));
System.out.println(driver.getTitle());
Assert.assertEquals(driver.getTitle(),"My Account");
TakesScreenshot screenShot = (TakesScreenshot) driver;
File file= screenShot.getScreenshotAs(OutputType.FILE);
String date = new Date().toString().replace(":", "-");
FileUtils.copyFile(file, new File("./screenshots/Img"+date+".png"));
driver.findElement(By.xpath("//a[contains(text(),'Out')]")).click();
}
@AfterClass
public void closeBrowser()
{
driver.quit();
}
}
<file_sep>package com.ust.magentopages;
public class HomePage {
}
<file_sep>package com.ust.magentopages;
public class LoginPage {
}
| df4c1cd0c4bc8dc4f840fbfffd3586bf437e5eb4 | [
"Java"
] | 3 | Java | balaji-githubstore/magentoustmaven | 023fbeb02de5296251ff01c123b51f47939abc04 | c81eb6d10d21344f3ed877965c0bf1305b885848 |
refs/heads/main | <file_sep><?php
function kg_conversion( int $kg, float $convertL ) {
$berat[0] = $kg;
$berat[1] = $kg * 1000;
$berat[2] = $kg * 1000000;
if( $convertL == 0 )
$berat[3] = -1;
else
$berat[3] = $kg * $convertL;
return $berat;
}
function g_conversion( int $g, float $convertL ) {
$berat[0] = $g / 1000.0;
$berat[1] = $g;
$berat[2] = $g * 1000;
if( $convertL == 0 )
$berat[3] = -1;
else
$berat[3] = $berat[0] * $convertL;
return $berat;
}
function mg_conversion( int $mg, float $convertL ) {
$berat[0] = $mg / 1000000.0;
$berat[1] = $mg / 1000.0;
$berat[2] = $mg;
if( $convertL == 0 )
$berat[3] = -1;
else
$berat[3] = $mg * $convertL;
return $berat;
}
function L_conversion( int $L, float $convertL ) {
$berat[0] = $L * $convertL;
$berat[1] = $berat[0] / 1000.0;
$berat[2] = $berat[1] / 1000.0;
$berat[3] = $L;
return $berat;
}
function get_all_berat( string $berat, float $convertL ) {
switch( $berat ) {
case ( substr( $berat, -2 ) == "kg" ) :
$weight = kg_conversion( (int)$berat, $convertL ); break;
case ( substr( $berat, -2 ) == "mg" ) :
$weight = mg_conversion( (int)$berat, $convertL ); break;
case ( substr( $berat, -1 ) == "g" ) :
$weight = g_conversion( (int)$berat, $convertL ); break;
case ( substr( $berat, -1 ) == "L" ) :
$weight = L_conversion( (int)$berat, $convertL ); break;
}
return $weight;
}
$no = 0;
$satuan = [ "kg", "g", "mg", "L" ];
$barang = [ [ "Jagung", "303g", 24, 0.0 ], [ "Air aqua botol", "1L", 18, 1 ], [ "Jamur Truffle", "40g", 0, 0.0 ],
[ "Bubuk Cabai", "400mg", 40, 0.0 ], [ "Beras", "33L", 3, 1.328 ], [ "Selada", "450g", 27, 0.0 ],
[ "Bubuk merica", "300mg", 35, 0.0 ], [ "Labu", "2kg", 13, 0.0 ], [ "Semangka", "3kg", 7, 0.0 ],
[ "saffron", "3mg", 0, 0.0 ] ];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tugas 3 Praktikum Pemrograman Web</title>
<link rel="stylesheet" href="style.css">
</head>
<nav>
<h1> Konversi Berat Barang Dagangan </br> Warung Sayur Pak Joy </h1>
</nav>
<section>
<table class="initial">
<tr>
<th>Nama barang</th>
<th>Berat satuan</th>
</tr>
<tr>
<?php for( $i = 0; $i < 2; $i++ ) { ?>
<td> <?php echo $barang[0][$i]; ?> </td>
<?php } ?>
</tr>
<tr>
<?php for( $i = 0; $i < 2; $i++ ) { ?>
<td> <?php echo $barang[1][$i]; ?> </td>
<?php } ?>
</tr>
<tr>
<?php for( $i = 0; $i < 2; $i++ ) { ?>
<td> <?php echo $barang[2][$i]; ?> </td>
<?php } ?>
</tr>
<tr>
<?php for( $i = 0; $i < 2; $i++ ) { ?>
<td> <?php echo $barang[3][$i]; ?> </td>
<?php } ?>
</tr>
<tr>
<?php for( $i = 0; $i < 2; $i++ ) { ?>
<td> <?php echo $barang[4][$i]; ?> </td>
<?php } ?>
</tr>
<tr>
<?php for( $i = 0; $i < 2; $i++ ) { ?>
<td> <?php echo $barang[5][$i]; ?> </td>
<?php } ?>
</tr>
<tr>
<?php for( $i = 0; $i < 2; $i++ ) { ?>
<td> <?php echo $barang[6][$i]; ?> </td>
<?php } ?>
</tr>
<tr>
<?php for( $i = 0; $i < 2; $i++ ) { ?>
<td> <?php echo $barang[7][$i]; ?> </td>
<?php } ?>
</tr>
<tr>
<?php for( $i = 0; $i < 2; $i++ ) { ?>
<td> <?php echo $barang[8][$i]; ?> </td>
<?php } ?>
</tr>
<tr>
<?php for( $i = 0; $i < 2; $i++ ) { ?>
<td> <?php echo $barang[9][$i]; ?> </td>
<?php } ?>
</tr>
</table>
<p> *Tabel barang dengan berat satuannya </p>
</section>
<body>
<table class="conversion-table">
<tr>
<th>No</th>
<th>Nama barang</th>
<th>Berat (kg)</th>
<th>Berat (g)</th>
<th>Berat (mg)</th>
<th>Berat (Litre)</th>
<th>Stock</th>
</tr>
<tr>
<td> <?php echo $no + 1; ?> </td>
<?php for( $i = 0; $i < 3; $i++ ) {
switch( $i ) {
case 0 : ?>
<td> <?php echo $barang[$no][$i];?> </td>
<?php break;
case 1 : {
if( $barang[$no][$i + 1] == 0 ) {
$k = 0;
while( $k < 4 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php $k += 1;
}
break;
} else {
$berat = get_all_berat( $barang[$no][$i], $barang[$no][3] );
$j = 0;
while( $j < 4 ) {
if( $berat[$j] == -1 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php } else { ?>
<td> <?php echo (string)( $berat[$j] * $barang[$no][$i + 1] ) . $satuan[$j]; ?> </td>
<?php }
$j++;
}
break;
}
}
case 2 : {
if( $barang[$no][$i] != 0 ) { ?>
<td> <?php echo $barang[$no][$i]; break; ?> </td>
<?php } else { ?>
<td style="background: red; color: white"> <?php echo "kosong"; break; ?> </td>
<?php }
}
}
} $no += 1; ?>
</tr>
<tr>
<td> <?php echo $no + 1; ?> </td>
<?php for( $i = 0; $i < 3; $i++ ) {
switch( $i ) {
case 0 : ?>
<td> <?php echo $barang[$no][$i];?> </td>
<?php break;
case 1 : {
if( $barang[$no][$i + 1] == 0 ) {
$k = 0;
while( $k < 4 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php $k += 1;
}
break;
} else {
$berat = get_all_berat( $barang[$no][$i], $barang[$no][3] );
$j = 0;
while( $j < 4 ) {
if( $berat[$j] == -1 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php } else { ?>
<td> <?php echo (string)( $berat[$j] * $barang[$no][$i + 1] ) . $satuan[$j]; ?> </td>
<?php }
$j++;
}
break;
}
}
case 2 : {
if( $barang[$no][$i] != 0 ) { ?>
<td> <?php echo $barang[$no][$i]; break; ?> </td>
<?php } else { ?>
<td style="background: red; color: white"> <?php echo "kosong"; break; ?> </td>
<?php }
}
}
} $no += 1; ?>
</tr>
<tr>
<td> <?php echo $no + 1; ?> </td>
<?php for( $i = 0; $i < 3; $i++ ) {
switch( $i ) {
case 0 : ?>
<td> <?php echo $barang[$no][$i];?> </td>
<?php break;
case 1 : {
if( $barang[$no][$i + 1] == 0 ) {
$k = 0;
while( $k < 4 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php $k += 1;
}
break;
} else {
$berat = get_all_berat( $barang[$no][$i], $barang[$no][3] );
$j = 0;
while( $j < 4 ) {
if( $berat[$j] == -1 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php } else { ?>
<td> <?php echo (string)( $berat[$j] * $barang[$no][$i + 1] ) . $satuan[$j]; ?> </td>
<?php }
$j++;
}
break;
}
}
case 2 : {
if( $barang[$no][$i] != 0 ) { ?>
<td> <?php echo $barang[$no][$i]; break; ?> </td>
<?php } else { ?>
<td style="background: red; color: white"> <?php echo "kosong"; break; ?> </td>
<?php }
}
}
} $no += 1; ?>
</tr>
<tr>
<td> <?php echo $no + 1; ?> </td>
<?php for( $i = 0; $i < 3; $i++ ) {
switch( $i ) {
case 0 : ?>
<td> <?php echo $barang[$no][$i];?> </td>
<?php break;
case 1 : {
if( $barang[$no][$i + 1] == 0 ) {
$k = 0;
while( $k < 4 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php $k += 1;
}
break;
} else {
$berat = get_all_berat( $barang[$no][$i], $barang[$no][3] );
$j = 0;
while( $j < 4 ) {
if( $berat[$j] == -1 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php } else { ?>
<td> <?php echo (string)( $berat[$j] * $barang[$no][$i + 1] ) . $satuan[$j]; ?> </td>
<?php }
$j++;
}
break;
}
}
case 2 : {
if( $barang[$no][$i] != 0 ) { ?>
<td> <?php echo $barang[$no][$i]; break; ?> </td>
<?php } else { ?>
<td style="background: red; color: white"> <?php echo "kosong"; break; ?> </td>
<?php }
}
}
} $no += 1; ?>
</tr>
<tr>
<td> <?php echo $no + 1; ?> </td>
<?php for( $i = 0; $i < 3; $i++ ) {
switch( $i ) {
case 0 : ?>
<td> <?php echo $barang[$no][$i];?> </td>
<?php break;
case 1 : {
if( $barang[$no][$i + 1] == 0 ) {
$k = 0;
while( $k < 4 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php $k += 1;
}
break;
} else {
$berat = get_all_berat( $barang[$no][$i], $barang[$no][3] );
$j = 0;
while( $j < 4 ) {
if( $berat[$j] == -1 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php } else { ?>
<td> <?php echo (string)( $berat[$j] * $barang[$no][$i + 1] ) . $satuan[$j]; ?> </td>
<?php }
$j++;
}
break;
}
}
case 2 : {
if( $barang[$no][$i] != 0 ) { ?>
<td> <?php echo $barang[$no][$i]; break; ?> </td>
<?php } else { ?>
<td style="background: red; color: white"> <?php echo "kosong"; break; ?> </td>
<?php }
}
}
} $no += 1; ?>
</tr>
<tr>
<td> <?php echo $no + 1; ?> </td>
<?php for( $i = 0; $i < 3; $i++ ) {
switch( $i ) {
case 0 : ?>
<td> <?php echo $barang[$no][$i];?> </td>
<?php break;
case 1 : {
if( $barang[$no][$i + 1] == 0 ) {
$k = 0;
while( $k < 4 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php $k += 1;
}
break;
} else {
$berat = get_all_berat( $barang[$no][$i], $barang[$no][3] );
$j = 0;
while( $j < 4 ) {
if( $berat[$j] == -1 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php } else { ?>
<td> <?php echo (string)( $berat[$j] * $barang[$no][$i + 1] ) . $satuan[$j]; ?> </td>
<?php }
$j++;
}
break;
}
}
case 2 : {
if( $barang[$no][$i] != 0 ) { ?>
<td> <?php echo $barang[$no][$i]; break; ?> </td>
<?php } else { ?>
<td style="background: red; color: white"> <?php echo "kosong"; break; ?> </td>
<?php }
}
}
} $no += 1; ?>
</tr>
<tr>
<td>
<?php echo $no + 1; ?> </td>
<?php for( $i = 0; $i < 3; $i++ ) {
switch( $i ) {
case 0 : ?>
<td> <?php echo $barang[$no][$i];?> </td>
<?php break;
case 1 : {
if( $barang[$no][$i + 1] == 0 ) {
$k = 0;
while( $k < 4 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php $k += 1;
}
break;
} else {
$berat = get_all_berat( $barang[$no][$i], $barang[$no][3] );
$j = 0;
while( $j < 4 ) {
if( $berat[$j] == -1 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php } else { ?>
<td> <?php echo (string)( $berat[$j] * $barang[$no][$i + 1] ) . $satuan[$j]; ?> </td>
<?php }
$j++;
}
break;
}
}
case 2 : {
if( $barang[$no][$i] != 0 ) { ?>
<td> <?php echo $barang[$no][$i]; break; ?> </td>
<?php } else { ?>
<td style="background: red; color: white"> <?php echo "kosong"; break; ?> </td>
<?php }
}
}
} $no += 1; ?>
</tr>
<tr>
<td>
<?php echo $no + 1; ?> </td>
<?php for( $i = 0; $i < 3; $i++ ) {
switch( $i ) {
case 0 : ?>
<td> <?php echo $barang[$no][$i];?> </td>
<?php break;
case 1 : {
if( $barang[$no][$i + 1] == 0 ) {
$k = 0;
while( $k < 4 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php $k += 1;
}
break;
} else {
$berat = get_all_berat( $barang[$no][$i], $barang[$no][3] );
$j = 0;
while( $j < 4 ) {
if( $berat[$j] == -1 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php } else { ?>
<td> <?php echo (string)( $berat[$j] * $barang[$no][$i + 1] ) . $satuan[$j]; ?> </td>
<?php }
$j++;
}
break;
}
}
case 2 : {
if( $barang[$no][$i] != 0 ) { ?>
<td> <?php echo $barang[$no][$i]; break; ?> </td>
<?php } else { ?>
<td style="background: red; color: white"> <?php echo "kosong"; break; ?> </td>
<?php }
}
}
} $no += 1; ?>
</tr>
<tr>
<td>
<?php echo $no + 1; ?> </td>
<?php for( $i = 0; $i < 3; $i++ ) {
switch( $i ) {
case 0 : ?>
<td> <?php echo $barang[$no][$i];?> </td>
<?php break;
case 1 : {
if( $barang[$no][$i + 1] == 0 ) {
$k = 0;
while( $k < 4 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php $k += 1;
}
break;
} else {
$berat = get_all_berat( $barang[$no][$i], $barang[$no][3] );
$j = 0;
while( $j < 4 ) {
if( $berat[$j] == -1 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php } else { ?>
<td> <?php echo (string)( $berat[$j] * $barang[$no][$i + 1] ) . $satuan[$j]; ?> </td>
<?php }
$j++;
}
break;
}
}
case 2 : {
if( $barang[$no][$i] != 0 ) { ?>
<td> <?php echo $barang[$no][$i]; break; ?> </td>
<?php } else { ?>
<td style="background: red; color: white"> <?php echo "kosong"; break; ?> </td>
<?php }
}
}
} $no += 1; ?>
</tr>
<tr>
<td>
<?php echo $no + 1; ?> </td>
<?php for( $i = 0; $i < 3; $i++ ) {
switch( $i ) {
case 0 : ?>
<td> <?php echo $barang[$no][$i];?> </td>
<?php break;
case 1 : {
if( $barang[$no][$i + 1] == 0 ) {
$k = 0;
while( $k < 4 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php $k += 1;
}
break;
} else {
$berat = get_all_berat( $barang[$no][$i], $barang[$no][3] );
$j = 0;
while( $j < 4 ) {
if( $berat[$j] == -1 ) { ?>
<td> <?php echo "---"; ?> </td>
<?php } else { ?>
<td> <?php echo (string)( $berat[$j] * $barang[$no][$i + 1] ) . $satuan[$j]; ?> </td>
<?php }
$j++;
}
break;
}
}
case 2 : {
if( $barang[$no][$i] != 0 ) { ?>
<td> <?php echo $barang[$no][$i]; break; ?> </td>
<?php } else { ?>
<td style="background: red; color: white"> <?php echo "kosong"; break; ?> </td>
<?php }
}
}
} $no += 1; ?>
</tr>
</table>
</body>
</html> | d72c37b8483742675640fcaa719a91a17094c23f | [
"PHP"
] | 1 | PHP | TiC-123/pw-pratikum-3 | 36c29078fc8f696fd283ebfc18e40a7ed16123e8 | aeeeafb6b3015bce7a9edd2a26239bea21c880e9 |
refs/heads/master | <file_sep>
<!DOCTYPE html>
<html>
<head>
<title>Blog - @yield('Titulo')</title>
</head>
<body>
<h1>Abarrotes</h1>
<div class="contenido">
<a href="{{ route('Home')}}" class="btn-btn">Home</a>
<a href="{{ route('lacteos')}}" class="btn-btn">Lacteos</a>
<a href="{{ route('limpieza')}}" class="btn-btn">Limpieza</a>
<a href="{{ route('carnes')}}" class="btn-btn">Carnes Frias</a>
<a href="{{ route('abarrotesgen')}}" class="btn-btn">Abarrotes en General</a>
<a href="{{ route('embotellados')}}" class="btn-btn">Embotellados</a>
</div>
<div >
@yield('seccion')
</div>
@yield('TP')
<footer>pie de pagina</footer>
</body>
</html><file_sep>@extends('layaut')
@section('Titulo','Embotellados')
@section('TP')
<h1>Embotellados</h1>
<p>Bienvenidos a la pagina de abarrores "Mili"</p>
<br>
@foreach ($embotellados as $nom)
<li>{{$nom['nombre']}}</li>
@endforeach
@endsection<file_sep>@extends('layaut')
@section('Titulo','Carnes')
@section('TP')
<h1>Carnes</h1>
<p>Bienvenidos a la pagina de abarrores "Mili"</p>
<br>
@foreach ($carnes as $nom)
<li>{{$nom['nombre']}}</li>
@endforeach
@endsection<file_sep>@extends('layaut')
@section('Titulo','Lacteos')
@section('TP')
<h1>Lacteos</h1>
<p>Bienvenidos a la pagina de abarrores "Mili"</p>
<br>
@foreach ($lacteos as $nom)
<li>{{$nom['nombre']}}</li>
@endforeach
@endsection<file_sep>@extends('layaut')
@section('Titulo','home')
@section('TP')
<h1>Abarrotes " Mili"</h1>
<p>Bienvenidos a la pagina de abarrores "Mili"</p>
@endsection<file_sep>@extends('layaut')
@section('Titulo','Abarrotesgen')
@section('TP')
<h1>Abarrotes en General</h1>
<p>Bienvenidos a la pagina de abarrores "Mili"</p>
<br>
@foreach ($abarrotesgen as $nom)
<li>{{$nom['nombre']}}</li>
@endforeach
@endsection | e3aeaad1a957a787ad2e235994326272934ae530 | [
"Blade"
] | 6 | Blade | Cocom98/tienda | 1586ea1b5e893dc1681cfdaa35af70de65379bc9 | a1d9efb5ced9247eca041db2691098e0df887df0 |
refs/heads/master | <repo_name>richardkeast/friendly-octo-meme<file_sep>/ArduinoLibraryMock/MockPins.cpp
#include "MockPins.h"
extern "C"
{
u8 PinDirections[100];
bool IsPinDirectionSet[100];
u8 PinVoltages[100];
void MockPins_ResetPinStates()
{
for (size_t i = 0; i < 100; i++)
{
PinDirections[i] = 0;
IsPinDirectionSet[i] = false;
PinVoltages[i] = 0;
}
}
void MockPins_SetPinDirection(u8 pin, u8 direction)
{
PinDirections[pin] = direction;
IsPinDirectionSet[pin] = true;
}
bool MockPins_IsPinDirectionSet(u8 pin)
{
return IsPinDirectionSet[pin];
}
u8 MockPins_GetPinDirection(u8 pin)
{
return PinDirections[pin];
}
bool MockPins_IsPinHigh(u8 pin)
{
return PinVoltages[pin] == HIGH;
}
void MockPins_SetPinVoltage(u8 pin, u8 voltage)
{
PinVoltages[pin] = voltage;
}
bool MockPins_IsPinLow(u8 pin)
{
return PinVoltages[pin] == LOW;
}
}
<file_sep>/ArduinoLibraryMock/MockPins.h
#pragma once
#include "stdint_ex.h"
extern "C"
{
#define HIGH 0x1
#define LOW 0x0
#define OUTPUT 0x1
void MockPins_ResetPinStates();
void MockPins_SetPinDirection(u8 pin, u8 direction);
bool MockPins_IsPinDirectionSet(u8 pin);
u8 MockPins_GetPinDirection(u8 pin);
bool MockPins_IsPinHigh(u8 pin);
void MockPins_SetPinVoltage(u8 pin, u8 voltage);
bool MockPins_IsPinLow(u8 pin);
}<file_sep>/Blinky/LED.h
#pragma once
#include "Arduino.h"
class LED
{
private:
u8 m_ledPin;
public:
LED();
LED(u8 pin);
void TurnOn();
void TurnOff();
};<file_sep>/Blinky/LED.cpp
#include "LED.h"
LED::LED()
{
}
LED::LED(u8 pin)
{
m_ledPin = pin;
pinMode(m_ledPin, OUTPUT);
}
void LED::TurnOn()
{
digitalWrite(m_ledPin, HIGH);
}
void LED::TurnOff()
{
digitalWrite(m_ledPin, LOW);
}
<file_sep>/Blinky/Blinky.ino
#include "LED.h"
LED m_led;
void setup()
{
m_led = LED(13);
}
void loop()
{
m_led.TurnOn(); // turn the LED on (HIGH is the voltage level)
delay(5000); // wait for a second
m_led.TurnOff(); // turn the LED off by making the voltage LOW
delay(5000); // wait for a second
}
<file_sep>/ArduinoLibraryMock/Arduino.h
#pragma once
#include "stdint_ex.h"
#include "MockPins.h"
extern "C"
{
void pinMode(u8 pin, u8 direction);
void digitalWrite(u8 pin, u8 voltage);
}<file_sep>/ArduinoLibraryMock/Arduino.cpp
#include "Arduino.h"
extern "C"
{
void pinMode(u8 pin, u8 direction)
{
MockPins_SetPinDirection(pin, direction);
}
void digitalWrite(u8 pin, u8 voltage)
{
MockPins_SetPinVoltage(pin, voltage);
}
} | 470c3316d36e2127ab732af0e4cc43e8d3b42d3a | [
"C",
"C++"
] | 7 | C | richardkeast/friendly-octo-meme | 4666f33a75de1e261e389d6a75a2342841908b14 | 71abd8a38a659bfe80d69989f78f855d2d4d15d1 |
refs/heads/master | <file_sep>[INPUT]
[PANEL]
BACK_STYLE=116
SIZE=480,372
NO_BLUR=1
KEY_NUM=6
TIP_NUM=3
[MORE]
GRID=4,4
[LIST]
BACK_STYLE=121
CELL_STYLE=120
FORE_STYLE=130
CELL_SIZE=71,58
POS=5,6
LIST_NUM=5
LIST_ORDER=0
NAMES=, 。 ? ! ~
VALUES=, 。 ? ! ~
PADDING=2,2,2,0
[KEY1]
BACK_STYLE=286
VIEW_RECT=5,304,470,63
TOUCH_RECT=0,0,0,0
[KEY2]
VIEW_RECT=81,6,394,292
CENTER=F55
[KEY3]
BACK_STYLE=134
FORE_STYLE=152
VIEW_RECT=354,304,120,63
CENTER=F4
[KEY4]
BACK_STYLE=134
FORE_STYLE=279
VIEW_RECT=125,304,114,63
CENTER=F22
STAT_STYLE=S7_2
[KEY5]
BACK_STYLE=134
FORE_STYLE=278
VIEW_RECT=240,304,114,63
CENTER=F23
STAT_STYLE=S8_3
[KEY6]
BACK_STYLE=134
FORE_STYLE=393
VIEW_RECT=5,304,120,63
CENTER=F26
STAT_STYLE=S5_1
[TIP1]
BACK_STYLE=134
FORE_STYLE=136
CENTER=F26
[TIP2]
FORE_STYLE=277
[TIP3]
FORE_STYLE=276
<file_sep>[INPUT]
[CAND]
VIEW_RECT=0,0,800,55
LAYOUT_NAME=cand0
TYPE=4
[PANEL]
BACK_STYLE=116
SIZE=800,185
NO_BLUR=1
KEY_NUM=6
[MORE]
GRID=5,4
SYM_LAYOUT=symbol_hw
LAYOUT_NAME=sel_hw
[HINT]
[LIST]
BACK_STYLE=117
CELL_STYLE=132
FORE_STYLE=129
CELL_SIZE=80,55
POS=6,4
TYPE=2
LIST_NUM=10
[KEY1]
BACK_STYLE=144
VIEW_RECT=6,4,621,175
CENTER=F53
[KEY2]
BACK_STYLE=119
FORE_STYLE=415
VIEW_RECT=632,4,162,55
LEFT=F40
CENTER=F36
[KEY3]
BACK_STYLE=118
FORE_STYLE=507
VIEW_RECT=632,64,80,55
UP=!
CENTER=,
[KEY4]
BACK_STYLE=119
FORE_STYLE=502
VIEW_RECT=715,64,79,55
CENTER=F38
[KEY5]
BACK_STYLE=118
FORE_STYLE=508
VIEW_RECT=632,124,80,55
UP=?
CENTER=。
[KEY6]
BACK_STYLE=119
FORE_STYLE=416
VIEW_RECT=715,124,79,55
CENTER=F39
<file_sep>[INPUT]
[PANEL]
BACK_STYLE=116
SIZE=800,333
NO_BLUR=1
KEY_NUM=7
TIP_NUM=3
[MORE]
GRID=5,4
[LIST]
CELL_SIZE=117,52
POS=6,5
LIST_NUM=5
LIST_ORDER=0
NAMES=, 。 ? ! ~
VALUES=, 。 ? ! ~
PADDING=2,0,2,0
[KEY1]
BACK_STYLE=286
VIEW_RECT=6,271,788,55
TOUCH_RECT=0,0,0,0
[KEY2]
VIEW_RECT=128,4,667,263
CENTER=F55
[KEY3]
BACK_STYLE=134
FORE_STYLE=415
VIEW_RECT=461,271,165,55
CENTER=F36
[KEY4]
BACK_STYLE=134
FORE_STYLE=279
VIEW_RECT=127,271,165,55
CENTER=F22
STAT_STYLE=S7_2
[KEY5]
BACK_STYLE=134
FORE_STYLE=278
VIEW_RECT=293,271,165,55
CENTER=F23
STAT_STYLE=S8_3
[KEY6]
BACK_STYLE=134
FORE_STYLE=280
VIEW_RECT=2,271,124,55
CENTER=F27
STAT_STYLE=S6_1
[KEY7]
BACK_STYLE=134
FORE_STYLE=152
VIEW_RECT=630,271,165,55
CENTER=F4
[TIP1]
BACK_STYLE=134
FORE_STYLE=275
CENTER=F27
[TIP2]
FORE_STYLE=277
[TIP3]
FORE_STYLE=276
<file_sep>[INPUT]
[CAND]
[PANEL]
NO_BLUR=1
KEY_NUM=33
[MORE]
[HINT]
[KEY1]
BACK_STYLE=118
FORE_STYLE=243
VIEW_RECT=6,4,77,53
CENTER=1
[KEY2]
BACK_STYLE=118
FORE_STYLE=244
VIEW_RECT=85,4,77,53
CENTER=2
[KEY3]
BACK_STYLE=118
FORE_STYLE=245
VIEW_RECT=164,4,77,53
CENTER=3
[KEY4]
BACK_STYLE=118
FORE_STYLE=246
VIEW_RECT=243,4,77,53
CENTER=4
[KEY5]
BACK_STYLE=118
FORE_STYLE=247
VIEW_RECT=322,4,77,53
CENTER=5
[KEY6]
BACK_STYLE=118
FORE_STYLE=248
VIEW_RECT=401,4,77,53
CENTER=6
[KEY7]
BACK_STYLE=118
FORE_STYLE=249
VIEW_RECT=480,4,77,53
CENTER=7
[KEY8]
BACK_STYLE=118
FORE_STYLE=250
VIEW_RECT=559,4,77,53
CENTER=8
[KEY9]
BACK_STYLE=118
FORE_STYLE=251
VIEW_RECT=638,4,77,53
CENTER=9
[KEY10]
BACK_STYLE=118
FORE_STYLE=252
VIEW_RECT=717,4,77,53
CENTER=0
[KEY11]
BACK_STYLE=118
FORE_STYLE=231
VIEW_RECT=45,64,77,53
CENTER=!
[KEY12]
BACK_STYLE=118
FORE_STYLE=218
VIEW_RECT=124,64,77,53
CENTER=@
[KEY13]
BACK_STYLE=118
FORE_STYLE=219
VIEW_RECT=203,64,77,53
CENTER=#
[KEY14]
BACK_STYLE=118
FORE_STYLE=221
VIEW_RECT=282,64,77,53
CENTER=$
[KEY15]
BACK_STYLE=118
FORE_STYLE=222
VIEW_RECT=361,64,77,53
CENTER=%
[KEY16]
BACK_STYLE=118
FORE_STYLE=223
VIEW_RECT=440,64,78,53
CENTER=&
[KEY17]
BACK_STYLE=118
FORE_STYLE=220
VIEW_RECT=520,64,78,53
CENTER=*
[KEY18]
BACK_STYLE=118
FORE_STYLE=224
VIEW_RECT=600,64,78,53
CENTER=(
[KEY19]
BACK_STYLE=118
FORE_STYLE=225
VIEW_RECT=680,64,77,53
CENTER=)
[KEY20]
BACK_STYLE=118
FORE_STYLE=217
VIEW_RECT=96,124,77,53
CENTER=~
[KEY21]
BACK_STYLE=118
FORE_STYLE=230
VIEW_RECT=175,124,77,53
CENTER=/
[KEY22]
BACK_STYLE=118
FORE_STYLE=228
VIEW_RECT=254,124,77,53
CENTER=-
[KEY23]
BACK_STYLE=118
FORE_STYLE=229
VIEW_RECT=333,124,77,53
CENTER=_
[KEY24]
BACK_STYLE=118
FORE_STYLE=226
VIEW_RECT=412,124,77,53
CENTER=:
[KEY25]
BACK_STYLE=118
FORE_STYLE=227
VIEW_RECT=491,124,77,53
CENTER=;
[KEY26]
BACK_STYLE=118
FORE_STYLE=242
VIEW_RECT=570,124,77,53
CENTER=?
[KEY27]
BACK_STYLE=118
FORE_STYLE=125
VIEW_RECT=186,184,88,53
CENTER=,
[KEY28]
BACK_STYLE=118
FORE_STYLE=426
VIEW_RECT=276,184,248,53
CENTER=F38
[KEY29]
BACK_STYLE=118
FORE_STYLE=92
VIEW_RECT=526,184,88,53
CENTER=。
[KEY30]
BACK_STYLE=119
FORE_STYLE=510
VIEW_RECT=6,124,88,53
CENTER=F1
[KEY31]
BACK_STYLE=119
FORE_STYLE=415
VIEW_RECT=649,124,145,53
LEFT=F40
CENTER=F36
[KEY32]
BACK_STYLE=119
FORE_STYLE=503
VIEW_RECT=6,184,178,53
CENTER=F4
[KEY33]
BACK_STYLE=119
FORE_STYLE=416
VIEW_RECT=616,184,178,53
CENTER=F39
<file_sep>[INPUT]
[CAND]
VIEW_RECT=0,0,800,55
LAYOUT_NAME=cand2
TYPE=4
[PANEL]
BACK_STYLE=116
SIZE=800,64
NO_BLUR=1
KEY_NUM=8
[MORE]
[HINT]
[LIST]
BACK_STYLE=117
CELL_STYLE=132
FORE_STYLE=129
CELL_SIZE=80,55
TYPE=2
LIST_NUM=10
[KEY1]
BACK_STYLE=119
FORE_STYLE=418
VIEW_RECT=6,3,86,55
CENTER=F6
[KEY2]
BACK_STYLE=119
FORE_STYLE=413
VIEW_RECT=95,3,86,55
UP=F16
CENTER=F16
[KEY3]
BACK_STYLE=119
FORE_STYLE=510
VIEW_RECT=185,3,86,55
UP=F7
CENTER=F1
HOLD=F7
[KEY4]
BACK_STYLE=118
FORE_STYLE=424
VIEW_RECT=275,3,86,55
UP=!
CENTER=,
[KEY5]
BACK_STYLE=118
FORE_STYLE=425
VIEW_RECT=365,3,86,55
UP=?
CENTER=。
[KEY6]
BACK_STYLE=118
FORE_STYLE=502
VIEW_RECT=454,3,160,55
CENTER=F38
[KEY7]
BACK_STYLE=119
FORE_STYLE=416
VIEW_RECT=617,3,87,55
CENTER=F39
[KEY8]
BACK_STYLE=119
FORE_STYLE=415
VIEW_RECT=707,3,87,55
LEFT=F40
CENTER=F36
<file_sep>[INPUT]
[CAND]
[PANEL]
NO_BLUR=0
KEY_NUM=17
TIP_NUM=2
[MORE]
GRID=5,2
LAYOUT_NAME=sel_en
[HINT]
LAYOUT_NAME=hint1
TYPE=0
[LIST]
BACK_STYLE=121
CELL_STYLE=120
FORE_STYLE=130
CELL_SIZE=125,47
POS=6,4
LIST_NUM=5
LIST_ORDER=0
NAMES=, . ? ! ~
VALUES=, . ? ! ~
PADDING=2,0,2,1
[KEY1]
BACK_STYLE=118
FORE_STYLE=419
VIEW_RECT=134,4,163,55
UP=1
LEFT=@
RIGHT=/
CENTER=…
SHOW=1
HOLD=1
STAT_STYLE=S4_2
[KEY2]
BACK_STYLE=118
FORE_STYLE=404
VIEW_RECT=300,4,163,55
UP=2
LEFT=a
RIGHT=c
CENTER=b
SHOW=2
[KEY3]
BACK_STYLE=118
FORE_STYLE=405
VIEW_RECT=466,4,163,55
UP=3
LEFT=d
RIGHT=f
CENTER=e
SHOW=3
[KEY4]
BACK_STYLE=118
FORE_STYLE=406
VIEW_RECT=134,64,163,55
UP=4
LEFT=g
RIGHT=i
CENTER=h
SHOW=4
[KEY5]
BACK_STYLE=118
FORE_STYLE=407
VIEW_RECT=300,64,163,55
UP=5
LEFT=j
RIGHT=l
CENTER=k
SHOW=5
[KEY6]
BACK_STYLE=118
FORE_STYLE=408
VIEW_RECT=466,64,163,55
UP=6
LEFT=m
RIGHT=o
CENTER=n
SHOW=6
[KEY7]
BACK_STYLE=118
FORE_STYLE=409
VIEW_RECT=134,124,163,55
UP=7
DOWN=s
LEFT=p
RIGHT=r
CENTER=q
SHOW=7
[KEY8]
BACK_STYLE=118
FORE_STYLE=410
VIEW_RECT=300,124,163,55
UP=8
LEFT=t
RIGHT=v
CENTER=u
SHOW=8
[KEY9]
BACK_STYLE=118
FORE_STYLE=411
VIEW_RECT=466,124,163,55
UP=9
DOWN=z
LEFT=w
RIGHT=y
CENTER=x
SHOW=9
[KEY10]
BACK_STYLE=118
FORE_STYLE=412
VIEW_RECT=300,184,163,55
UP=0
CENTER=F38
[KEY11]
BACK_STYLE=119
FORE_STYLE=415
VIEW_RECT=632,4,162,55
LEFT=F40
CENTER=F36
[KEY12]
BACK_STYLE=119
FORE_STYLE=416
VIEW_RECT=632,64,162,55
CENTER=F39
[KEY13]
BACK_STYLE=119
FORE_STYLE=484
VIEW_RECT=632,124,162,55
CENTER=F10
[KEY14]
BACK_STYLE=119
FORE_STYLE=418
VIEW_RECT=632,184,162,55
CENTER=F6
[KEY15]
BACK_STYLE=119
FORE_STYLE=509
VIEW_RECT=466,184,163,55
CENTER=F1
[KEY16]
BACK_STYLE=119
FORE_STYLE=420
VIEW_RECT=134,184,80,55
UP=F15
CENTER=F15
[KEY17]
BACK_STYLE=119
FORE_STYLE=109
VIEW_RECT=217,184,80,55
CENTER=F25
STAT_STYLE=S3_1
[TIP1]
BACK_STYLE=119
FORE_STYLE=110
CENTER=F25
[TIP2]
BACK_STYLE=118
FORE_STYLE=96
CENTER='
<file_sep>[INPUT]
[CAND]
[PANEL]
NO_BLUR=1
KEY_NUM=35
[MORE]
[HINT]
LAYOUT_NAME=hint1
[KEY1]
BACK_STYLE=118
FORE_STYLE=337
VIEW_RECT=5,6,44,75
TOUCH_RECT=5,6,44,75
UP=1
LEFT=1
RIGHT=1
CENTER=q
[KEY2]
BACK_STYLE=118
FORE_STYLE=338
VIEW_RECT=52,6,44,75
TOUCH_RECT=52,6,44,75
UP=2
LEFT=2
RIGHT=2
CENTER=w
[KEY3]
BACK_STYLE=118
FORE_STYLE=339
VIEW_RECT=99,6,44,75
TOUCH_RECT=99,6,44,75
UP=3
LEFT=3
RIGHT=3
CENTER=e
[KEY4]
BACK_STYLE=118
FORE_STYLE=340
VIEW_RECT=146,6,44,75
TOUCH_RECT=146,6,44,75
UP=4
LEFT=4
RIGHT=4
CENTER=r
[KEY5]
BACK_STYLE=118
FORE_STYLE=341
VIEW_RECT=193,6,44,75
TOUCH_RECT=193,6,44,75
UP=5
LEFT=5
RIGHT=5
CENTER=t
[KEY6]
BACK_STYLE=118
FORE_STYLE=342
VIEW_RECT=240,6,44,75
TOUCH_RECT=240,6,44,75
UP=6
LEFT=6
RIGHT=6
CENTER=y
[KEY7]
BACK_STYLE=118
FORE_STYLE=343
VIEW_RECT=287,6,45,75
TOUCH_RECT=287,6,45,75
UP=7
LEFT=7
RIGHT=7
CENTER=u
[KEY8]
BACK_STYLE=118
FORE_STYLE=344
VIEW_RECT=335,6,45,75
TOUCH_RECT=335,6,45,75
UP=8
LEFT=8
RIGHT=8
CENTER=i
[KEY9]
BACK_STYLE=118
FORE_STYLE=345
VIEW_RECT=383,6,45,75
TOUCH_RECT=383,6,45,75
UP=9
LEFT=9
RIGHT=9
CENTER=o
[KEY10]
BACK_STYLE=118
FORE_STYLE=346
VIEW_RECT=431,6,44,75
TOUCH_RECT=431,6,44,75
UP=0
LEFT=0
RIGHT=0
CENTER=p
[KEY11]
BACK_STYLE=118
FORE_STYLE=347
VIEW_RECT=28,84,44,75
TOUCH_RECT=28,84,44,75
UP=!
LEFT=!
RIGHT=!
CENTER=a
[KEY12]
BACK_STYLE=118
FORE_STYLE=348
VIEW_RECT=75,84,44,75
TOUCH_RECT=75,84,44,75
UP=@
LEFT=@
RIGHT=@
CENTER=s
[KEY13]
BACK_STYLE=118
FORE_STYLE=349
VIEW_RECT=122,84,44,75
TOUCH_RECT=122,84,44,75
UP=#
LEFT=#
RIGHT=#
CENTER=d
[KEY14]
BACK_STYLE=118
FORE_STYLE=350
VIEW_RECT=169,84,44,75
TOUCH_RECT=169,84,44,75
UP=$
LEFT=$
RIGHT=$
CENTER=f
[KEY15]
BACK_STYLE=118
FORE_STYLE=351
VIEW_RECT=216,84,44,75
TOUCH_RECT=216,84,44,75
UP=%
LEFT=%
RIGHT=%
CENTER=g
[KEY16]
BACK_STYLE=118
FORE_STYLE=352
VIEW_RECT=264,84,45,75
TOUCH_RECT=264,84,45,75
UP=&
LEFT=&
RIGHT=&
CENTER=h
[KEY17]
BACK_STYLE=118
FORE_STYLE=353
VIEW_RECT=312,84,45,75
TOUCH_RECT=312,84,45,75
UP=*
LEFT=*
RIGHT=*
CENTER=j
[KEY18]
BACK_STYLE=118
FORE_STYLE=354
VIEW_RECT=360,84,45,75
TOUCH_RECT=360,84,45,75
UP=(
LEFT=(
RIGHT=(
CENTER=k
[KEY19]
BACK_STYLE=118
FORE_STYLE=355
VIEW_RECT=408,84,44,75
TOUCH_RECT=408,84,44,75
UP=)
LEFT=)
RIGHT=)
CENTER=l
[KEY20]
BACK_STYLE=118
FORE_STYLE=356
VIEW_RECT=58,162,44,75
TOUCH_RECT=58,162,44,75
UP=~
LEFT=~
RIGHT=~
CENTER=z
[KEY21]
BACK_STYLE=118
FORE_STYLE=357
VIEW_RECT=105,162,44,75
TOUCH_RECT=105,162,44,75
UP=/
LEFT=/
RIGHT=/
CENTER=x
[KEY22]
BACK_STYLE=118
FORE_STYLE=358
VIEW_RECT=152,162,44,75
TOUCH_RECT=152,162,44,75
UP=-
LEFT=-
RIGHT=-
CENTER=c
[KEY23]
BACK_STYLE=118
FORE_STYLE=359
VIEW_RECT=199,162,44,75
TOUCH_RECT=199,162,44,75
UP=_
LEFT=_
RIGHT=_
CENTER=v
[KEY24]
BACK_STYLE=118
FORE_STYLE=360
VIEW_RECT=246,162,45,75
TOUCH_RECT=246,162,45,75
UP=:
LEFT=:
RIGHT=:
CENTER=b
[KEY25]
BACK_STYLE=118
FORE_STYLE=361
VIEW_RECT=294,162,45,75
TOUCH_RECT=294,162,45,75
UP=;
LEFT=;
RIGHT=;
CENTER=n
[KEY26]
BACK_STYLE=118
FORE_STYLE=362
VIEW_RECT=342,162,45,75
TOUCH_RECT=342,162,45,75
UP=?
LEFT=?
RIGHT=?
CENTER=m
[KEY27]
BACK_STYLE=118
FORE_STYLE=123
VIEW_RECT=111,239,51,68
UP=!
CENTER=,
[KEY28]
BACK_STYLE=118
FORE_STYLE=95
VIEW_RECT=165,239,115,68
CENTER=F38
[KEY29]
BACK_STYLE=118
FORE_STYLE=124
VIEW_RECT=283,239,51,68
UP=?
CENTER=。
[KEY30]
BACK_STYLE=119
FORE_STYLE=106
VIEW_RECT=4,162,51,75
TOUCH_RECT=4,162,51,75
CENTER=*
[KEY31]
BACK_STYLE=119
FORE_STYLE=299
VIEW_RECT=390,162,86,75
TOUCH_RECT=390,162,86,75
LEFT=F40
CENTER=F36
[KEY32]
BACK_STYLE=119
FORE_STYLE=302
VIEW_RECT=4,239,51,68
CENTER=F6
[KEY33]
BACK_STYLE=119
FORE_STYLE=304
VIEW_RECT=58,239,50,68
UP=F16
CENTER=F16
[KEY34]
BACK_STYLE=119
FORE_STYLE=104
VIEW_RECT=336,239,51,68
UP=F7
CENTER=F1
HOLD=F7
[KEY35]
BACK_STYLE=119
FORE_STYLE=300
VIEW_RECT=390,239,86,68
CENTER=F39
<file_sep>[INPUT]
[PANEL]
BACK_STYLE=116
SIZE=480,372
NO_BLUR=1
KEY_NUM=5
TIP_NUM=2
[MORE]
GRID=5,2
[LIST]
BACK_STYLE=121
CELL_STYLE=120
FORE_STYLE=130
CELL_SIZE=71,58
POS=5,6
LIST_NUM=5
LIST_ORDER=0
PADDING=2,0,2,0
[KEY1]
BACK_STYLE=286
VIEW_RECT=5,304,470,63
TOUCH_RECT=0,0,0,0
[KEY2]
VIEW_RECT=81,6,394,294
CENTER=F55
[KEY3]
BACK_STYLE=134
FORE_STYLE=152
VIEW_RECT=346,304,128,63
CENTER=F4
[KEY4]
BACK_STYLE=134
FORE_STYLE=279
VIEW_RECT=0,304,106,63
CENTER=F22
STAT_STYLE=S7_1
[KEY5]
BACK_STYLE=134
FORE_STYLE=278
VIEW_RECT=182,304,106,63
CENTER=F23
STAT_STYLE=S8_2
[TIP1]
FORE_STYLE=277
[TIP2]
FORE_STYLE=276
<file_sep>[INPUT]
[CAND]
LAYOUT_NAME=cand1
TYPE=4
[PANEL]
NO_BLUR=1
KEY_NUM=33
[MORE]
[HINT]
[KEY1]
BACK_STYLE=118
FORE_STYLE=243
VIEW_RECT=5,6,44,75
TOUCH_RECT=5,6,44,75
CENTER=1
[KEY2]
BACK_STYLE=118
FORE_STYLE=244
VIEW_RECT=52,6,44,75
TOUCH_RECT=52,6,44,75
CENTER=2
[KEY3]
BACK_STYLE=118
FORE_STYLE=245
VIEW_RECT=99,6,44,75
TOUCH_RECT=99,6,44,75
CENTER=3
[KEY4]
BACK_STYLE=118
FORE_STYLE=246
VIEW_RECT=146,6,44,75
TOUCH_RECT=146,6,44,75
CENTER=4
[KEY5]
BACK_STYLE=118
FORE_STYLE=247
VIEW_RECT=193,6,44,75
TOUCH_RECT=193,6,44,75
CENTER=5
[KEY6]
BACK_STYLE=118
FORE_STYLE=248
VIEW_RECT=240,6,44,75
TOUCH_RECT=240,6,44,75
CENTER=6
[KEY7]
BACK_STYLE=118
FORE_STYLE=249
VIEW_RECT=287,6,45,75
TOUCH_RECT=287,6,45,75
CENTER=7
[KEY8]
BACK_STYLE=118
FORE_STYLE=250
VIEW_RECT=335,6,45,75
TOUCH_RECT=335,6,45,75
CENTER=8
[KEY9]
BACK_STYLE=118
FORE_STYLE=251
VIEW_RECT=383,6,45,75
TOUCH_RECT=383,6,45,75
CENTER=9
[KEY10]
BACK_STYLE=118
FORE_STYLE=252
VIEW_RECT=431,6,44,75
TOUCH_RECT=431,6,44,75
CENTER=0
[KEY11]
BACK_STYLE=118
FORE_STYLE=231
VIEW_RECT=28,84,44,75
TOUCH_RECT=28,84,44,75
CENTER=!
[KEY12]
BACK_STYLE=118
FORE_STYLE=218
VIEW_RECT=75,84,44,75
TOUCH_RECT=75,84,44,75
CENTER=@
[KEY13]
BACK_STYLE=118
FORE_STYLE=219
VIEW_RECT=122,84,44,75
TOUCH_RECT=122,84,44,75
CENTER=#
[KEY14]
BACK_STYLE=118
FORE_STYLE=221
VIEW_RECT=169,84,44,75
TOUCH_RECT=169,84,44,75
CENTER=^
[KEY15]
BACK_STYLE=118
FORE_STYLE=222
VIEW_RECT=216,84,44,75
TOUCH_RECT=216,84,44,75
CENTER="
[KEY16]
BACK_STYLE=118
FORE_STYLE=223
VIEW_RECT=264,84,45,75
TOUCH_RECT=264,84,45,75
CENTER=——
[KEY17]
BACK_STYLE=118
FORE_STYLE=220
VIEW_RECT=312,84,45,75
TOUCH_RECT=312,84,45,75
CENTER=*
[KEY18]
BACK_STYLE=118
FORE_STYLE=224
VIEW_RECT=360,84,45,75
TOUCH_RECT=360,84,45,75
CENTER=(
[KEY19]
BACK_STYLE=118
FORE_STYLE=225
VIEW_RECT=408,84,44,75
TOUCH_RECT=408,84,44,75
CENTER=)
[KEY20]
BACK_STYLE=118
FORE_STYLE=217
VIEW_RECT=58,162,44,75
TOUCH_RECT=58,162,44,75
CENTER=~
[KEY21]
BACK_STYLE=118
FORE_STYLE=230
VIEW_RECT=105,162,44,75
TOUCH_RECT=105,162,44,75
CENTER=…
[KEY22]
BACK_STYLE=118
FORE_STYLE=228
VIEW_RECT=152,162,44,75
TOUCH_RECT=152,162,44,75
CENTER=-
[KEY23]
BACK_STYLE=118
FORE_STYLE=229
VIEW_RECT=199,162,44,75
TOUCH_RECT=199,162,44,75
CENTER=_
[KEY24]
BACK_STYLE=118
FORE_STYLE=226
VIEW_RECT=246,162,45,75
TOUCH_RECT=246,162,45,75
CENTER=:
[KEY25]
BACK_STYLE=118
FORE_STYLE=227
VIEW_RECT=294,162,45,75
TOUCH_RECT=294,162,45,75
CENTER=;
[KEY26]
BACK_STYLE=118
FORE_STYLE=242
VIEW_RECT=342,162,45,75
TOUCH_RECT=342,162,45,75
CENTER=?
[KEY27]
BACK_STYLE=118
FORE_STYLE=125
VIEW_RECT=110,240,51,68
CENTER=,
[KEY28]
BACK_STYLE=118
FORE_STYLE=95
VIEW_RECT=164,240,152,68
CENTER=F38
[KEY29]
BACK_STYLE=118
FORE_STYLE=92
VIEW_RECT=319,240,51,68
CENTER=。
[KEY30]
BACK_STYLE=119
FORE_STYLE=260
VIEW_RECT=4,162,51,75
TOUCH_RECT=4,162,51,75
CENTER=F1
[KEY31]
BACK_STYLE=119
FORE_STYLE=299
VIEW_RECT=390,162,86,75
TOUCH_RECT=390,162,86,75
LEFT=F40
CENTER=F36
[KEY32]
BACK_STYLE=119
FORE_STYLE=152
VIEW_RECT=3,240,104,68
CENTER=F4
[KEY33]
BACK_STYLE=119
FORE_STYLE=300
VIEW_RECT=373,240,102,68
CENTER=F39
<file_sep># my_baidu_input_skin
A Baidu mobile phone input method skin optimized for one-handed input of English.
### Baidu mobile phone input method
#### Download
https://srf.baidu.com/default/
#### Advanced skinning function
##### Choose skin
setting->super skin->lcoal
##### Use custom skin
1. Download the appropriate "*.bds" file.
2. Single click to enable.
1. If the file has an internal error, the input method will prompt an error and use the initial skin.
2. The above internal error usually refers to the use of the wrong compression method.
3. If the character of the button response does not match the picture of the button, you can solve this by choose a background (anything is okay, for example, a pure white background) for the keyboard with the built-in customize skin function.
### Preparation of skin files
#### Unpack the skin file
```shell
mv test.bds test.zip
unzip test.zip
```
#### File structure
```shell
.
├── demo.png
├── Info.txt
├── land (Landscape)
├── port (Portrait)
│ ├── en_26.ini (26 key keyboard for english input)
│ ├── en_26s.ini (26 key layout after pressing the shift key)
│ ├── others
└── res
```
#### Example
```ini
[KEY1]
BACK_STYLE=118
FORE_STYLE=337
VIEW_RECT=5,65,44,75
TOUCH_RECT=5,65,44,75
UP=1
LEFT=1
RIGHT=1
CENTER=F41
[KEY2]
BACK_STYLE=118
FORE_STYLE=520
VIEW_RECT=52,65,44,75
TOUCH_RECT=52,65,44,75
UP=2
LEFT=2
RIGHT=2
CENTER=z
```
- Of course, other changes are needed.
- `F41` means `Tab` key.
#### Package skin file
```shell
zip -r myskin.bds ./*
```<file_sep>[INPUT]
BACK_STYLE=127
FORE_STYLE=128
[CAND]
VIEW_RECT=0,0,480,60
LAYOUT_NAME=cand1
TYPE=4
[PANEL]
BACK_STYLE=116
FORE_STYLE=126
SIZE=480,312
OFFSET_NUM=3
[MORE]
GRID=4,4
SYM_LAYOUT=symbol
LAYOUT_NAME=sel_ch
FORE_STYLE=129
CELL_STYLE=135
[HINT]
LAYOUT_NAME=hint1
TYPE=0
[LIST]
CELL_SIZE=71,60
POS=6,6
PADDING=2,0,2,0
[OFFSET1]
POS=0,12
[OFFSET2]
POS=0,-24
[OFFSET3]
POS=0,20<file_sep>[INPUT]
[CAND]
[PANEL]
NO_BLUR=0
KEY_NUM=16
TIP_NUM=1
[MORE]
[HINT]
LAYOUT_NAME=hint1
TYPE=0
[LIST]
BACK_STYLE=121
CELL_STYLE=120
FORE_STYLE=130
CELL_SIZE=71,60
POS=5,6
TYPE=0
LIST_NUM=5
LIST_ORDER=0
NAMES=, 。 ? ! ~
VALUES=, 。 ? ! ~
PADDING=2,0,2,1
[KEY1]
BACK_STYLE=118
FORE_STYLE=289
VIEW_RECT=81,6,104,75
TOUCH_RECT=81,6,104,75
UP=1
CENTER=B1
[KEY2]
BACK_STYLE=118
FORE_STYLE=290
VIEW_RECT=189,6,104,75
TOUCH_RECT=189,6,104,75
UP=2
CENTER=B2
[KEY3]
BACK_STYLE=118
FORE_STYLE=291
VIEW_RECT=298,6,104,75
TOUCH_RECT=298,6,104,75
UP=3
CENTER=B3
[KEY4]
BACK_STYLE=118
FORE_STYLE=292
VIEW_RECT=81,84,104,75
TOUCH_RECT=81,84,104,75
UP=4
CENTER=B4
[KEY5]
BACK_STYLE=118
FORE_STYLE=293
VIEW_RECT=189,84,104,75
TOUCH_RECT=189,84,104,75
UP=5
CENTER=B5
[KEY6]
BACK_STYLE=118
FORE_STYLE=294
VIEW_RECT=298,84,104,75
TOUCH_RECT=298,84,104,75
UP=6
CENTER=B6
[KEY7]
BACK_STYLE=118
FORE_STYLE=295
VIEW_RECT=81,162,104,75
TOUCH_RECT=81,162,104,75
UP=7
CENTER='
[KEY8]
BACK_STYLE=118
FORE_STYLE=296
VIEW_RECT=189,162,104,75
TOUCH_RECT=189,162,104,75
UP=8
CENTER=:
[KEY9]
BACK_STYLE=118
FORE_STYLE=297
VIEW_RECT=298,162,104,75
TOUCH_RECT=298,162,104,75
UP=9
CENTER=;
[KEY10]
BACK_STYLE=118
FORE_STYLE=298
VIEW_RECT=189,239,104,68
UP=0
CENTER=F38
[KEY11]
BACK_STYLE=119
FORE_STYLE=299
VIEW_RECT=407,6,69,75
TOUCH_RECT=407,6,69,75
LEFT=F40
CENTER=F36
[KEY12]
BACK_STYLE=119
FORE_STYLE=300
VIEW_RECT=407,84,69,75
TOUCH_RECT=407,84,69,75
CENTER=F39
[KEY13]
BACK_STYLE=119
FORE_STYLE=301
VIEW_RECT=407,162,69,75
TOUCH_RECT=407,162,69,75
CENTER=F7
STAT_STYLE=S4_1
[KEY14]
BACK_STYLE=119
FORE_STYLE=302
VIEW_RECT=407,239,69,68
CENTER=F6
[KEY15]
BACK_STYLE=119
FORE_STYLE=304
VIEW_RECT=81,239,104,68
TOUCH_RECT=81,239,104,68
UP=F16
CENTER=F16
[KEY16]
BACK_STYLE=119
FORE_STYLE=303
VIEW_RECT=298,239,104,68
CENTER=F1
[TIP1]
BACK_STYLE=119
FORE_STYLE=512
CENTER=F40
<file_sep>[INPUT]
[PANEL]
BACK_STYLE=116
SIZE=480,407
NO_BLUR=1
KEY_NUM=7
TIP_NUM=3
[MORE]
GRID=5,4
[LIST]
BACK_STYLE=121
CELL_STYLE=120
FORE_STYLE=130
CELL_SIZE=71,65
POS=5,6
LIST_NUM=5
LIST_ORDER=0
PADDING=2,0,2,0
[KEY1]
BACK_STYLE=286
VIEW_RECT=5,337,470,63
TOUCH_RECT=0,0,0,0
[KEY2]
VIEW_RECT=81,6,394,327
CENTER=F55
[KEY3]
BACK_STYLE=134
FORE_STYLE=152
VIEW_RECT=370,337,106,63
CENTER=F4
[KEY4]
BACK_STYLE=134
FORE_STYLE=280
VIEW_RECT=0,337,106,63
CENTER=F27
STAT_STYLE=S6_1
[KEY5]
BACK_STYLE=134
FORE_STYLE=279
VIEW_RECT=84,337,106,63
CENTER=F22
STAT_STYLE=S7_2
[KEY6]
BACK_STYLE=134
FORE_STYLE=278
VIEW_RECT=180,337,106,63
CENTER=F23
STAT_STYLE=S8_3
[KEY7]
BACK_STYLE=134
FORE_STYLE=299
VIEW_RECT=278,337,106,63
LEFT=F40
CENTER=F36
[TIP1]
BACK_STYLE=134
FORE_STYLE=275
CENTER=F27
[TIP2]
FORE_STYLE=277
[TIP3]
FORE_STYLE=276
<file_sep>[INPUT]
[CAND]
VIEW_RECT=0,0,480,60
LAYOUT_NAME=cand0
TYPE=4
[PANEL]
BACK_STYLE=116
SIZE=480,345
NO_BLUR=1
KEY_NUM=6
[MORE]
SYM_LAYOUT=symbol_hw
LAYOUT_NAME=sel_hw
[HINT]
[LIST]
BACK_STYLE=117
CELL_STYLE=132
FORE_STYLE=129
CELL_SIZE=80,62
POS=6,4
TYPE=2
LIST_NUM=6
PADDING=0,0,0,0
[KEY1]
BACK_STYLE=144
VIEW_RECT=6,6,380,333
CENTER=F53
[KEY2]
BACK_STYLE=119
FORE_STYLE=299
VIEW_RECT=392,6,84,65
LEFT=F40
CENTER=F36
[KEY3]
BACK_STYLE=118
FORE_STYLE=390
VIEW_RECT=392,74,84,65
CENTER=。
HOLDSYM=,。.@/’
[KEY4]
BACK_STYLE=119
FORE_STYLE=259
VIEW_RECT=392,210,84,63
CENTER=F38
[KEY5]
BACK_STYLE=119
FORE_STYLE=300
VIEW_RECT=392,277,84,62
CENTER=F39
[KEY6]
BACK_STYLE=118
FORE_STYLE=389
VIEW_RECT=392,142,84,65
CENTER=,
<file_sep>[PANEL]
BACK_STYLE=116
FORE_STYLE=126
SIZE=800,245
[INPUT]
BACK_STYLE=127
FORE_STYLE=128
[CAND]
VIEW_RECT=0,0,800,55
LAYOUT_NAME=cand1
TYPE=4
[HINT]
LAYOUT_NAME=hint1
TYPE=0
[MORE]
GRID=4,5
LAYOUT_NAME=sel_ch
SYM_LAYOUT=symbol
CELL_STYLE=135
FORE_STYLE=129
[LIST]
BACK_STYLE=121
CELL_STYLE=120
FORE_STYLE=130
<file_sep>[INPUT]
[PANEL]
BACK_STYLE=116
SIZE=800,300
NO_BLUR=1
KEY_NUM=5
TIP_NUM=2
[MORE]
GRID=5,2
[LIST]
CELL_SIZE=125,57
POS=6,6
LIST_NUM=4
LIST_ORDER=0
PADDING=2,0,2,0
[KEY1]
BACK_STYLE=286
VIEW_RECT=6,239,788,55
TOUCH_RECT=0,0,0,0
[KEY2]
VIEW_RECT=135,6,659,228
CENTER=F55
[KEY3]
BACK_STYLE=134
FORE_STYLE=279
VIEW_RECT=0,239,220,55
CENTER=F22
STAT_STYLE=S7_1
[KEY4]
BACK_STYLE=134
FORE_STYLE=278
VIEW_RECT=290,239,220,55
CENTER=F23
STAT_STYLE=S8_2
[KEY5]
BACK_STYLE=134
FORE_STYLE=152
VIEW_RECT=552,239,242,55
CENTER=F4
[TIP1]
FORE_STYLE=277
[TIP2]
FORE_STYLE=276
<file_sep>[INPUT]
[CAND]
[PANEL]
NO_BLUR=0
KEY_NUM=16
TIP_NUM=1
[MORE]
[HINT]
[LIST]
CELL_SIZE=125,47
POS=6,4
LIST_NUM=5
LIST_ORDER=0
NAMES=, 。 ? ! ~
VALUES=, 。 ? ! ~
PADDING=2,0,2,1
[KEY1]
BACK_STYLE=118
FORE_STYLE=394
VIEW_RECT=134,4,163,55
UP=1
CENTER=B1
[KEY2]
BACK_STYLE=118
FORE_STYLE=395
VIEW_RECT=300,4,163,55
UP=2
CENTER=B2
[KEY3]
BACK_STYLE=118
FORE_STYLE=396
VIEW_RECT=466,4,163,55
UP=3
CENTER=B3
[KEY4]
BACK_STYLE=118
FORE_STYLE=397
VIEW_RECT=134,64,163,55
UP=4
CENTER=B4
[KEY5]
BACK_STYLE=118
FORE_STYLE=398
VIEW_RECT=300,64,163,55
UP=5
CENTER=B5
[KEY6]
BACK_STYLE=118
FORE_STYLE=399
VIEW_RECT=466,64,163,55
UP=6
CENTER=B6
[KEY7]
BACK_STYLE=118
FORE_STYLE=400
VIEW_RECT=134,124,163,55
UP=7
CENTER='
[KEY8]
BACK_STYLE=118
FORE_STYLE=401
VIEW_RECT=300,124,163,55
UP=8
CENTER=:
[KEY9]
BACK_STYLE=118
FORE_STYLE=402
VIEW_RECT=466,124,163,55
UP=9
CENTER=;
[KEY10]
BACK_STYLE=118
FORE_STYLE=412
VIEW_RECT=300,184,163,55
UP=0
CENTER=F38
[KEY11]
BACK_STYLE=119
FORE_STYLE=415
VIEW_RECT=632,4,162,55
LEFT=F40
CENTER=F36
[KEY12]
BACK_STYLE=119
FORE_STYLE=416
VIEW_RECT=632,64,162,55
CENTER=F39
[KEY13]
BACK_STYLE=119
FORE_STYLE=417
VIEW_RECT=632,124,162,55
CENTER=F7
STAT_STYLE=S4_1
[KEY14]
BACK_STYLE=119
FORE_STYLE=418
VIEW_RECT=632,184,162,55
CENTER=F6
[KEY15]
BACK_STYLE=119
FORE_STYLE=413
VIEW_RECT=134,184,163,55
UP=F16
CENTER=F16
[KEY16]
BACK_STYLE=119
FORE_STYLE=509
VIEW_RECT=466,184,163,55
CENTER=F1
[TIP1]
BACK_STYLE=119
FORE_STYLE=513
CENTER=F40
<file_sep>[INPUT]
[PANEL]
BACK_STYLE=116
SIZE=480,372
NO_BLUR=1
KEY_NUM=7
TIP_NUM=3
[MORE]
GRID=4,4
[LIST]
BACK_STYLE=121
CELL_STYLE=120
FORE_STYLE=130
CELL_SIZE=71,58
POS=5,6
LIST_NUM=5
LIST_ORDER=0
PADDING=2,0,2,0
[KEY1]
BACK_STYLE=286
VIEW_RECT=5,302,470,63
TOUCH_RECT=0,0,0,0
[KEY2]
VIEW_RECT=81,6,394,292
CENTER=F55
[KEY3]
BACK_STYLE=134
FORE_STYLE=152
VIEW_RECT=370,302,106,63
CENTER=F4
[KEY4]
BACK_STYLE=134
FORE_STYLE=280
VIEW_RECT=0,302,106,63
CENTER=F27
STAT_STYLE=S6_1
[KEY5]
BACK_STYLE=134
FORE_STYLE=279
VIEW_RECT=84,302,106,63
CENTER=F22
STAT_STYLE=S7_2
[KEY6]
BACK_STYLE=134
FORE_STYLE=278
VIEW_RECT=180,302,106,63
CENTER=F23
STAT_STYLE=S8_3
[KEY7]
BACK_STYLE=134
FORE_STYLE=299
VIEW_RECT=278,302,106,63
LEFT=F40
CENTER=F36
[TIP1]
BACK_STYLE=134
FORE_STYLE=275
CENTER=F27
[TIP2]
FORE_STYLE=277
[TIP3]
FORE_STYLE=276
<file_sep>[INPUT]
[PANEL]
BACK_STYLE=116
SIZE=800,333
NO_BLUR=1
KEY_NUM=6
TIP_NUM=3
[MORE]
GRID=5,4
[LIST]
CELL_SIZE=117,52
POS=6,5
LIST_NUM=5
LIST_ORDER=0
NAMES=, 。 ? ! ~
VALUES=, 。 ? ! ~
PADDING=2,0,2,0
[KEY1]
BACK_STYLE=286
VIEW_RECT=6,271,788,55
TOUCH_RECT=0,0,0,0
[KEY2]
VIEW_RECT=128,4,667,263
CENTER=F55
[KEY3]
BACK_STYLE=134
FORE_STYLE=137
VIEW_RECT=25,271,175,55
CENTER=F26
STAT_STYLE=S5_1
[KEY4]
BACK_STYLE=134
FORE_STYLE=279
VIEW_RECT=225,271,175,55
CENTER=F22
STAT_STYLE=S7_2
[KEY5]
BACK_STYLE=134
FORE_STYLE=278
VIEW_RECT=425,271,175,55
CENTER=F23
STAT_STYLE=S8_3
[KEY6]
BACK_STYLE=134
FORE_STYLE=152
VIEW_RECT=625,271,172,55
CENTER=F4
[TIP1]
BACK_STYLE=134
FORE_STYLE=136
CENTER=F26
[TIP2]
FORE_STYLE=277
[TIP3]
FORE_STYLE=276
<file_sep>[INPUT]
[CAND]
LAYOUT_NAME=cand1
TYPE=4
[PANEL]
NO_BLUR=1
KEY_NUM=20
[KEY1]
BACK_STYLE=118
FORE_STYLE=320
VIEW_RECT=80,6,104,75
TOUCH_RECT=80,6,104,75
CENTER=1
[KEY2]
BACK_STYLE=118
FORE_STYLE=321
VIEW_RECT=189,6,104,75
TOUCH_RECT=189,6,104,75
CENTER=2
[KEY3]
BACK_STYLE=118
FORE_STYLE=322
VIEW_RECT=298,6,104,75
TOUCH_RECT=298,6,104,75
CENTER=3
[KEY4]
BACK_STYLE=118
FORE_STYLE=323
VIEW_RECT=80,84,104,75
TOUCH_RECT=80,84,104,75
CENTER=4
[KEY5]
BACK_STYLE=118
FORE_STYLE=324
VIEW_RECT=189,84,104,75
TOUCH_RECT=189,84,104,75
CENTER=5
[KEY6]
BACK_STYLE=118
FORE_STYLE=325
VIEW_RECT=298,84,104,75
TOUCH_RECT=298,84,104,75
CENTER=6
[KEY7]
BACK_STYLE=118
FORE_STYLE=326
VIEW_RECT=80,162,104,75
TOUCH_RECT=80,162,104,75
CENTER=7
[KEY8]
BACK_STYLE=118
FORE_STYLE=327
VIEW_RECT=189,162,104,75
TOUCH_RECT=189,162,104,75
CENTER=8
[KEY9]
BACK_STYLE=118
FORE_STYLE=328
VIEW_RECT=298,162,104,75
TOUCH_RECT=298,162,104,75
CENTER=9
[KEY10]
BACK_STYLE=118
FORE_STYLE=336
VIEW_RECT=189,239,104,68
CENTER=0
[KEY11]
BACK_STYLE=119
FORE_STYLE=330
VIEW_RECT=5,6,70,75
TOUCH_RECT=5,6,70,75
CENTER=@
[KEY12]
BACK_STYLE=119
FORE_STYLE=331
VIEW_RECT=5,84,70,75
TOUCH_RECT=5,84,70,75
CENTER=%
[KEY13]
BACK_STYLE=119
FORE_STYLE=332
VIEW_RECT=5,162,70,75
TOUCH_RECT=5,162,70,75
CENTER=¥
[KEY14]
BACK_STYLE=119
FORE_STYLE=333
VIEW_RECT=5,239,70,68
CENTER=+
[KEY15]
BACK_STYLE=119
FORE_STYLE=334
VIEW_RECT=80,239,104,68
CENTER=-
[KEY16]
BACK_STYLE=119
FORE_STYLE=335
VIEW_RECT=298,239,104,68
CENTER=.
[KEY17]
BACK_STYLE=119
FORE_STYLE=329
VIEW_RECT=407,239,69,68
CENTER=F4
[KEY18]
BACK_STYLE=119
FORE_STYLE=259
VIEW_RECT=407,162,69,75
TOUCH_RECT=407,162,69,75
CENTER=F38
[KEY19]
BACK_STYLE=119
FORE_STYLE=300
VIEW_RECT=407,84,69,75
TOUCH_RECT=407,84,69,75
CENTER=F39
[KEY20]
BACK_STYLE=119
FORE_STYLE=299
VIEW_RECT=407,6,69,75
TOUCH_RECT=407,6,69,75
CENTER=F36
<file_sep>[INPUT]
[CAND]
[PANEL]
NO_BLUR=1
KEY_NUM=20
[HINT]
[KEY1]
BACK_STYLE=118
FORE_STYLE=487
VIEW_RECT=134,4,163,55
CENTER=1
[KEY2]
BACK_STYLE=118
FORE_STYLE=488
VIEW_RECT=300,4,163,55
CENTER=2
[KEY3]
BACK_STYLE=118
FORE_STYLE=489
VIEW_RECT=466,4,163,55
CENTER=3
[KEY4]
BACK_STYLE=118
FORE_STYLE=491
VIEW_RECT=134,64,163,55
CENTER=4
[KEY5]
BACK_STYLE=118
FORE_STYLE=492
VIEW_RECT=300,64,163,55
CENTER=5
[KEY6]
BACK_STYLE=118
FORE_STYLE=493
VIEW_RECT=466,64,163,55
CENTER=6
[KEY7]
BACK_STYLE=118
FORE_STYLE=495
VIEW_RECT=134,124,163,55
CENTER=7
[KEY8]
BACK_STYLE=118
FORE_STYLE=496
VIEW_RECT=300,124,163,55
CENTER=8
[KEY9]
BACK_STYLE=118
FORE_STYLE=497
VIEW_RECT=466,124,163,55
CENTER=9
[KEY10]
BACK_STYLE=118
FORE_STYLE=500
VIEW_RECT=300,184,163,55
CENTER=0
[KEY11]
BACK_STYLE=119
FORE_STYLE=486
VIEW_RECT=6,4,125,55
CENTER=@
[KEY12]
BACK_STYLE=119
FORE_STYLE=490
VIEW_RECT=6,64,125,55
CENTER=%
[KEY13]
BACK_STYLE=119
FORE_STYLE=494
VIEW_RECT=6,124,125,55
CENTER=¥
[KEY14]
BACK_STYLE=119
FORE_STYLE=498
VIEW_RECT=6,184,125,55
CENTER=+
[KEY15]
BACK_STYLE=119
FORE_STYLE=499
VIEW_RECT=134,184,163,55
CENTER=-
[KEY16]
BACK_STYLE=119
FORE_STYLE=501
VIEW_RECT=466,184,163,55
CENTER=.
[KEY17]
BACK_STYLE=119
FORE_STYLE=503
VIEW_RECT=632,184,162,55
CENTER=F4
[KEY18]
BACK_STYLE=119
FORE_STYLE=502
VIEW_RECT=632,124,162,55
CENTER=F38
[KEY19]
BACK_STYLE=119
FORE_STYLE=416
VIEW_RECT=632,64,162,55
CENTER=F39
[KEY20]
BACK_STYLE=119
FORE_STYLE=415
VIEW_RECT=632,4,162,55
CENTER=F36
<file_sep>[INPUT]
[CAND]
[PANEL]
NO_BLUR=0
KEY_NUM=17
TIP_NUM=3
[MORE]
GRID=5,2
LAYOUT_NAME=sel_en
[HINT]
LAYOUT_NAME=hint1
TYPE=0
[LIST]
BACK_STYLE=121
CELL_STYLE=120
FORE_STYLE=130
CELL_SIZE=71,60
POS=5,6
TYPE=0
LIST_NUM=5
LIST_ORDER=0
NAMES=, . ? ! ~
VALUES=, . ? ! ~
PADDING=2,0,2,1
[KEY1]
BACK_STYLE=118
FORE_STYLE=314
VIEW_RECT=81,6,104,75
TOUCH_RECT=81,6,104,75
UP=1
LEFT=@
RIGHT=/
CENTER=…
SHOW=1
HOLD=1
STAT_STYLE=S4_3
[KEY2]
BACK_STYLE=118
FORE_STYLE=306
VIEW_RECT=189,6,104,75
TOUCH_RECT=189,6,104,75
UP=2
LEFT=a
RIGHT=c
CENTER=b
SHOW=2
[KEY3]
BACK_STYLE=118
FORE_STYLE=307
VIEW_RECT=298,6,104,75
TOUCH_RECT=298,6,104,75
UP=3
LEFT=d
RIGHT=f
CENTER=e
SHOW=3
[KEY4]
BACK_STYLE=118
FORE_STYLE=308
VIEW_RECT=81,84,104,75
TOUCH_RECT=81,84,104,75
UP=4
LEFT=g
RIGHT=i
CENTER=h
SHOW=4
[KEY5]
BACK_STYLE=118
FORE_STYLE=309
VIEW_RECT=189,84,104,75
TOUCH_RECT=189,84,104,75
UP=5
LEFT=j
RIGHT=l
CENTER=k
SHOW=5
[KEY6]
BACK_STYLE=118
FORE_STYLE=310
VIEW_RECT=298,84,104,75
TOUCH_RECT=298,84,104,75
UP=6
LEFT=m
RIGHT=o
CENTER=n
SHOW=6
[KEY7]
BACK_STYLE=118
FORE_STYLE=311
VIEW_RECT=81,162,104,75
TOUCH_RECT=81,162,104,75
UP=7
DOWN=s
LEFT=p
RIGHT=r
CENTER=q
SHOW=7
[KEY8]
BACK_STYLE=118
FORE_STYLE=312
VIEW_RECT=189,162,104,75
TOUCH_RECT=189,162,104,75
UP=8
LEFT=t
RIGHT=v
CENTER=u
SHOW=8
[KEY9]
BACK_STYLE=118
FORE_STYLE=313
VIEW_RECT=298,162,104,75
TOUCH_RECT=298,162,104,75
UP=9
DOWN=z
LEFT=w
RIGHT=y
CENTER=x
SHOW=9
[KEY10]
BACK_STYLE=118
FORE_STYLE=298
VIEW_RECT=189,239,104,68
UP=0
CENTER=F38
[KEY11]
BACK_STYLE=119
FORE_STYLE=299
VIEW_RECT=407,6,69,75
TOUCH_RECT=407,6,69,75
LEFT=F40
CENTER=F36
[KEY12]
BACK_STYLE=119
FORE_STYLE=300
VIEW_RECT=407,84,69,75
TOUCH_RECT=407,84,69,75
CENTER=F39
[KEY13]
BACK_STYLE=119
FORE_STYLE=318
VIEW_RECT=407,162,69,75
TOUCH_RECT=407,162,69,75
CENTER=F11
STAT_STYLE=S2_2
[KEY14]
BACK_STYLE=119
FORE_STYLE=302
VIEW_RECT=407,239,69,68
CENTER=F6
[KEY15]
BACK_STYLE=119
FORE_STYLE=303
VIEW_RECT=298,239,104,68
CENTER=F1
[KEY16]
BACK_STYLE=119
FORE_STYLE=316
VIEW_RECT=81,239,50,68
TOUCH_RECT=81,239,50,68
UP=F15
CENTER=F15
[KEY17]
BACK_STYLE=119
FORE_STYLE=317
VIEW_RECT=135,239,50,68
TOUCH_RECT=135,239,50,68
CENTER=F25
STAT_STYLE=S3_1
[TIP1]
BACK_STYLE=119
FORE_STYLE=110
CENTER=F25
[TIP2]
BACK_STYLE=119
FORE_STYLE=114
CENTER=F11
[TIP3]
BACK_STYLE=118
FORE_STYLE=96
CENTER='
<file_sep>[INPUT]
[PANEL]
BACK_STYLE=116
SIZE=800,300
NO_BLUR=1
KEY_NUM=7
TIP_NUM=3
[MORE]
[LIST]
CELL_SIZE=125,57
POS=6,6
LIST_NUM=4
LIST_ORDER=0
PADDING=2,0,2,0
[KEY1]
BACK_STYLE=286
VIEW_RECT=6,239,788,55
TOUCH_RECT=0,0,0,0
[KEY2]
VIEW_RECT=135,6,659,228
CENTER=F55
[KEY3]
BACK_STYLE=134
FORE_STYLE=415
VIEW_RECT=459,239,173,55
CENTER=F36
[KEY4]
BACK_STYLE=134
FORE_STYLE=279
VIEW_RECT=127,239,165,55
CENTER=F22
STAT_STYLE=S7_2
[KEY5]
BACK_STYLE=134
FORE_STYLE=278
VIEW_RECT=293,239,165,55
CENTER=F23
STAT_STYLE=S8_3
[KEY6]
BACK_STYLE=134
FORE_STYLE=280
VIEW_RECT=1,239,126,55
CENTER=F27
STAT_STYLE=S6_1
[KEY7]
BACK_STYLE=134
FORE_STYLE=152
VIEW_RECT=636,239,162,55
CENTER=F4
[TIP1]
BACK_STYLE=134
FORE_STYLE=275
CENTER=F27
[TIP2]
FORE_STYLE=277
[TIP3]
FORE_STYLE=276
<file_sep>[INPUT]
[CAND]
LAYOUT_NAME=cand1
TYPE=4
[PANEL]
NO_BLUR=1
KEY_NUM=33
[MORE]
[HINT]
[KEY1]
BACK_STYLE=118
FORE_STYLE=243
VIEW_RECT=4,7,44,75
TOUCH_RECT=4,7,44,75
CENTER=1
[KEY2]
BACK_STYLE=118
FORE_STYLE=244
VIEW_RECT=51,7,44,75
TOUCH_RECT=51,7,44,75
CENTER=2
[KEY3]
BACK_STYLE=118
FORE_STYLE=245
VIEW_RECT=98,7,44,75
TOUCH_RECT=98,7,44,75
CENTER=3
[KEY4]
BACK_STYLE=118
FORE_STYLE=246
VIEW_RECT=145,7,44,75
TOUCH_RECT=145,7,44,75
CENTER=4
[KEY5]
BACK_STYLE=118
FORE_STYLE=247
VIEW_RECT=192,7,44,75
TOUCH_RECT=192,7,44,75
CENTER=5
[KEY6]
BACK_STYLE=118
FORE_STYLE=248
VIEW_RECT=239,7,44,75
TOUCH_RECT=239,7,44,75
CENTER=6
[KEY7]
BACK_STYLE=118
FORE_STYLE=249
VIEW_RECT=286,7,45,75
TOUCH_RECT=286,7,45,75
CENTER=7
[KEY8]
BACK_STYLE=118
FORE_STYLE=250
VIEW_RECT=334,7,45,75
TOUCH_RECT=334,7,45,75
CENTER=8
[KEY9]
BACK_STYLE=118
FORE_STYLE=251
VIEW_RECT=382,7,45,75
TOUCH_RECT=382,7,45,75
CENTER=9
[KEY10]
BACK_STYLE=118
FORE_STYLE=252
VIEW_RECT=430,7,44,75
TOUCH_RECT=430,7,44,75
CENTER=0
[KEY11]
BACK_STYLE=118
FORE_STYLE=231
VIEW_RECT=28,85,44,75
TOUCH_RECT=28,85,44,75
CENTER=!
[KEY12]
BACK_STYLE=118
FORE_STYLE=218
VIEW_RECT=75,85,44,75
TOUCH_RECT=75,85,44,75
CENTER=@
[KEY13]
BACK_STYLE=118
FORE_STYLE=219
VIEW_RECT=122,85,44,75
TOUCH_RECT=122,85,44,75
CENTER=#
[KEY14]
BACK_STYLE=118
FORE_STYLE=221
VIEW_RECT=169,85,44,75
TOUCH_RECT=169,85,44,75
CENTER=$
[KEY15]
BACK_STYLE=118
FORE_STYLE=222
VIEW_RECT=216,85,44,75
TOUCH_RECT=216,85,44,75
CENTER=%
[KEY16]
BACK_STYLE=118
FORE_STYLE=223
VIEW_RECT=264,85,45,75
TOUCH_RECT=264,85,45,75
CENTER=&
[KEY17]
BACK_STYLE=118
FORE_STYLE=220
VIEW_RECT=312,85,45,75
TOUCH_RECT=312,85,45,75
CENTER=*
[KEY18]
BACK_STYLE=118
FORE_STYLE=224
VIEW_RECT=360,85,45,75
TOUCH_RECT=360,85,45,75
CENTER=(
[KEY19]
BACK_STYLE=118
FORE_STYLE=225
VIEW_RECT=408,85,44,75
TOUCH_RECT=408,85,44,75
CENTER=)
[KEY20]
BACK_STYLE=118
FORE_STYLE=217
VIEW_RECT=57,163,44,75
TOUCH_RECT=57,163,44,75
CENTER=~
[KEY21]
BACK_STYLE=118
FORE_STYLE=230
VIEW_RECT=104,163,44,75
TOUCH_RECT=104,163,44,75
CENTER=/
[KEY22]
BACK_STYLE=118
FORE_STYLE=228
VIEW_RECT=151,163,44,75
TOUCH_RECT=151,163,44,75
CENTER=-
[KEY23]
BACK_STYLE=118
FORE_STYLE=229
VIEW_RECT=198,163,44,75
TOUCH_RECT=198,163,44,75
CENTER=_
[KEY24]
BACK_STYLE=118
FORE_STYLE=226
VIEW_RECT=245,163,45,75
TOUCH_RECT=245,163,45,75
CENTER=:
[KEY25]
BACK_STYLE=118
FORE_STYLE=227
VIEW_RECT=293,163,45,75
TOUCH_RECT=293,163,45,75
CENTER=;
[KEY26]
BACK_STYLE=118
FORE_STYLE=242
VIEW_RECT=341,163,45,75
TOUCH_RECT=341,163,45,75
CENTER=?
[KEY27]
BACK_STYLE=118
FORE_STYLE=125
VIEW_RECT=110,240,51,68
CENTER=,
[KEY28]
BACK_STYLE=118
FORE_STYLE=95
VIEW_RECT=164,240,152,68
CENTER=F38
[KEY29]
BACK_STYLE=118
FORE_STYLE=92
VIEW_RECT=319,240,51,68
CENTER=.
[KEY30]
BACK_STYLE=119
FORE_STYLE=260
VIEW_RECT=3,163,51,75
TOUCH_RECT=3,163,51,75
CENTER=F1
[KEY31]
BACK_STYLE=119
FORE_STYLE=299
VIEW_RECT=389,163,86,75
TOUCH_RECT=389,163,86,75
LEFT=F40
CENTER=F36
[KEY32]
BACK_STYLE=119
FORE_STYLE=152
VIEW_RECT=3,240,104,68
CENTER=F4
[KEY33]
BACK_STYLE=119
FORE_STYLE=300
VIEW_RECT=373,240,102,68
CENTER=F39
<file_sep>[INPUT]
[CAND]
[PANEL]
NO_BLUR=1
KEY_NUM=33
[MORE]
[HINT]
[KEY1]
BACK_STYLE=118
FORE_STYLE=243
VIEW_RECT=4,5,77,56
CENTER=1
[KEY2]
BACK_STYLE=118
FORE_STYLE=244
VIEW_RECT=83,5,77,56
CENTER=2
[KEY3]
BACK_STYLE=118
FORE_STYLE=245
VIEW_RECT=162,5,77,56
CENTER=3
[KEY4]
BACK_STYLE=118
FORE_STYLE=246
VIEW_RECT=241,5,77,56
CENTER=4
[KEY5]
BACK_STYLE=118
FORE_STYLE=247
VIEW_RECT=320,5,77,56
CENTER=5
[KEY6]
BACK_STYLE=118
FORE_STYLE=248
VIEW_RECT=399,5,77,56
CENTER=6
[KEY7]
BACK_STYLE=118
FORE_STYLE=249
VIEW_RECT=478,5,78,56
CENTER=7
[KEY8]
BACK_STYLE=118
FORE_STYLE=250
VIEW_RECT=558,5,78,56
CENTER=8
[KEY9]
BACK_STYLE=118
FORE_STYLE=251
VIEW_RECT=638,5,78,56
CENTER=9
[KEY10]
BACK_STYLE=118
FORE_STYLE=252
VIEW_RECT=718,5,77,56
CENTER=0
[KEY11]
BACK_STYLE=118
FORE_STYLE=231
VIEW_RECT=44,65,77,56
CENTER=!
[KEY12]
BACK_STYLE=118
FORE_STYLE=218
VIEW_RECT=123,65,77,56
CENTER=@
[KEY13]
BACK_STYLE=118
FORE_STYLE=219
VIEW_RECT=202,65,77,56
CENTER=#
[KEY14]
BACK_STYLE=118
FORE_STYLE=221
VIEW_RECT=281,65,77,56
CENTER=$
[KEY15]
BACK_STYLE=118
FORE_STYLE=222
VIEW_RECT=360,65,77,56
CENTER=%
[KEY16]
BACK_STYLE=118
FORE_STYLE=223
VIEW_RECT=439,65,78,56
CENTER=&
[KEY17]
BACK_STYLE=118
FORE_STYLE=220
VIEW_RECT=519,65,78,56
CENTER=*
[KEY18]
BACK_STYLE=118
FORE_STYLE=224
VIEW_RECT=599,65,78,56
CENTER=(
[KEY19]
BACK_STYLE=118
FORE_STYLE=225
VIEW_RECT=678,65,77,56
CENTER=)
[KEY20]
BACK_STYLE=118
FORE_STYLE=217
VIEW_RECT=82,126,77,56
CENTER=~
[KEY21]
BACK_STYLE=118
FORE_STYLE=230
VIEW_RECT=162,126,77,56
CENTER=/
[KEY22]
BACK_STYLE=118
FORE_STYLE=228
VIEW_RECT=240,126,77,56
CENTER=-
[KEY23]
BACK_STYLE=118
FORE_STYLE=229
VIEW_RECT=319,126,77,56
CENTER=_
[KEY24]
BACK_STYLE=118
FORE_STYLE=226
VIEW_RECT=399,126,78,56
CENTER=:
[KEY25]
BACK_STYLE=118
FORE_STYLE=227
VIEW_RECT=479,126,78,56
CENTER=;
[KEY26]
BACK_STYLE=118
FORE_STYLE=242
VIEW_RECT=559,126,78,56
CENTER=?
[KEY27]
BACK_STYLE=118
FORE_STYLE=125
VIEW_RECT=184,187,88,53
CENTER=,
[KEY28]
BACK_STYLE=118
FORE_STYLE=426
VIEW_RECT=274,187,251,53
CENTER=F38
[KEY29]
BACK_STYLE=118
FORE_STYLE=92
VIEW_RECT=527,187,88,53
CENTER=.
[KEY30]
BACK_STYLE=119
FORE_STYLE=510
VIEW_RECT=4,126,76,56
CENTER=F1
[KEY31]
BACK_STYLE=119
FORE_STYLE=415
VIEW_RECT=638,126,157,56
LEFT=F40
CENTER=F36
[KEY32]
BACK_STYLE=119
FORE_STYLE=503
VIEW_RECT=4,187,178,53
CENTER=F4
[KEY33]
BACK_STYLE=119
FORE_STYLE=416
VIEW_RECT=617,187,178,53
CENTER=F39
<file_sep>[INPUT]
[CAND]
VIEW_RECT=0,0,480,61
TYPE=1
[PANEL]
NO_BLUR=1
KEY_NUM=37
TIP_NUM=1
SIZE=480,371
[MORE]
GRID=5,2
LAYOUT_NAME=sel_en
[HINT]
LAYOUT_NAME=hint1
[LIST]
BACK_STYLE=121
CELL_STYLE=120
FORE_STYLE=130
CELL_SIZE=60,61
POS=0,0
TYPE=0
LIST_NUM=8
LIST_ORDER=1
NAMES=, 。 ? ! ~
VALUES=, 。 ? ! ~
PADDING=2,0,2,0
[KEY1]
BACK_STYLE=118
FORE_STYLE=337
VIEW_RECT=5,65,44,75
TOUCH_RECT=5,65,44,75
UP=1
DOWN=!
CENTER=F41
[KEY2]
BACK_STYLE=118
FORE_STYLE=520
VIEW_RECT=52,65,44,75
TOUCH_RECT=52,65,44,75
UP=2
DOWN=@
CENTER=z
[KEY3]
BACK_STYLE=118
FORE_STYLE=340
VIEW_RECT=99,65,44,75
TOUCH_RECT=99,65,44,75
UP=3
DOWN=#
CENTER=b
[KEY4]
BACK_STYLE=118
FORE_STYLE=338
VIEW_RECT=146,65,44,75
TOUCH_RECT=146,65,44,75
UP=4
DOWN=$
CENTER=m
[KEY5]
BACK_STYLE=118
FORE_STYLE=531
VIEW_RECT=193,65,44,75
TOUCH_RECT=193,65,44,75
UP=5
CENTER=d
[KEY6]
BACK_STYLE=118
FORE_STYLE=524
VIEW_RECT=240,65,44,75
TOUCH_RECT=240,65,44,75
UP=6
DOWN=^
CENTER=n
[KEY7]
BACK_STYLE=118
FORE_STYLE=521
VIEW_RECT=287,65,45,75
TOUCH_RECT=287,65,45,75
UP=7
CENTER=i
[KEY8]
BACK_STYLE=118
FORE_STYLE=343
VIEW_RECT=335,65,45,75
TOUCH_RECT=335,65,45,75
UP=8
CENTER=c
[KEY9]
BACK_STYLE=118
FORE_STYLE=346
VIEW_RECT=383,65,45,75
TOUCH_RECT=383,65,45,75
UP=9
DOWN=F8
CENTER=g
[KEY10]
BACK_STYLE=118
FORE_STYLE=367
VIEW_RECT=431,65,44,75
TOUCH_RECT=431,65,44,75
UP=0
DOWN=F8
CENTER=k
[KEY11]
BACK_STYLE=118
FORE_STYLE=518
VIEW_RECT=5,143,44,75
TOUCH_RECT=5,143,44,75
UP=+
CENTER=j
[KEY12]
BACK_STYLE=118
FORE_STYLE=519
VIEW_RECT=52,143,44,75
TOUCH_RECT=52,143,44,75
UP=-
CENTER=x
[KEY13]
BACK_STYLE=118
FORE_STYLE=523
VIEW_RECT=99,143,44,75
TOUCH_RECT=99,143,44,75
UP=*
CENTER=y
[KEY14]
BACK_STYLE=118
FORE_STYLE=341
VIEW_RECT=146,143,44,75
TOUCH_RECT=146,143,44,75
UP=/
DOWN=%
CENTER=l
[KEY15]
BACK_STYLE=118
FORE_STYLE=522
VIEW_RECT=193,143,44,75
TOUCH_RECT=193,143,44,75
UP=<
DOWN=>
CENTER=a
[KEY16]
BACK_STYLE=118
FORE_STYLE=342
VIEW_RECT=240,143,45,75
TOUCH_RECT=240,143,45,75
UP="
DOWN='
CENTER=e
[KEY17]
BACK_STYLE=118
FORE_STYLE=536
VIEW_RECT=287,143,45,75
TOUCH_RECT=287,143,45,75
UP=[
DOWN=]
CENTER=t
[KEY18]
BACK_STYLE=118
FORE_STYLE=339
VIEW_RECT=335,143,45,75
TOUCH_RECT=335,143,45,75
UP={
DOWN=}
CENTER=h
[KEY19]
BACK_STYLE=118
FORE_STYLE=345
VIEW_RECT=383,143,44,75
TOUCH_RECT=383,143,44,75
UP=(
DOWN=)
CENTER=w
[KEY37]
BACK_STYLE=118
FORE_STYLE=344
VIEW_RECT=431,143,44,75
TOUCH_RECT=431,143,44,75
UP==
CENTER=v
[KEY20]
BACK_STYLE=118
FORE_STYLE=527
VIEW_RECT=58,221,44,75
TOUCH_RECT=58,221,44,75
CENTER=q
[KEY21]
BACK_STYLE=118
FORE_STYLE=528
VIEW_RECT=105,221,44,75
TOUCH_RECT=105,221,44,75
CENTER=p
[KEY22]
BACK_STYLE=118
FORE_STYLE=533
VIEW_RECT=152,221,44,75
TOUCH_RECT=152,221,44,75
UP=&
DOWN=|
CENTER=u
[KEY23]
BACK_STYLE=118
FORE_STYLE=529
VIEW_RECT=199,221,44,75
TOUCH_RECT=199,221,44,75
UP=?
DOWN=:
CENTER=s
[KEY24]
BACK_STYLE=118
FORE_STYLE=530
VIEW_RECT=246,221,45,75
TOUCH_RECT=246,221,45,75
UP=_
CENTER=r
[KEY25]
BACK_STYLE=118
FORE_STYLE=525
VIEW_RECT=294,221,45,75
TOUCH_RECT=294,221,45,75
UP=\
CENTER=o
[KEY26]
BACK_STYLE=118
FORE_STYLE=537
VIEW_RECT=342,221,45,75
TOUCH_RECT=342,221,45,75
UP=;
CENTER=f
[KEY27]
BACK_STYLE=119
FORE_STYLE=556,558
POS_TYPE=1,2
VIEW_RECT=111,298,51,68
CENTER=F51
UP=F49
[KEY28]
BACK_STYLE=118
FORE_STYLE=95
VIEW_RECT=165,298,115,68
LEFT=F51
RIGHT=F52
CENTER=F38
[KEY29]
BACK_STYLE=119
FORE_STYLE=557,559
POS_TYPE=1,2
VIEW_RECT=283,298,51,68
UP=F50
CENTER=F52
[KEY30]
BACK_STYLE=119
FORE_STYLE=315
VIEW_RECT=4,221,51,75
TOUCH_RECT=4,221,51,75
CENTER=F10
[KEY31]
BACK_STYLE=119
FORE_STYLE=299,565,567
POS_TYPE=0,2,3
VIEW_RECT=390,221,86,75
TOUCH_RECT=390,221,86,75
LEFT=F40
CENTER=F36
UP=F42
DOWN=F43
[KEY32]
BACK_STYLE=119
FORE_STYLE=302,104
POS_TYPE=1,2
VIEW_RECT=4,298,51,68
CENTER=Z+num_26_1
UP=F1
RIGHT=F7
HOLD=F7
[KEY33]
BACK_STYLE=119
FORE_STYLE=316,109
POS_TYPE=1,2
VIEW_RECT=58,298,50,68
UP=F25
CENTER=F15
STAT_STYLE=S3_1
[KEY34]
BACK_STYLE=118
VIEW_RECT=336,298,51,68
FORE_STYLE=94
UP=,
CENTER=.
[KEY35]
BACK_STYLE=119
FORE_STYLE=300
VIEW_RECT=390,298,86,68
CENTER=F39
[KEY36]
BACK_STYLE=91
FORE_STYLE=107
CENTER=F8
VIEW_RECT=382,65,94,76
TOUCH_RECT=0,0,0,0
[TIP1]
BACK_STYLE=119
FORE_STYLE=316,110
POS_TYPE=1,2
CENTER=F15
UP=F25
<file_sep>[INPUT]
[CAND]
[PANEL]
NO_BLUR=1
KEY_NUM=35
[MORE]
[HINT]
[KEY1]
BACK_STYLE=118
FORE_STYLE=427
VIEW_RECT=6,4,77,53
UP=1
CENTER=q
[KEY2]
BACK_STYLE=118
FORE_STYLE=455
VIEW_RECT=85,4,77,53
UP=2
CENTER=w
[KEY3]
BACK_STYLE=118
FORE_STYLE=456
VIEW_RECT=164,4,77,53
UP=3
CENTER=e
[KEY4]
BACK_STYLE=118
FORE_STYLE=457
VIEW_RECT=243,4,77,53
UP=4
CENTER=r
[KEY5]
BACK_STYLE=118
FORE_STYLE=458
VIEW_RECT=322,4,77,53
UP=5
CENTER=t
[KEY6]
BACK_STYLE=118
FORE_STYLE=459
VIEW_RECT=401,4,77,53
UP=6
CENTER=y
[KEY7]
BACK_STYLE=118
FORE_STYLE=460
VIEW_RECT=480,4,77,53
UP=7
CENTER=u
[KEY8]
BACK_STYLE=118
FORE_STYLE=461
VIEW_RECT=559,4,77,53
UP=8
CENTER=i
[KEY9]
BACK_STYLE=118
FORE_STYLE=462
VIEW_RECT=638,4,77,53
UP=9
CENTER=o
[KEY10]
BACK_STYLE=118
FORE_STYLE=463
VIEW_RECT=717,4,77,53
UP=0
CENTER=p
[KEY11]
BACK_STYLE=118
FORE_STYLE=464
VIEW_RECT=45,64,77,53
UP=!
LEFT=!
RIGHT=!
CENTER=a
[KEY12]
BACK_STYLE=118
FORE_STYLE=465
VIEW_RECT=124,64,77,53
UP=@
LEFT=@
RIGHT=@
CENTER=s
[KEY13]
BACK_STYLE=118
FORE_STYLE=466
VIEW_RECT=203,64,77,53
UP=#
LEFT=#
RIGHT=#
CENTER=d
[KEY14]
BACK_STYLE=118
FORE_STYLE=467
VIEW_RECT=282,64,77,53
UP=$
LEFT=$
RIGHT=$
CENTER=f
[KEY15]
BACK_STYLE=118
FORE_STYLE=468
VIEW_RECT=361,64,77,53
UP=%
LEFT=%
RIGHT=%
CENTER=g
[KEY16]
BACK_STYLE=118
FORE_STYLE=469
VIEW_RECT=440,64,78,53
UP=&
LEFT=&
RIGHT=&
CENTER=h
[KEY17]
BACK_STYLE=118
FORE_STYLE=470
VIEW_RECT=520,64,78,53
UP=*
LEFT=*
RIGHT=*
CENTER=j
[KEY18]
BACK_STYLE=118
FORE_STYLE=471
VIEW_RECT=600,64,78,53
UP=(
LEFT=(
RIGHT=(
CENTER=k
[KEY19]
BACK_STYLE=118
FORE_STYLE=472
VIEW_RECT=680,64,77,53
UP=)
LEFT=)
RIGHT=)
CENTER=l
[KEY20]
BACK_STYLE=118
FORE_STYLE=473
VIEW_RECT=96,124,77,53
UP=~
LEFT=~
RIGHT=~
CENTER=z
[KEY21]
BACK_STYLE=118
FORE_STYLE=474
VIEW_RECT=175,124,77,53
UP=/
LEFT=/
RIGHT=/
CENTER=x
[KEY22]
BACK_STYLE=118
FORE_STYLE=475
VIEW_RECT=254,124,77,53
UP=-
LEFT=-
RIGHT=-
CENTER=c
[KEY23]
BACK_STYLE=118
FORE_STYLE=476
VIEW_RECT=333,124,77,53
UP=_
LEFT=_
RIGHT=_
CENTER=v
[KEY24]
BACK_STYLE=118
FORE_STYLE=477
VIEW_RECT=412,124,77,53
UP=:
LEFT=:
RIGHT=:
CENTER=b
[KEY25]
BACK_STYLE=118
FORE_STYLE=478
VIEW_RECT=491,124,77,53
UP=;
LEFT=;
RIGHT=;
CENTER=n
[KEY26]
BACK_STYLE=118
FORE_STYLE=479
VIEW_RECT=570,124,77,53
UP=?
LEFT=?
RIGHT=?
CENTER=m
[KEY27]
BACK_STYLE=118
FORE_STYLE=507
VIEW_RECT=186,184,88,53
UP=!
CENTER=,
[KEY28]
BACK_STYLE=118
FORE_STYLE=504
VIEW_RECT=276,184,248,53
CENTER=F38
[KEY29]
BACK_STYLE=118
FORE_STYLE=508
VIEW_RECT=526,184,88,53
UP=?
CENTER=。
[KEY30]
BACK_STYLE=119
FORE_STYLE=481
VIEW_RECT=6,124,88,53
CENTER='
[KEY31]
BACK_STYLE=119
FORE_STYLE=415
VIEW_RECT=649,124,145,53
LEFT=F40
CENTER=F36
[KEY32]
BACK_STYLE=119
FORE_STYLE=418
VIEW_RECT=6,184,88,53
CENTER=F6
[KEY33]
BACK_STYLE=119
FORE_STYLE=413
VIEW_RECT=96,184,88,53
UP=F16
CENTER=F16
[KEY34]
BACK_STYLE=119
FORE_STYLE=510
VIEW_RECT=616,184,88,53
UP=F7
CENTER=F1
HOLD=F7
[KEY35]
BACK_STYLE=119
FORE_STYLE=416
VIEW_RECT=706,184,88,53
CENTER=F39
<file_sep>[INPUT]
[CAND]
VIEW_RECT=0,0,480,60
LAYOUT_NAME=cand2
TYPE=4
[PANEL]
BACK_STYLE=116
SIZE=480,156
NO_BLUR=1
KEY_NUM=10
[MORE]
[HINT]
[LIST]
BACK_STYLE=117
CELL_STYLE=132
FORE_STYLE=129
CELL_SIZE=80,60
TYPE=2
LIST_NUM=6
[KEY1]
BACK_STYLE=118
FORE_STYLE=389
VIEW_RECT=5,6,84,71
CENTER=,
[KEY2]
BACK_STYLE=118
FORE_STYLE=390
VIEW_RECT=94,6,84,71
CENTER=。
[KEY3]
BACK_STYLE=118
FORE_STYLE=391
VIEW_RECT=183,6,84,71
CENTER=?
[KEY4]
BACK_STYLE=118
FORE_STYLE=392
VIEW_RECT=272,6,84,71
CENTER=!
[KEY5]
BACK_STYLE=119
FORE_STYLE=299
VIEW_RECT=361,6,114,71
LEFT=F40
CENTER=F36
[KEY6]
BACK_STYLE=119
FORE_STYLE=302
VIEW_RECT=5,83,84,68
CENTER=F6
[KEY7]
BACK_STYLE=119
FORE_STYLE=304
VIEW_RECT=94,83,84,68
UP=F16
CENTER=F16
[KEY8]
BACK_STYLE=119
FORE_STYLE=104
VIEW_RECT=183,83,84,68
UP=F7
CENTER=F1
HOLD=F7
[KEY9]
BACK_STYLE=118
FORE_STYLE=95
VIEW_RECT=272,83,115,68
CENTER=F38
[KEY10]
BACK_STYLE=119
FORE_STYLE=300
VIEW_RECT=392,83,84,68
CENTER=F39
| 4cc7a08a86cd2a888e43b02ef5ca6a8355dccdb1 | [
"Markdown",
"INI"
] | 28 | Markdown | chougousui/my_baidu_input_skin | ca7c6933042a3b291c9d77a42a31d57cdc6a88d4 | d73bc49653755cbd988537ae78d81fb164d890dd |
refs/heads/master | <file_sep>package bol.bconnex.settlement.action.authen;
import java.util.Date;
import java.util.List;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import bol.bconnex.settlement.business.service.SettleTxnService;
import bol.bconnex.settlement.data.entity.SettleTxn;
import com.opensymphony.xwork2.ActionSupport;
@Controller
@Namespace("/authenticated/check")
@ResultPath(value="/")
public class SwiftSettlementCheckAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
@Autowired
private SettleTxnService settleTxnService;
private Date date;
private List<SettleTxn> settleTxns;
public void setDate(Date date){
this.date = date;
}
public List<SettleTxn> getSettleTxns(){
return settleTxns;
}
public void setSettleTxnService(SettleTxnService settleTxnService){
this.settleTxnService = settleTxnService;
}
@Action(value="checkResult",results={
@Result(name="success", location="resultFetch.jsp"),
})
public String execute() throws Exception{
java.sql.Date sdate = new java.sql.Date(date.getTime());
settleTxns = settleTxnService.getSettleTxns(sdate);
return SUCCESS;
}
}
<file_sep>package bol.bconnex.settlement.data.dao;
import java.util.Arrays;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import bol.bconnex.settlement.data.entity.Account;
@Repository("AccountDao")
public class AccountDaoImp implements AccountDao {
private HibernateTemplate hibernateTemplate;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory){
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
@Override
public List<Account> getAccounts() {
String hql = "from Account";
return toList(hibernateTemplate.find(hql));
}
@Override
public List<Account> getAccountsNotEqual(String bic) {
String hql = "from Account a where a.bic != :bic";
String paramName = "bic";
String value = bic;
return toList(hibernateTemplate.findByNamedParam(hql, paramName, value));
}
@Override
public Account getAccount(String bic) {
String hql = "from Account a where a.bic = :bic";
String paramName = "bic";
Account account =toList(hibernateTemplate.findByNamedParam(hql, paramName, bic)).get(0);
return account;
}
private List<Account> toList(final List<?> beans){
if(beans==null) return null;
if(beans.isEmpty()) return null;
int size = beans.size();
Account[] list = new Account[size];
list = beans.toArray(list);
return Arrays.asList(list);
}
}
<file_sep><?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Settlement Page</title>
</head>
<body>
<h3>
<a href="/BOLRGTS/authenticated/welcome.jsp">Home</a>
</h3>
<h1>Settlement Detail</h1>
<table>
<s:iterator value="accounts" status="stat">
<tr>
<td><s:property value="%{#stat.count}"/></td>
<td><s:property value="name"/></td>
<td><s:property value="shortName"/></td>
<td><s:property value="account"/></td>
<td><s:property value="bic"/></td>
<td>
<s:text name="format.money">
<s:param name="value" value="amount"/>
</s:text>
</td>
<td>
<s:url action="download.action" var="urlTag">
<s:param name="name">
<s:property value="%{shortName}"/>
</s:param>
</s:url>
<s:a href="%{urlTag}">download</s:a>
</td>
</tr>
</s:iterator>
</table>
<p/>
<s:form action="/authenticated/upload/confirm.action" method="POST">
<s:submit value="confirm"/>
</s:form>
</body>
</html><file_sep>package bol.bconnex.settlement.business.service;
import bol.bconnex.settlement.data.entity.User;
public interface UserService {
public boolean checkUser(User usr);
}
<file_sep>package bol.bconnex.settlement.action.authen;
import java.io.File;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import bol.bconnex.settlement.business.service.FtpAccessService;
import bol.bconnex.settlement.business.util.UtilityService;
import com.opensymphony.xwork2.ActionSupport;
@Controller
@Namespace("/authenticated/upload")
@ResultPath(value="/")
public class SwiftFileUploadAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
@Autowired
private FtpAccessService ftpAccessService;
public void setFtpAccessService(FtpAccessService ftpAccessService){
this.ftpAccessService = ftpAccessService;
}
@Action(value="confirm",results={
@Result(name="success",location="success.jsp"),
@Result(name="error",location="error.jsp")
})
public String execute() throws Exception{
String path = ServletActionContext.getServletContext().getRealPath("/swift");
String dir = path+"/"+UtilityService.backStrDate();
File directory = new File(dir);
File[] files = directory.listFiles();
for(int i=0;i<files.length;i++){
File file = files[i];
ftpAccessService.swiftUpload(file);
}
return SUCCESS;
}
}
<file_sep>package bol.bconnex.settlement.data.dao;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.jdbc.Work;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import bol.bconnex.settlement.business.util.UtilityService;
import bol.bconnex.settlement.data.entity.Settlement;
@Repository("settlementDao")
public class SettlementDaoImp implements SettlementDao {
private HibernateTemplate hibernateTemplate;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory){
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
@Transactional
@Override
public void save(Settlement settlement) {
hibernateTemplate.save(settlement);
}
@Override
public List<Settlement> getSettlement(Date settleDate) {
String hql = "from Settlement s where s.settleDate = :settleDate";
String paramName = "settleDate";
return toList(hibernateTemplate.findByNamedParam(hql, paramName, settleDate));
}
@Override
public List<Settlement> getSettlement(String rrn) {
String hql = "from Settlement s where s.rrn = :rrn";
String paramName = "rrn";
return toList(hibernateTemplate.findByNamedParam(hql,paramName,rrn));
}
@Override
public String getLastSettleDate() {
LastSettleDateCallback action = new LastSettleDateCallback();
return (String )hibernateTemplate.execute(action);
}
private class LastSettleDateCallback implements HibernateCallback<String>{
@Override
public String doInHibernate(Session session) throws HibernateException,
SQLException {
LastSettleDateWork work = new LastSettleDateWork();
session.doWork(work);
return work.getLastSettleDate();
}
private class LastSettleDateWork implements Work{
private Date lastSettleDate;
@Override
public void execute(Connection conn) throws SQLException {
String sql = "SELECT MAX(SETTLEDATE) AS SETTLEDATE FROM SETTLEMENT_TXN ORDER BY SETTLEDATE DESC;";
PreparedStatement stat = conn.prepareStatement(sql);
ResultSet rs = stat.executeQuery();
while(rs.next()){
this.lastSettleDate = rs.getDate("SETTLEDATE");
}
}
public String getLastSettleDate(){
return UtilityService.dateToStr(this.lastSettleDate);
}
}
}
private List<Settlement> toList(final List<?> beans){
if(beans == null) return null;
if(beans.isEmpty()) return null;
int size = beans.size();
Settlement[] list = new Settlement[size];
list = beans.toArray(list);
return Arrays.asList(list);
}
}
<file_sep>package bol.bconnex.settlement.data.entity;
import java.io.Serializable;
import java.sql.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="USERS")
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@Column(name="USRID")
private String usrId;
@Column(name="PASSWD")
private String passwd;
@Column(name="NAME")
private String name;
@Column(name="SURNAME")
private String surname;
@Column(name="TEL")
private String tel;
@Column(name="BIRTH")
private Date birth;
@Column(name="ENABLE")
private String enable;
@OneToMany
private List<Role> roles;
public String getUsrId() {
return usrId;
}
public void setUsrId(String usrId) {
this.usrId = usrId;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String getEnable() {
return enable;
}
public void setEnable(String enable) {
this.enable = enable;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
<file_sep>package bol.bconnex.settlement.data.dao;
public interface RoleDao {
}
<file_sep>package bol.bconnex.settlement.business.listener;
public interface SwiftResponseWork {
public void swiftResCheck();
}
<file_sep>package bol.bconnex.settlement.data.dao;
import java.sql.Date;
import java.util.List;
import bol.bconnex.settlement.data.entity.Settlement;
public interface SettlementDao {
public void save(Settlement settlement);
public List<Settlement> getSettlement(Date settleDate);
public List<Settlement> getSettlement(String rrn);
public String getLastSettleDate();
}
<file_sep>package bol.bconnex.settlement.logon.action;
import java.util.List;
import bol.bconnex.settlement.data.entity.Member;
import bol.bconnex.settlement.data.entity.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class LogOnAction extends ActionSupport implements ModelDriven<User> {
private static final long serialVersionUID = 1L;
private User user;
private List<Member> members;
public void setUser(User user){
this.user = user;
}
@Override
public User getModel() {
return user;
}
public String execute() throws Exception{
return null;
}
}
<file_sep>package bol.bconnex.settlement.data.dao;
import java.util.List;
import bol.bconnex.settlement.data.entity.Account;
public interface AccountDao {
public List<Account> getAccounts();
public List<Account> getAccountsNotEqual(String bic);
public Account getAccount(String bic);
}
<file_sep>package bol.bconnex.settlment.file.generator;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import bol.bconnex.settlement.data.entity.Member;
public class SwiftCodeGeneratorImp implements SwiftCodeGenerator {
private String filePath;
private String source;
private String destinate;
@Override
public void generateSwift(List<Member> members, File file) throws IOException {
for (Member member : members){
String fileName = filePath+member.getName();
}
}
private void swiftTemplate(Member member, File file){
String header = "{1:F01COEBLALAAATM}{2:I202LPDRLALAXRTGN}{3:{113:0010}{108:PARTICIPANT}}{4:";
String body = ":20:";
String body1 = ":21:NONREF";
String body2 = ":32A:";
String body3 = ":53A:/D/";
String body4 = null;
String body5 = ":58A:/";
String body6 = null;
String body7 = ":72:/CODTYPTR/001";
String body8 = "/BNF/Bconnex Net Settlment";
String body9 = "-}";
String backDate = backDate();
}
private String backDate() {
DateFormat dateFormat = new SimpleDateFormat("yyMMdd");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return dateFormat.format(cal.getTime());
}
}
<file_sep>package bol.bconnex.settlement.data.dao;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import bol.bconnex.settlement.data.entity.SettleTxn;
@Repository("settleTransactionDaoImp")
public class SettleTxnDaoImp implements SettleTxnDao {
private HibernateTemplate hibernateTemplate;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory){
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
@Transactional
@Override
public void save(SettleTxn settle) {
hibernateTemplate.save(settle);
}
@Override
public SettleTxn getSettleTxn(String rrn) {
String hql = "from SettleTransaction st where st.rrn= :rrn";
String paramName = "rrn";
return toList(hibernateTemplate.findByNamedParam(hql, paramName, rrn)).get(0);
}
private List<SettleTxn> toList(final List<?> beans){
if(beans==null) return null;
if(beans.isEmpty()) return null;
int size = beans.size();
SettleTxn[] list = new SettleTxn[size];
list = beans.toArray(list);
return Arrays.asList(list);
}
@Override
public void update(SettleTxn settle) {
hibernateTemplate.update(settle);
}
@Override
public List<String> getFileNames() {
FileNameListCallback action = new FileNameListCallback();
return hibernateTemplate.execute(action);
}
private class FileNameListCallback implements HibernateCallback<List<String>>{
@SuppressWarnings({ "unchecked", "deprecation" })
@Override
public List<String> doInHibernate(Session session) throws HibernateException,
SQLException {
String sql = "SELECT SWIFTNAME AS SWFNAME FROM TXN_DETAIL";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.addScalar("SWFNAME", Hibernate.STRING);
return sqlQuery.list();
}
}
@Override
public List<SettleTxn> getSettleTxn(Date date) {
String hql = "from SettleTxn s where s.sysDate = :sysDate order by s.id";
String paramName = "sysDate";
return toList(hibernateTemplate.findByNamedParam(hql, paramName, date));
}
}
<file_sep>package bol.bconnex.settlement.business.service;
import java.io.IOException;
import bol.bconnex.settlement.data.entity.Account;
import bol.bconnex.settlement.data.entity.Settlement;
public interface SwiftSettlementService {
public void setPath(String path);
public void setLastSettleDate(String lastSettleDate);
public void swiftFileOutPut(Settlement from, Settlement to,String name) throws Exception;
public void accountSettlement(Settlement bolSettle, Account account, String name)
throws Exception;
public void swiftReadOutput() throws IOException;
}
<file_sep>package bol.bconnex.settlement.data.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.jdbc.Work;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import bol.bconnex.settlement.data.entity.User;
@Repository("userDao")
public class UserDaoImp implements UserDao {
private HibernateTemplate hibernateTemplate;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory){
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
@Override
public boolean authen(User usr) {
UserInnerAction action = new UserInnerAction(usr);
int count = (int) hibernateTemplate.execute(action);
return count > 0 ? true : false;
}
// private class for user check
private class UserInnerAction implements HibernateCallback<Integer>{
private User user;
public UserInnerAction(User user){
this.user = user;
}
@Override
public Integer doInHibernate(Session session) throws HibernateException,
SQLException {
UsrInnerWork work = new UsrInnerWork(user);
session.doWork(work);
return work.getNum();
}
}
private class UsrInnerWork implements Work{
private User usr;
private int num;
public UsrInnerWork(User usr){
this.usr = usr;
}
public int getNum(){
return num;
}
@Override
public void execute(Connection conn) throws SQLException {
//String sql = "SELECT COUNT(*) AS NUM FROM USERS WHERE USRID = ? AND PASSWD = SHA1(?)";
String sql = "SELECT COUNT(*) AS NUM FROM USERS WHERE USRID = ? AND PASSWD = <PASSWORD>(?)";
PreparedStatement stat = conn.prepareStatement(sql);
stat.setString(1, usr.getUsrId());
stat.setString(2, usr.getPasswd());
ResultSet ret = stat.executeQuery();
num = 0;
while(ret.next()){
num = ret.getInt("NUM");
}
}
}
}
<file_sep>package bol.bconnex.settlement.business.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import jxl.common.Logger;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FtpAccessServiceImp implements FtpAccessService {
private static final Logger logger = Logger.getLogger(FtpAccessServiceImp.class);
private FTPClient ftpClient;
private String host;
private String user;
private String passwd;
private String in;
private String out;
public FtpAccessServiceImp(FTPClient ftpClient, String host, String user, String passwd, String in, String out){
this.ftpClient = ftpClient;
this.host = host;
this.user = user;
this.passwd = <PASSWORD>;
this.in = in;
this.out = out;
}
@Override
public void swiftUpload(File file) {
FileInputStream fis = null;
try {
ftpClient.connect(host);
ftpClient.login(user, passwd);
ftpClient.pasv();
String source = file.getPath();
fis = new FileInputStream(source);
String dest = in+"/"+file.getName();
// Store file to server
ftpClient.storeFile(dest, fis);
ftpClient.logout();
} catch (IOException e) {
logger.debug("IOException throws for ftp access", e);
} finally {
try {
if (fis != null) {
fis.close();
}
ftpClient.disconnect();
} catch (IOException e) {
logger.debug("IOException throws for ftp access", e);
}
}
}
@Override
public List<String> swiftDownload(List<String> names, String path) {
try{
ftpClient.connect(host);
ftpClient.login(user, passwd);
ftpClient.pasv();
FTPFile[] files = ftpClient.listFiles(out);
List<String> list = new ArrayList<String>();
if (files != null && files.length > 0) {
for (FTPFile file : files) {
if (!file.isFile()) {
continue;
}
String fileName = file.getName();
boolean check = true;
for(String name : names){
if(fileName.equals(name)){
check = false;
break;
}
}
if(check){
// local file
String localPath = path+"/"+fileName;
OutputStream outStream = new FileOutputStream(localPath);
String remotePath = out+"/"+fileName;
ftpClient.retrieveFile(remotePath, outStream);
outStream.close();
list.add(localPath);
}
}
}
ftpClient.logout();
ftpClient.disconnect();
return list;
}
catch(IOException ex){
logger.debug("IOException throws for ftp access", ex);
return null;
}
}
}
<file_sep><?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8" session="false"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Log On Successful</title>
</head>
<body>
<h2>Welcome</h2>
<h3>Settlement Amount</h3>
<div id="main-menu">
<ul>
<li>
<a href="settlement/settleMenu.action"> PROCESS SETTLE </a>
</li>
<li>
<a href="check/checking.jsp"> CHECK PROCESS </a>
</li>
</ul>
</div>
</body>
</html><file_sep>package bol.bconnex.settlement.action.authen;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import bol.bconnex.settlement.business.service.AccountService;
import bol.bconnex.settlement.business.service.UserService;
import bol.bconnex.settlement.data.entity.Account;
import bol.bconnex.settlement.data.entity.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@Controller
@Namespace("/authenticated")
@ResultPath(value="/")
public class LogOnAction extends ActionSupport implements ModelDriven<User> {
private static final long serialVersionUID = 1L;
@Autowired
private AccountService accountService;
@Autowired
private UserService userService;
private User user;
private List<Account> accounts;
public void setAccountService(AccountService accountService){
this.accountService = accountService;
}
public void setUserService(UserService userService){
this.userService = userService;
}
public void setUser(User user){
this.user = user;
}
public User getUser(){
return this.user;
}
public void setAccounts(List<Account> members){
this.accounts = members;
}
public List<Account> getAccounts(){
return accounts;
}
@Override
public User getModel() {
return user;
}
@Action(value="logon", results={
@Result(name="success",location="welcome.jsp"),
@Result(name="error",location="/logon.jsp",type="redirect")
})
public String execute() throws Exception{
HttpSession session = ServletActionContext.getRequest().getSession(true);
boolean check = userService.checkUser(user);
session.setAttribute("user", user);
return check ? SUCCESS : ERROR;
}
}
| c42545c2d2fa30ea33b18b9fd6e5a284e227dfb7 | [
"Java",
"Java Server Pages"
] | 19 | Java | i0712326/BCNXSETL | 5ce20e611c3fd2b7823f2ab6d156e53042a10531 | 7a45cce3d4082c08de962690f19e5ab136aac922 |