branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep># workReporter
工作报告生成
<file_sep>package com.adj.workreporter.worker;
import com.adj.workreporter.Constants;
import com.adj.workreporter.model.Work;
import com.adj.workreporter.service.WorkService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.sql.SQLException;
import java.time.Instant;
/**
* 每日工作内容入库
* Created by dhx on 2017/4/11.
*/
public class DailyGatherWorker {
private Logger logger = LoggerFactory.getLogger(DailyGatherWorker.class);
private WorkService workService = new WorkService();
public void gather() throws SQLException, IOException {
File dailyFile = new File(Constants.DAILY_WORKS_DATA_URL);
if (!dailyFile.exists()) {
logger.debug("文件不存在 url: " + dailyFile.toURI());
dailyFile.createNewFile();
return;
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(dailyFile), "UTF8"))) {
String line = br.readLine();
while (line != null) {
line = line.trim();
if (line.length() != 0) {
logger.debug("工作内容: " + line);
Work work = new Work(Instant.now().getEpochSecond(), line);
workService.saveWork(work);
}
line = br.readLine();
}
}
try (PrintWriter writer = new PrintWriter(dailyFile)) {
writer.print("");
}
}
}
<file_sep>package com.adj.workreporter.service;
import com.adj.workreporter.model.DayWorks;
import com.adj.workreporter.model.Work;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.time.Instant;
/**
* test
* Created by dhx on 2017/4/10.
*/
public class WorkServiceTest {
private WorkService fileService;
@Before
public void setUp() throws Exception {
fileService = new WorkService();
}
@After
public void tearDown() throws Exception {
}
@Test
public void saveDayWorks() throws Exception {
DayWorks dayWorks = new DayWorks();
Work work1 = new Work(Instant.now().getEpochSecond(), "第一个work");
Work work2 = new Work(Instant.now().getEpochSecond() + 1000, "第二个work");
dayWorks.getWorks().add(work1);
dayWorks.getWorks().add(work2);
}
}<file_sep>package com.adj.workreporter.util;
import java.time.*;
/**
* 日期时间工具
* Created by dhx on 2017/4/13.
*/
public class DateTimeUtil {
public static long getWeekStartEpochSecond(long someMoment) {
ZonedDateTime dateTime = ZonedDateTime.ofInstant(Instant.ofEpochSecond(someMoment), ZoneId.systemDefault());
LocalDateTime weekBegin = dateTime.with(DayOfWeek.MONDAY).toLocalDateTime().with(LocalTime.MIN);
return weekBegin.toEpochSecond(ZoneId.systemDefault().getRules().getOffset(weekBegin));
}
public static long getWeekEndEpochSecond(long someMoment) {
ZonedDateTime dateTime = ZonedDateTime.ofInstant(Instant.ofEpochSecond(someMoment), ZoneId.systemDefault());
LocalDateTime weekBegin = dateTime.with(DayOfWeek.SUNDAY).toLocalDateTime().with(LocalTime.MAX);
return weekBegin.toEpochSecond(ZoneId.systemDefault().getRules().getOffset(weekBegin));
}
public static LocalDate getMondayOfWeek(LocalDate someDate) {
return someDate.with(DayOfWeek.MONDAY);
}
public static LocalDate getFridayOfWeek(LocalDate someDate) {
return someDate.with(DayOfWeek.FRIDAY);
}
}
<file_sep>package com.adj.workreporter.service;
import com.adj.workreporter.model.Work;
import com.adj.workreporter.util.SqlUtil;
import com.j256.ormlite.dao.Dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.List;
/**
* 数据持久化service
* Created by dhx on 2017/4/10.
*/
public class WorkService {
private Logger logger = LoggerFactory.getLogger(WorkService.class);
private Dao<Work, Integer> workDao;
public WorkService() {
workDao = SqlUtil.getWorkDao();
}
public void saveWork(Work work) throws SQLException {
workDao.create(work);
}
public List<Work> queryWorksInPeriod(long startEpochSecond, long endEpochSecond) throws SQLException {
logger.debug("收到查询 [queryWorksInPeriod] beginSecond:{} + endSecond:{}", startEpochSecond, endEpochSecond);
return workDao.queryBuilder().where().ge(Work.EPOCH_SECOND_FIELD_NAME, startEpochSecond).and()
.le(Work.EPOCH_SECOND_FIELD_NAME, endEpochSecond).query();
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.adj</groupId>
<artifactId>workReporter</artifactId>
<version>0.0.1</version>
<dependencies>
<!--<dependency>-->
<!--<groupId>org.apache.poi</groupId>-->
<!--<artifactId>poi</artifactId>-->
<!--<version>3.15</version>-->
<!--</dependency>-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>[3.16.1,)</version>
</dependency>
<dependency>
<groupId>com.j256.ormlite</groupId>
<artifactId>ormlite-jdbc</artifactId>
<version>[5.0,)</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>[1.0.9,)</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>[1.0.9,)</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<excludes>
<exclude>classworlds:classworlds</exclude>
<exclude>junit:junit</exclude>
<exclude>jmock:*</exclude>
<exclude>*:xml-apis</exclude>
<exclude>org.apache.maven:lib:tests</exclude>
<exclude>log4j:log4j:jar:</exclude>
</excludes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<!-- 生成MANIFEST.MF的设置 -->
<manifest>
<!-- 为依赖包添加路径, 这些路径会写在MANIFEST文件的Class-Path下 -->
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<!-- jar启动入口类-->
<mainClass>com.adj.workreporter.WorkReporter</mainClass>
</manifest>
<manifestEntries>
<!-- 在Class-Path下添加配置文件的路径 -->
<Class-Path>conf/</Class-Path>
</manifestEntries>
</archive>
<includes>
<!-- 打jar包时,只打包class文件 -->
<include>**/*.class</include>
</includes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project> | 318c250085e6a18297522feef57f198a7664b47d | [
"Markdown",
"Java",
"Maven POM"
] | 6 | Markdown | Zz-m/workReporter | fced8e562082b96e084e43ba064b672a25f68133 | dbd9856c376e4f9cb7eb976e93dba19cbffafd01 |
refs/heads/master | <file_sep>#include<stdio.h>
void print_multiples()
{
int counter = 3;
int sum = 0;
while (counter < 1000)
{
if (counter % 3 == 0 | counter % 5 == 0)
{
sum = sum + counter;
}
counter ++;
}
printf("Sum of numbers below 1000 that are multiples of 3 and 5 is %d \n", sum);
}
int main ()
{
print_multiples();
return 0;
}
<file_sep>#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
bool is_pangram(const char *str_in) {
char alphabet[26] = "abcdefghijklmnopqrstuvwxyz";
int unique_counter = 0;
if (strlen(str_in)< 26)
{
return false;
}
for(int letter_index = 0; letter_index < strlen(alphabet); letter_index++)
{
char alphabet_letter = alphabet[letter_index];
for(int x=0; x < strlen(str_in); x++)
{
if (!isspace(str_in[x]))
{
char text_letter = tolower(str_in[x]);
if(alphabet_letter == text_letter)
{
unique_counter++;
break; //breaking second loop
}
}
}
}
return unique_counter == 26;
}
int main()
{
char *str = "DspSaFMeQTgG(h{;ycBvdknqmAoRCKiufNXIZrUML\"Pc_bnxOjLWJ";
bool response = is_pangram(str);
if (response == 1)
printf("Is Pangram\n");
else
printf("No Pangram\n");
}<file_sep># project-euler-c
A repository for resolving Project Euler's problems in C
| a6fb0d166eb5adc1913588ec96ec9b9d5e35bd61 | [
"Markdown",
"C"
] | 3 | C | michaelhidalgo/project-euler-c | 31598261d61f1f8a8e3219527990dbb826b573af | 7d3777266a5ad938cb5f1d2bfe70bacf43bb5f2d |
refs/heads/master | <repo_name>barmaglot-server/hotspotlogin<file_sep>/lang/ru.php
<?php
global $lang;
$lang = array(
'chillispot' => 'Barmaglot hotspot',
'errornonssl' => 'Для входа использовать https:// соединение',
'already_logged_in' => 'Already logged in',
'logout' => 'Logout',
'login' => 'Login',
'new_register' => 'New? Register now..',
'register' => 'Регистрация',
'register_cancel' => 'Cancel (back to Login)',
'pleasewait' => 'Пожалуста подождите....',
'login_email' => 'Почтовый адрес',
'login_password' => '<PASSWORD>',
'password' => '<PASSWORD>',
'please_login' => 'Ваш логин',
'please_register' => 'Пожалуйста, зарегистрируйтесь',
'forgot_password' => '<PASSWORD>?',
'firstname' => 'Имя',
'lastname' => 'Фамилия',
'email' => 'Почта',
'telephone' => 'Номер телефона',
'question' => 'Секретный вопрос',
'answer' => 'Секретный Ответ',
'show_password' => '<PASSWORD>',
'login_failed' => 'Ваши данные для входа, являются недействительными.',
'not_unique_userid' => 'Этот адрес электронной почты уже зарегистрирован. Пожалуйста, войдите с этим адресом электронной почты. Если вы forgotton пароль, используйте кнопку Напоминание пароля для его получения.',
'chooseoption' => 'Выберите',
'gender' => 'Пол',
'age' => 'Age',
'gender_male' => 'Male',
'gender_female' => 'Female',
'failed_fields' => 'The following fields are either invalid or required',
'enter_username' => 'Пожалуйста, введите Ваш адрес электронной почты.',
'forgot_password_no_question' => 'There was a problem retrieving your security question - please contact the site administrator.',
'forgot_password_invalid_answer' => 'There was a problem retrieving your password. Please check your memorable answer.',
'please_answer_security_question' => 'Please provide the answer to your security question, so I can retrieve your password.',
'enter_reminderanswer' => 'Please enter your memorable answer.',
'pwd_reminder_title' => 'Your Password Reminder',
'pwd_reminder_copy' => 'Your password is below. Click OK to complete your login.',
'pwd_reminder_button' => 'OK (Login)'
);
$lang['pagetitle'] = $lang['chillispot'].' Login';
$lang['title_login'] = $lang['chillispot'].' Login';
$lang['title_loginfailed'] = $lang['chillispot'].' Login Failed';
$lang['daemon_error'] = 'Login must be performed through '.$lang['chillispot'].' server';
$lang['loggedin_title'] = 'Logged in to '.$lang['chillispot'];
$lang['loggingin_title'] = 'Logging in to '.$lang['chillispot'];
$lang['loggedout_title'] = 'Logged out from '.$lang['chillispot'];
$lang['welcome_title'] = 'Добро пожаловать в '.$lang['chillispot'];
| f23bb5ad0eab9eeb6757566268320cc31d9350e0 | [
"PHP"
] | 1 | PHP | barmaglot-server/hotspotlogin | c85332b16823d9e2edf29500ae9f302f29078006 | 925b63471c16c500600bf9450a66665898c2d6a5 |
refs/heads/master | <repo_name>Gavrilajava/count-elements-houston-web-012720<file_sep>/count_elements.rb
def count_elements(array)
# code goes here
myhash = {}
array.each{ |element|
if myhash.has_key?(element)
myhash[element] += 1
else
myhash[element] = 1
end
}
myhash
end
| 2b8b37789f5ddf0d7bf687b0c8eaef732991afda | [
"Ruby"
] | 1 | Ruby | Gavrilajava/count-elements-houston-web-012720 | e07c2d4fd6d57ec634bb84abfbaff713724a3e89 | ed8a9b8c9591447992a47615d67f21feaa1803a6 |
refs/heads/master | <repo_name>itwizalekh/getdata-003<file_sep>/run_analysis.R
# 7352 observations
# setwd("")
# Read various datasets
X_train<-read.table("UCI HAR Dataset/train/X_train.txt")
y_train<-read.table("UCI HAR Dataset/train/y_train.txt")
X_test<-read.table("UCI HAR Dataset/test/X_test.txt")
y_test<-read.table("UCI HAR Dataset/test/y_test.txt")
subject_train<-read.table("UCI HAR Dataset/train/subject_train.txt")
subject_test<-read.table("UCI HAR Dataset/test/subject_test.txt")
# Combine various datasets
myDF <- rbind(cbind(subject_train, y_train, X_train), cbind(subject_test, y_test, X_test))
# as noted by "features_info.txt" file, tAcc-XYZ and tGyro-XYZ are the only raw
# signals measured. Rest of the values are some or the other transformations
# from tAcc-XYZ and tGyro-XYZ.
# Hence, only extracting mean() and std() for tAcc-XYZ and tGyro-XYZ:
# (these are the following columns as per "features.txt")
# 1 tBodyAcc-mean()-X
# 2 tBodyAcc-mean()-Y
# 3 tBodyAcc-mean()-Z
# 4 tBodyAcc-std()-X
# 5 tBodyAcc-std()-Y
# 6 tBodyAcc-std()-Z
# 41 tGravityAcc-mean()-X
# 42 tGravityAcc-mean()-Y
# 43 tGravityAcc-mean()-Z
# 44 tGravityAcc-std()-X
# 45 tGravityAcc-std()-Y
# 46 tGravityAcc-std()-Z
#
# The offset (+2) is to account for activity and subject columns added
myDF2 <- myDF[,c(1,2,seq(1+2,6+2),seq(41+2,46+2))]
# assigning meaningful column names
colnames(myDF2) <- c("subject_id", "activity_id", "tBodyAcc_mean_X", "tBodyAcc_mean_Y", "tBodyAcc_mean_Z", "tBodyAcc_std_X", "tBodyAcc_std_Y", "tBodyAcc_std_Z", "tGravityAcc_mean_X", "tGravityAcc_mean_Y", "tGravityAcc_mean_Z", "tGravityAcc_std_X", "tGravityAcc_std_Y", "tGravityAcc_std_Z")
# loading activity names (labels)
activity_labels<-read.table("UCI HAR Dataset/activity_labels.txt")
colnames(activity_labels) <- c("activity_id", "activity_name")
myDF3 <- merge(activity_labels, myDF2, by.x="activity_id", by.y="activity_id")
# myDF4 <- myDF3[,!(colnames(myDF3) %in% "activity_id")]
# rm(myDF4)
# ls()
myDF3 <- myDF3[,!(colnames(myDF3) %in% "activity_id")]
library(plyr)
# colnames(myDF3)
tidyDF <- ddply(myDF3, .(activity_name, subject_id), summarise,
ave_tBodyAcc_mean_X=mean(tBodyAcc_mean_X),
ave_tBodyAcc_mean_Y=mean(tBodyAcc_mean_Y),
ave_tBodyAcc_mean_Z=mean(tBodyAcc_mean_Z),
ave_tBodyAcc_std_X=mean(tBodyAcc_std_X),
ave_tBodyAcc_std_Y=mean(tBodyAcc_std_Y),
ave_tBodyAcc_std_Z=mean(tBodyAcc_std_Z),
ave_tGravityAcc_mean_X=mean(tGravityAcc_mean_X),
ave_tGravityAcc_mean_Y=mean(tGravityAcc_mean_Y),
ave_tGravityAcc_mean_Z=mean(tGravityAcc_mean_Z),
ave_tGravityAcc_std_X=mean(tGravityAcc_std_X),
ave_tGravityAcc_std_Y=mean(tGravityAcc_std_Y),
ave_tGravityAcc_std_Z=mean(tGravityAcc_std_Z)
)
write.table(tidyDF, file = "tidyDF.txt")
<file_sep>/README.md
getdata-003
===========
Course project submission for Coursera MOOC "Getting and Cleaning Data"
The data for the project was taken from the following URL at 23:49 20-05-2014 IST:
https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip
The intention was to create an R script run_analysis.R that does the following:
1. Merges the training and the test sets to create one data set.
2. Extracts only the measurements on the mean and standard deviation for each measurement.
3. Uses descriptive activity names to name the activities in the data set
4. Appropriately labels the data set with descriptive activity names.
5. Creates a second, independent tidy data set with the average of each variable for each activity and each subject.
Readme.md
===========
A readme file containing brief description of each file submitted for the Course pPoject.
Here is a summary of what this script does:
- Read various datasets
- Combine various datasets (training set with corresponding test set)
- As noted by "features_info.txt" file, tAcc-XYZ and tGyro-XYZ are the only raw
signals measured. Rest of the values are some or the other transformations
from tAcc-XYZ and tGyro-XYZ.
Hence, only extracting mean() and std() for tAcc-XYZ and tGyro-XYZ:
(these are the following columns as per "features.txt")
- 1 tBodyAcc-mean()-X
- 2 tBodyAcc-mean()-Y
- 3 tBodyAcc-mean()-Z
- 4 tBodyAcc-std()-X
- 5 tBodyAcc-std()-Y
- 6 tBodyAcc-std()-Z
- 41 tGravityAcc-mean()-X
- 42 tGravityAcc-mean()-Y
- 43 tGravityAcc-mean()-Z
- 44 tGravityAcc-std()-X
- 45 tGravityAcc-std()-Y
- 46 tGravityAcc-std()-Z
- Assign meaningful column names
- Load activity names (labels)
- Average all mean and SD measures over subject and activity for tidy data set
- Write the final tidy dataset to an ouptut file tidyDF.txt for submission
run_analysis.R
==============
This is the actual R script that was written for intended data processing required for submission towards the Course Project.
tidyDF.txt
==========
This is the final data frame written to the output file containing three variables (columns in file) and 180 observatoins (rows in file, excluding header for column names).
<file_sep>/CodeBook.md
tidyDF.txt
==========
This is the final data frame written to the output file containing three variables (columns in file) and 180 observatoins (rows in file, excluding header for column names).
This Data Set contains the following two key variables:
- activity_name
- subject_id
This Data Set also contains the following average values corresponding to each unique combination of key values:
- ave_tBodyAcc_mean_X
- ave_tBodyAcc_mean_Y
- ave_tBodyAcc_mean_Z
- ave_tBodyAcc_std_X
- ave_tBodyAcc_std_Y
- ave_tBodyAcc_std_Z
- ave_tGravityAcc_mean_X
- ave_tGravityAcc_mean_Y
- ave_tGravityAcc_mean_Z
- ave_tGravityAcc_std_X
- ave_tGravityAcc_std_Y
- ave_tGravityAcc_std_Z
Processing done on input data to produce tidyDF.txt (output)
=====================
Here is a summary of what this script does:
- Read various datasets
- Combine various datasets (training set with corresponding test set)
- As noted by "features_info.txt" file, tAcc-XYZ and tGyro-XYZ are the only raw
signals measured. Rest of the values are some or the other transformations
from tAcc-XYZ and tGyro-XYZ.
Hence, mean() and std() are extracted only for tAcc-XYZ and tGyro-XYZ:
- Meaningful column names are assigned to the Data Frame
- Activity names (labels) are read
- All mean and SD measures are averaged over subject and activity for tidy data set
- Tidy dataset is written to an ouptut file tidyDF.txt for submission
| 167d71fd32de169d54ada89d1bbb1e92b1f85c71 | [
"Markdown",
"R"
] | 3 | R | itwizalekh/getdata-003 | ebef626cc84b090d2182837c763bf329b8519c97 | 9ec91fdcecb926810879fda118170cb5b8aa6a42 |
refs/heads/master | <repo_name>MJCaister/MC-Server-Query-Discord-Bot<file_sep>/main.py
# MC Server Query Bot for Discord by NKSCPreditive
import discord
import asyncio
from mcipc.query import Client
from datetime import datetime
bot = discord.Client()
# SETUP
token = open(r'token.txt', 'r').read() or "" # Your Discord bot's token (Don't share this token with anyone)
server_ip = '127.0.0.1' # Set to the minecraft server's ip address
ports = [25565] # If you have mutiple servers running off the same IP you can add the ports for each server here
message_channel = 0 # Set to the ID of the discord text channel you want to use
# Make sure the channel you are using is an empty channel
update_rate = 30.0 # Time in seconds that the server information is refreshed
bot_timezone = "UTC+0" # The UTC timezone the bot is running in
# END OF SETUP
async def queryMinecraftServer(port, ip=server_ip):
channel = bot.get_channel(message_channel)
now = datetime.now()
current_time = now.strftime("%H:%M:%S {}".format(bot_timezone))
try:
# Attempts a query connection to the minecraft server
with Client(ip, port, timeout=5.0) as client:
stats = client.full_stats
await channel.send('**Server**: {} **MC Version**: {} **IP**: {}:{} **Player Count**: {}/{}'.format(stats.host_name, stats.version,
server_ip, stats.host_port, stats.num_players,
stats.max_players), delete_after=update_rate)
await channel.send('**Connected Players**: {}'.format(', '.join(stats.players)), delete_after=update_rate)
await channel.send('*Last Updated: {}*'.format(current_time), delete_after=update_rate)
except:
await channel.send('**ERROR**: *Timed out trying to connect to server* __{}:{}__'.format(ip, port), delete_after=update_rate)
@bot.event
async def on_ready():
channel = bot.get_channel(message_channel)
print('Logged onto Discord as {0.user}'.format(bot))
doing = discord.CustomActivity(name="Checking Server Infomation")
await bot.change_presence(status=discord.Status.online, activity=doing)
bot.loop.create_task(autoRun())
msgs = await channel.history().flatten()
await channel.delete_messages(msgs)
async def autoRun():
while True:
for port in ports:
await queryMinecraftServer(port)
await asyncio.sleep(update_rate)
bot.run(token) | 4e7d1d9086c53482821940c03e50d6fc0f6e1b66 | [
"Python"
] | 1 | Python | MJCaister/MC-Server-Query-Discord-Bot | 5cd2c7e8df847f07bde4ebf9f3e0665aba2dfb9b | ce6f176c7c20f414889d86dcc4b9e8e6797d4321 |
refs/heads/master | <repo_name>romfrancois/GoT-Houses<file_sep>/GoT-Houses/HouseInfo.swift
//
// HouseInfo.swift
// GoT-Houses
//
// Created by <NAME> on 23/07/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
struct HouseInfo: Codable {
var name: String
var region: String
var coatOfArms: String
var words: String
}
<file_sep>/GoT-Houses/SplashScreenViewController.swift
//
// SplashScreenViewController.swift
// GoT-Houses
//
// Created by <NAME> on 24/07/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import AVFoundation
class SplashScreenViewController: UIViewController {
@IBOutlet weak var throneImageView: UIImageView!
var throneImageY: CGFloat!
var audioPlayer: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
playSound(name: "GoT_theme")
// Save original location so we can animate back to this spot. Only the y value will change since we're moving vertically
throneImageY = throneImageView.frame.origin.y
// move the upper left point of the image so it's just off screen, to the bottom of the view controller
throneImageView.frame.origin.y = self.view.frame.height
UIView.animate(
withDuration: 1.0,
delay: 1.0,
animations: {
self.throneImageView.frame.origin.y = self.throneImageY
}
)
}
func playSound(name: String) {
if let sound = NSDataAsset(name: name) {
do {
try audioPlayer = AVAudioPlayer(data: sound.data)
audioPlayer.play()
} catch {
print(" ERROR: \(error.localizedDescription)")
}
} else {
print("ERROR: Could not read data from file \(name)")
}
}
@IBAction func imageTapped(_ sender: UITapGestureRecognizer) {
if audioPlayer != nil {
audioPlayer.stop()
}
performSegue(withIdentifier: "ShowTableView", sender: nil)
}
}
<file_sep>/GoT-Houses/ViewController.swift
//
// ViewController.swift
// GoT-Houses
//
// Created by <NAME> on 22/07/2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
// var houses = ["Dartford", "Bellegarde", "Nimes"]
var houses = Houses()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// Fake data to make sure tableView is working properly
// houses.houseArray.append(HouseInfo(name: "Dartford", region: "", coatOfArms: "", words: ""))
// houses.houseArray.append(HouseInfo(name: "Bellegarde", region: "", coatOfArms: "", words: ""))
houses.getData {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowDetail" {
let destination = segue.destination as! DetailViewController
let selectedIndexPath = tableView.indexPathForSelectedRow!
destination.houseInfo = houses.houseArray[selectedIndexPath.row]
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
houses.houseArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// If you're displaying the very last array in houses.houseArray, then load more
if indexPath.row == houses.houseArray.count - 1 && houses.continueLoading {
houses.getData {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
// Minimum to populate the tableView
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "\(indexPath.row + 1). " + houses.houseArray[indexPath.row].name
return cell
}
}
| 7ddd802eed476a3a1c4ea131f6b30e6ec68b5338 | [
"Swift"
] | 3 | Swift | romfrancois/GoT-Houses | b7d21442853677520b6938968ee37c6732ff439f | eb7bafce3a76c7c1857e3d084608e12f96a84205 |
refs/heads/master | <file_sep>#ifndef cassiere_h
#define cassiere_h
#include "utility.h"
// initialize cashier variable
void cassiere_create(threadCassiere *tc, int tprod, int intTime, int index);
// insert client in the tail of queue
void insertClient(queue *head, queue *tail, queue *client);
// life cycle cashier
void *cassiere_work(void *arg);
#endif /* cassiere_h */
<file_sep># Makefile
CC = gcc
CFLAGS = -Wall -g
LDFLAGS = -L ./lib -Wl,-rpath=./lib
obj = ./src/supermercato.c ./lib/libbt.so
TARGET = ./bin/myprog
.PHONY: all test2 clean
./bin/myprog : $(obj)
$(CC) -pthread $(CFLAGS) $^ -I ./include -o $@ $(LDFLAGS) -lbt
./lib/libbt.so : ./src/cliente.o ./src/direttore.o ./src/cassiere.o
$(CC) $(CFLAGS) -shared -o $@ $^
./src/direttore.o : ./src/direttore.c
$(CC) $(CFLAGS) $< -I ./include -fPIC -c -o $@
./src/cliente.o : ./src/cliente.c
$(CC) $(CFLAGS) $< -I ./include -fPIC -c -o $@
./src/cassiere.o : ./src/cassiere.c
$(CC) $(CFLAGS) $< -I ./include -fPIC -c -o $@
all: $(TARGET)
test2: ./bin/myprog
@echo "Eseguo il test"
./bin/myprog
@echo "Test2 OK"
./analisi.sh
clean:
@echo "Removing garbage"
-rm -f ./bin/myprog
-rm -f ./log.txt
-rm -f ./src/*.o ./lib/libbt.so
<file_sep>#define _POSIX_C_SOURCE 200112L
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include "cliente.h"
#include "cassiere.h"
#include "direttore.h"
#include "utility.h"
_Thread_local unsigned int seed; // seed thread local for rand_r
// insert the client in cashier's tail of that index
void insertInCashiersQueue(queue *client, int index, var_struct *vcm, threadCassiere *cashiers){
// generate a random number that corresponds at one cashier open
int reg = rand_r(&seed)%( vcm->openCashiers);
#if defined(DEBUG)
printf("[Client %d] mi metto in coda nella cassa %d\n",index, reg+1);
#endif
pthread_mutex_lock(&(cashiers[reg].lock));
cashiers[reg].queueSize++;
#if defined(DEBUG)
printf("lunghezza coda: %d, cassa: %d\n", cashiers[reg].queueSize, reg+1);
#endif
insertClient(&(cashiers[reg].head), &(cashiers[reg].tail), client);
pthread_cond_signal(&(cashiers[reg].notEmpty));
pthread_mutex_unlock(&(cashiers[reg].lock));
}
// life cycle of client
void *client(void *arg) {
struct var_cashier_client *var = arg;
var_struct *vcm = var->vcm;
threadCassiere *cashiers = var->regs;
int tBuy, index = var->index, pBuy, cQueue, oldType;
float diff, sTime, qTime;
queue client = malloc(sizeof(nodoC));
struct timespec t1;
struct timespec queueStartTime;
struct timespec queueEndTime;
pthread_detach(pthread_self());
if( pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldType) != 0){
perror("Error setcanceltype");
exit(EXIT_FAILURE);
}
seed = (unsigned int)pthread_self()*100000;
// block signals
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGHUP);
sigaddset(&set, SIGQUIT);
if( pthread_sigmask(SIG_BLOCK, &set, NULL) != 0){
perror("Error pthread sigmask");
exit(EXIT_FAILURE);
}
client->served = 0;
client->queueTime = -1;
client->changedQueue = 0;
client->next = NULL;
client->serviceTime = 0;
client->supermarketTime = 0;
if( pthread_mutex_init(&(client->lock), NULL) != 0){
perror("Error initialize lock");
exit(EXIT_FAILURE);
}
if( pthread_cond_init(&(client->myTurn), NULL) != 0){
perror("Error initialize var cond");
exit(EXIT_FAILURE);
}
if( pthread_cond_init(&(client->modified), NULL) != 0){
perror("Error initialize var cond");
exit(EXIT_FAILURE);
}
srand(seed);
// time for buy products
client->buyTime = (float)(rand_r(&seed)%( (T + 1) - 10) + 10) / 1000;
tBuy = client->buyTime * 1000000000;
if(tBuy >= 1000000000 ){
t1.tv_sec = tBuy / 1000000000;
t1.tv_nsec = (tBuy % 1000000000);
}
else{
t1.tv_sec = 0;
t1.tv_nsec = tBuy;
}
// simulate time for buy products
nanosleep(&t1, NULL);
client->buyProducts = rand_r(&seed)%(P + 1);
pBuy = client->buyProducts;
// check client's buyProducts, if is 0 not insert in queue but
// wait the manager for leave, otherwise insert in cashier's queue
if( client->buyProducts != 0){
pthread_mutex_lock(&(vcm->mtx));
// take start time of queue client
clock_gettime(CLOCK_MONOTONIC, &queueStartTime);
insertInCashiersQueue(&client, index, vcm, cashiers);
pthread_mutex_unlock(&(vcm->mtx));
pthread_mutex_lock(&(client->lock));
// Wait client turn
while( client->served == 0)
pthread_cond_wait(&(client->myTurn), &(client->lock));
#if defined(DEBUG)
printf("[Client %d] è il mio turno\n", index);
#endif
// take end time of queue client
clock_gettime(CLOCK_MONOTONIC, &queueEndTime);
diff = (queueEndTime.tv_sec - queueStartTime.tv_sec) ;
if( (queueEndTime.tv_nsec - queueStartTime.tv_nsec) <0)
diff += (float)( queueEndTime.tv_nsec -queueStartTime.tv_nsec)* (-1) / 1000000000;
else
diff += (float)(queueEndTime.tv_nsec -queueStartTime.tv_nsec) / 1000000000;
client->queueTime = diff;
// signal to cashier the changed
pthread_cond_signal(&(client->modified));
pthread_mutex_unlock(&(client->lock));
pthread_mutex_lock(&(client->lock));
// wait that cashier calculate value of client
while( client->supermarketTime == 0)
pthread_cond_wait(&(client->modified), &(client->lock));
}else{
pthread_mutex_lock(&(client->lock));
#if defined(DEBUG)
printf("[Cliente %d] ho acquistato 0 prodotti, chiedo il permesso di uscire\n", index);
#endif
client->queueTime = 0;
client->serviceTime = 0;
client->supermarketTime = client->buyTime;
}
pBuy = client->buyProducts;
cQueue = client->changedQueue;
sTime = client->supermarketTime;
qTime = client->queueTime;
pthread_mutex_unlock(&(client->lock));
updateInfoClients(pthread_self(), pBuy, cQueue, sTime, qTime);
fflush(stdout);
// ask to manager to exit
pthread_mutex_lock(&(vcm->mtx));
vcm->numClient--;
clientExit(index);
printf("Il cliente %d è uscito, clienti dentro il supermercato: %d\n ", index, vcm->numClient);
// the last client in the supermarket
if(vcm->numClient == 0){
#if defined(DEBUG)
printf("SEGNALE ULTIMO CLIENT MANDATO\n");
#endif
pthread_cond_signal(&(vcm->NotFullClient));
pthread_cond_signal(&(vcm->Empty));
pthread_mutex_unlock(&(vcm->mtx));
free(client);
return NULL;
}
// signal to manager that the threashold has been reached
if((vcm->numClient < (C - E)) && (vcm->finish == 0)){
pthread_cond_signal(&(vcm->NotFullClient));
pthread_mutex_unlock(&(vcm->mtx));
free(client);
return NULL;
}
pthread_mutex_unlock(&(vcm->mtx));
free(client);
return NULL;
}
<file_sep>### ProgettoSol
progetto sistemi operativi 2019/2020
Università di Pisa-- Dipartimento di Informatica
Corso di Laurea in Informatica
Progetto di Laboratorio di Sistemi Operativi
a.a. 2019-20
Docenti: <NAME> (Corso A), <NAME> (Corso B)
Data pubblicazione 2 Maggio 2020
Revisione: 5 Maggio 2020
## Introduzione
Lo studente dovrà realizzare la simulazione di un sistema che modella un supermercato con K casse e
frequentato da un certo numero di clienti. Il supermercato è diretto da un direttore che ha facoltà di aprire e
chiudere una o più casse delle K totali (lasciandone attiva almeno una). Il numero dei clienti nel supermercato è
contingentato: non ci possono essere più di C clienti che fanno acquisti (o che sono in coda alle casse) in ogni
istante. All’inizio, tutti i clienti entrano contemporaneamente nel supermercato, successivamente, non appena il
numero dei clienti scende a C-E (0<E<C), ne vengono fatti entrare altri E. Ogni cliente spende un tempo
variabile T all’interno del supermercato per fare acquisti, quindi si mette in fila in una delle casse che sono in
quel momento aperte ed aspetta il suo turno per “pagare” la merce acquistata. Periodicamente, ogni cliente in
coda, controlla se gli conviene cambiare coda per diminuire il suo tempo di attesa. Infine esce dal supermercato.
Un cliente acquista fino a P>=0 prodotti. Ogni cassa attiva ha un cassiere che serve i clienti in ordine FIFO con
un certo tempo di servizio. Il tempo di servizio del cassiere ha una parte costante (diversa per ogni cassiere) più
una parte variabile che dipende linearmente dal numero di prodotti acquistati dal cliente che sta servendo.
I clienti che non hanno acquistato prodotti (P=0), non si mettono in coda alle casse, ma prima di uscire dal
supermercato devono attendere il permesso di uscire dal direttore.
## Il supermercato
Il supermercato è modellato come un singolo processo multi-threaded con al più K thread attivi come cassieri e
C thread attivi corrispondenti ai clienti che sono nel supermercato. Eventuali altri thread di “supporto” (oltre al
thread main) possono essere presenti nel sistema a discrezione dello studente.
Il direttore è un processo separato dal processo supermercato. Quando necessario, i due processi interagiscono
tramite socket di tipo AF_UNIX e segnali POSIX. Al loro avvio, entrambi i processi leggono i rispettivi
parametri di configurazione da un file comune chiamato config.txt (non è un header file). Il formato di tale file
non viene specificato e deve essere deciso dallo studente.
Il supermercato all’inizio apre con un numero limitato di casse (ad esempio 1 sola). Tale valore iniziale è definito
nel file di configurazione.
Il supermercato chiude quando il direttore riceve un segnale SIGQUIT o SIGHUP. Nel primo caso la chiusura
deve essere immediata, ossia gli eventuali clienti ancora presenti nel supermercato non vengono serviti ma
vengono fatti uscire immediatamente. Nel secondo caso (SIGHUP), non vengono più fatti entrare nuovi client ed
il supermercato termina quando tutti i clienti nel supermercato escono perchè hanno terminato gli acquisti.
Prima di terminare, il processo supermercato scrive in un file di log (il cui nome è specificato nel file di
configurazione) tutte le statistiche collezionate dal sistema durante il periodo di apertura. Tra queste: il numero
di clienti serviti, il numero di prodotti acquistati; per ogni cliente: il tempo di permanenza nel supermercato, il
tempo di attesa in coda, se e quante volte ha cambiato coda, il numero di prodotti acquistati; per le casse: il
numero di clienti serviti, il tempo di ogni periodo di apertura della cassa, il numero di chiusure, il tempo di
servizio di ogni cliente servito.
## Il cassiere
I clienti si accodano in modo random alle casse aperte nel momento in cui hanno terminano gli acquisti, e
vengono serviti in ordine di arrivo dal cassiere. Il thread cassiere impiega un tempo fisso (diverso per ogni
cassiere nel range 20-80 millisecondi) ed un tempo variabile che dipende in modo lineare dal numero di prodotti
che il cliente ha acquistato (il tempo di gestione di un singolo prodotto da parte di un cassiere è fisso, ed è
specificato nel file di configurazione). Il direttore viene informato ad intervalli regolari dai cassieri (l’ampiezza
di tale intervallo è definita anch’essa nel file di configurazione) sul numero di clienti in coda alla cassa. Quando
una cassa viene chiusa dal direttore, il thread cassiere termina dopo aver servito il cliente corrente. Gli eventuali
altri clienti in coda si devono rimettere in coda in altre casse.
## Il cliente
Ogni cliente che entra nel supermercato ha associato un tempo per gli acquisti che varia in modo casuale da 10 a
T>10 millisecondi, ed un numero di prodotti che acquisterà che varia da 0 a P>0. Tali valori vengono associati
al thread cliente all’atto della sua entrata nel supermercato.
Il cliente in coda ad una cassa può decidere di spostarsi in un’altra cassa. La decisione viene presa in base al
numero di clienti che ha davanti a lui ed al numero di clienti in coda nelle altre casse. In particolare, ogni S
millisecondi (S, T e P sono parametri specificati nel file di configurazione), ogni cliente decide se spostarsi o
meno. L’algoritmo che implementa la decisione di spostarsi è lasciato allo studente. Il cliente che decide di
spostarsi, si prende il rischio che la cassa in cui si muoverà potrebbe essere chiusa (nel frattempo) dal direttore.
In tal caso perderà la posizione che aveva nella vecchia cassa e dovrà rimettersi in coda in una delle casse aperte.
Un cliente con 0 prodotti acquistati non si mette in coda in nessuna cassa, ma dovrà informare il direttore che
intende uscire e dovrà attendere la sua autorizzazione prima di farlo.
## Il direttore
Il direttore, sulla base delle informazioni ricevute dai cassieri, decide se aprire o chiudere casse (al massimo le
casse aperte sono K, ed almeno 1 cassa deve rimanere aperta). La decisione viene presa sulla base di alcuni
valori soglia S1 ed S2 definiti dallo studente nel file di configurazione. S1 stabilisce la soglia per la chiusura di
una cassa, nello specifico, definisce il numero di casse con al più un cliente in coda (es. S1=2: chiude una cassa
se ci sono almeno 2 casse che hanno al più un cliente). S2 stabilisce la soglia di apertura di una cassa, nello
specifico, definisce il numero di clienti in coda in almeno una cassa (es. S2=10: apre una cassa (se possibile) se
c’è almeno una cassa con almeno 10 clienti in coda).
Quando il processo direttore riceve un signale SIGQUIT o SIGHUP informa immediatamente il processo
supermercato inviandogli lo stesso segnale. Nel caso di SIGHUP, il supermercato non deve più far entrare altri
clienti e deve attendere che tutti i clienti presenti nel supermercato terminino gli acquisti. Nel caso di segnale
SIGQUIT, il supermercato chiude immediatamente facendo uscire tutti i clienti al suo interno. Il direttore attende
che il supermercato termini prima di terminare a sua volta.
## Makefile
Il progetto dovrà includere un Makefile avente, tra gli altri, i target all (per generare gli eseguibili del programma
supermercato e direttore), clean (per ripulire la directory di lavoro dai file generati, socket file, logs, librerie,
etc.), e due target di tests: test1 e test2. Il target test1 deve far partire il processo direttore, quindi il processo
supermercato con i seguenti parametri di configurazioni (quelli non specificati, sono a scelta dello studente):
K=2, C=20, E=5, T=500, P=80, S=30 (gli altri parametri a scelta dello studente). Il processo supermercato deve
essere eseguito con valgrind utilizzando il seguente comando: “valgrind –leak-check=full”. Dopo 15s deve
inviare un segnale SIGQUIT al processo direttore. Il test si intende superato se valgrind non riporta errori né
memoria non deallocata (il n. di malloc deve essere uguale al n. di free).
Il test2 deve lanciare il proccesso direttore che provvederà ad aprire il supermercato lanciando il processo
supermercato con i seguenti parametri (gli altri a scelta dello studente): K=6, C=50, E=3, T=200, P=100, S=20.
Dopo 25s viene inviato un segnale SIGHUP, quindi viene lanciato lo script Bash di analisi (analisi.sh) che, al
termine dell’esecuzione del supermercato, fornirà sullo standard output un sunto delle statistiche relative
all’intera simulazione appena conclusa. Il test si intende superato se non si producoro errori a run-time e se il
sunto delle statistiche relative alla simulazione riporta “valori ragionevoli” (cioè, non ci sono valori negativi,
valori troppo alti, campi vuoti, etc...).
## Lo script analisi.sh
Lo studente dovrà realizzare uno script Bash con nome analisi.sh che effettua il parsing del file di log prodotto
dal processo supermercato al termine della sua esecuzione, e produce un sunto della simulazione. Nello
specifico, lo script produce sullo standard output le seguenti informazioni.
Per i clienti:
`<| id cliente | n. prodotti acquistati | tempo totale nel super. | tempo tot. speso in coda | n. di code visitate |>`
Per le casse:
`<| id cassa | n. prodotti elaborati | n. di clienti | tempo tot. di apertura | tempo medio di servizio | n. di chiusure |>`
I tempi vanno espressi in secondi con al più 3 cifre decimali. Lo studente, se lo ritiene, può arricchire le
informazioni prodotte dallo script.
## Note finali
Ci si attende che tutto il codice sviluppato sia, per quanto possibile, conforme POSIX. Eventuali eccezioni (come
ad esempio l’uso di estensioni GNU) devono essere documentate nella relazione di accompagnamento.
Per attendere un certo numero di millesecondi, si può utilizzare la chiamata nanosleep. Fare attenzione alla
generazione dei numeri casuali: utilizzare differenti seed per ogni thread distinto che invoca la rand_r.
La consegna dovrà avvenire, entro i termini previsti per la consegna in ogni appello, attraverso l'upload sul sito
Moodle del corso di un archivio con nome nome_cognome-CorsoX.tar.gz contenente tutto il codice necessario
per compilare ed eseguire il progetto (CorsoX sarà CorsoA o CorsoB a seconda del corso di appartenenza dello
studente). Scompattando l'archivio in una directory vuota, dovrà essere possibile eseguire i comandi make (con
target di default) per costruire tutti gli eseguibili, e make test1 e make test2 per eseguire i tests e vederne i
risultati. L'archivio dovrà anche contenere una relazione in formato PDF (di massimo 5 pagine – Times New
Roman, 11pt, margini di 2cm formato A4, interlinea singola) in cui sono descritti gli aspetti più significativi
dell’implementazione del progetto e le scelte fatte. Il progetto può essere realizzato su una qualsiasi
distribuzione Linux a 64bit. In ogni caso, i test devono girare senza errori almeno sulla macchina virtuale
Xubuntu fornita per il corso e configurata con almeno 2 cores.
Infine, si ricorda che per sostenere l’esame è necessario iscriversi sul portale esami.
PER CHI CONSEGNA IL PROGETTO ENTRO
L’APPELLO DI LUGLIO 2020
Per chi consegna il progetto entro la sessione estiva, il progetto che lo studente deve realizzare è ridotto e
semplificato nel modo seguente rispetto a quanto specificato nelle sezioni precedenti:
1. I clienti in coda in una cassa non si spostano in altre casse (non va implementato l’algoritmo di
decisione);
2. I l direttore non è più un processo separato, ma un thread all’interno del processo supermercato . I segnali
SIGQUIT e SIGHUP vengono quindi inviati al processo supermercato, e non c’è alcuna interazione via
socket AF_UNIX.
3. Il test che ha come target del Makefile test1 non deve essere realizzato. Il Makefile avrà solamente un
target test che corrisponde a quanto descritto per il target test2.
<file_sep>#ifndef utily_h
#define utily_h
#include <pthread.h>
struct vcm{
int numClient; // number of clients in the supermarket
int openCashiers; // number of open cashiers
volatile sig_atomic_t finish; // 1 if the supermarket is closing
volatile sig_atomic_t sigquitReceived; // 1 if the manager received the SIGQUIT signal
pthread_mutex_t mtx;
pthread_cond_t NotFullClient;
pthread_cond_t Empty;
};
typedef struct vcm var_struct;
extern int productTime;
extern int intervalTime;
extern int C;
extern int E;
extern int K;
extern int P;
extern int T;
extern int S1;
extern int S2;
struct nodo{
int buyProducts; // number of products buy
int served; // served client = 1, otherwise 0
int changedQueue; // numbers of changed queue
float buyTime; // time for buy products
float serviceTime; // time of service
float supermarketTime; // time permanence of the client in the supermarket
float queueTime; // time in queue
pthread_mutex_t lock;
pthread_cond_t myTurn;
pthread_cond_t modified;
struct nodo *next;
};
typedef struct nodo nodoC;
typedef nodoC *queue;
// struct for save info of client after terminate
struct node{
pthread_t idClient; // id client
int buyProducts; // number of products buy
int changedQueue; // numbers of changed queue
float supermarketTime; // time permanence of the client in the supermarket
float queueTime; // time in queue
struct node *next;
};
typedef struct node nodoInfoClient;
typedef nodoInfoClient *infoQueueClient;
// struct for save info of cashier after terminate
struct node1{
int idCashier; // id cashier
int processedProducts; // number of processed products
int clientServed; // number of clients
int numberClosures; // number of closures
float openTime; // open time cashier
float averangeTimeService; // averange time of service
};
typedef struct node1 nodoInfoCashier;
typedef nodoInfoCashier *infoQueueCashier;
struct tC{
int index; // index of cashier
int queueSize; // queue size
int fixedTime; // fixed time
int productTime; // product time
int intervalTime; // interval time
volatile sig_atomic_t notFinish; // 1 if supermarket is open, 0 otherwise
pthread_t reg; // cashier thread
pthread_t sup; // support thread for notify the manager
pthread_mutex_t lock;
pthread_cond_t notEmpty;
queue head; // queue of clients
queue tail; // queue of clients
};
typedef struct tC threadCassiere;
// struct info flow between clients and cashiers
struct var_cashier_client{
int index;
var_struct *vcm;
threadCassiere *regs;
};
// struct info flow to manager
struct var_manager{
var_struct *vcm;
infoQueueClient iqClientHead;
infoQueueClient iqClientTail;
infoQueueCashier *iqCashier;
};
#endif /* utily_h */
<file_sep>#define _POSIX_C_SOURCE 200112L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <signal.h>
#include <sys/time.h>
#include <errno.h>
#include <string.h>
#include "direttore.h"
#include "cassiere.h"
#include "utility.h"
_Thread_local unsigned int seed1; // seed thread local for rand_r
// insert client in the tail of queue
void insertClient(queue *head, queue *tail, queue *client){
if(*head == NULL){
*head = *client;
*tail = *head;
}
else{
(*tail)->next = *client;
(*tail) = *client;
}
}
// return the products buy by client in the head of queue
int clientAtCashier(queue head){
if(head == NULL)
return -1;
return head->buyProducts;
}
// remove the client in the head of queue
queue removeClient(queue *head, queue *tail){
if(*head == NULL){
perror(" Error rimosso cliente da lista vuota");
exit(EXIT_FAILURE);
}
if(*head == *tail){
pthread_mutex_lock(&(*head)->lock);
(*head)->served = 1;
pthread_cond_signal(&((*head)->myTurn));
pthread_mutex_unlock(&(*head)->lock);
queue aux = *head;
*head = NULL;
*tail = NULL;
return aux;
}
queue aux = *head;
pthread_mutex_lock(&(*head)->lock);
(*head)->served = 1;
pthread_cond_signal(&((*head)->myTurn));
pthread_mutex_unlock(&(*head)->lock);
*head = (*head)->next;
return aux;
}
// function for support thread of cashier, notify the manager
void *waitTimer(void *arg){
threadCassiere *tc = arg;
struct timespec t1;
int oldType;
pthread_detach(pthread_self());
if( pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldType) != 0){
perror("Error setcanceltype");
exit(EXIT_FAILURE);
}
// block signals
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGHUP);
sigaddset(&set, SIGQUIT);
if( pthread_sigmask(SIG_BLOCK, &set, NULL) != 0){
perror("Error pthread sigmask");
exit(EXIT_FAILURE);
}
t1.tv_sec = 0;
t1.tv_nsec = tc->intervalTime*100000000;
// dalay for inizializate cashier
nanosleep(&t1, NULL);
t1.tv_nsec = tc->intervalTime*1000000;
//notify manager at regular interval time
while(1){
nanosleep(&t1, NULL);
updateCashiers(tc->queueSize, tc->index);
}
return NULL;
}
// life cycle cashier
void *cassiere_work(void *arg){
threadCassiere *tc = arg;
struct timespec t1;
struct timespec openTime;
struct timespec closeTime;
queue client;
float diff, tService, tServiceTotal = 0;
int nProducts,clientServed = 0, totalProducts = 0, oldType;
if( pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldType) != 0){
perror(" Error setcanceltype");
exit(EXIT_FAILURE);
}
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGHUP);
sigaddset(&set, SIGQUIT);
if( pthread_sigmask(SIG_BLOCK, &set, NULL) != 0){
perror(" Error pthread sigmask");
exit(EXIT_FAILURE);
}
pthread_mutex_lock(&(tc->lock));
tc->reg = pthread_self();
// create the support thread for cashier
if( pthread_create(&(tc->sup), NULL, &waitTimer, (void*) tc) != 0 ){
perror(" Error create support thread reg");
exit(EXIT_FAILURE);
}
pthread_mutex_unlock(&(tc->lock));
// take start time of cashier
clock_gettime(CLOCK_MONOTONIC, &openTime);
while(1){
pthread_mutex_lock(&(tc->lock));
// wait clients, or to terminate
while(tc->head == NULL && tc->notFinish == 1){
pthread_cond_wait(&(tc->notEmpty), &(tc->lock));
}
if(tc->notFinish == 0){
#if defined(DEBUG)
printf(" [Cassiere %d] sto terminando\n", tc->index+1);
#endif
// take end time of cashier
clock_gettime(CLOCK_MONOTONIC, &closeTime);
diff = (closeTime.tv_sec - openTime.tv_sec) ;
if( (closeTime.tv_nsec -openTime.tv_nsec) < 0)
diff += ((float)( closeTime.tv_nsec -openTime.tv_nsec) *(-1) / 1000000000);
else
diff += ((float)( closeTime.tv_nsec -openTime.tv_nsec) / 1000000000);
updateInfoCashiers(tc->index, totalProducts, clientServed, diff, (float)tServiceTotal/1000000000);
pthread_mutex_unlock(&(tc->lock));
return NULL;
}
if ( (nProducts = clientAtCashier(tc->head))== -1){
perror(" Error clientAtCashier ");
exit(EXIT_FAILURE);
}
totalProducts += nProducts;
// calculate service time
tService = (tc->fixedTime + tc->productTime * nProducts) * 1000000;
if(tService >= 1000000000 ){
t1.tv_sec = tService / 1000000000;
t1.tv_nsec = ((int)tService % 1000000000);
}
else{
t1.tv_sec = 0;
t1.tv_nsec = tService;
}
// simulate to serve a client
nanosleep(&t1, NULL);
// save statistics of work
clientServed++;
tServiceTotal += tService;
client = removeClient(&(tc->head), &(tc->tail));
#if defined(DEBUG)
printf(" [Cassiere %d] sto servendo un nuovo cliente\n", tc->index+1);
#endif
pthread_mutex_lock(&(client->lock));
// served client and now wait client that calculate his queue time
while( client->queueTime == -1)
pthread_cond_wait(&(client->modified), &(client->lock));
client->serviceTime = (float)tService / 1000000000;
client->supermarketTime = client->serviceTime + client->buyTime + client->queueTime;
pthread_cond_signal(&(client->modified));
pthread_mutex_unlock(&(client->lock));
tc->queueSize--;
pthread_mutex_unlock(&(tc->lock));
fflush(stdout);
}
return NULL;
}
// initialize cashier variable
void cassiere_create(threadCassiere *tc, int tprod, int intTime, int index){
seed1 = (unsigned int) pthread_self()*(index+1)*10000;
srand(seed1);
tc->queueSize = 0;
tc->fixedTime = rand_r(&seed1)% ((80 +1) -20) +20;
tc->productTime = tprod;
tc->intervalTime = intTime;
tc->notFinish = 1;
if( pthread_mutex_init(&(tc->lock), NULL) != 0){
perror("Error initialize lock");
exit(EXIT_FAILURE);
}
if( pthread_cond_init(&(tc->notEmpty), NULL) != 0){
perror("Error initialize var cond");
exit(EXIT_FAILURE);
}
tc->head = NULL;
tc->tail = NULL;
tc->index = index;
}
<file_sep>// Created by <NAME> on 06/05/20.
// Copyright © 2020 <NAME>. All rights reserved.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include "direttore.h"
#include "utility.h"
//define K // numero di casse del supermercato
//define C // numero massimo di persone all'interno del supermercato
//define T // T tempo variabile speso dai clienti per fare acquisti
//define E // se il numero di clienti all'interno del supermercato
// scende sotto di E, ne vengono fatti entrare altri E
//define P // numero massimo di articoli acquistati per cliente
//define S1 // soglia per cui se S1 casse hanno al massimo un
// cliente una viene chiusa (una rimane sempre aperta)
//define S2 // soglia per cui se almeno una cassa ha S2 clienti in coda
// apre una nuova cassa (se possibile)
#define bufzise 128
#define namesize 32
pthread_mutex_t Mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t MtxInfo = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t NotFullClient = PTHREAD_COND_INITIALIZER;
pthread_cond_t Empty = PTHREAD_COND_INITIALIZER;
int numClient = 0;
int K, P, T, E, C, S1, S2, productTime, intervalTime, openCas;
infoQueueClient iqClientHead;
infoQueueClient iqClientTail;
infoQueueCashier *iqCashier;
// load the config file for the start info
void loadInputFile(char *config, char *log){
char *line = NULL, *word, *value;
FILE *f;
size_t len = 0;
ssize_t r;
f = fopen(config, "r");
if(f == NULL){
perror("Error fopen");
exit(EXIT_FAILURE);
}
while( (r = getline(&line , &len, f)) != -1){
word = strtok(line, " ");
value = strtok(NULL, " ");
if(strcmp(word, "K") == 0 ){
K = (int) atol(value);
continue;
}
if(strcmp(word, "P") == 0 ){
P = (int) atol(value);
continue;
}
if(strcmp(word, "T") == 0 ){
T = (int) atol(value);
continue;
}
if(strcmp(word, "E") == 0 ){
E = (int) atol(value);
continue;
}
if(strcmp(word, "C") == 0 ){
C = (int) atol(value);
continue;
}
if(strcmp(word, "S1") == 0 ){
S1 = (int) atol(value);
continue;
}
if(strcmp(word, "S2") == 0 ){
S2 = (int) atol(value);
continue;
}
if(strcmp(word, "logfile") == 0 ){
int n = strlen(value);
char *fchar = strpbrk( value, "\n");
strcpy(fchar, "");
strncpy(log, value, n);
continue;
}
if(strcmp(word, "product_time") == 0 ){
productTime = (int) atol(value);
continue;
}
if(strcmp(word, "interval_time") == 0 ){
intervalTime = (int) atol(value);
continue;
}
if( strcmp(word, "open_cashiers") == 0){
openCas = (int) atol(value);
continue;
}
printf("Stringa %s non roconosciuta\n", word);
exit(EXIT_FAILURE);
}
free(word);
fclose(f);
}
// load final info in the log file, if sigquitReceived is equal to 1
// don't load the cashier info in the log file, otherwise yes
void loadOutputFile(char* log, int sigquitReceived){
int i;
FILE *f;
f = fopen(log, "w+");
if(f == NULL){
perror("Error fopen");
exit(EXIT_FAILURE);
}
while(iqClientHead != NULL){
fprintf(f, "[Cliente] id %ld pBuy %d supermarketTime %0.3fs QueueTime %0.3fs changedQueue %d\n"
, iqClientHead->idClient, iqClientHead->buyProducts, iqClientHead->supermarketTime, iqClientHead->queueTime, iqClientHead->changedQueue );
infoQueueClient aux = iqClientHead;
iqClientHead = iqClientHead->next;
free(aux);
}
iqClientTail = NULL;
for(i=0; i<K; i++){
if( sigquitReceived != 1){
fprintf(f, "[Cassa] id %d processedProducts %d clients %d openTime %0.3fs averangeTimeService %0.3fs closures %d\n"
, iqCashier[i]->idCashier, iqCashier[i]->processedProducts, iqCashier[i]->clientServed, iqCashier[i]->openTime, iqCashier[i]->averangeTimeService
, iqCashier[i]->numberClosures);
}
free(iqCashier[i]);
}
free(iqCashier);
fclose(f);
#if defined(DEBUG)
printf("Dati raccolti durante il sistema, caricati nel file di log\n");
#endif
}
// supermarket
int main(int argc, const char * argv[]) {
var_struct *vcm = malloc(sizeof(var_struct));
struct var_manager *vcmM = malloc(sizeof(struct var_manager));
char config[namesize], log[namesize];
int i, status;
strcpy(config, "config.txt");
loadInputFile(config, log);
vcmM->iqClientHead = iqClientHead;
vcmM->iqClientTail = iqClientTail;
iqCashier = malloc(sizeof(nodoInfoCashier)*K);
for(i=0; i<K; i++){
iqCashier[i] = malloc(sizeof(nodoInfoCashier));
iqCashier[i]->idCashier = i+1;
iqCashier[i]->processedProducts = 0;
iqCashier[i]->clientServed = 0;
iqCashier[i]->numberClosures = 0;
iqCashier[i]->openTime = 0;
iqCashier[i]->averangeTimeService = 0;
}
vcm->numClient = C; // at start all clients enter in the supermarket
vcm->openCashiers = openCas;
vcm->finish = 0;
vcm->sigquitReceived = 0;
vcm->NotFullClient = NotFullClient;
vcm->Empty = Empty;
vcm->mtx = Mtx;
vcmM->iqCashier = iqCashier;
vcmM->vcm = vcm;
// create the manager
pthread_t manager;
pthread_create(&manager, NULL, &direttore, (void*) vcmM);
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGHUP);
sigaddset(&set, SIGQUIT);
if( pthread_sigmask(SIG_BLOCK, &set, NULL) != 0){
perror("Error pthread sigmask");
exit(EXIT_FAILURE);
}
sleep(25);
pthread_kill(manager, SIGHUP);
#if defined(DEBUG)
printf("\n\n mandato SIGHUP\n\n");
#endif
pthread_join(manager,(void*) &status);
loadOutputFile(log, vcm->sigquitReceived);
free(vcm);
free(vcmM);
return 0;
}
<file_sep>#define _POSIX_C_SOURCE 200112L
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include "direttore.h"
#include "cliente.h"
#include "cassiere.h"
#include "utility.h"
int *queueSize;
int threshold1 , threshold2;
int count = 0;
volatile sig_atomic_t notFinishManager = 1; // 1 if supermarket is open
volatile sig_atomic_t sigquitReceived; // 1 if sigquit received
threadCassiere *cassieri;
var_struct *vcm;
struct var_cashier_client *var;
pthread_t *threadCashiers; // pthread_t array of cashiers
pthread_t *threadClients; // pthread_t array of clients
infoQueueClient iqClientHead;
infoQueueClient iqClientTail;
infoQueueCashier *iqCashier;
// move the client in the cashier's queue of other cashier
// randomly, index represent the cashier that is closing
void moveClient(int index){
queue client;
queue aux = cassieri[index].head;
while( aux != NULL){
client = aux;
client->next = NULL;
client->changedQueue += 1;
insertInCashiersQueue(&client, index, vcm, cassieri);
aux = aux->next;
}
cassieri[index].head = NULL;
cassieri[index].tail = NULL;
#if defined(DEBUG)
printf(" [Direttore] i clienti del cassiere %d sono stati spostati\n", index+1);
#endif
}
// close the cashier with bigger index, and move the clients
// in the queue of other cashiers. If numbers of cashiers are > 1
void closeCashier(){
static int index, status;
pthread_mutex_lock(&(vcm->mtx));
if( vcm->openCashiers == 1){
pthread_mutex_unlock(&(vcm->mtx));
return;
}
vcm->openCashiers--;
index = vcm->openCashiers;
// block the cashiers that must close
pthread_mutex_lock(&(cassieri[index].lock));
moveClient(index);
cassieri[index].notFinish = 0;
pthread_mutex_unlock(&(vcm->mtx));
pthread_mutex_unlock(&(cassieri[index].lock));
pthread_cancel(cassieri[index].sup);
pthread_mutex_lock(&(cassieri[index].lock));
pthread_cond_signal(&(cassieri[index].notEmpty));
pthread_mutex_unlock(&(cassieri[index].lock));
pthread_join(cassieri[index].reg, (void*)&status);
printf(" [Direttore] cassiere %d chiuso\n", index+1);
}
// open the cashier with smaller index, if
// numbers of cashiers are < K
void openCashier(){
int index;
pthread_mutex_lock(&(vcm->mtx));
if(vcm->openCashiers == K){
pthread_mutex_unlock(&(vcm->mtx));
return;
}
vcm->openCashiers ++;
index = vcm->openCashiers -1 ;
cassiere_create(&cassieri[index], productTime, intervalTime, index);
if( pthread_create(&threadCashiers[index], NULL, &cassiere_work,(void*) &(cassieri[index])) != 0){
perror("Error create cashier ");
exit(EXIT_FAILURE);
}
pthread_mutex_unlock(&(vcm->mtx));
printf(" [Direttore] cassiere %d aperto\n", index+1);
}
// check the thresholds, and if the values are not respected
// open or close the cashiers
void checkCashiers(){
static int numRegOneClient = 0, numCashiers;
pthread_mutex_lock(&(vcm->mtx));
numCashiers = vcm->openCashiers;
pthread_mutex_unlock(&(vcm->mtx));
for(int i=0; i<numCashiers; i++){
if( queueSize[i] <= 1 )
numRegOneClient++;
if(S1 == numRegOneClient){
closeCashier();
return;
}
if( queueSize[i] >= S2){
openCashier();
return;
}
}
}
// this function is used by cashier to notify the manager
void updateCashiers(int qSize, int index){
pthread_mutex_lock(&(vcm->mtx));
count++;
queueSize[index] = qSize;
if( vcm->openCashiers == count && !vcm->finish ){
count = 0;
pthread_mutex_unlock(&(vcm->mtx));
checkCashiers();
return;
}
pthread_mutex_unlock(&(vcm->mtx));
}
// handler for SIGQUIT; Terminate all clients and cashiers immediatly
void handlerSigQuit(int sig){
write(1, "catturato SIGQUIT\n", 20);
notFinishManager = 0;
vcm->sigquitReceived = 1;
vcm->finish = 1;
}
// handler for SIGHUP; Wait the termination of clients inside the
// supermarket, after close the cashiers
void handlerSigHup(int sig){
write(1, "catturato SIGHUP\n", 20);
notFinishManager = 0;
vcm->finish = 1;
}
// clean pthread_t of client with this index
void clientExit(int index){
threadClients[index] = 0;
}
// wait client to terminate
void waitClient(){
#if defined(DEBUG)
printf("Entrato nella waitClient\n");
#endif
pthread_mutex_lock(&(vcm->mtx));
#if defined(DEBUG)
printf(" Devo far uscire %d clients\n", vcm->numClient);
#endif
if(vcm->numClient != 0){
while(vcm->numClient != 0){
pthread_cond_wait(&(vcm->Empty), &(vcm->mtx));
}
}else{
#if defined(DEBUG)
printf(" [Direttore] Non ho clienti nel supermercato esco\n");
#endif
}
pthread_mutex_unlock(&(vcm->mtx));
}
void updateInfoClients(pthread_t idClient, int buyProducts, int changedQueue, float supermarketTime, float queueTime) {
pthread_mutex_lock(&(vcm->mtx));
infoQueueClient new = malloc(sizeof(nodoInfoClient));
new->idClient = idClient;
new->buyProducts = buyProducts;
new->changedQueue = changedQueue;
new->supermarketTime = supermarketTime;
new->queueTime = queueTime;
new->next = NULL;
if(iqClientHead == NULL){
iqClientHead = new;
iqClientTail = new;
}
else{
iqClientTail->next = new;
iqClientTail = new;
}
pthread_mutex_unlock(&(vcm->mtx));
}
void updateInfoCashiers(int index, int processedProducts, int clientServed, float openTime, float averangeTimeService){
pthread_mutex_lock(&(vcm->mtx));
iqCashier[index]->processedProducts += processedProducts;
iqCashier[index]->clientServed += clientServed;
iqCashier[index]->numberClosures++;
iqCashier[index]->openTime += openTime;
iqCashier[index]->averangeTimeService += averangeTimeService;
pthread_mutex_unlock(&(vcm->mtx));
}
// life cycle of manager
void *direttore(void *arg){
struct var_manager *vcmM = arg;
vcm = vcmM->vcm;
iqCashier = vcmM->iqCashier;
iqClientHead = vcmM->iqClientHead;
iqClientTail = vcmM->iqClientTail;
static int i;
int status, thresholdC = C-E, add = 0, numCashiers;
queueSize = malloc(sizeof(int)*K);
for(i=0; i<K; i++)
queueSize[i] = 0;
cassieri = malloc(sizeof(threadCassiere)*K);
var = malloc(sizeof(struct var_cashier_client)*C);
struct sigaction sa;
sigaction(SIGQUIT, NULL, &sa);
memset(&sa, 0, sizeof(sa));
sa.sa_handler = handlerSigQuit;
sigaction(SIGQUIT, &sa, NULL);
sa.sa_handler = handlerSigHup;
sigaction(SIGHUP, &sa, NULL);
// at start open a number of cashiers define in the config file
pthread_mutex_lock(&(vcm->mtx));
printf(" [Direttore] cassieri aperti all'inizio: %d\n", vcm->openCashiers);
pthread_mutex_unlock(&(vcm->mtx));
// create first cashiers
threadCashiers = malloc(sizeof(pthread_t)*K);
threadClients = malloc(sizeof(pthread_t)*C);
for( i=0; i<vcm->openCashiers; i++){
cassiere_create(&cassieri[i], productTime, intervalTime, i);
if( pthread_create(&threadCashiers[i], NULL, &cassiere_work,(void*) &(cassieri[i])) != 0){
perror(" Error create register ");
exit(EXIT_FAILURE);
}
}
// create first C clients
for( i=0; i<C; i++){
var[i].vcm = vcm;
var[i].regs = cassieri;
var[i].index = i;
if( pthread_create(&threadClients[i], NULL, &client, (void*) &var[i]) != 0){
perror(" Error create client ");
exit(EXIT_FAILURE);
}
}
// cycle for insert new client in the supermarket when
// C-E clients are exit
while(notFinishManager){
fflush(stdout);
pthread_mutex_lock(&(vcm->mtx));
// if numbers of client inside supermarket is less
// than numbers of threshold then add new E client
while( vcm->numClient > thresholdC)
pthread_cond_wait(&(vcm->NotFullClient), &(vcm->mtx));
if( !notFinishManager ){
pthread_mutex_unlock(&(vcm->mtx));
continue;
}
printf(" [Direttore] creo %d nuovi clienti\n", E);
vcm->numClient += E;
i = 0;
while(add < E && i<C){
if(threadClients[i] != 0){
i++;
continue;
}
var[i].vcm = vcm;
var[i].regs = cassieri;
var[i].index = i;
add++;
if( pthread_create(&threadClients[i], NULL, &client, (void*) &var[i]) != 0){
perror(" Error create client ");
exit(EXIT_FAILURE);
}
i++;
}
if(add != E){
perror(" Error create new client");
exit(EXIT_FAILURE);
}
add = 0;
pthread_mutex_unlock(&(vcm->mtx));
}
// if i received a signal SIGQUIT i must close the clients
// and the cashiers as fast as possible
if( vcm->sigquitReceived ){
pthread_mutex_lock(&(vcm->mtx));
for(i=0; i<C; i++){
pthread_cancel(threadClients[i]);
}
for(i=0; i<vcm->openCashiers; i++){
cassieri[i].notFinish = 0;
pthread_cancel(cassieri[i].sup);
pthread_cancel(threadCashiers[i]);
}
pthread_mutex_unlock(&(vcm->mtx));
#if defined(DEBUG)
printf(" [Direttore] Ho fatto uscire tutti i clienti e chiuso i cassieri\n");
#endif
return NULL;
}
// wait all clients
waitClient();
pthread_mutex_lock(&(vcm->mtx));
printf(" [Direttore] Persone ancora nel supermercato: %d, cassieri aperti %d\n", vcm->numClient, vcm->openCashiers);
numCashiers = vcm->openCashiers;
// close all open cashiers
pthread_mutex_unlock(&(vcm->mtx));
for(i=0; i<numCashiers; i++){
pthread_mutex_lock(&(cassieri[i].lock));
cassieri[i].notFinish = 0;
pthread_mutex_unlock(&(cassieri[i].lock));
pthread_cancel(cassieri[i].sup);
pthread_cond_signal(&(cassieri[i].notEmpty));
pthread_join(threadCashiers[i], (void*)&status);
}
// update info cashiers
for(i=0; i<K; i++){
if(iqCashier[i]->clientServed != 0)
iqCashier[i]->averangeTimeService = (float)iqCashier[i]->averangeTimeService / iqCashier[i]->clientServed;
}
#if defined(DEBUG)
printf(" [Direttore] ho finito di chiudere i cassieri\n");
#endif
free(queueSize);
free(cassieri);
free(var);
free(threadClients);
free(threadCashiers);
return NULL;
}
<file_sep>#ifndef cliente_h
#define cliente_h
#include "utility.h"
// life cycle of client
void *client(void *arg);
// insert the client in cashier's tail of that index
void insertInCashiersQueue(queue *client, int index, var_struct *vcm, threadCassiere *registers);
#endif /* cliente_h */
<file_sep>#!/bin/bash
chmod +x $0
echo " Statistiche Clienti:"
awk '$1 == "[Cliente]"' log.txt | awk -F' ' '{ print "|id: " $3 " |buyProducts: " $5 "|supermarketTime: " $7 "|queueTime: " $9 "|changedQueue: " $11 "|"}'
echo ""
echo " Statistiche Cassieri:"
awk '$1 == "[Cassa]"' log.txt | awk -F' ' '{ print "|id: " $3 " |processedProducts: " $5 "|clientServed: " $7 "|openTime: " $9 "|avgTime: " $11 "|closures: " $13 "|"}'
<file_sep>#ifndef direttore_h
#define direttore_h
// life cycle of manager
void *direttore(void *arg);
// this function is used by cashier to notify the manager
void updateCashiers(int queueSize, int index);
// clean pthread_t of client with this index
void clientExit(int index);
void updateInfoClients(pthread_t idClient, int buyProducts, int changedQueue, float supermarketTime, float queueTime);
void updateInfoCashiers(int index, int processedProducts, int clientServed, float openTime, float averangeTimeService);
#endif /* direttore_h */
<file_sep>// Created by <NAME> on 06/05/20.
// Copyright © 2020 <NAME>. All rights reserved.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include "direttore.h"
#include "utility.h"
//define K 4 // numero di casse del supermercato
//define C 20 // numero massimo di persone all'interno del supermercato
//define T 200 // T tempo variabile speso dai clienti per fare acquisti
//define E 5 // se il numero di clienti all'interno del supermercato
// scende sotto di E, ne vengono fatti entrare altri E
//define P 6 // numero massimo di articoli acquistati per cliente
//define S1 2 // soglia per cui se S1 casse hanno al massimo un
// cliente una viene chiusa
//define S2 7 // soglia per cui se almeno una cassa ha S2 clienti in coda
// apre una nuova cassa (se possibile)
#define bufzise 128
#define namesize 32
pthread_mutex_t Mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t NotFullClient = PTHREAD_COND_INITIALIZER;
pthread_cond_t Empty = PTHREAD_COND_INITIALIZER;
int numClient = 0;
int K, P, T, E, C, S1, S2, productTime, intervalTime;
void loadFile(char *config, char *log){
char *line = NULL, *word, *value;
FILE *f;
size_t len = 0;
ssize_t r;
f = fopen(config, "r");
if(f == NULL){
perror("Error fopen");
exit(EXIT_FAILURE);
}
while( (r = getline(&line , &len, f)) != -1){
word = strtok(line, " ");
value = strtok(NULL, " ");
if(strcmp(word, "K") == 0 ){
K = (int) atol(value);
continue;
}
if(strcmp(word, "P") == 0 ){
P = (int) atol(value);
continue;
}
if(strcmp(word, "T") == 0 ){
T = (int) atol(value);
continue;
}
if(strcmp(word, "E") == 0 ){
E = (int) atol(value);
continue;
}
if(strcmp(word, "C") == 0 ){
C = (int) atol(value);
continue;
}
if(strcmp(word, "S1") == 0 ){
S1 = (int) atol(value);
continue;
}
if(strcmp(word, "S2") == 0 ){
S2 = (int) atol(value);
continue;
}
if(strcmp(word, "logfile") == 0 ){
strcpy(log, value);
continue;
}
if(strcmp(word, "product_time") == 0 ){
productTime = (int) atol(value);
continue;
}
if(strcmp(word, "interval_time") == 0 ){
intervalTime= (int) atol(value);
continue;
}
printf("Stringa %s non roconosciuta\n", word);
exit(EXIT_FAILURE);
}
//free(filename);
free(word);
//free(value);
fclose(f);
}
int main(int argc, const char * argv[]) {
var_client_manager *vcm = malloc(sizeof(var_client_manager));
char config[namesize], log[namesize];
int status;
sigset_t set;
FILE *f;
sigemptyset(&set);
sigaddset(&set, SIGQUIT);
sigaddset(&set, SIGHUP);
if( pthread_sigmask(SIG_SETMASK, &set, NULL) != 0 ){
perror("Error pthread_simask ");
exit(EXIT_FAILURE);
}
strcpy(config, "config.txt");
loadFile(config, log);
vcm->numClient = C; // all'inizio entrano tutti i clienti
vcm->finish = 0;
vcm->NotFullClient = NotFullClient;
vcm->Empty = Empty;
vcm->mtx = Mtx;
pthread_t supermercato;
pthread_create(&supermercato, NULL, &direttore, (void*) vcm);
//pthread_detach(supermercato);
printf(" PID SUPERMARKET: %ld\n", supermercato);
f = fopen(log, "w+");
fprintf(f, "%ld", supermercato);
fclose(f);
//printf("T: %d\n", vcm->t);
pthread_join(supermercato,(void*) &status);
printf("Stato di terminazione del manager: %d\n", status);
free(vcm);
//pthread_exit(0);
return 0;
}
| 5ca5cc8ce9fe467eec7e969016ba90fa9f9a16c2 | [
"Markdown",
"C",
"Makefile",
"Shell"
] | 12 | C | alexnicco98/ProgettoSol | 242b6178aef531a5772c9a70854fb904da3c0465 | 16c56c0065382d307160b9220a53830e8e2aad9f |
refs/heads/master | <file_sep># coding=utf-8
import re
import numpy as np
import random
import logging
import logging.handlers
from apscheduler.schedulers.blocking import BlockingScheduler
from twython import Twython, TwythonError
from secrets import *
LOGGER = logging.getLogger('boiade_service')
LOGGER.setLevel(logging.DEBUG)
# rotating file handler
FH = logging.handlers.RotatingFileHandler('boiade.log', maxBytes=10000000, backupCount=5)
FH.setLevel(logging.INFO)
# console handler
CH = logging.StreamHandler()
CH.setLevel(logging.INFO)
# add the handlers to the logger
LOGGER.addHandler(FH)
LOGGER.addHandler(CH)
STATES = ['<START>', 'dé', 'ma', 'allora', 'certo', 'però', 'comunque', 'boia', '<EOM>']
MARKOV = [[0, 1/7, 1/7, 1/7, 1/7, 1/7, 1/7, 1/7, 0], # <START>
[0, 0, 0.7/7, 0.8/7, 0.7/7, 0.4/7, 0.7/7, 0.7/7, 3/7], # dé
[0, 6/25, 0, 6/25, 3/25, 6/25, 0, 4/25, 0], # ma
[0, 1.4/4, 0, 0, 0, 1.2/4, 0, 1.2/4, 0.2/4], # allora
[0, 11/25, 2/25, 2/25, 0, 5/25, 0, 3/25, 2/25], # certo
[0, 14/20, 0, 2/20, 2/20, 0, 0, 2/20, 0], # però
[0, 12/25, 0, 1/25, 1/25, 1/25, 0, 10/25, 0], # comunque
[0, 1/7, 0.7/7, 0.6/7, 0.6/7, 0.6/7, 0.5/7, 0, 3/7]] # boia
TWITTER_API = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
SCHEDULER = BlockingScheduler()
def generate_next_token(last_token):
row_index = STATES.index(last_token)
next_token = np.random.choice(STATES, 1, p=MARKOV[row_index])
return next_token[0]
def generate_status():
generated_sequence = []
last_token = '<START>'
while True:
next_token = generate_next_token(last_token)
if next_token == '<EOM>':
status = ''
for token in generated_sequence:
status += token + ' '
# status = status[:-1] + '.'
status = re.sub(r'(boia dé|dé|boia)', r'\1,', status)
status = re.sub(r',\s$|.$', '.', status)
# A sentence should end with 'certo...' rather than 'certo.'
status = re.sub(r'certo.$', 'certo...', status)
return status.capitalize()
generated_sequence.append(next_token)
last_token = next_token
def tweet():
status = generate_status()
try:
TWITTER_API.update_status(status=status, lat=43.5519, long=10.308)
LOGGER.info('Tweeted status: %s', status.encode())
except TwythonError as err:
LOGGER.error(err)
fallback = status[:-1] + '!'
LOGGER.info('Tweeted status: %s', fallback)
TWITTER_API.update_status(status=fallback)
SCHEDULER.remove_job('boiade')
next_run = random.randint(30, 60)
LOGGER.info('Next tweet scheduled in %s minutes', next_run)
SCHEDULER.add_job(tweet, 'interval', minutes=next_run, id='boiade')
SCHEDULER.add_job(tweet, 'interval', seconds=0, id='boiade')
try:
SCHEDULER.start()
except (KeyboardInterrupt, SystemExit, TwythonError) as err:
LOGGER.error(err) | 4297e76d7d706a7ffda43e05591a7dfa9c6efc55 | [
"Python"
] | 1 | Python | andremann/twitter-bot-livornese-imbruttito | 11c1c1a043412ec7d9d5e925707855b44d705eb7 | dc14feb782f755774b7a44c9338324aab345c358 |
refs/heads/master | <repo_name>faierbol/soxialit-landing<file_sep>/spec/routing/paintings_routing_spec.rb
require "spec_helper"
describe PaintingsController do
describe "routing" do
it "routes to #index" do
get("/paintings").should route_to("paintings#index")
end
it "routes to #new" do
get("/paintings/new").should route_to("paintings#new")
end
it "routes to #show" do
get("/paintings/1").should route_to("paintings#show", :id => "1")
end
it "routes to #edit" do
get("/paintings/1/edit").should route_to("paintings#edit", :id => "1")
end
it "routes to #create" do
post("/paintings").should route_to("paintings#create")
end
it "routes to #update" do
put("/paintings/1").should route_to("paintings#update", :id => "1")
end
it "routes to #destroy" do
delete("/paintings/1").should route_to("paintings#destroy", :id => "1")
end
end
end
<file_sep>/app/models/membership.rb
class Membership < ActiveRecord::Base
attr_accessible :group_id, :user_id
belongs_to :user
belongs_to :group
validates :group_id, presence: true
validates :user_id, presence: true
def self.get_group_stories(user)
get_group_stories = "SELECT user_id FROM memberships
WHERE user_id = :user_id"
where("user_id IN (#{get_group_stories}) OR user_id = :user_id",
user_id: user.id)
end
end
<file_sep>/app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
if user.role? :admin
can :manage, :all
elsif user.role? :designer
can :update, User, :id => user.id
can [:items, :muro, :biografia, :favorites, :bio, :followers, :following, :designer, :boutique, :fashionlover, :fotografo, :blogger, :ubicacion, :perfil, :notificacion, :product_modal], User
can [:paypal_checkout, :envio_df, :tallas, :comprar, :envio, :mercadopago_checkout], Product
can :create, Product
can :update, Product do |product|
product.try(:user) == user
end
can :destroy, Product do |product|
product.try(:user) == user
end
can :vote, Product
cannot :vote, Product, :user_id => user.id
can :vote, Micropost
cannot :vote, Micropost, :user_id => user.id
#can :create, Micropost
can :read, :all
elsif user.role? :'fashion lover'
can :update, User, :id => user.id
can [:items, :muro, :biografia, :favorites, :list_projects, :followers, :bio,:following, :designer, :boutique, :fashionlover, :fotografo, :blogger, :ubicacion, :perfil, :notificacion], User
can [:paypal_checkout, :envio_df, :tallas, :comprar, :envio, :mercadopago_checkout], Product
can :vote, Product
cannot :vote, Micropost, :user_id => user.id
#can :create, Micropost
can :read, :all
elsif user.role? :'blogger'
can :update, User, :id => user.id
can [:items, :muro, :biografia, :favorites, :list_projects, :followers, :following, :bio,:designer, :boutique, :fashionlover, :fotografo, :blogger, :ubicacion, :perfil, :notificacion], User
can [:paypal_checkout, :envio_df, :tallas, :comprar, :envio, :mercadopago_checkout], Product
can :vote, Product
cannot :vote, Micropost, :user_id => user.id
#can :create, Micropost
can :read, :all
elsif user.role? :'fotografo'
can :update, User, :id => user.id
can [:items, :muro, :biografia, :favorites, :list_projects, :followers, :following, :designer, :bio,:boutique, :fashionlover, :fotografo, :blogger, :ubicacion, :perfil, :notificacion], User
can [:paypal_checkout, :envio_df, :tallas, :comprar, :envio, :mercadopago_checkout], Product
can :vote, Product
cannot :vote, Micropost, :user_id => user.id
#can :create, Micropost
can :read, :all
elsif user.role? :'boutique store'
can :update, User, :id => user.id
can [:items, :muro, :biografia, :favorites, :list_projects, :bio, :followers, :following, :designer, :boutique, :fashionlover, :fotografo, :blogger, :ubicacion, :perfil, :notificacion, :product_modal], User
can [:paypal_checkout, :envio_df, :tallas, :comprar, :envio, :mercadopago_checkout], Product
can :create, Product
can :update, Product do |product|
product.try(:user) == user
end
can :destroy, Product do |product|
product.try(:user) == user
end
can :vote, Product
cannot :vote, Product, :user_id => user.id
can :vote, Micropost
cannot :vote, Micropost, :user_id => user.id
#can :create, Micropost
can :read, :all
else
can :read, :all
can [:items, :muro, :biografia, :favorites, :list_projects, :followers, :following, :designer, :boutique, :bio, :fashionlover, :fotografo, :blogger, :ubicacion, :perfil], User
can [:show, :envio_df, :tallas, :comprar, :envio, :mercadopago_checkout], Product
can [:paypal_checkout, :new, :create, :show], Pay
end
end
end<file_sep>/app/uploaders/group_picture_uploader.rb
# encoding: utf-8
class GroupPictureUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :index_500 do
process :resize_to_fill => [500,270, Magick::NorthGravity]
end
end<file_sep>/app/controllers/paintings_controller.rb
class PaintingsController < ApplicationController
def index
@paintings = Painting.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @paintings }
end
end
def show
@painting = Painting.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @painting }
end
end
# GET /paintings/new
# GET /paintings/new.json
def new
@painting = Painting.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @painting }
end
end
# GET /paintings/1/edit
def edit
@product = Product.find(params[:id])
@painting = @product.paintings.create(params[:painting])
respond_to do |format|
format.html { redirect_to @painting, notice: 'Painting was successfully created.' }
format.json { render json: @painting, status: :created, location: @painting }
format.js
end
end
def create
@painting = Painting.create(params[:painting])
@product = Product.find(@painting.product_id)
if @product.paintings.any?
picture_first = @product.paintings.first.image_url(:feed).to_s
@product.update_attribute(:picture, picture_first)
end
#if @product.paintings.any?
# @product.update_attribute(:picture, @product.paintings.first.image_url(:feed).to_s)
# logger.debug "parametro envio es: #{@product.paintings.first.image_url.to_s}\n\n\n\n\n\n"
#end
end
def update
@painting = Painting.find(params[:id])
respond_to do |format|
if @painting.update_attributes(params[:painting])
format.html { redirect_to @painting, notice: 'Painting was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @painting.errors, status: :unprocessable_entity }
end
end
end
def destroy
@painting = Painting.find(params[:id])
@painting.destroy
respond_to do |format|
format.html { redirect_to paintings_url }
format.json { head :ok }
format.js
end
end
end
def find_id
@paintings = @product.paintings.first
return @paintings.product_id
end<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
before_filter :authenticate_user!, :except => [:show, :list_items, :list_projects, :favorites, :muro, :biografia, :items,
:followers, :following, :fotografo, :boutique, :fashionlover, :blogger, :bio, :designer, :index, :ubicacion, :product_modal ]
#before_filter :authenticate_user!, :only => [:index, :new, :edit, :create, :update]
load_and_authorize_resource
layout "test", :only => [:show, :coleccion, :biografia, :favorites, :muro, :following, :followers]
def index
#@users = User.all
@users = User.find(:all, :order => "created_at DESC") #Show in reverse order
@fashionlovers = find_fashionlover(@users)
@admin = User.find(1) unless Rails.env.development?
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end
def show
#@user = User.find(params[:id])
@user = User.find_by_username(params[:username])
@last = Micropost.last
if @user.nil?
flash[:error] = "No se ha encontrado la URL."
redirect_to root_path
else
@products = product_ok(@user.products)
@activities = @user.activities.order("created_at DESC")
@comment = Comment.new
respond_to do |format|
format.html
end
end
end
def product_ok(items)
products = []
items.each do |item|
if item.status == true
products << item
end
end
return products
end
def avoid_nil(products)
items = []
products.each do |product|
if product.title.nil? && product.description.nil?
product.destroy
else
items << product
end
end
return items
end
# GET /users/new
# GET /users/new.json
def new
@user = User.new
respond_to do |format|
format.html # new.html.erb
end
end
# GET /users/1/edit
def edit
#@user = User.find(params[:id])
@user = User.find_by_username(params[:username])
@direction = Direction.new
@address = @user.direction
end
# POST /users
# POST /users.json
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
else
format.html { render action: "new" }
end
end
end
# PUT /users/1
# PUT /users/1.json
def update
#@user = User.find(params[:id])
@user = User.find_by_username(params[:username])
respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to @user, notice: 'Tus datos fueron actualizados correctamente.' }
else
format.html { render action: "edit" }
end
end
end
def following
#@user = User.find(params[:id])
@user = User.find_by_username(params[:username])
@users = @user.followed_users
end
def followers
@user = User.find_by_username(params[:username])
#@user = User.find(params[:id])
@users = @user.followers
end
def bio
@user = User.find(params[:user_id])
end
def coleccion
@user = User.find_by_username(params[:username])
@galleries = @user.galleries.all
if @user.nil?
flash[:error] = "No se ha encontrado la URL."
redirect_to root_path
else
@products = product_ok(@user.products)
@activities = @user.activities.order("created_at DESC")
@comment = Comment.new
end
end
def list_projects
#@user = User.find(params[:id])
@user = User.find_by_username(params[:username])
@projects = @user.projects.find(:all, :order => 'created_at DESC')
end
def list_items
#@user = User.find(params[:id])
@user = User.find_by_username(params[:username])
@products = product_ok(@user.products)
respond_to do |format|
format.js
end
end
def items
@user = User.find_by_username(params[:username])
if @user.username == "eileen"
@items = [Product.find(276),Product.find(277), Product.find(279), Product.find(280), Product.find(281), Product.find(282)]
elsif @user.username == "missviva"
@items = [Product.find(290), Product.find(291), Product.find(292), Product.find(293), Product.find(294), Product.find(295), Product.find(296), Product.find(297), Product.find(298), Product.find(299), Product.find(300)]
end
end
def muro
@user = User.find_by_username(params[:username])
@activities = @user.activities.order("created_at DESC")
@comment = Comment.new
end
def biografia
@user = User.find_by_username(params[:username])
end
def favorites
#@user = User.find(params[:id], :order => "created_at DESC")
@user = User.find_by_username(params[:username], :order => "created_at DESC")
end
def designer
@users = User.all
@designers = find_designer(@users)
@admin = User.find(1)
end
def find_designer(users)
designers = []
users.each do |user|
if user.roles.first.name == "designer"
designers << user
end
end
return designers
end
def product_modal
end
def fashionlover
@users = User.all
@fashionlovers = find_fashionlover(@users)
@admin = User.find(1)
end
def find_fashionlover(users)
fashionlover = []
users.each do |user|
if user.roles.first.name == "fashion lover"
fashionlover << user
end
end
return fashionlover
end
def boutique
@users = User.all
@boutiques = find_boutiques(@users)
@admin = User.find(1)
end
def find_boutiques(users)
boutiques = []
users.each do |user|
if user.roles.first.name == "boutique store"
boutiques << user
end
end
return boutiques
end
def blogger
@users = User.all
@bloggers = find_bloggers(@users)
@admin = User.find(1)
end
def find_bloggers(users)
bloggers = []
users.each do |user|
if user.roles.first.name == "blogger"
bloggers << user
end
end
return bloggers
end
def fotografo
@users = User.all
@fotografos = User.find(:all, :conditions )
@fotografos = find_fotografos(@users)
@admin = User.find(1)
end
def find_fotografos(users)
fotografos = []
users.each do |user|
if user.roles.first.name == "fotografo"
fotografos << user
end
end
return fotografos
end
def ubicacion
@user = User.find(params[:user_id])
@direction = Direction.new
@address = @user.direction
end
def perfil
@user = User.find(params[:user_id])
end
def notificacion
@user = User.find(params[:user_id])
end
#Not finished, better using only AJAX
def subscribed
@user = find_by_username(params[:username])
@groups = @user.groups
end
end<file_sep>/app/helpers/projects_helper.rb
module ProjectsHelper
def find_user_project(project)
a = User.find(project)
a.username
end
def find_user_image(project)
a = User.find(project)
b = "http://graph.facebook.com/#{a.uid}/picture?type=square"
end
def find_location(project)
a = User.find(project)
a.location
end
def find_user_image_profile(project)
a = User.find(project)
a.picture_url(:profile)
end
end
<file_sep>/app/models/activity.rb
class Activity < ActiveRecord::Base
attr_accessible :activitable_id, :activitable_type, :user_id, :action, :created_at
belongs_to :activitable, :polymorphic => true
belongs_to :user
has_many :comments, :as => :commentable, :dependent => :destroy
def self.from_users_followed_by(user)
followed_user_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
where("user_id IN (#{followed_user_ids}) OR user_id = :user_id",
user_id: user.id)
end
def self.expire_feed_cache(current_user)
user = current_user
Rails.cache.delete("feed_user_#{user.id}")
end
end<file_sep>/app/controllers/sources_controller.rb
class SourcesController < ApplicationController
def index
@sources = Source.order(:name)
respond_to do |format|
format.html
format.json { render json: @sources.tokens(params[:q]) }
end
end
def show
end
end
<file_sep>/db/migrate/20130106164230_add_postion_to_picture.rb
class AddPostionToPicture < ActiveRecord::Migration
def change
add_column :pictures, :position, :boolean
end
end
<file_sep>/spec/routing/pays_routing_spec.rb
require "spec_helper"
describe PaysController do
describe "routing" do
it "routes to #index" do
get("/pays").should route_to("pays#index")
end
it "routes to #new" do
get("/pays/new").should route_to("pays#new")
end
it "routes to #show" do
get("/pays/1").should route_to("pays#show", :id => "1")
end
it "routes to #edit" do
get("/pays/1/edit").should route_to("pays#edit", :id => "1")
end
it "routes to #create" do
post("/pays").should route_to("pays#create")
end
it "routes to #update" do
put("/pays/1").should route_to("pays#update", :id => "1")
end
it "routes to #destroy" do
delete("/pays/1").should route_to("pays#destroy", :id => "1")
end
end
end
<file_sep>/app/controllers/partners_controller.rb
class PartnersController < ApplicationController
def index
@partner = Partner.new
respond_to do |format|
format.html # new.html.erb
end
end
def create
if user_signed_in?
@partner = current_user.partners.build(params[:partner])
else
@partner = Partner.create(params[:partner])
end
respond_to do |format|
if @partner.save
if user_signed_in?
format.html { redirect_to current_user, notice: 'Gracias, en breve nos pondremos en contacto contigo.' }
else
format.html { redirect_to root_path, notice: 'Gracias, en breve nos pondremos en contacto contigo.' }
end
else
format.html { render action: "index" }
end
end
end
end
<file_sep>/app/controllers/feedbacks_controller.rb
class FeedbacksController < ApplicationController
def index
@feedback = Feedback.new
@feedbacks = Feedback.all
respond_to do |format|
format.html # new.html.erb
end
end
def create
@feedback = current_user.feedbacks.build(params[:feedback])
respond_to do |format|
if @feedback.save
format.html { redirect_to current_user, notice: 'Gracias por tu ayuda.' }
else
format.html { render action: "index" }
end
format.js
end
end
end<file_sep>/app/helpers/microposts_helper.rb
module MicropostsHelper
def find_micropost_imagefile(id)
a = Micropost.find(id)
b = User.find(a.user_id)
c = b.picture_url(:profile)
return c
end
def find_micropost_userimage(id)
a = Micropost.find(id)
b = User.find(a.user_id)
c = "http://graph.facebook.com/#{b.uid}/picture?type=square"
return c
end
def find_micropost_nickname(id)
a = Micropost.find(id)
b = User.find(a.user_id)
b.nickname
end
def reputation_value(evaluations)
evaluation = []
if !evaluations.nil?
evaluations.each do |voto|
evaluation << voto.value
end
evaluation.inject{|sum, x| sum + x}
else
0
end
end
end
<file_sep>/app/mailers/notifier.rb
class Notifier < ActionMailer::Base
def support_notification(sender)
@sender = sender
mail(:to => "<EMAIL>", :from => sender.email, :subject => "New")
end
end
<file_sep>/db/migrate/20121219003950_add_status_to_microposts.rb
class AddStatusToMicroposts < ActiveRecord::Migration
def change
add_column :microposts, :status, :boolean
add_index :microposts, :status
end
end<file_sep>/app/models/pay.rb
class Pay < ActiveRecord::Base
attr_accessible :email, :product_id
attr_accessible :paypal_customer_token, :paypal_payment_token, :paypal_recurring_profile_token
belongs_to :product
validates_presence_of :product_id
validates_presence_of :email
attr_accessor :paypal_payment_token
#attr_accessor :paypal_customer_token
def save_with_payment
if valid?
if paypal_payment_token.present?
ppr = PayPal::Recurring.new(
token: paypal_payment_token,
payer_id: paypal_customer_token,
description: product.title,
amount: product.price,
currency: "MXN"
)
response = ppr.request_payment
end
end
def paypal
PaypalPayment.new(self)
end
def save_with_paypal_payment
ppr = PayPal::Recurring.new(
token: paypal_payment_token,
payer_id: paypal_customer_token,
description: @pay.product.title,
amount: @pay.product.price,
currency: "MXN"
)
response = ppr.request_payment
#self.paypal_recurring_profile_token = response.profile_id
#save!
end
def payment_provided?
paypal_payment_token.present?
end
end
end
<file_sep>/app/models/group.rb
class Group < ActiveRecord::Base
attr_accessible :description, :name, :picture, :user_id
has_many :memberships, :dependent => :destroy
has_many :users, :through => :memberships
has_many :microposts
VALID_GROUPNAME_REGEX = /^[a-zA-Z0-9_]*[a-zA-Z][a-zA-Z0-9_]*$/
validates :name, presence: true, format: { with: VALID_GROUPNAME_REGEX },
uniqueness: { case_sensitive: false }
before_save { self.name.downcase! }
mount_uploader :picture, GroupPictureUploader
def to_param
name
end
def self.get_all_stories(group)
return group.microposts.order("created_at DESC")
end
def self.get_new_stories(group)
return group.microposts.order("created_at DESC").limit(4)
end
def self.get_top_stories(group)
return Micropost.find_with_reputation(:votes, :all,
{:conditions => ["microposts.group_id = ?", group.id], :order => 'votes desc'})
end
def self.get_trend_stories(group)
days = Micropost.where('created_at >= ?', 4.day.ago).count
return Micropost.find_with_reputation(:votes, :all,
{:conditions => ["microposts.group_id = ?", group.id], :order => 'created_at desc', :limit => days})
end
def self.get_stories(group)
return Micropost.find_with_reputation(:votes, :all,
{:conditions => ["microposts.group_id = ?", group], :order => 'votes desc'})
end
end
<file_sep>/app/controllers/microposts_controller.rb
class MicropostsController < ApplicationController
before_filter :authenticate_user!, :except => [:show, :index, :modal_micropost, :microposts_lov, :microposts_order, :microposts_search]
#load_and_authorize_resource
def new
@micropost = Micropost.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @micropost }
end
end
def index
if params[:tag]
@microposts = Micropost.page(params[:page]).per_page(50).tagged_with(params[:tag])
@search = Micropost.search(params[:search])
@last = Micropost.last
else
@microposts = Micropost.page(params[:page]).per_page(50).find(:all, :order => "created_at DESC")
@search = Micropost.search(params[:search])
@last = Micropost.last
end
respond_to do |format|
format.html # new.html.erb
format.json { render json: @microposts.tokens(params[:q]) }
format.js
end
end
def microposts_lov
@microposts = Micropost.page(params[:page]).per_page(50).find_with_reputation(:lovs, :all, order: 'lovs desc')
end
def microposts_order
@microposts = Micropost.page(params[:page]).per_page(50).find(:all, :order => "created_at DESC")
end
def microposts_search
@search = Micropost.search(params[:search])
@microposts = @search.page(params[:page]).per_page(50)
end
def show
@micropost = Micropost.find_by_id(params[:id])
@posts = Micropost.all.last(20)
# @tags = Micropost.tagged_with([@micropost.tag_list], :any => true)
if @micropost.nil?
flash[:error] = "No se ha encontrado el Post."
redirect_to microposts_path
else
@user = @micropost.user
@comment = Comment.new
@comments = @micropost.comments
respond_to do |format|
format.html # show.html.erb
end
end
end
def edit
@micropost = Micropost.find_by_id(params[:id])
@groups = Group.all
if !@micropost.picture.present?
if !@micropost.thumbnail.nil?
images = @micropost.thumbnail
@img = images.split( /\r?\n- / )
else
@img = @micropost.thumbnail
end
else
@img = @micropost.picture
end
end
def create
@micropost = current_user.microposts.build(params[:micropost])
#@micropost.remote_picture_url = @micropost.thumbnail
# @micropost.activities.create(:user_id => current_user.id, :action => "create")
#Activity.expire_feed_cache(current_user)
#Micropost.delay.publish_link_facebook(@micropost) unless @micropost.user.fb == false
if !@micropost.picture.present?
require 'embedly'
require 'json'
embedly_api = Embedly::API.new :key => '80abb9f8804a4cad90d3f21d33b49037',
:user_agent => 'Mozilla/5.0 (compatible; mytestapp/1.0; <EMAIL>)'
obj = embedly_api.extract :url => @micropost.url
json_obj = JSON.pretty_generate(obj[0].marshal_dump)
result = JSON.parse(json_obj)
images = []
puts result['images']
result['images'].each do |s|
size = s['width'].to_i
if size >= 400
images << s['url']
end
end
puts images
@micropost.assign_attributes(thumbnail: images, title: result['title'], url: result['url'], provider: result['provider_url'])
#@micropost.assign_attributes(thumbnail: images)
# @micropost.update_attributes()
# @micropost.update_attributes()
@micropost.save!
@micropost.activities.create(:user_id => current_user.id, :action => "create")
Activity.expire_feed_cache(current_user)
puts json_obj
else
@micropost.assign_attributes(thumbnail: @micropost.picture, provider: "http://soxialit.com", url: "http://soxialit.com")
@micropost.save!
end
respond_to do |format|
format.html { redirect_to edit_micropost_path(@micropost)}
end
end
def destroy
@micropost = Micropost.find(params[:id])
Activity.expire_feed_cache(@micropost.user)
@micropost.destroy
respond_to do |format|
format.html { redirect_to root_url, notice: 'Micropost eliminado correctamente' }
end
end
def lovs
value = params[:type] == "up" ? 1 : -1
@micropost = Micropost.find(params[:id])
@micropost.add_or_update_evaluation(:lovs, value, current_user)
@micropost.activities.create(:user_id => current_user.id, :action => "like")
@user = User.find(@micropost.user_id)
Micropost.delay.publish_link_like_facebook(@micropost, current_user) unless current_user.fb == false
@followers_list = current_user.followers.map do |u|
{ :id => u.id, :follower_name => u.nickname}
end
if !@user.notification.nil?
if @user.notification.lov_micropost == true
UserMailer.lov_micropost(@user, current_user, @micropost).deliver
end
end
respond_to do |format|
format.js
end
end
def vote
value = params[:type]
@micropost = Micropost.find(params[:id])
if value == "up"
@micropost.add_or_update_evaluation(:votes, 1, current_user)
else
if @micropost.has_evaluation?(:votes, current_user)
@micropost.add_or_update_evaluation(:votes, 0, current_user)
else
@micropost.add_or_update_evaluation(:votes, -1, current_user)
end
end
=begin
voto = params[:type]
logger.debug "Tipo voto: #{voto}"
@micropost = Micropost.find(params[:id])
if voto == "up"
@x = @micropost.reputation_for(:ups).to_i
logger.debug "Valor actual: #{@x}"
@value = @x + 1
@value.to_i
logger.debug "Voto despues: #{@value}"
@micropost.add_or_update_evaluation(:ups, @value, current_user)
logger.debug "Reputation after: #{@micropost.reputation_for(:ups).to_i}"
else
@x = @micropost.reputation_for(:ups).to_i
logger.debug "Valor actual: #{@x}"
@value = @x - 1
logger.debug "Voto despues: #{@value}"
@micropost.decrease_evaluation(:ups, @value, current_user)
logger.debug "Reputation after: #{@micropost.reputation_for(:ups).to_i}"
end
=end
#== "up" ? 1 : -1
# @micropost = Micropost.find(params[:id])
# @x = @micropost.reputation_for(:votes)
#logger.debug "Valor actual: #{@x}"
#logger.debug "Voto nuevo: #{voto}"
#@value = @x + (voto)
#@value
#logger.debug "Voto despues: #{@value}"
#@micropost.add_or_update_evaluation(:votes, voto, current_user)
#@micropost.activities.create(:user_id => current_user.id, :action => "like")
#@user = User.find(@micropost.user_id)
#Micropost.delay.publish_link_like_facebook(@micropost, current_user) unless current_user.fb == false
#@followers_list = current_user.followers.map do |u|
# { :id => u.id, :follower_name => u.nickname}
#end
end
def modal_micropost
@micropost = Micropost.find(params[:micropost_id])
@tags = Micropost.tagged_with([@micropost.tag_list], :any => true)
@posts = Micropost.all.last(3)
@user = @micropost.user
@comment = Comment.new
@comments = @micropost.comments
end
def collect
@micropost = Micropost.find(params[:micropost_id])
#@gallery = Gallery.new
#@gallery.token = @gallery.generate_token
@galleries = current_user.galleries
@pin = Pin.new
end
def update
@groups = Group.all
@micropost = Micropost.find_by_id(params[:id])
if !@micropost.picture.present?
if !@micropost.thumbnail.nil?
images = @micropost.thumbnail
@img = images.split( /\r?\n- / )
else
@img = @micropost.thumbnail
end
else
@img = @micropost.picture
end
respond_to do |format|
if @micropost.update_attributes(params[:micropost])
@micropost.activities.create(:user_id => current_user.id, :action => "create")
Activity.expire_feed_cache(current_user)
format.html { redirect_to @micropost, notice: '' }
else
format.html { render action: "edit" }
end
end
end
end<file_sep>/app/models/newsletter.rb
class Newsletter < ActiveRecord::Base
attr_accessible :description, :imagen, :title, :url
end
<file_sep>/db/migrate/20130125014520_add_status_to_users.rb
class AddStatusToUsers < ActiveRecord::Migration
def change
add_column :users, :status, :boolean, :default => true
add_index :users, :status
end
end
<file_sep>/app/helpers/galleries_helper.rb
module GalleriesHelper
def find_micropost_image(id)
micropost = Micropost.find(id)
if micropost.id > 450
if !micropost.picture_url(:modal).nil?
micropost.picture_url(:modal)
else
micropost.thumbnail
end
else
micropost.thumbnail
end
end
end
<file_sep>/config/initializers/paypal.rb
PayPal::Recurring.configure do |config|
#config.sandbox = true
#config.username = "<EMAIL>"
#config.password = "<PASSWORD>"
#config.signature = "AHu2KCVM.UAZmaQI2JFVySleym2UAT2d26kBryEOGzmoYR0hJst-DfHR"
config.username = "beta.<EMAIL>"
config.password = "<PASSWORD>"
config.signature = "A.FkMa-b6OC3gDoqlk7aR21Am1olAvmxr7y43sEN1IymYFk-CfrRsgai"
end<file_sep>/db/migrate/20130124185319_add_facebook_to_users.rb
class AddFacebookToUsers < ActiveRecord::Migration
def change
add_column :users, :facebook, :boolean, :default => true
add_index :users, :facebook
end
end
<file_sep>/db/migrate/20130615233457_change_url_type_for_micropost.rb
class ChangeUrlTypeForMicropost < ActiveRecord::Migration
def self.up
change_table :microposts do |t|
t.change :url, :text, :limit => nil
end
end
def self.down
change_table :microposts do |t|
t.change :url, :string
end
end
end<file_sep>/app/controllers/notifications_controller.rb
class NotificationsController < ApplicationController
def new
Notification.new
end
def create
@notification = current_user.build_notification(params[:notification])
@notification.save!
end
end
<file_sep>/config/initializers/mixpanel.rb
if ["test"].include?(Rails.env)
MIXPANEL_TOKEN = "5e344db467e2f971ffccde4566fe2da4"
YourApplication::Application.config.middleware.use "Mixpanel::Tracker::Middleware", MIXPANEL_TOKEN
else
class DummyMixpanel
def method_missing(m, *args, &block)
true
end
end
end<file_sep>/config/routes.rb
DeviseFacebook::Application.routes.draw do
#root :to => 'static_pages#home'
root :to => 'static_pages#feed'
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
devise_scope :user do
get 'users/sign_in', :to => 'devise/sessions#new', :as => :new_user_session
get 'users/sign_out', :to => 'devise/sessions#destroy', :as => :destroy_user_session
end
match '/tags', to: 'tags#show_tags'
get '/products_all', to: 'products#products_all'
#----
resources :users, only: [:index, :create, :new]
resources :user_steps
resources :relationships, only: [:create, :destroy]
resources :products do
#member { post :vote }
# member { post :have}
put :envio_df, on: :member
put :create, on: :collection
put :status, on: :collection
end
match "list_items/:username" => "users#list_items", :as => "list_items"
match "followers/:username" => "users#followers", :as => "followers_user"
match "following/:username" => "users#following", :as => "following_user"
match "favorites/:username" => "users#favorites", :as => "favorites"
match "list_projects/:username" => "users#list_projects", :as => "list_projects"
match "items/:username" => "users#items", :as => "items"
match "muro/:username" => "users#muro", :as => "muro"
match "biografia/:username" => "users#biografia", :as => "biografia"
match 'coleccion/:username' => "users#coleccion", :as => "coleccion"
#get '/muro', to: 'users#muro'
resources :feedbacks
resources :comments
resources :direction
resources :notifications
resources :paintings
resources :sizes
# get 'sources/:source', to: 'sources#index', as: :source
get 'tags/:tag', to: 'microposts#index', as: :tag
match '/microposts' => 'microposts#index', :as => 'p'
match '/microposts/:id' => 'microposts#show', :as => 'p'
match '/microposts/:id/edit' => 'microposts#edit', :as => 'p'
resources :microposts, :path => "p" do
member { post :vote}
member { post :lovs}
end
match "microposts_lov/" => "microposts#microposts_lov", :as => "microposts_lov"
match "microposts_order/" => "microposts#microposts_order", :as => "microposts_order"
match "microposts_search/" => "microposts#microposts_search", :as => "microposts_search"
get '/envio', to: 'products#envio'
get '/comprar', to: 'products#comprar'
get '/comprar_login', to: 'products#comprar_login'
get '/tallas', to: 'products#tallas'
get '/product_modal', to: 'users#product_modal'
match 'preview', to: 'static_pages#preview'
get '/modal_micropost', to: 'microposts#modal_micropost'
get '/modal_post', to: 'static_pages#modal_post'
get '/collect', to: 'microposts#collect'
get '/story', to: 'static_pages#story'
get 'scrap', to: 'static_pages#scrap'
# get users/index
get '/designer', to: 'users#designer'
get '/fashionlover', to: 'users#fashionlover'
get '/boutique', to: 'users#boutique'
get '/blogger', to: 'users#blogger'
get '/fotografo', to: 'users#fotografo'
get '/bio', to: 'users#bio'
# get 'paypal/checkout', to: 'products#paypal_checkout'
get 'paypal/checkout', to: 'pays#paypal_checkout'
get 'mercadopago/checkout', to: 'products#mercadopago_checkout'
match "/about", to: 'static_pages#about'
match "/payment", to: 'static_pages#payment_complete'
match "soxialit", to: 'static_pages#soxialit'
match "sell", to: 'static_pages#sell'
match "buy", to: 'static_pages#buy'
match "examples", to: 'static_pages#examples'
match "guides", to: 'static_pages#guides'
match "term", to:'static_pages#term'
match "privacy", to:'static_pages#privacy'
match "faq", to:'static_pages#faq'
match "registro", to: 'static_pages#registro'
match "500mx", to: 'five_hundred#fivehundred'
match "instrucciones", to: "static_pages#instrucciones"
match "black", to: "static_pages#black"
match "las7depauline", to:'static_pages#las7depauline'
match "team", to:'static_pages#team'
#designers_pages
match "demo", to: 'static_pages#demo'
match "men_heute", to: 'static_pages#men_heute'
get '/modal_item', to: 'static_pages#modal_item'
match "arbol_viento", to: 'static_pages#arbol_viento'
# profile edit
match "ubicacion", to: 'users#ubicacion'
match "perfil", to: 'users#perfil'
match "notificacion", to: 'users#notificacion'
match 'publish', to: 'posts#publish'
resources :posts do
put :create, on: :collection
member {post :likes}
end
resources :slides
resources :pictures
resources :projects do
put :change_position, on: :member
end
get 'tags/:tag', to: 'projects#index', as: :tag
resources :partners
resources :pays
#Testing
match "feed", to: "static_pages#feed"
match "index", to: "static_pages#index"
#ORDENA TU DESMADREEEEEEEEE
resources :pins
resources :galleries
resources :newsletters
resources :sources
resources :supports, :only => [:new, :create]
match "collections/:name" => "galleries#show", :as => "collections"
resources :groups, only: [:index, :create, :new]
# Groups Routes
match "groups/:name/edit", :to => "groups#edit", path: "s/:name/edit", :as => "edit_group", :via => :get
match "groups/:name", :to => "groups#show", path: "s/:name", :as => "group", :via => :get
match "groups/:name", :to => "groups#update", path: "s/:name", :as => "group", :via => :put
match "square/s/:name" => "groups#square", :as => "square"
match "list/s/:name" => "groups#list", :as => "list"
# Memberships Routes
resources :memberships, only: [:create, :destroy]
# Customized Routes for Profile Page should be at th END
match ":username/edit", :to => "users#edit", :as => "edit_user", :via => :get
match ":username", :to => "users#show", :as => "user", :via => :get
match ":username", :to => "users#update", :as => "user", :via => :put
match ":username", :to => "users#destroy", :as => "user", :via => :delete
end<file_sep>/app/models/paypal_payment.rb
class PaypalPayment
def initialize(pay)
@pay = pay
end
def checkout_details
#PayPal::Recurring.new(token: @pay.paypal_payment_token).checkout_details
process :checkout_details
end
def checkout_url(options)
process(:checkout, options).checkout_url
end
def make_recurring
process :request_payment
process :create_recurring_profile, period: :monthly, frequency: 1, start_at: Time.zone.now
end
private
def process(action, options = {})
options = options.reverse_merge(
token: @pay.paypal_payment_token,
payer_id: @pay.paypal_customer_token,
description: @pay.product.title,
amount: @pay.product.price,
currency: "MXN"
)
response = PayPal::Recurring.new(options).send(action)
raise response.errors.inspect if response.errors.present?
response
end
end<file_sep>/app/controllers/groups_controller.rb
class GroupsController < ApplicationController
#before_filter :authenticate_user!
#load_and_authorize_resource
layout "index", :only => :index
def index
@groups = Group.all
#Groups I am suscribed
if user_signed_in?
@suscribed_groups = current_user.groups
@my_groups = Group.where("user_id = ?", current_user.id)
else
@suscribed_groups = User.find(1).groups
@my_groups = Group.where("user_id = ?", User.find(1).id)
end
end
def show
@group = Group.find_by_name(params[:name])
@stories = Group.get_all_stories(@group)
@all_stories = @stories.paginate(:page => params[:page], :per_page => 10)
@new = Group.get_new_stories(@group)
@new_stories = @new.paginate(:page => params[:page], :per_page => 10)
@top_stories = Group.get_top_stories(@group)
@top = @top_stories.paginate(:page => params[:page], :per_page => 10).sort! {|mp1, mp2| mp2.reputation(mp2) <=> mp1.reputation(mp1) }
@trend_stories = Group.get_trend_stories(@group)
@trend = @trend_stories.sort! {|mp1, mp2| mp2.reputation(mp2) <=> mp1.reputation(mp1) }
#Get profile picture of group creator
@group_creator = User.find(@group.user_id)
end
def new
@group = Group.new
respond_to do |format|
format.html # new.html.erb
end
end
def edit
@group = Group.find_by_name(params[:name])
end
def create
@group = Group.new(params[:group])
@group.update_attributes(user_id: current_user.id)
respond_to do |format|
if @group.save
format.html { redirect_to @group }
else
format.html { render action: "new" }
end
end
end
def update
@group = Group.find_by_name(params[:name])
respond_to do |format|
if @group.update_attributes(params[:group])
format.html { redirect_to @group, notice: 'Group was successfully updated.' }
else
format.html { render action: "edit" }
end
end
end
def square
@group = Group.find_by_name(params[:name])
@stories = Group.get_all_stories(@group)
@all_stories = @stories.paginate(:page => params[:page], :per_page => 10)
@new = Group.get_new_stories(@group)
@new_stories = @new.paginate(:page => params[:page], :per_page => 10)
@top_stories = Group.get_top_stories(@group)
@top = @top_stories.paginate(:page => params[:page], :per_page => 10).sort! {|mp1, mp2| mp2.reputation(mp2) <=> mp1.reputation(mp1) }
@trend_stories = Group.get_trend_stories(@group)
@trend = @trend_stories.sort! {|mp1, mp2| mp2.reputation(mp2) <=> mp1.reputation(mp1) }
end
def list
@group = Group.find_by_name(params[:name])
@stories = Group.get_all_stories(@group)
@all_stories = @stories.paginate(:page => params[:page], :per_page => 10)
@new = Group.get_new_stories(@group)
@new_stories = @new.paginate(:page => params[:page], :per_page => 10)
@top_stories = Group.get_top_stories(@group)
@top = @top_stories.paginate(:page => params[:page], :per_page => 10).sort! {|mp1, mp2| mp2.reputation(mp2) <=> mp1.reputation(mp1) }
@trend_stories = Group.get_trend_stories(@group)
@trend = @trend_stories.sort! {|mp1, mp2| mp2.reputation(mp2) <=> mp1.reputation(mp1) }
end
end<file_sep>/app/controllers/five_hundred_controller.rb
class FiveHundredController < ApplicationController
layout "fivehundred"
def fivehundred
end
end<file_sep>/app/helpers/users_helper.rb
module UsersHelper
def find_title(evaluations)
b = Product.find(evaluations)
return b.title
end
def find_product(evaluations)
product = Product.find(evaluations)
return product
end
def find_price(evaluations)
b = Product.find(evaluations)
return b.price
end
def find_foto(evaluations)
b = Product.find(evaluations)
return b.picture
end
def find_designer(evaluations)
b = Product.find(evaluations)
return b.brand
end
def find_user(evaluations)
b = Product.find(evaluations)
b.user_id
end
def find_micropost_title(evaluations)
a = Micropost.find(evaluations)
a.title
end
def find_micropost_image(evaluations)
a = Micropost.find(evaluations)
a.thumbnail
end
def find_micropost_url(evaluations)
a = Micropost.find(evaluations)
a.url
end
def find_micropost_username(evaluations)
a = User.find(evaluations)
a.username
end
def find_micropost_userimage(evaluations)
a = Micropost.find(evaluations)
b = User.find(a.user_id)
c = "http://graph.facebook.com/#{b.uid}/picture?type=square"
return c
end
def find_micropost_imagefile(evaluations)
a = Micropost.find(evaluations)
b = User.find(a.user_id)
c = b.picture_url(:profile)
return c
end
def find_micropost_userurl(evaluations)
a = Micropost.find(evaluations)
b = User.find(a.user_id)
b.username
end
def find_micropost_description(evaluations)
a = Micropost.find(evaluations)
a.description
end
def find_micropost(evaluations)
micropost = Micropost.find(evaluations)
end
def find_micropost_nickname(evaluations)
a = Micropost.find(evaluations)
b = User.find(a.user_id)
b.nickname
end
def find_micropost_userid(evaluations)
a = Micropost.find(evaluations)
a.user_id
end
def find_user_project(project)
a = User.find(project)
a.username
end
def find_post_image(evaluations)
a = Post.find(evaluations)
if a.slides.any?
a.slides.first.picture_url
end
end
def find_post_url(evaluations)
a = Post.find(evaluations)
a.id
end
def find_post_body(evaluations)
a = Post.find(evaluations)
a.body
end
def find_post_title(evaluations)
a = Post.find(evaluations)
a.title
end
def find_post_link(evaluations)
a = Post.find(evaluations)
a.url
end
def find_post_userimage(evaluations)
a = Post.find(evaluations)
b = User.find(a.user_id)
c = "http://graph.facebook.com/#{b.uid}/picture?type=square"
return c
end
def find_post_imagefile(evaluations)
a = Post.find(evaluations)
b = User.find(a.user_id)
c = b.picture_url(:profile)
return c
end
def find_post_userurl(evaluations)
a = Post.find(evaluations)
b = User.find(a.user_id)
b.username
end
def find_post(evaluations)
product = Post.find(evaluations)
end
def find_post_nickname(evaluations)
a = Post.find(evaluations)
b = User.find(a.user_id)
b.nickname
end
def find_post_userid(evaluations)
a = Post.find(evaluations)
a.user_id
end
end<file_sep>/db/migrate/20130124200957_fix_column_facebook_name.rb
class FixColumnFacebookName < ActiveRecord::Migration
def change
rename_column :users, :facebook, :fb
end
end
<file_sep>/app/controllers/pays_controller.rb
class PaysController < ApplicationController
def new
product = Product.find(params[:product_id])
@pay = product.pays.build
if params[:PayerID]
@pay.paypal_customer_token = params[:PayerID]
@pay.paypal_payment_token = params[:token]
@pay.email = @pay.paypal.checkout_details.email
logger.debug "paypal email es: #{@pay.email}\n\n\n\n\n\n"
end
end
def create
@pay = Pay.new(params[:pay])
product = Product.find(@pay.product_id)
product.pays.create(email:@pay.email, paypal_recurring_profile_token: @pay.paypal_recurring_profile_token, paypal_customer_token: @pay.paypal_customer_token)
respond_to do |format|
if @pay.save_with_payment
elsif user_signed_in?
format.html {redirect_to current_user, notice: 'Gracias por tu compra, en un momento te enviaremos informacion'}
else
format.html {redirect_to products_path, notice: 'Gracias por tu compra, en un momento te enviaremos informacion'}
end
end
end
def show
@pay = Pay.find(params[:id])
end
=begin
def paypal_checkout
product = Product.find(params[:product_id])
pay = product.pays.build
redirect_to pay.paypal.checkout_url(
return_url: product_url(:product_id => product_id),
cancel_url: products_url
)
end
=end
def paypal_checkout
product = Product.find(params[:product_id])
ppr = PayPal::Recurring.new(
return_url: product_url(product),
cancel_url: products_url,
description: product.title,
amount: product.price,
currency: "MXN"
)
response = ppr.checkout
if response.valid?
redirect_to response.checkout_url
else
raise response.errors.inspect
end
end
end<file_sep>/app/models/picture.rb
class Picture < ActiveRecord::Base
attr_accessible :image, :project_id, :position
belongs_to :project
mount_uploader :image, ProjectPictureUploader
validate :picture_size_validation, :if => "image?", :on => :create
def picture_size_validation
errors[:image] << "la imagen debe ser menor a 2MB, intenta con otra imagen" if image.size > 2.megabytes
end
end
<file_sep>/app/models/notification.rb
class Notification < ActiveRecord::Base
attr_accessible :follow, :lov_item, :lov_micropost, :lov_post, :user_id
belongs_to :user
end
<file_sep>/app/controllers/pins_controller.rb
class PinsController < ApplicationController
def new
@gallery = Gallery.find(params[:gallery_id])
@pin = @gallery.pins.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: @item }
end
end
def create
@pin = Pin.new(params[:pin])
respond_to do |format|
if @pin.save
format.html { redirect_to @pin, notice: 'Item was successfully created.' }
format.json { render json: @pin, status: :created, location: @pin }
format.js
else
format.html { render action: "new" }
format.json { render json: @pin.errors, status: :unprocessable_entity }
format.js
end
end
end
end<file_sep>/app/helpers/comments_helper.rb
module CommentsHelper
def parse_url(text)
#url_regexp = /http[s]?:\/\/\w/
x = ""
url_regexp = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/
x << text.scan(url_regexp).to_s
end
end<file_sep>/spec/views/paintings/edit.html.erb_spec.rb
require 'spec_helper'
describe "paintings/edit" do
before(:each) do
@painting = assign(:painting, stub_model(Painting,
:image => "MyString",
:name => "MyString",
:product_id => 1
))
end
it "renders the edit painting form" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "form", :action => paintings_path(@painting), :method => "post" do
assert_select "input#painting_image", :name => "painting[image]"
assert_select "input#painting_name", :name => "painting[name]"
assert_select "input#painting_product_id", :name => "painting[product_id]"
end
end
end
<file_sep>/app/models/item.rb
class Item < ActiveRecord::Base
attr_accessible :description, :gallery_id, :gallery_token, :micropost_id
belongs_to :gallery
end
<file_sep>/db/migrate/20121206153830_add_data_to_products.rb
class AddDataToProducts < ActiveRecord::Migration
def change
add_column :products, :shipping, :decimal
add_column :products, :total_price, :decimal
add_column :products, :ship_int, :decimal
add_column :products, :color, :string
add_column :products, :material, :string
add_column :products, :quantity, :integer
add_column :products, :refund_policy, :text
add_column :products, :price, :decimal
end
end
<file_sep>/app/controllers/slides_controller.rb
class SlidesController < ApplicationController
def create
@slide = Slide.create(params[:slide])
end
def destroy
@slide = Slide.find(params[:id])
@slide.destroy
end
end<file_sep>/app/models/staticpages.rb
class StaticPages < ActiveRecord::Base
attr_accessible :source_tokens
attr_reader :source_tokens
def source_tokens=(ids)
self.source_ids = ids.split(",")
end
end
<file_sep>/app/models/post.rb
class Post < ActiveRecord::Base
attr_accessible :body, :quote, :title, :url, :user_id, :status
has_many :slides
belongs_to :user
has_many :activities, :as => :activitable, :dependent => :destroy
has_many :comments, :as => :commentable, :dependent => :destroy
validates :body, presence: true,
length: { maximum: 550, :too_long => "Intenta otra vez: maximo %{count} caracteres." },
:on => :update
validates :title, presence: true, :on => :update
validates :user_id, :presence => true
has_reputation :likes, source: :user, aggregated_by: :sum
def self.publish_post_facebook(post)
@post = post
@user = @post.user
options = {
:message => "Acabo de publicar un Micropost en Soxialit.",
:picture => @post.slides.first.picture.to_s,
:link => "http://soxialit.com/posts/#{@post.id}",
:name => "#{@post.title} by #{@post.user.nickname}",
:description => @post.quote
}
@user.facebook.put_connections("me", "feed", options)
end
def self.publish_post_like_facebook(post, user)
@post = post
options = {
:message => "Me gusto el siguiente micropost en Soxialit.",
:picture => @post.slides.first.picture.to_s,
:link => "http://soxialit.com/posts/#{@post.id}",
:name => "#{@post.title} by #{@post.user.nickname}",
:description => @post.quote
}
user.facebook.put_connections("me", "feed", options)
end
end<file_sep>/app/models/project.rb
class Project < ActiveRecord::Base
attr_accessible :description, :location, :name, :user_id, :picture
attr_accessible :tag_list
has_many :pictures, :dependent => :destroy
has_many :activities, :as => :activitable, :dependent => :destroy
has_many :comments, :as => :commentable, :dependent => :destroy
belongs_to :user
validates :description, :location, :name, :presence => { :message => "*dato requerido" }, :allow_blank => true
attr_accessible :tag_list
acts_as_taggable
def self.publish_project_facebook(project)
@project = project
@user = @project.user
options = {
:message => "Acabo de crear un proyecto en Soxialit.",
:picture => @project.picture.to_s,
:link => "http://soxialit.com/projects/#{@project.id}",
:name => "#{@project.name} by #{@project.user.nickname}",
:description => @project.description
}
@user.facebook.put_connections("me", "feed", options)
end
def self.publish_project_like_facebook(project)
@project = project
@user = current_user
options = {
:message => "Me gusto el siguiente proyecto en Soxialit.",
:picture => @project.picture.to_s,
:link => "http://soxialit.com/projects/#{@project.id}",
:name => "#{@project.name} by #{@project.user.nickname}",
:description => @project.description
}
@user.facebook.put_connections("me", "feed", options)
end
end
<file_sep>/app/controllers/activities_controller.rb
class ActivitiesController < ApplicationController
#after_filter :expire_feed_cache, only: :create
def create
end
#def expire_feed_cache
# user = current_user
# Rails.cache.delete('feed_user_#{user.id}')
#end
end<file_sep>/db/migrate/20130116234514_add_status_to_projects.rb
class AddStatusToProjects < ActiveRecord::Migration
def change
add_column :projects, :status, :boolean, :default => true
add_index :projects, :status
end
end
<file_sep>/app/controllers/user_steps_controller.rb
class UserStepsController < ApplicationController
include Wicked::Wizard
#before_filter :authenticate_user!
before_filter :check_signup
layout "black", :only => [:show, :update]
steps :personal, :friends, :colecciones1, :colecciones2
def show
@user = current_user
@users = @user.friends
render_wizard
end
def update
@user = current_user
@user.attributes = params[:user]
@user.update_attributes(params[:user])
render_wizard @user
end
#Method that determines where the user will be sent after creating its profile
def finish_wizard_path
#user_path(current_user)
root_url
end
#Method that ensures user can get a role only
def check_signup
@user = current_user
if current_user.sign_in_count > 1
redirect_to root_url
end
end
end<file_sep>/app/models/product.rb
class Product < ActiveRecord::Base
ENV["APP_ID"] = '439343236107925'
ENV["APP_SECRET"] = 'fb1c82f1f5893548e750e18e0b67362e'
ENV["MAILCHIMP_API_KEY"] = '8acea2d56fff73cbaa8a707bf2d2d880-us5'
attr_accessible :name
attr_accessible :size_tokens
attr_accessible :created_at
attr_accessible :brand, :description, :picture, :title, :user_id, :shipping, :total_price, :ship_int,
:ship_df, :color, :material, :quantity, :refund_policy, :size, :price
attr_accessible :tipo_envio, :peso, :alto, :largo, :ancho, :price_estafeta, :delivery_time
attr_accessible :tag_list
attr_accessible :url
attr_accessible :name, :image
attr_accessible :ships_attributes
attr_accessible :status
attr_reader :size_tokens
attr_reader :tag_list
attr_accessor :paypal_payment_token
attr_accessor :email
belongs_to :user
has_reputation :votes, source: :user, aggregated_by: :sum, :order => "created_at DESC"
has_many :activities, :as => :activitable, :dependent => :destroy
has_many :comments, :as => :commentable, :dependent => :destroy
has_many :paintings, :dependent => :destroy
has_many :ships, :dependent => :destroy
has_many :pays, :dependent => :destroy
has_many :sizeships
has_many :sizes, through: :sizeships
accepts_nested_attributes_for :ships
acts_as_taggable
=begin
validates :price, :numericality => {:greater_than_or_equal_to => 0.01}, :on => :update
validates_numericality_of :quantity, :greater_than => 0, :less_than => 6, :on => :update
validates :quantity, :presence => {:message => "*debe ser menor 6"}, :on => :update
validates :price, :color, :description, :material, :refund_policy, :title, :brand, :presence => { :message => "*dato requerido" },
:allow_blank => true, :on => :update
validates :picture, :presence => {:message => "*el producto debe tener al menos una foto"}, :on => :update
validates :price, :numericality => {:message => "*debe ser valor numerico"}, :on => :update
validates :delivery_time, :presence => {:message => "*dato requerido"}, :on => :update
validates_numericality_of :delivery_time, :greater_than => 0, :less_than => 11, :on => :update
validates :ship_df, :ship_int, :tipo_envio, :presence => { :message => "*seleciona al menos una opcion de envio" },
:allow_blank => true, :on => :update, :if => :any_present?
validates :picture, :presence => {:message => "*debes elegir cual es la imagen principal del producto."}, :on => :update
=end
default_scope order: 'products.created_at DESC'
def any_present?
if %w(ship_df tipo_envio ship_int).all?{|attr| self[attr].blank?}
message = ("*seleciona al menos una opcion de envio")
end
end
def size_tokens=(tokens)
self.size_ids = Size.ids_from_tokens(tokens)
end
def mercadopago_url(datos)
client_id = '4268569064335968'
client_secret = '<KEY>'
mp_client = MercadoPago::Client.new(client_id, client_secret)
payment = mp_client.create_preference(datos)
end
def payment_provided?
paypal_payment_token.present?
end
def self.publish_product_facebook(product)
Rails.logger.info(product)
logger.debug "Product no sirve #{product}"
@user = product.user
options = {
:message => "Acabo de publicar un item en Soxialit.",
:picture => product.picture.to_s,
:link => "https://soxialit.com/products/#{product.id}",
:name => "#{product.title} by #{product.user.nickname}",
:description => product.description
}
@user.facebook.put_connections("me", "feed", options)
end
def self.publish_product_like_facebook(product, user)
Rails.logger.info(product)
logger.debug "Product like no sirve #{product}"
options = {
:message => "A #{user.nickname} le gusta un item en Soxialit.",
:picture => product.picture.to_s,
:link => "https://soxialit.com/products/#{product.id}",
:name => "#{product.title} by #{product.user.nickname}",
:description => product.description
}
user.facebook.put_connections("me", "feed", options)
end
end<file_sep>/app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def index
@comments = Comment.all
respond_to do |format|
format.html # index.html.erb
end
end
def show
@comment = Comment.find(params[:id])
respond_to do |format|
format.html # show.html.erb
end
end
def new
@comment = Comment.new
respond_to do |format|
format.html # new.html.erb
end
end
def create
@comment = current_user.comments.build(params[:comment])
if @comment.commentable_type == "Product"
@type = Product.find(@comment.commentable_id)
@user = User.find(@type.user_id)
else
@type = Micropost.find(@comment.commentable_id)
@user = User.find(@type.user_id)
end
if current_user != @user
UserMailer.user_comment(@user, current_user, @type, @comment).deliver
end
respond_to do |format|
if @comment.save
format.html { redirect_to :back, notice: 'Comment was successfully created.' }
format.js
else
format.html { render action: "new" }
end
end
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
end<file_sep>/app/models/partner.rb
class Partner < ActiveRecord::Base
attr_accessible :skype, :paypal, :address, :brand, :category, :city, :email, :name, :phone, :user_id, :website, :zipcode
belongs_to :user
validates :paypal, :address, :category, :city, :email, :name, :phone, :presence => { :message => "*dato requerido" }, :allow_blank => true
validates :phone, :numericality => {:message => "*debe ser valor numerico"}
validates_format_of :email, :paypal, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
end
<file_sep>/app/models/ship.rb
class Ship < ActiveRecord::Base
attr_accessible :product_id, :ship_name, :ship_selected, :user_id
belongs_to :product
end
<file_sep>/app/uploaders/biografia_picture_uploader.rb
# encoding: utf-8
class BiografiaPictureUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
storage :file
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :biografia do
process :resize_and_pad => [750,250,"#240902"]
end
end<file_sep>/config/initializers/mailer.rb
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:enable_starttls_auto => true,
:address => "smtp.mandrillapp.com",
:port => 587, # or 587
:enable_starttls_auto => true, # detects and uses STARTTLS
:user_name => "<EMAIL>",
:password => "<PASSWORD>",
:authentication => 'login' # Mandrill supports 'plain' or 'login'
}
=begin
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "soxialit.com",
:user_name => "<EMAIL>",
:password => "<PASSWORD>",
:authentication => "plain",
:enable_starttls_auto => true
}
=end
ActionMailer::Base.default_url_options[:host] = "soxialit.com"
<file_sep>/spec/views/partners/edit.html.erb_spec.rb
require 'spec_helper'
describe "partners/edit" do
before(:each) do
@partner = assign(:partner, stub_model(Partner,
:user_id => 1,
:name => "MyString",
:email => "MyString",
:phone => "",
:category => "MyString",
:brand => "MyString",
:website => "MyString",
:city => "MyString",
:address => "MyString",
:zipcode => "MyString"
))
end
it "renders the edit partner form" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "form", :action => partners_path(@partner), :method => "post" do
assert_select "input#partner_user_id", :name => "partner[user_id]"
assert_select "input#partner_name", :name => "partner[name]"
assert_select "input#partner_email", :name => "partner[email]"
assert_select "input#partner_phone", :name => "partner[phone]"
assert_select "input#partner_category", :name => "partner[category]"
assert_select "input#partner_brand", :name => "partner[brand]"
assert_select "input#partner_website", :name => "partner[website]"
assert_select "input#partner_city", :name => "partner[city]"
assert_select "input#partner_address", :name => "partner[address]"
assert_select "input#partner_zipcode", :name => "partner[zipcode]"
end
end
end
<file_sep>/app/helpers/paintings_helper.rb
module PaintingsHelper
end
<file_sep>/app/models/painting.rb
class Painting < ActiveRecord::Base
attr_accessible :image, :name, :product_id
mount_uploader :image, ProductPictureUploader
belongs_to :product
validate :picture_size_validation, :if => "image?"
def picture_size_validation
errors[:image] << "la imagen debe ser menor a 2MB, intenta con otra imagen" if image.size > 2.megabytes
end
end
<file_sep>/app/uploaders/product_picture_uploader.rb
# encoding: utf-8
class ProductPictureUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :thumb do
process :resize_to_fit => [100,100]
end
version :feed do
process :resize_to_fit => [500,500]
end
version :timeline do
process :resize_and_pad => [460,590, "#FFFFFF"]
end
version :picture_300 do
process :resize_and_pad => [150,300,"#FFFFFF"]
end
version :fancy do
process :resize_and_pad => [200, 300, "#FFFFFF"]
end
def extension_white_list
%w(jpg jpeg gif png)
end
end<file_sep>/app/models/direction.rb
class Direction < ActiveRecord::Base
attr_accessible :user_id, :zipcode, :product_id, :name, :street, :suburb, :town, :state
belongs_to :user
# validates :zipcode, :name, :street, :suburb, :town, :state, :presence => { :message => "*dato requerido" },
# :allow_blank => true
end<file_sep>/app/helpers/products_helper.rb
module ProductsHelper
def find_id
a = Product.last
b = a.id
return b
end
def url_painting(product)
if product.nil?
else
a = product.first
return a.image_url
end
end
def find_user(user)
user = User.find_by_id(user)
return user.username
end
def find_picture(user)
user = User.find_by_id(user)
return user.picture
end
def find_evaluation_id(evaluation)
if current_user.evaluations.nil?
a = evaluation.first
b = a.source_id
return b
else
end
end
def find_sizes(product)
size = product.all
sizes = []
size.each do |x|
sizes << x.name
end
sizes.join(' - ')
end
def total_price(price, envio)
total = price + envio
return number_to_currency(total)
end
def related_items(product)
a = product.first
return a.image_url
end
end
<file_sep>/Gemfile
source 'http://rubygems.org'
gem 'rails', '3.2.11'
gem 'bcrypt-ruby', '3.1.1.rc1', :require => 'bcrypt'
#Authentication and Authorizations
gem 'devise'
gem 'omniauth'
#gem 'omniauth-facebook'
gem 'omniauth-facebook', '1.4.1'
gem 'cancan'
gem 'wicked'
gem 'hominid'
gem 'koala'
#gem cache
gem 'dalli'
#gem to delay processes in Facebook
gem 'delayed_job_active_record'
gem "workless", "~> 1.1.1"
#gem copy text_field entry into clipboard
gem 'zclip-rails'
#Reputation
gem 'activerecord-reputation-system'
#Pictures
gem 'carrierwave'
gem 'rmagick', '2.13.2'
gem 'fog'
gem "fastimage", "~> 1.2.13"
#notification
gem 'exception_notification'
gem 'letter_opener', group: :development
#CSS
gem "bootstrap-sass", "~> 2.1.0.1"
#tags
gem 'acts-as-taggable-on', '3.3.0'
#payment methods
gem 'mercadopago'
gem 'paypal-recurring'
#estafeta_scrapping
gem "net-ssh"
gem 'nokogiri'
#facebook_metatags
gem 'metamagic'
#metasearch
gem "meta_search"
#Improve files readability
gem 'annotate', '~> 2.4.1.beta'
#Improve performance in server
gem 'newrelic_rpm'
#Redirect
gem 'rack-rewrite'
#Embedly
gem 'embedly'
#Online validation
gem 'client_side_validations'
#Pagination
gem 'will_paginate', '> 3.0'
#browser detection
gem "browser"
group :development, :test do
gem 'sqlite3', '1.3.5'
gem 'rspec-rails', '2.11.0'
gem 'thin'
gem 'quiet_assets'
end
group :production do
gem 'pg', '0.12.2'
gem 'thin'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem "therubyracer", "~> 0.12"
gem 'uglifier', '>= 1.0.3'
#gem fileupload paintings
gem 'jquery-fileupload-rails'
gem "twitter-bootstrap-rails"
end
gem 'jquery-rails'<file_sep>/db/migrate/20130323194045_add_micropostid_to_sources.rb
class AddMicropostidToSources < ActiveRecord::Migration
def change
add_column :sources, :micropost_id, :integer
end
end<file_sep>/app/controllers/directions_controller.rb
class DirectionsController < ApplicationController
def new
Direction.new
end
def create
@direction = current_user.build_direction(params[:direction])
@direction.save!
if !@direction.product_id.nil?
logger.debug "product id: #{@direction.product_id}"
@product = Product.find(@direction.product_id)
user_cp = find_user_product(@product)
logger.debug "user cp: #{user_cp}"
if user_signed_in?
if current_user.direction.nil? || user_cp.nil?
else
user_product_cp = find_user_product(@product)
current_user_cp = current_user.direction.zipcode
logger.debug "User cp: #{user_product_cp}\n\n\n\n\n\n"
logger.debug "current_user cp: #{current_user_cp}\n\n\n\n\n\n"
if @product.tipo_envio == "sobre"
url = "http://rastreo2.estafeta.com:7001/Tarificador/admin/TarificadorAction.do?dispatch=doGetTarifas&cCodPosOri=#{user_product_cp}&cCodPosDes=#{current_user_cp}&cTipoEnvio=#{@product.tipo_envio}&cIdioma=Esp"
else
url = "http://rastreo2.estafeta.com:7001/Tarificador/admin/TarificadorAction.do?dispatch=doGetTarifas&cCodPosOri=#{user_product_cp}&cCodPosDes=#{current_user_cp}&cTipoEnvio=#{@product.tipo_envio}&cIdioma=Esp&nPeso=#{@product.peso}&nLargo=#{@product.largo}&nAncho=#{@product.ancho}&nAlto=#{@product.alto}"
end
logger.debug "#{url}\n\n\n\n\n\n"
require 'net/http'
require 'rubygems'
require 'nokogiri'
require 'open-uri'
doc = Nokogiri::HTML(open(url))
@dias = []
doc.css(':nth-child(6) .style5 strong , :nth-child(7) strong, :nth-child(8) strong').each do |node|
@dias.push(node.text)
end
@tarifas = []
doc.css(':nth-child(6) td:nth-child(8) , :nth-child(7) :nth-child(8), :nth-child(8) td:nth-child(8)').each do |node|
@tarifas.push(node.text)
end
end
end
end
end
def find_user_product(product)
id_user = product.user_id
user = User.find(id_user)
if user.direction.nil?
else
user.direction.zipcode
end
end
end<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
has_and_belongs_to_many :roles
has_many :activities, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationship",
dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
has_many :followed_users, through: :relationships, source: :followed
has_many :products, :dependent => :destroy, :order => "created_at DESC"
has_many :evaluations, class_name: "RSEvaluation", as: :source, :order => "created_at DESC"
#has_many :activities, :as => :activitable, :dependent => :destroy
has_many :feedbacks, :dependent => :destroy
has_many :partners, :dependent => :destroy
has_many :microposts, :dependent => :destroy
has_many :projects, :dependent => :destroy
has_many :pictures, :through => :projects
has_one :direction, :dependent => :destroy
has_one :notification, :dependent => :destroy
has_many :posts, :dependent => :destroy
has_many :galleries, :dependent => :destroy
has_many :memberships, :dependent => :destroy
has_many :groups, :through => :memberships
# has_reputation :votes, source: {reputation: :votes, of: :products}, aggregated_by: :sum, :order => "created_at DESC"
#has_reputation :haves, source: {reputation: :haves, of: :products}, aggregated_by: :sum
has_reputation :lovs, source: {reputation: :lovs, of: :microposts}, aggregated_by: :sum
has_reputation :likes, source: {reputation: :likes, of: :posts}, aggregated_by: :sum
has_reputation :votes, source: {reputation: :votes, of: :microposts}, aggregated_by: :sum
#has_reputation :ups, source: {reputation: :ups, of: :microposts}, aggregated_by: :sum
#has_reputation :user_votes, source: {reputation: :votes, of: :microposts}, aggregated_by: :sum
mount_uploader :picture, ProfilePictureUploader
mount_uploader :cover, CoverPictureUploader
mount_uploader :biopic, BiografiaPictureUploader
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me,
:username, :picture, :picture_cache, :location, :website, :bio,
:role_ids, :provider, :uid, :token, :nickname, :fb, :status, :cover, :biopic
#VALID_USERNAME_REGEX = /^[a-zA-Z0-9_]*[a-zA-Z][a-zA-Z0-9_]*$/
#validates :username, presence: true, format: { with: VALID_USERNAME_REGEX },
# uniqueness: { case_sensitive: false }
before_save { self.username.downcase! }
after_create :add_user_to_mailchimp
#before_destroy :remove_user_from_mailchimp
def role?(role)
return self.roles.find_by_name(role).try(:name) == role.to_s
#return self.roles.exists?(:name => role.to_s) #ALTERNATIVE
end
def must_have_one_role
if role_ids.count == 0
errors.add(:base, 'Elige un perfil: designer, blogger, boutique, fotografo o fashion lover.')
end
errors.add(:base, 'Solamente puedes elegir un rol') if role_ids.count > 1
end
def self.find_for_facebook_oauth(auth, signed_in_resource=nil)
user = User.where(:provider => auth.provider, :uid => auth.uid).first
unless user
user = User.create(username:"usuario"+rand(9).to_s+rand(9).to_s+rand(9).to_s,
nickname:auth.info.name,
picture:auth.info.image,
provider:auth.provider,
uid:auth.uid,
token:auth.credentials.token,
email:auth.info.email,
website:"http://",
password:<PASSWORD>[0,10]
)
user.update_attributes(role_ids:"6")
user.build_notification
user.follow!(User.find(1))
user.subscribe!(Group.find(1)) #Every user is subscribed to main Group
#user.save(:validate => false)
#user.activities.create(:user_id => user.id, :action => "create")
@api = Koala::Facebook::API.new(user.token)
begin
options = {
:message => "Me acabo de unir a Soxialit, la Red Social que conecta Fashion
Lovers. Registrate en: http://soxialit.com",
:picture => "http://24.media.tumblr.com/54465c721550d83d6ff4485a014b0424/tumblr_mdq2fja5Ws1rv5ghbo2_r1_1280.jpg",
:link => "http://soxialit.com",
:name => "Soxialit es una red social que conecta a los amantes de la Moda",
:description => "Comparte posts, items y fotos: deja que el mundo conozca tu talento y pasion por la moda."
}
@api.put_connections("me", "feed", options)
@friends = @api.get_connections("me", "friends")
@users = User.all
@users.each do |u|
@friends.each do |friend|
if friend["id"] == u.uid
if u.id != User.find(1).id
user.follow!(User.find(u.id))
usuario = User.find(u.id)
UserMailer.followers(usuario, user).deliver
end
end
end
end
rescue Exception=>ex
puts ex.message
end
#User.find(1).follow!(user)
end
user.update_attributes(token:auth.credentials.token)
#user.save(:validate => false)
user.build_notification unless !user.notification.nil?
user
end
def following? (other_user)
relationships.find_by_followed_id(other_user.id)
end
def follow!(other_user)
relationships.create!(followed_id: other_user.id)
end
def unfollow!(other_user)
relationships.find_by_followed_id(other_user.id).destroy
end
def voted_for?(haiku)
evaluations.where(target_type: haiku.class, target_id: haiku.id).present?
end
def vote_evaluation(micropost, user)
a = micropost.evaluations
a.each do |eval|
return eval.value if (eval.source_id == user.id && eval.reputation_name == "votes")
end
end
def voted_by?(haiku, eva)
haiku.each do |test|
if test.target_id == eva
return test.target_id
end
end
end
def add_user_to_mailchimp
mailchimp = Hominid::API.new(ENV["MAILCHIMP_API_KEY"])
list_id = mailchimp.find_list_id_by_name "Soxialit Registros"
info = { 'FNAME' => self.nickname }
result = mailchimp.list_subscribe(list_id, self.email, info, 'html', false, true, false, true)
Rails.logger.info("MAILCHIMP SUBSCRIBE: result #{result.inspect} for #{self.email}")
end
def remove_user_from_mailchimp
unless self.email.include?('@example.com')
mailchimp = Hominid::API.new(ENV["MAILCHIMP_API_KEY"])
list_id = mailchimp.find_list_id_by_name "Soxialit Registros"
result = mailchimp.list_unsubscribe(list_id, self.email, true, false, true)
Rails.logger.info("MAILCHIMP UNSUBSCRIBE: result #{result.inspect} for #{self.email}")
end
end
def feed
@feed = Activity.from_users_followed_by(self).order("created_at DESC").limit(100)
end
def self.feed_cached(current_user)
user = current_user
Rails.cache.fetch("feed_user_#{user.id}") { user.feed }
end
def friends
User.all.shuffle.take(24)
end
def to_param
username
end
def facebook
@facebook ||= Koala::Facebook::API.new(token)
block_given? ? yield(@facebook) : @facebook
rescue Koala::Facebook::APIError => e
logger.info. e.to_s
nil
end
#Check if thee user is already a member of a Group
def subscribed?(group)
memberships.find_by_group_id(group.id)
end
#The member is added to a Group
def subscribe!(group)
memberships.create!(group_id: group.id)
end
#The member is removed from a Group
def unsubscribe!(group)
memberships.find_by_group_id(group.id).destroy
end
end<file_sep>/app/controllers/posts_controller.rb
class PostsController < ApplicationController
before_filter :authenticate_user!, :except => :show
before_filter :avoid_nil, only: :show
def edit
@post = Post.find(params[:id])
@slides = @post.slides
end
def new
@post = current_user.posts.create(:url => "http://")
@slides = @post.slides
respond_to do |format|
format.html
end
end
def show
@post = Post.find(params[:id])
@user = @post.user
@photos = @post.slides
@comment = Comment.new
@comments = @post.comments
respond_to do |format|
format.html # show.html.erb
end
end
def create
@post = Post.find(params[:post_id])
@post.update_attributes(params[:post])
redirect_to @post
end
def update
@post = Post.find(params[:id])
respond_to do |format|
if @post.update_attributes(params[:post])
format.html { redirect_to @post }
else
format.html { render action: "edit" }
end
end
end
def destroy
@post = Post.find(params[:id])
Activity.expire_feed_cache(@post.user)
@post.destroy
respond_to do |format|
format.html { redirect_to root_url, notice: 'Micropost eliminado correctamente' }
end
end
def publish
@post = Post.find(params[:post_id])
@user = @post.user
if @post.status == false
@post.update_attributes(:status => true)
@post.activities.create(:user_id => current_user.id, :action => "create")
@followers_list = @user.followers.map do |u|
{ :id => u.id, :follower_name => u.nickname}
end
require 'json'
url = 'http://10.0.1.38:3000/push'
uri = URI.parse(url)
post_params = {
:title => @post.title,
:body => @post.body,
:user_id => @post.user_id,
:name => @user.nickname,
:followers => @followers_list
}
req = Net::HTTP::Post.new(uri.path)
req.body = JSON.generate(post_params)
req["Content-Type"] = "application/json"
http = Net::HTTP.new(uri.host, uri.port)
http.start {|htt| htt.request(req)}
Activity.expire_feed_cache(@user)
Post.delay.publish_post_facebook(@post) unless @user.fb == false
else
end
redirect_to :back
end
def avoid_nil
@posts = Post.all
@posts.each do |post|
if post.title.nil? && post.body.nil?
post.destroy
end
end
end
def likes
value = params[:type] == "up" ? 1 : -1
@post = Post.find(params[:id])
@post.add_evaluation(:likes, value, current_user)
@post.activities.create(:user_id => current_user.id, :action => "like")
@user = User.find(@post.user_id)
Post.delay.publish_post_like_facebook(@post, current_user) unless current_user.fb == false
if !@user.notification.nil?
if @user.notification.lov_post == true
UserMailer.lov_post(@user, current_user, @post).deliver
end
end
respond_to do |format|
format.js
end
end
end<file_sep>/README.rdoc
Soxialit
http://soxialit.com is a fashion social network for Mexico and Latinamerica.
Soxialit 2012. [Mexico]<file_sep>/db/migrate/20130615234241_change_provider_type_for_micropost.rb
class ChangeProviderTypeForMicropost < ActiveRecord::Migration
def self.up
change_table :microposts do |t|
t.change :provider, :text, :limit => nil
t.change :thumbnail, :text, :limit => nil
end
end
def self.down
change_table :microposts do |t|
t.change :provider, :string
t.change :thumbnail, :string
end
end
end<file_sep>/app/models/slide.rb
class Slide < ActiveRecord::Base
attr_accessible :picture, :post_id
belongs_to :posts
mount_uploader :picture, PictureMicropostUploader
end
<file_sep>/app/controllers/products_controller.rb
class ProductsController < ApplicationController
before_filter :authenticate_user!, :except => [:show, :index, :tallas, :comprar, :mercadopago_checkout, :paypal_checkout, :PayerID, :envio_df, :envio]
load_and_authorize_resource
layout "products_index", :only => [:index]
layout "show_product", :only => [:show]
def status
Product.update_all({:status => true}, {:id => params[:status_ids]})
a = []
b = params[:status_ids]
b.each do |id|
logger.debug "producto id: #{id}"
b = Product.find(id)
logger.debug "producto: #{b}"
end
Product.delay.publish_product_facebook(b) unless b.user.fb == false
redirect_to products_path
end
def products_all
@products = avoid_nil(Product.all)
@users = User.all
end
def index
if params[:tag]
@products = product_ok(Product.tagged_with(params[:tag]))
@users = User.all
else
@products = product_ok(Product.all)
@products.sort_by!(&:reputations)
@tags = Tag.where("name like ?", "%#{params[:q]}%")
@users = User.all
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @products.map(&:attributes) }
format.js
end
end
def product_ok(items)
products = []
items.each do |item|
if item.status == true
products << item
end
end
return products
end
def avoid_nil(products)
items = []
products.each do |product|
if product.title.blank? && product.description.blank?
else
items << product
end
end
return items
end
# GET /products/1
# GET /products/1.json
def show
@product = Product.find_by_id(params[:id])
@tags = Product.tagged_with([@product.tag_list], :any => true)
id = @product.user_id
@user = User.find(id)
@users = User.all
@products = avoid_nil(@user.products.all)
user_cp = find_user_product(@product)
@pay = @product.pays.build
if params[:PayerID]
logger.debug "PayPal #{params[:PayerID]}\n\n\n\n\n\n"
@pay.paypal_customer_token = params[:PayerID]
@pay.paypal_payment_token = params[:token]
@pay.email = PayPal::Recurring.new(token: params[:token]).checkout_details.email
end
if signed_in?
if current_user.direction.nil? || user_cp.nil?
else
=begin
user_product_cp = find_user_product(@product)
current_user_cp = current_user.direction.zipcode
logger.debug "#{user_product_cp}\n\n\n\n\n\n"
logger.debug "#{current_user_cp}\n\n\n\n\n\n"
if @product.tipo_envio == "sobre"
url = "http://rastreo2.estafeta.com:7001/Tarificador/admin/TarificadorAction.do?dispatch=doGetTarifas&cCodPosOri=#{user_product_cp}&cCodPosDes=#{current_user_cp}&cTipoEnvio=#{@product.tipo_envio}&cIdioma=Esp"
else
url = "http://rastreo2.estafeta.com:7001/Tarificador/admin/TarificadorAction.do?dispatch=doGetTarifas&cCodPosOri=#{user_product_cp}&cCodPosDes=#{current_user_cp}&cTipoEnvio=#{@product.tipo_envio}&cIdioma=Esp&nPeso=#{@product.peso}&nLargo=#{@product.largo}&nAncho=#{@product.ancho}&nAlto=#{@product.alto}"
end
logger.debug "#{url}\n\n\n\n\n\n"
require 'net/http'
require 'rubygems'
require 'nokogiri'
require 'open-uri'
doc = Nokogiri::HTML(open(url))
@dias = []
doc.css(':nth-child(6) .style5 strong , :nth-child(7) strong, :nth-child(8) strong').each do |node|
@dias.push(node.text)
end
logger.debug "#{@dias}\n\n\n\n\n\n"
@tarifas = []
doc.css(':nth-child(6) td:nth-child(8) , :nth-child(7) :nth-child(8), :nth-child(8) td:nth-child(8)').each do |node|
@tarifas.push(node.text)
end
logger.debug "#{@tarifas}\n\n\n\n\n\n"
=end
end
end
respond_to do |format|
format.html # show.html.erb
format.json { render json: @product }
format.js
end
end
def new
@product = current_user.products.create
@product.activities.create(:user_id => current_user.id, :action => "create")
Activity.expire_feed_cache(@product.user)
respond_to do |format|
format.html # new.html.erb
format.json { render json: @product }
end
end
# GET /products/1/edit
def edit
@product = Product.find(params[:id])
@paintings = @product.paintings.all
@tags = @product.tags.all
respond_to do |format|
format.html
format.json
format.js
end
end
def create
@product = Product.find(params[:product_id])
@paintings = @product.paintings.all
if @product.paintings.any?
if params[:position].nil?
else
painting = Painting.find(params[:position])
@product.update_attribute(:picture, painting.image_url(:picture_300).to_s)
end
end
respond_to do |format|
if @product.update_attributes(params[:product])
format.html { redirect_to @product, notice: 'El producto fue creado correctamente, en menos de 12 hrs. sera publicado' }
format.json { render json: @product, status: :created, location: @product }
format.js
else
format.html { render action: "edit" }
format.json { render json: @product.errors, status: :unprocessable_entity }
format.js
end
end
end
def update
@product = Product.find(params[:id])
if @product.paintings.any?
if params[:position].nil?
else
painting = Painting.find(params[:position])
@product.update_attribute(:picture, painting.image_url(:picture_300).to_s)
end
end
respond_to do |format|
if @product.update_attributes(params[:product])
format.html { redirect_to @product, notice: 'Producto editado correctamente' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
def destroy
@product = Product.find(params[:id])
@product.destroy
respond_to do |format|
format.html { redirect_to current_user, notice: 'El producto fue eliminado.' }
format.json { head :no_content }
end
end
=begin
def paypal_checkout
product = Product.find(params[:product_id])
ppr = PayPal::Recurring.new(
return_url: product_url(product),
cancel_url: products_url,
description: product.title,
amount: product.total_price,
currency: "MXN"
)
response = ppr.checkout
if response.valid?
redirect_to response.checkout_url
else
raise response.errors.inspect
end
end
=end
def envio_df
@product = Product.find(params[:id])
if user_signed_in?
user = current_user.id
else
user = "nil"
end
@product.ships.create(:ship_selected => params[:envio], :user_id => user, :ship_name => params[:id])
@product.total_price = (@product.price + @product.ships.last.ship_selected).to_i
@product.save
end
def tallas
@product = Product.find(params[:product_id])
end
def comprar_login
@product = Product.find(params[:product_id])
end
def comprar
@product = Product.find(params[:product_id])
# @product.ships.build
@user = User.find(@product.user_id)
# @direction = Direction.new
#if user_signed_in?
# @address = current_user.direction
#end
#user_cp = find_user_product(@product)
#if user_signed_in?
# if current_user.direction.nil? || user_cp.nil?
#else
# user_product_cp = find_user_product(@product)
# current_user_cp = current_user.direction.zipcode
# logger.debug "#{user_product_cp}\n\n\n\n\n\n"
#logger.debug "#{current_user_cp}\n\n\n\n\n\n"
#if @product.tipo_envio == "sobre"
# url = "http://rastreo2.estafeta.com:7001/Tarificador/admin/TarificadorAction.do?dispatch=doGetTarifas&cCodPosOri=#{user_product_cp}&cCodPosDes=#{current_user_cp}&cTipoEnvio=#{@product.tipo_envio}&cIdioma=Esp"
# else
# url = "http://rastreo2.estafeta.com:7001/Tarificador/admin/TarificadorAction.do?dispatch=doGetTarifas&cCodPosOri=#{user_product_cp}&cCodPosDes=#{current_user_cp}&cTipoEnvio=#{@product.tipo_envio}&cIdioma=Esp&nPeso=#{@product.peso}&nLargo=#{@product.largo}&nAncho=#{@product.ancho}&nAlto=#{@product.alto}"
# end
# logger.debug "#{url}\n\n\n\n\n\n"
# require 'net/http'
# require 'rubygems'
#require 'nokogiri'
#require 'open-uri'
# doc = Nokogiri::HTML(open(url))
# @dias = []
# doc.css(':nth-child(6) .style5 strong , :nth-child(7) strong, :nth-child(8) strong').each do |node|
# @dias.push(node.text)
# end
# @tarifas = []
# doc.css(':nth-child(6) td:nth-child(8) , :nth-child(7) :nth-child(8), :nth-child(8) td:nth-child(8)').each do |node|
# @tarifas.push(node.text)
# end
#end
#end
end
def envio
@product = Product.find(params[:product_id])
respond_to do |format|
format.js
end
end
def vote
value = params[:type] == "up" ? 1 : -1
@product = Product.find(params[:id])
@product.add_or_update_evaluation(:votes, value, current_user)
@product.activities.create(:user_id => current_user.id, :action => "like")
@user = User.find(@product.user_id)
Product.delay.publish_product_like_facebook(@product, current_user) unless current_user.fb == false
if !@user.notification.nil?
if @user.notification.lov_item == true
UserMailer.lov_item(@user ,current_user, @product ).deliver
end
end
respond_to do |format|
format.js
format.xml
end
end
def products_as_json(product)
if user_signed_in?
username = current_user.username
surname = current_user.username
email = current_user.email
else
username = "Usuario Nuevo"
surname = "<NAME>"
email = "email nuevo"
end
data = {
"external_reference" => "ARTICLE-ID-#{product.id}",
"items" => [
{
"id" => product.id,
"title" => product.title,
"description" => product.description,
"quantity" => 1,
"unit_price" => product.price.to_i,
"currency_id" => "MEX",
"picture_url" => "http://i1266.photobucket.com/albums/jj523/JulioAhuactzin/Safari3_zpsb24612a1.png"
}
],
"payer" => {
"name"=> username,
"surname"=> surname,
"email"=> email
},
"back_urls"=> {
"pending"=> "https://www.soxialit.com",
"success"=> "http://www.soxialit.com/",
"failure"=> "http://www.soxialit.com/"
}
}
return data
# logger.debug "#{json}\n\n\n\n\n\n"
end
# your_view.html.erb
def mercadopago_checkout
product = Product.find(params[:product_id])
test = products_as_json(product)
mp_data = product.mercadopago_url(test)
result = JSON.parse(mp_data.to_json)
initpoint = result["init_point"]
redirect_to initpoint
end
def tags
query = params[:q]
if query[-1,1] == " "
query = query.gsub(" ", "")
Tag.find_or_create_by_name(query)
end
@tags = ActsAsTaggableOn::Tag.all
@tags = @tags.select { |v| v.name =~ /#{query}/i }
respond_to do |format|
format.json { render :json => @tags.collect{|t| {:id => t.name, :name => t.name }}}
end
end
def find_user_product(product)
id_user = product.user_id
user = User.find(id_user)
if user.direction.nil?
else
user.direction.zipcode
end
end
end
<file_sep>/db/migrate/20130427170834_add_group_id_to_microposts.rb
class AddGroupIdToMicroposts < ActiveRecord::Migration
def change
add_column :microposts, :group_id, :integer
add_index :microposts,:group_id
end
end
<file_sep>/db/migrate/20121211062027_add_estafeta_to_products.rb
class AddEstafetaToProducts < ActiveRecord::Migration
def change
add_column :products, :tipo_envio, :string
add_column :products, :peso, :int
add_column :products, :alto, :int
add_column :products, :largo, :int
add_column :products, :ancho, :int
add_column :products, :price_estafeta, :decimal
end
end
<file_sep>/app/models/micropost.rb
class Micropost < ActiveRecord::Base
attr_accessible :description, :provider, :thumbnail, :title, :url, :user_id, :status, :picture,
:remote_picture_url, :group_id
scope :since, lambda {|time| where("created_at > ?", time) }
belongs_to :user
belongs_to :group
has_many :activities, :as => :activitable, :dependent => :destroy
has_many :comments, :as => :commentable, :dependent => :destroy
has_many :sourceships
has_many :sources, through: :sourceships
has_reputation :lovs, source: :user, aggregated_by: :sum
attr_accessible :source_tokens
attr_reader :source_tokens
acts_as_taggable_on :source_tokens
attr_reader :tag_list
attr_accessible :tag_list
acts_as_taggable
has_reputation :votes, source: :user, aggregated_by: :sum
#has_reputation :votes, source: :user, aggregated_by: :sum, source_of: [{ :reputation => :user_votes, :of => :user }]
mount_uploader :picture, PictureMicropostUploader
validates :url, presence: true, :allow_blank => true, format: { with: URI::regexp(%w(http https)) }
validates :thumbnail, :length => {:minimum => 10, :too_short => "Por favor agrega una imagen a tu historia."}, :on => :update
validates :title, :presence => {:message => "Escribe el titulo de tu historia."}, :on => :update
#validates :url, :length => { :in => 0..255 }, :allow_nil => true, :allow_blank => true
def reputation(micropost)
evaluation = []
micropost.evaluations.each do |voto|
if voto.reputation_name == "votes"
evaluation << voto.value
end
end
evaluation.inject{|sum, x| sum + x}.to_i
end
def self.publish_link_facebook(micropost)
@micropost = micropost
@user = @micropost.user
options = {
:message => "Acabo de compartir un post en Soxialit.",
:picture => @micropost.thumbnail.to_s,
:link => "http://soxialit.com/microposts/#{micropost.id}",
:name => "#{@micropost.title} via #{@micropost.provider}",
:description => @micropost.description
}
@user.facebook.put_connections("me", "feed", options)
end
def self.publish_link_like_facebook(micropost, user)
@micropost = micropost
options = {
:message => "Me gusto este post en Soxialit.",
:picture => @micropost.thumbnail.to_s,
:link => "http://soxialit.com/microposts/#{micropost.id}",
:name => "#{@micropost.title} via #{@micropost.provider}",
:description => @micropost.description
}
user.facebook.put_connections("me", "feed", options)
end
end<file_sep>/app/controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
auth = request.env["omniauth.auth"]
# You need to implement the method below in your model (e.g. app/models/user.rb)
@user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
if @user.persisted?
sign_in(:user, @user)
redirect_to user_steps_path
set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
flash[:error] = "Error gabito."
redirect_to root_url
#redirect_to @user
end
end
end<file_sep>/app/controllers/projects_controller.rb
class ProjectsController < ApplicationController
# GET /projects
# GET /projects.json
def index
if params[:tag]
@projects = Project.tagged_with(params[:tag])
else
@projects = Project.all
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @projects }
end
end
# GET /projects/1
# GET /projects/1.json
def show
@project = Project.find(params[:id])
@pictures = @project.pictures.find(:all)
respond_to do |format|
format.html # show.html.erb
format.json { render json: @project }
end
end
# GET /projects/new
# GET /projects/new.json
def new
@project = Project.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @project }
end
end
# GET /projects/1/edit
def edit
@project = Project.find(params[:id])
@pictures = @project.pictures.find(:all)
end
# POST /projects
# POST /projects.json
def create
@project = Project.new(params[:project])
respond_to do |format|
if @project.save
format.html { redirect_to @project }
format.json { render json: current_user, status: :created, location: @project }
else
format.html { render action: "new" }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
# PUT /projects/1
# PUT /projects/1.json
def update
@project = Project.find(params[:id])
if @project.pictures.any?
logger.debug "position: #{params[:position]}\n\n\n\n\n\n"
if params[:position].nil?
else
logger.debug "postion: #{params[:position]}\n\n\n\n\n\n"
picture = Picture.find(params[:position])
logger.debug "picture: #{picture}\n\n\n\n\n\n"
@project.update_attribute(:picture, picture.image_url(:timeline).to_s)
end
end
respond_to do |format|
if @project.update_attributes(params[:project])
format.html { redirect_to current_user, notice: 'El proyecto fue actualizado exitosamente.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
# DELETE /projects/1
# DELETE /projects/1.json
def destroy
@project = Project.find(params[:id])
@project.destroy
respond_to do |format|
format.html { redirect_to current_user }
format.json { head :no_content }
end
end
def change_position
@project = Project.find(params[:id])
logger.debug "position: #{params[:position]}\n\n\n\n\n\n"
logger.debug "position: #{params[:position]}\n\n\n\n\n\n"
if params[:position].nil?
else
logger.debug "position: #{params[:position]}\n\n\n\n\n\n"
picture = Picture.find(params[:position])
logger.debug "picture: #{picture}\n\n\n\n\n\n"
@project.update_attribute(:picture, picture.image_url(:timeline).to_s)
end
@project.activities.create(:user_id => current_user.id, :action => "create")
Project.delay.publish_project_facebook(@project)
respond_to do |format|
if @project.update_attributes(params[:project])
format.html { redirect_to current_user, notice: 'El proyecto fue creado correctamente' }
format.js
else
format.json { render json: @project.errors, status: :unprocessable_entity }
format.js
end
end
end
end
<file_sep>/db/migrate/20130122165645_add_datos_personales_to_direction.rb
class AddDatosPersonalesToDirection < ActiveRecord::Migration
def change
add_column :directions, :name, :string
add_column :directions, :street, :string
add_column :directions, :suburb, :string
add_column :directions, :town, :string
add_column :directions, :state, :string
end
end
<file_sep>/app/uploaders/picture_micropost_uploader.rb
# encoding: utf-8
class PictureMicropostUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
# Choose what kind of storage to use for this uploader:
#storage :file
storage :file
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :feed do
process :resize_to_fill => [120,120]
end
version :modal do
process :resize_and_pad => [460,500,"white"]
end
version :index do
process :resize_and_pad => [226, 255, "white"]
end
#version :link_430 do
# process :resize_to_fill => [430,280, Magick::NorthGravity]
#end
#version :link_500 do
# process :resize_to_fill => [500,500, Magick::NorthGravity]
#end
end<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
def flash_class(type)
case type
when :alert
"alert-error"
when :notice
"alert-success"
else
""
end
end
def current_user?(user)
user == current_user
end
def nl2br(s)
s.gsub(/\n/, '<br>')
end
end<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
rescue_from CanCan::AccessDenied do |exception|
redirect_to user_path(current_user), :alert => exception.message
exception.default_message = "blage"
end
end<file_sep>/app/helpers/static_pages_helper.rb
module StaticPagesHelper
def find_evaluation_id(evaluation)
if current_user.evaluations.nil?
a = evaluation.first
b = a.target_id
return b
else
end
end
end<file_sep>/app/models/gallery.rb
class Gallery < ActiveRecord::Base
attr_accessible :description, :name, :token, :user_id, :cover
belongs_to :user
has_many :pins
def generate_token
self.token = loop do
random_token = SecureRandom.urlsafe_base64
break random_token unless Gallery.where(token: random_token).exists?
end
end
end
<file_sep>/db/migrate/20121227181809_add_skype_to_partners.rb
class AddSkypeToPartners < ActiveRecord::Migration
def change
add_column :partners, :skype, :string
end
end
<file_sep>/app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
default :from => "Soxialit<<EMAIL>>"
def followers(user, current)
@user = user
@user_following = current
mail(:to => user.email, :subject => "Tienes un nuevo seguidor en Soxialit")
end
def lov_item(user, current, product)
@user = user
@user_following = current
@product = product
mail(:to => user.email, :subject => "Tu item tiene un nuevo Like")
end
def lov_micropost(user, current, micropost)
@user = user
@user_following = current
@micropost = micropost
mail(:to => user.email, :subject => "Tu Micropost tiene un nuevo Like")
end
def lov_post(user, current, post)
@user = user
@user_following = current
@post = post
mail(:to => user.email, :subject => "Tu Post tiene un nuevo Like")
end
def registration_confirmation(user)
mail(:to => user.email, :subject => "Test")
end
def user_comment(user, current, type, comment)
@user = user
@user_following = current
@item = type
@comment = comment
mail(:to => user.email, :subject => "Han comentado tu publicacion.")
end
end
| f83baf5204e233fb567bd7344d4b9860e00b48fe | [
"RDoc",
"Ruby"
] | 82 | Ruby | faierbol/soxialit-landing | 0183044ee169e2fb990915fba43414efc752f78e | 4d050fdefaa77a86a2970bdc2313f0773336bf10 |
refs/heads/main | <file_sep># Usage
1. Clone the repo
2. Run `npm install`
3. Run `npm run dev`
4. Go to localhost:3000/mjml/:template?templateParam=templateValue
You can also use templates in other templates by adding a `sub_templates` query param and then comma separating main template properties and the template name joined by a colon.
Ex. localhost:3000/mjml/:template?sub_templates=nameOfVarInMainTemplate:template-file-name,nameOfOtherVarInMainTemplate:other-template-file-name
If you have a sub template that you need without the main html and head tag add `onlyBody=1` as a query param.
## How to add templates
All of the files except for index.js in the templates folder will be ignored by git.
To add a new template:
1. create a `.js` file that exports a function that should return an mjml template
2. the exported function is passed all query params as an object
Example: template-name.js
```
module.exports = function(data) {
return `<mjml>
<mj-head>
</mj-head>
<mj-body>
${data["query-param"]}
</mj-body>
</mjml>`;
}
```<file_sep>const Koa = require('koa');
const Router = require('@koa/router');
const cheerio = require('cheerio');
const app = new Koa();
const router = new Router();
const mjml = require('mjml');
const templates = require('./templates');
function wrap(mjmlCode) {
if (mjmlCode.indexOf('<mjml>') > -1) {
return mjmlCode;
}
return `
<mjml>
<mj-head>
<mj-font name="Nunito Sans" href="https://fonts.googleapis.com/css?family=Nunito Sans" />
<mj-breakpoint width="750px" />
</mj-head>
<mj-body>
${mjmlCode}
</mj-body>
</mjml>`;
}
function parseSubTemplates({ sub_templates = null, ...data }) {
if (!sub_templates) {
return data;
}
const subTemplates = {};
const split = String(sub_templates).split(",");
split.map(s => s.split(':')).forEach(([prop, template]) => {
const t = getTemplate(template, { ...data, ...subTemplates }, true);
if (t) {
subTemplates[prop] = t;
}
});
return { ...data, ...subTemplates };
}
function getTemplate(template, data = {}, isSub = false) {
const withSubTemplates = parseSubTemplates(data);
if (!templates[template]) {
return null;
}
const t = templates[template](withSubTemplates);
if (isSub) {
return t || null;
}
if (!t) {
return null;
}
try {
return mjml(wrap(t)).html;
} catch (e) {
return t;
}
}
router.get('/mjml/:template', (ctx, next) => {
// ctx.router available
const file = getTemplate(ctx.params.template, ctx.request.query);
if (file === null) {
ctx.body = 'No template exists'
}
if (ctx.request.query.onlyBody) {
const $ = cheerio.load(file);
ctx.body = $('body').html();
return;
}
ctx.body = file;
});
router.get('/', async (ctx, next) => {
// ctx.router available
ctx.body = "Hey, make a template already.";
})
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(process.env.PORT || 3000); | 9e75fa00964590f6036d573a73d3141c8b6b4a87 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | spiffy2006/test-mjml-api | a1e2f8bc948408e8b85b249467f597a4bf99553f | 5b2a1ab5615ee8b55b8e25511ccd1dfd6c602837 |
refs/heads/master | <file_sep>import numpy as np
import matplotlib.pyplot as plt
def create_image():
my_image = np.zeros((20, 20))
my_image[1:-1, -2] = 1
my_image[1, 1:5] = 1
my_image[1, 7:12] = 1
my_image[2, 1:3] = 1
my_image[2, 6:8] = 1
my_image[3:4, 1:7] = 1
my_image[7:11, 11] = 1
my_image[7:11, 14] = 1
my_image[10:15, 10:15] = 1
my_image[5:10, 5] = 1
my_image[5:10, 6] = 1
return my_image
def negate(B):
return B.copy() * -1
def neighbours8(y, x):
return (
(y-1, x-1),
(y-1, x),
(y-1, x+1),
(y, x+1),
(y, x-1),
(y+1, x+1),
(y+1, x),
(y+1, x-1)
)
def search(LB, label, y, x):
LB[y, x] = label
neighbours = neighbours8(y, x)
for ny, nx in neighbours:
if LB[ny, nx] == -1:
search(LB, label, ny, nx)
def recursive_labeling(B):
LB = negate(B)
label = 0
for y in range(LB.shape[0]):
for x in range(LB.shape[1]):
px = LB[y, x]
if px == -1:
label += 1
search(LB, label, y, x)
return LB
def count_objects(my_labeled_picture):
count = my_labeled_picture.max();
return count
image = np.load("ps.npy.txt")
labeled_image = recursive_labeling(image)
final_count = count_objects(labeled_image)
print("count objects = ", final_count)
plt.subplot(121)
plt.imshow(image)
plt.subplot(122)
plt.imshow(labeled_image)
plt.show()
| 11786000dcbea019b8601acb5cffbf60e922f4d8 | [
"Python"
] | 1 | Python | AndreyZhunenko/Computer_vision_count_objects | 43a188b0c5caa177ddcdf9395280b07cc304a5eb | 1969a433374ace2b3aeb206c84fcfd44201d2976 |
refs/heads/master | <file_sep>//TODO: use jquery html to jquery append, so only new content is added or removed, instead
// instead if everything being refreshed
$(function(){
updateServerInfo();
$("#sendCmd").click(function(){
var updata = {"cmd": $("#command").val(), "clients": []};
var clients = $("#clientIDs").val().replace(" ", "").split(",");
updata["clients"] = clients;
$.ajax({
url: "/uploadCommand",
data: JSON.stringify(updata),
type: "POST",
success: function(resp){
r = eval(resp);
html = r[0] == -1 ? "Command upload unsuccessful: " + r[1] : "Command upload successful"
$("#sentCmdStatus").text(html);
}
})
})
})
function updateCommandInfo(){
$.ajax({
url: "/getCommandInfo",
data: "",
type: "GET",
success: function(resp){
clientInfo = eval(resp);
html = "<tr><td>ClientID - HostName</td><td>CommandID</td><td>Command</td><td>Sent</td><td>Result</td></tr>";
for(var i = 0; i < clientInfo.length; i++){
c = clientInfo[i];
html = html + "<tr>" + "<td>" + c[0] + "</td> <td>" + c[1] + "</td><td>" + c[2] + "</td><td>" + c[3] + "</td><td>" + c[4] + "</td></tr>"
}
$("#CommandInfo").html(html);
}
})
}
function updateServerInfo(){
$.ajax({
url: "/activeServers",
data: "",
type: "GET",
success: function(resp){
var data = eval(resp);
servers = data[0];
clients = data[1];
if(resp == "0"){
$("#active").html("Active Servers: False");
$("#serverInfo").html("");
$("#clientInfo").html("");
}
else{
$("#active").html("Active Servers: True");
clientHTML = "<tr><td>ClientID</td><td>Host Name</td><td>ServerID</td></tr>";
serverHTML = "<tr><td>ServerID</td><td>isActive</td><td>IP Address</td><td>Port Number</td></tr>";
for(var i = 0; i < clients.length; i++){
c = clients[i];
clientHTML = clientHTML + "<tr>" + "<td>" + c[0] + "</td>" + "<td>" + c[1] + "</td>" + "<td>" + c[2] + "</td>" + "</tr>"
}
for(var i = 0; i < servers.length; i++){
s = servers[i];
serverHTML = serverHTML + "<tr>" + "<td>" + s[0] + "</td>" + "<td>" + s[1] + "</td>" + "<td>" + s[2] + "</td>" + "<td>" + s[3] + "</td>" + "</tr>"
}
$("#clientInfo").html(clientHTML);
$("#serverInfo").html(serverHTML);
}
}
})
}
window.setInterval(function(){
updateServerInfo();
updateCommandInfo();
}, 500);
<file_sep>/* creates tables for clients, commands, server info */
CREATE TABLE Server(
ServerID integer primary key AUTO_INCREMENT,
isActive integer not null,
IPAddress varchar(15) not null,
PortNumber integer not null,
check (isActive in (0, 1))
);
\
CREATE TABLE Client(
ClientID varchar(32) primary key,
HostName varchar(256),
ServerID integer,
constraint FK foreign key(ServerID) references Server(ServerID)
);
\
CREATE TABLE Command(
CommandID varchar(32) primary key,
Command varchar(256) not null
);
\
CREATE TABLE ClientCommand(
ClientID varchar(32),
CommandID varchar(32),
Sent integer,
Result varchar(256),
primary key (ClientID, CommandID),
constraint FK_1 foreign key(ClientID) references Client(ClientID),
constraint FK_2 foreign key(CommandID) references Command(CommandID)
);
\
<file_sep>#!/usr/bin/env python3
import os
import sys
import ssl
import socket
from threading import Thread
import subprocess
import time
import pymysql
"""
Python BOTs server: runs on hosts PC, clients connected to it can then be controlled
sent commands, move mouse, etc, from server.py.
openssl req -x509 -sha512 -days 365 -nodes -newkey rsa:2048 -keyout key.key -out certificate.crt
GB, Scotland, Glasgow, Bots, [blank], BotServer, [blank]
"""
#TODO: Add ClientName to client, ID is default can be changed through web UI
#TODO: Server should have to modes for clients, perm and temp, temp by default
#TODO: Have server and client send resource info - Ram, cpu, temp etc.
# upload to DB and have UI read it
#TODO: Tidy and Clean code up
#NOTE: If cursor not getting updated rows, transaction isolation level in mysql DB needs to be changed to "read commited"
# with statement: SET GLOBAL TRANSACTION ISOLATION LEVEL READ COMMITTED;
#BUG: Server cant commit to DB - and is stuck loading - if web app is started first
class Server:
cert = "ssl_files/certificate.crt"
key = "ssl_files/key.key"
colours = {"INFO": "\033[1;37m", "ADD": "\033[1;32m", "REMOVE": "\033[1;31m", "TITLE": "\033[1;34m"}
def __init__(self):
addr = (input("IP: "), int(input("Port: ")))
addr = ("127.0.0.1", 999)
self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_sock.bind(addr)
self.server_sock.listen(5)
db = pymysql.connect("localhost", "root", "pass", "Bots")
cursor = db.cursor()
cursor.execute("SET GLOBAL TRANSACTION ISOLATION LEVEL READ COMMITTED;")
db.commit()
clear_tables = "SET FOREIGN_KEY_CHECKS = 0;truncate table ClientCommand;truncate table Command;truncate table Client;SET FOREIGN_KEY_CHECKS = 1;"
cursor.execute(clear_tables)
db.commit()
results = cursor.execute("select * from Server where IPAddress = '{}' and PortNumber = {}".format(addr[0], addr[1]))
if results:
cursor.execute("update Server set isActive = 1 where IPAddress = '{}' and PortNumber = {};".format(addr[0], addr[1]))
db.commit()
else:
cursor.execute("insert into Server(isActive, IPAddress, PortNumber) values(1, '{}', {})".format(addr[0], addr[1]))
db.commit()
print("{}[*]{} Server binded to address:port:{} {}:{}".format("\033[1;36m", "\033[1;34m", "\033[1;37m", addr[0], addr[1]))
#db.close()
self.clients = {}
listen = Thread(target=self.client_listener, daemon=True)
listen.start()
try:
while True:
cursor = db.cursor()
rs = cursor.execute("select ClientCommand.CommandID, ClientID, Command from ClientCommand inner join Command on ClientCommand.CommandID = Command.CommandID where Sent is null")
results = cursor.fetchall()
if results:
for cmd in results:
print(["COMMAND", cmd])
try:
self.clients[cmd[1]][0].send(str(["COMMAND", cmd]).encode("utf-8"))
except KeyError:
cursor.execute("delete from ClientCommand where ClientID = '{}'".format(cmd[1]))
continue
cursor.execute("update ClientCommand set Sent = 1 where ClientID = '{}' and CommandID = '{}'".format(cmd[1], cmd[0]))
db.commit()
except (KeyboardInterrupt, ValueError):
pass
for i in self.clients:
self.clients[i][0].write("['EXIT']".encode("utf-8"))
self.clients[i][0].close()
self.server_sock.close()
print("Server closed.")
#db = pymysql.connect("localhost", "root", "pass", "<PASSWORD>")
cursor = db.cursor()
cursor.execute("update Server set isActive = 0 where IPAddress = '{}' and PortNumber = {};".format(addr[0], addr[1]))
cursor.execute(clear_tables)
db.commit()
db.close()
def client_listener(self):
print("{}[*]{} Listening for clients...".format("\033[1;36m", "\033[1;34m"))
while True:
client_sock, client_addr = self.server_sock.accept()
new_client = Thread(target=self.handle_client, args=[client_sock], daemon=True)
new_client.start()
def handle_client(self, client_sock):
ssl_sock = ssl.wrap_socket(client_sock, server_side=True, certfile=Server.cert, keyfile=Server.key, ssl_version=ssl.PROTOCOL_TLSv1)
hostname_ID = ssl_sock.read().decode("utf-8").split(":--_:_--:")
hostname = hostname_ID[0]
ID = hostname_ID[1]
#TODO: add lock to stop threads access self.clients and self.ID and same time
self.clients[ID] = (ssl_sock, hostname, [])
print("{}[+]{} Client connected:{} ID - {} , Hostname - {}".format("\033[1;32m", "\033[1;34m", "\033[1;37m", ID, hostname))
db = pymysql.connect("localhost", "root", "pass", "Bots")
cursor = db.cursor()
cursor.execute("SET FOREIGN_KEY_CHECKS = 0;insert into Client values ('{}', '{}', 0);SET FOREIGN_KEY_CHECKS = 1;".format(ID, hostname))
db.commit()
try:
while True:
data = ssl_sock.read().decode()
if not data or eval(data)[0] != "COMMAND_RESULT": break
data = eval(data)
print(data)
cursor.execute("SET FOREIGN_KEY_CHECKS = 0;update ClientCommand set Result = '{}' where ClientID = '{}' and CommandID = '{}';SET FOREIGN_KEY_CHECKS = 1;".format(data[-1], data[2], data[1]))
db.commit()
except ValueError:
pass
finally:
del self.clients[ID]
print("{}[-]{} Client disconnected:{} ID - {}, Hostname - {}".format("\033[1;31m", "\033[1;34m", "\033[1;37m", ID, hostname))
cursor.execute("SET FOREIGN_KEY_CHECKS = 0;delete from Client where ClientID = '{}';SET FOREIGN_KEY_CHECKS = 1;".format(ID))
db.commit()
ssl_sock.close()
db.close()
if __name__ == '__main__':
Server()
<file_sep>#!/usr/bin/env python3
from flask import Flask, render_template, request
from random import getrandbits, randint
from hashlib import md5
import pymysql
import sys
#TODO: Tidy and Clean code up
#TODO: sterilize inputs to prevent XSS and SQLI
#TODO: Add error handling
app = Flask(__name__)
try:
db = pymysql.connect("127.0.0.1", "root", "pass", "<PASSWORD>")
except pymysql.err.OperationalError as err:
print("\033[1;31m[-]\033[1;37m Unable to connect to database, the following error occured: \n {}".format(err))
sys.exit(-1)
@app.route("/getCommandInfo", methods=["GET"])
def get_command_info():
try:
cursor = db.cursor()
r = cursor.execute("select concat(ClientCommand.ClientID, ' - ', Client.HostName), Command.CommandID, Command.Command, ClientCommand.Sent, ClientCommand.Result from ClientCommand inner join Command on ClientCommand.CommandID = Command.CommandID inner join Client on ClientCommand.ClientID = Client.ClientID;")
results = [list(cursor.fetchone()) for x in range(r)]
cursor.close()
except Exception:
pass
return str(results)
@app.route("/uploadCommand", methods=["POST"])
def upload_command():
if check_server() == "0": return "[-1, 'Server offline']"
print(check_server)
cursor = db.cursor()
data = request.form
info = ""
for i in data: info = eval(i)
print("Clients: {}\nCommand: {}".format(str(info["clients"]), info["cmd"]))
cursor.execute("select ClientID from Client")
live_clients = cursor.fetchall()
for i in info["clients"]:
if i not in live_clients[0]:
return "[-1, 'Invalid ClientID']"
cmdID = md5(str(getrandbits(randint(0, 999999))).encode("utf-8")).hexdigest()
cursor.execute("insert into Command (CommandID, Command) values('{}', '{}')".format(cmdID, info["cmd"]))
db.commit()
for clientID in info["clients"]:
cursor.execute("SET FOREIGN_KEY_CHECKS = 0;insert into ClientCommand (ClientID, CommandID) values('{}', '{}');SET FOREIGN_KEY_CHECKS = 1;".format(clientID, cmdID))
db.commit()
cursor.close()
return "[0, '']"
@app.route("/activeServers", methods=["GET"])
def check_server():
cursor = db.cursor()
s = cursor.execute("select * from Server where isActive = 1")
s_data = [list(cursor.fetchone()) for x in range(s)]
c = cursor.execute("select * from Client")
c_data = [list(cursor.fetchone()) for x in range(c)]
cursor.close()
return str([s_data, c_data]) if s_data else "0"
def database_error(err):
print("\033[1;31m[-]\033[1;37m DATSBASE ERROR: \n {}".format(err))
@app.route("/")
def main():
return render_template("index.html")
if __name__ == '__main__':
app.run()
<file_sep>#!/usr/bin/env python3
import os, sys
import socket
from colours import Colours
from threading import Thread
import time
import subprocess
import re
#TODO: Setup basic of client, e.g. have it connecting to server and listenging for messages from server
#NOTE: If unable to connect check firewall rules...
class Client:
def __init__(self):
try:
created = False
server_addr = (input("Server IP: "), int(input("Server Port: ")))
self.c_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.c_sock.connect(server_addr)
created = True
print("{}[+]{} Client connected to server".format(Colours.green, Colours.white))
#NOTE: split __init__ up into small methods?
#send hostname to client
mac, name = self.get_mac(), socket.gethostname()
self.c_sock.send("('{}','{}')".format(name, mac).encode())
self.alive_count = 0
self.server_alive = True
alive = Thread(target=self.alive_timer, daemon=True)
alive.start()
#listen for cmds from server
while True:
cmd = self.c_sock.recv(1024).decode()
#alive check from server
if cmd == "\0": self.alive_count += 1
except ValueError:
print("{}[-] {}Invalid server address".format(Colours.red, Colours.white))
sys.exit(-1)
except ConnectionRefusedError:
print("{}[-] {}Unable to connect to server".format(Colours.red, Colours.white))
except BrokenPipeError:
print("{}[*]{} Server closed".format(Colours.blue, Colours.white))
except socket.error as err:
if not self.server_alive: print("{}[*] {}Unexpectedly disconnected from server".format(Colours.blue, Colours.white))
else: print("{}[-]{} The folling error occured: {}".format(Colours.red, Colours.white, err))
except KeyboardInterrupt:
pass
finally:
if created:
self.c_sock.close()
print("{}[*]{} Client closed".format(Colours.red, Colours.white))
def alive_timer(self):
while True:
prev = self.alive_count
time.sleep(5)
if prev == self.alive_count:
self.server_alive = False
self.c_sock.close()
def execute_command(self, cmd):
pass
''' Returns MAC Address of client machine with '''
def get_mac(self):
#cur_ip = self.c_sock.getsockname()[0]
cur_ip = "10.216.71.197"
if cur_ip == "127.0.0.1" or cur_ip == "": return "N/A"
interfaces = subprocess.getoutput("ifconfig").split("\n\n")
cur_int = ""
for i in interfaces:
if cur_ip in i:
cur_int = [x for j in i.split("\n") for x in j.split(" ") if x]
break
#primitive regex to check for mac: [A-Fa-f0-9]{2,2}[:][A-Fa-f0-9]{2,2}[:][A-Fa-f0-9]{2,2}[:][A-Fa-f0-9]{2,2}[:][A-Fa-f0-9]{2,2}[:][A-Fa-f0-9]{2,2}$
#cleaner regex for mac check: ([A-Fa-f0-9]{2,2}[:]){5,5}[A-Fa-f0-9]{2,2}$
# [A-Fa-f0-9]{2,2}[:] - checks for pairs of hex ending in ':'
# (...){5,5} - repeats '[A-Fa-f0-9]{2,2}[:]' 5 times, i.e. onlyy returns a match if 5 hex pairs ending with ':'
# [A-Fa-f0-9]{2,2}$ - find last hex pair at end
for i in cur_int:
r = re.search(r'([A-Fa-f0-9]{2,2}[:]){5,5}[A-Fa-f0-9]{2,2}$', i)
if r: break
mac = "N/A" if not r else r.group()
return mac
if __name__ == '__main__':
Client()
<file_sep>#!/usr/bin/env python3
import subprocess
from threading import Thread
"""
def x():
t = Thread(target=x)
p = subprocess.Popen(["python3", "test.py"])
t.run()
x()
x()
"""
<file_sep>#!/usr/bin/env python3
from colours import Colours
from threading import Thread
import os, sys
import socket
import time
from random import getrandbits
#TODO: Setup basic of server, e.g. have it listening and connecting to clients
#TODO: do normal connection first, tls later
#TODO: lock up locking variables used between threads
#TODO: write class for printing colour instead of passing colours as args to format
#NOTE: no-sql options, e.g. JSON, instead of databases?
#NOTE: have a single instance of db connecter created before start and then kpass it to both server and server-side for u
class Server:
clients = {}
#a dict of all commands to be sent to clients
#{"client_id": (cmd_id, cmd)}
command_queue = {}
command_results = {}
sock = ""
addr = ""
#code sent to clients to end connection
# kill_code = getrandbits(32)
BUFF_SIZE = 1024
def __init__(self):
try:
sock_created = False
Server.addr = (input("IP Address: "), int(input("Port Number: ")))
#create server socket and binds to address
Server.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Server.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Server.sock.bind(Server.addr)
Server.sock.listen(5)
sock_created = True
self.client_handler()
except ValueError:
print("{}[x] Server Error: Invalid address{}".format(Colours.red, Colours.white))
except PermissionError:
print("{}[x] Server Error: Don't have permisson to bind server to address{}".format(Colours.red, Colours.white))
except socket.error as err:
print("{}[x]{} The folling error occured: {}".format(Colours.red, Colours.white, err))
except KeyboardInterrupt:
pass
finally:
#closed server socket if socket has been created
if sock_created:
Server.sock.close()
print("\n{}[*] {}Server closed".format(Colours.blue, Colours.white))
def client_handler(self):
print("{}[*]{} Server listening for clients at: {}".format(Colours.blue, Colours.white, Server.addr))
while True:
c_sock, c_addr = Server.sock.accept()
c = Thread(target=Client, args=[c_sock, c_addr], daemon=True)
c.start()
'Instance of a client'
class Client(Server):
def __init__(self, sock, ip):
self.c_id = getrandbits(32)
self.sock = sock
#on the very small chance c_id repeats
while self.c_id in Server.clients: self.c_id = getrandbits(32)
#get basic info from client - ip, port, hostname
c_ip, c_port = sock.getpeername()
#c_name = sock.recv(Server.BUFF_SIZE).decode()
c_name, c_mac = eval(sock.recv(Server.BUFF_SIZE).decode())
self.c_alive = True
Server.clients[self.c_id] = [self.sock, c_ip, c_port, c_name, self.c_alive]
Server.command_queue[self.c_id] = {}
print("{}[+] {}Client connnected:{} ID {}, IP: {}:{}, Name {}, MAC: {}".format(Colours.green, Colours.blue, Colours.white, self.c_id, c_ip, c_port, c_name, c_mac))
send = Thread(target=self.send, daemon=True)
send.start()
recv = Thread(target=self.recieve, daemon=True)
recv.start()
#is_alive called last and not as seperate thread so client doesnt stop running
#untill after its infos been removed from server
self.is_alive()
def send(self):
while self.c_alive:
pass
def recieve(self):
pass
#NOTE: Should server being send to client or client sending to server for keep-alive?
def is_alive(self):
try:
while True:
self.sock.send("\0".encode())
time.sleep(5)
except socket.error:
self.disconnected()
def disconnected(self):
self.c_alive = False
print("{}[-] {}Client {}{}{} disconnected".format(Colours.red, Colours.white, Colours.blue, self.c_id, Colours.white))
#enough time for send and recieve threads to have seen clients disconnected
del Server.clients[self.c_id]
del Server.command_queue[self.c_id]
if __name__ == '__main__':
Server()
<file_sep>#!/usr/bin/env python3
#TODO: create custom print class, which has types of messages
# makes it cleaner than constantly passing colours as args to print
# method
class Colours:
black = "\033[1;30;1m"
red = "\033[1;31;1m"
green = "\033[1;32;1m"
yellow = "\033[1;33;1m"
blue = "\033[1;34;1m"
purple = "\033[1;35;1m"
cyan = "\033[1;36;1m"
white = "\033[1;37;1m"
#prints messages in colours based on there type
#NOTE: change to sub-classes
msg = {"info": lambda info: print(Colours.blue + "[*] " + Colours.white + info),
"err": lambda title, err: print(Colours.red + "[!] " + title + Colours.white + err),
"conn": lambda ID, addr: print(Colours.green + "[+] " + Colours.white + "Client " + Colours.blue + ID + Colours.white + " connected: " + addr),
"disconn": lambda ID, addr: print(Colours.red + "[-] " + Colours.white + "Client " + Colours.blue + ID + Colours.white + " disconnected: " + addr),}
if __name__ == "__main__":
Colours.msg["err"]("An error occured while creating server socket: ", "err")
<file_sep>drop table ClientCommand;
drop table Command;
drop table Client;
drop table Server;
<file_sep>#!/usr/bin/env python3
import os
' Capture all network traffic created and sent to a device '
class NetworkCapture:
def __init__(self):
pass
if __name__ == '__main__':
NetworkCapture()
<file_sep>#!/usr/bin/env python3
import sys
import ssl
import socket
import subprocess
import pymysql
from hashlib import md5
from random import randint, getrandbits
#TODO: Tidy and Clean code up
class Client:
cert = "ssl_files/certificate.crt"
def __init__(self):
try:
addr = (input("Server IP: "), int(input("Server Port: ")))
self.client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except ValueError:
exit_error("[-] Invalid server address")
except socket.error:
exit_error("[-] A problem occured while creating client socket")
ssl_client = self.ssl_wrap(addr)
if ssl_client == -1:
self.client_sock.close()
print("[-] Client closed.")
sys.exit(-1)
ID = str(getrandbits(randint(0, 999999)))
hashID = md5(ID.encode("utf-8")).hexdigest()
ssl_client.send("{}:--_:_--:{}".format(socket.gethostname(), hashID).encode("utf-8"))
print("[+] Connected to server, Client-ID: {}".format(hashID))
server_closed = False
try:
while True:
#receievs/replies command-ID and command
data = ssl_client.read().decode("utf-8")
if not data or eval(data)[0] != "COMMAND":
server_closed = True
break
data = eval(data)
print(data)
res = self.command(data[1][2])
if res != -1: res = res.stdout if res.stdout else res.stderr
else: res = "Unable to execute command"
rep = str(["COMMAND_RESULT", data[1][0], data[1][1], data[1][2], res.decode("utf-8")]).encode("utf-8")
ssl_client.write(rep)
except KeyboardInterrupt:
pass
except Exception as err:
print("[-] The following error occured: {}".format(err))
if server_closed: print("[-] Server closed")
if not server_closed: ssl_client.write("['EXIT']".encode("utf-8"))
ssl_client.close()
self.client_sock.close()
print("[-] Client closed.")
def ssl_wrap(self, addr):
ssl_sock = ssl.wrap_socket(self.client_sock, cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_TLSv1, ca_certs=Client.cert)
ssl_sock.connect(addr)
cert = ssl_sock.getpeercert()
if not cert or ssl.match_hostname(cert, "BotServer"):
print("{}Invalid certificate from server.".format("\033[1;31m"))
cont = input("\033[1;37mKeep connection to Server, may be unsecure [y/n]: ").lower()
if cont != "y" and cont != "yes": return -1
return ssl_sock
def command(self, cmd):
try:
print("COMMAND: {}\n".format(cmd))
res = subprocess.run(cmd.split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return res
except subprocess.error as err:
print("[-] Error occured while trying to run the command: {}".format(err))
return -1
def exit_error(self, msg):
print(msg)
sys.exit(-1)
if __name__ == '__main__':
Client()
| 3c0c93f18e2b79df74db4ec8d6c5bb6fe584143c | [
"JavaScript",
"SQL",
"Python"
] | 11 | JavaScript | murster972/Bots | a365fe76af951f80c4e0b7ec011d57e1c4eb5380 | f89097b2481ea1ebfb9f3f76d81997486051a523 |
refs/heads/master | <file_sep># moments-web
moments web client.
ヽ༼ຈل͜ຈ༽ノ
<file_sep>import React, { Component } from 'react'
import { connect } from 'react-redux'
import ReplyPanel from './ReplyPanel'
import filter from 'lodash/filter'
import CommentList from './CommentList'
import moment from 'moment'
import { replyMoment } from '../actions/reply'
import { postComment, deleteComment } from '../actions/postComment'
import { currentUserId } from '../globalData/index'
const mapStateToProps = (state, ownProps) => {
const { replyingMomentId } = state.page.state
const comments = filter(state.entities.comments, c =>
c.moment == ownProps.moment.id
&& c._delete != true
)
return { replyingMomentId, comments }
}
class MomentItem extends Component {
constructor(props) {
super(props)
this.onClickReply = this.onClickReply.bind(this)
this.onClickLike = this.onClickLike.bind(this)
}
onClickReply() {
const { replyingMomentId, replyMoment, moment: { id } } = this.props
if (id == replyingMomentId)
replyMoment(-1)
else
replyMoment(id)
}
onClickLike() {
const { postComment, deleteComment, moment: { id } } = this.props
const userLikeComment = this.userLikeComment()
if (typeof userLikeComment == 'undefined') {
postComment({
type: 2,
momentId: id
})
} else {
deleteComment({
momentId: id,
commentId: userLikeComment.id
})
}
}
renderReplyPanel() {
const { replyingMomentId, moment } = this.props
if (replyingMomentId != moment.id) return
return (
<div className="reply">
<ReplyPanel moment={moment} />
</div>
)
}
// TODO: refactor momentitem and comment list, move operations list into comment list
userLikeComment() {
const { comments } = this.props
return filter(comments, c => c.type == 2 && c.userId == currentUserId)[0]
}
renderOperations() {
const { replyingMomentId, moment: { id } } = this.props
const { onClickReply, onClickLike } = this
let likeClasses = 'icon icon-like'
let replyClasses = "icon icon-reply"
if (this.userLikeComment()) likeClasses += ' like'
if (id == replyingMomentId) replyClasses += ' focus'
return (
<ul className="operations">
<li onClick={onClickReply}>
<span className={replyClasses}></span>
</li>
<li className="like-container" onClick={onClickLike}>
<span className={likeClasses}>
</span>
</li>
</ul>
)
}
render() {
const { body, user, createdAt } = this.props.moment
const time = moment(createdAt).fromNow()
return (
<li className="moment block">
<div className="left">
<div className="user-avatar">
<img src={user.avatar}/>
</div>
</div>
<div className="inner">
<p className="userName">{user.name} <span className="timestamp">{time}</span></p>
<p className="body">{body}</p>
{ this.renderOperations() }
</div>
<div className="clear"></div>
<div className="bottom">
<CommentList comments={this.props.comments}/>
{ this.renderReplyPanel() }
</div>
</li>
)
}
}
export default connect(
mapStateToProps,
{ replyMoment, postComment, deleteComment }
)(MomentItem)
<file_sep>import React, { Component, PropTypes } from 'react'
export default class List extends Component {
render() {
const { items, renderItem, className } = this.props
return (
<ul className={className}>
{items.map(renderItem)}
</ul>
)
}
}
List.propTypes = {
renderItem: PropTypes.func.isRequired,
items: PropTypes.array.isRequired
}
<file_sep>import merge from 'lodash/merge'
import values from 'lodash/values'
import mapValues from 'lodash/mapValues'
// import * as action from '../actions/actionTypes'
import { postCommentReducers } from './post/comments'
const extendReducers = {}
merge(extendReducers, postCommentReducers)
const handleMore = (state, action) => {
return extendReducers[action.type](state, action)
}
const hasMore = (type) => {
return typeof extendReducers[type] === 'function'
}
// Updates an entity cache in response to any action with response.entities.
export default function entities(state = {
users: {}
}, action) {
if (action.response && action.response.entities) {
return merge({}, state, action.response.entities)
} else if (hasMore(action.type)) {
return handleMore(state, action)
} else {
return state
}
}
<file_sep>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { postMoment } from '../actions/postMoment'
import { updateCurrentPage } from '../actions/page'
import { currentUserId } from '../globalData/index'
const mapStateToProps = (state, ownProps) => {
const { entities: { users } } = state
return {
user: users[currentUserId]
}
}
class InputMoments extends Component {
constructor(props) {
super(props)
this.handleKeyPress = this.handleKeyPress.bind(this)
this.sendMoment = this.sendMoment.bind(this)
}
handleKeyPress(target) {
if (target.charCode == 13)
this.sendMoment()
}
sendMoment() {
this.props.postMoment({
body: this.refs.text.value
}).then(() => {
updateCurrentPage('feeds')
}).then(() => {
this.refs.text.value = ''
})
}
render() {
const { user } = this.props
return (
<div id="input-moments" className="block">
<div className="input-moments-inner">
<div className="avatar">
<img src={user && user.avatar}/>
</div>
<div className="inputs">
<textarea ref="text" onKeyPress={this.handleKeyPress} placeholder="想说点什么...">
</textarea>
<a href="javascript:;" onClick={this.sendMoment}>发送</a>
</div>
</div>
</div>
)
}
}
export default connect(
mapStateToProps,
{ postMoment, updateCurrentPage }
)(InputMoments)
<file_sep>export const REPLY_MOMENT = 'REPLY_MOMENT'
export const replyMoment = (momentId) => {
return (dispatch, getState) => {
dispatch({
type: REPLY_MOMENT,
momentId
})
return Promise.resolve()
}
}
<file_sep>import merge from 'lodash/merge'
import actions from '../actions/actionTypes'
import { combineReducers } from 'redux'
const state = (state = {
selectUserId: undefined,
current: 'feeds',
replyingMomentId: undefined
}, action) => {
if (action.type == actions.SELECT_USER) {
const { selectUserId } = action
return merge({}, state, { selectUserId })
} else if (action.type == actions.UPDATE_CURRENT_PAGE) {
const { current } = action
return merge({}, state, { current })
} else if (action.type == actions.REPLY_MOMENT) {
return merge({}, state, { replyingMomentId: action.momentId })
} else {
return state
}
}
export default combineReducers({
state
})
<file_sep>import { applyMiddleware, createStore } from 'redux'
import rootReducer from '../reducers/index'
import logger from 'redux-logger'
import thunk from 'redux-thunk'
import api from '../middleware/api'
export default function configureStore() {
return createStore(
rootReducer,
applyMiddleware(thunk, api, logger())
)
}
<file_sep>import React, { Component } from 'react'
import Header from '../components/Header'
import Footer from '../components/Footer'
import FollowerList from '../containers/FollowerList'
import MomentList from '../containers/MomentList'
import InputMoments from '../containers/InputMoments'
import FeedList from '../containers/FeedList'
import MyList from '../containers/MyList'
import UserList from '../containers/UserList'
import { connect } from 'react-redux'
import { currentUserId } from '../globalData/index'
const mapStateToProps = (state, ownProps) => {
const { current } = state.page.state
return { current }
}
class App extends Component {
list() {
const { current } = this.props
if (current == 'feeds') {
return <FeedList />
} else {
return <MomentList />
}
}
render() {
return (
<div>
<Header />
<main id="main-section">
<div className="row">
<div className="left">
<MyList />
</div>
<div className="middle">
<InputMoments />
{this.list()}
</div>
<div className="right">
<UserList />
<FollowerList />
</div>
</div>
</main>
</div>
)
}
}
export default connect(
mapStateToProps,
{}
)(App)
<file_sep>import { CALL_API, GET } from '../middleware/api'
import Schemas from '../schemas/index'
export const FEEDS_REQUEST = 'FEEDS_REQUEST'
export const FEEDS_SUCCESS = 'FEEDS_SUCCESS'
export const FEEDS_FAILURE = 'FEEDS_FAILURE'
export const UPDATE_FEEDS_PARAMS = 'UPDATE_FEEDS_PARAMS'
function fetchFeeds(params) {
return {
[CALL_API]: {
method: GET,
types: [ FEEDS_REQUEST, FEEDS_SUCCESS, FEEDS_FAILURE ],
endpoint: `users/${params.userId}/feeds`,
schema: Schemas.MOMENT_ARRAY,
params: params
}
}
}
export const loadFeeds = () => {
return (dispatch, getState) => {
const { params } = getState().pagination.feeds
return dispatch(fetchFeeds(params))
}
}
<file_sep>import merge from 'lodash/merge'
import * as followerAction from './followers'
import * as momentsAction from './moments'
import * as postMomentAction from './postMoment'
import * as pageAction from './page'
import * as feedsAction from './feeds'
import * as usersAction from './users'
import * as replyAction from './reply'
import * as postCommentAction from './postComment'
const actions = {}
merge(actions, followerAction)
merge(actions, momentsAction)
merge(actions, postMomentAction)
merge(actions, pageAction)
merge(actions, feedsAction)
merge(actions, usersAction)
merge(actions, replyAction)
merge(actions, postCommentAction)
export default actions
<file_sep>import { CALL_API, GET, POST } from '../middleware/api'
import Schemas from '../schemas/index'
import merge from 'lodash/merge'
import { currentUserId } from '../globalData/index'
export const FOLLOWERS_REQUEST = 'FOLLOWERS_REQUEST'
export const FOLLOWERS_SUCCESS = 'FOLLOWERS_SUCCESS'
export const FOLLOWERS_FAILURE = 'FOLLOWERS_FAILURE'
export const UPDATE_FOLLOWERS_PARAMS = 'UPDATE_FOLLOWERS_PARAMS'
export const UPDATE_FOLLOWERS_LIST = 'UPDATE_FOLLOWERS_LIST'
function fetchFollowers(params) {
return {
[CALL_API]: {
method: GET,
types: [ FOLLOWERS_REQUEST, FOLLOWERS_SUCCESS, FOLLOWERS_FAILURE ],
endpoint: `users/${params.userId}/followers`,
schema: Schemas.USER_ARRAY,
params: params
}
}
}
export const loadFollowers = () => {
return (dispatch, getState) => {
const { params } = getState().pagination.followers
return dispatch(fetchFollowers(params))
}
}
export const FOLLOWS_REQUEST = 'FOLLOWS_REQUEST'
export const FOLLOWS_SUCCESS = 'FOLLOWS_SUCCESS'
export const FOLLOWS_FAILURE = 'FOLLOWS_FAILURE'
const postFollow = (params) => {
return {
[CALL_API]: {
method: POST,
types: [ FOLLOWS_REQUEST, FOLLOWS_SUCCESS, FOLLOWS_FAILURE ],
endpoint: `users/${params.currentUserId}/followers`,
params: params
}
}
}
// can be follow / unfollow
export const follow = (params) => {
return (dispatch, getState) => {
params = merge(params, { currentUserId })
dispatch(postFollow(params))
return Promise.resolve()
}
}
export const updateFollowerList = (params) => {
return (dispatch, getState) => {
dispatch({
type: UPDATE_FOLLOWERS_LIST,
userId: params.userId,
actionType: params.action
})
return Promise.resolve()
}
}
<file_sep>import forOwn from 'lodash/forOwn'
import { Schema, arrayOf, normalize } from 'normalizr'
import { camelizeKeys } from 'humps'
import 'isomorphic-fetch'
import { API_ROOT } from '../api'
export function post(endpoint, params, schema) {
const fullUrl = (endpoint.indexOf(API_ROOT) === -1) ? API_ROOT + endpoint : endpoint
return fetch(fullUrl, {
body: JSON.stringify(params),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST'
}).then(response =>
response.json().then(json => ({ json, response }))
).then(({ json, response }) => {
if (!response.ok) {
return Promise.reject(json)
}
// when schema is not defined, no response is expected.
if (typeof schema == 'undefined') {
return {}
}
const camelizedJson = camelizeKeys(json)
const flat = normalize(camelizedJson.items, schema)
delete camelizedJson.items
return Object.assign({}, flat, { info: camelizedJson })
})
}
<file_sep>import { CALL_API, GET } from '../middleware/api'
import Schemas from '../schemas/index'
export const USERS_REQUEST = 'USERS_REQUEST'
export const USERS_SUCCESS = 'USERS_SUCCESS'
export const USERS_FAILURE = 'USERS_FAILURE'
export const UPDATE_USERS_PARAMS = 'UPDATE_USERS_PARAMS'
function fetchUsers(params) {
return {
[CALL_API]: {
method: GET,
types: [ USERS_REQUEST, USERS_SUCCESS, USERS_FAILURE ],
endpoint: 'users',
schema: Schemas.USER_ARRAY,
params: params
}
}
}
export const loadUsers = () => {
return (dispatch, getState) => {
const { params } = getState().pagination.users
return dispatch(fetchUsers(params))
}
}
<file_sep>import { CALL_API, POST } from '../middleware/api'
import Schemas from '../schemas/index'
import { currentUserId } from '../globalData/index'
import merge from 'lodash/merge'
export const POST_MOMENTS_REQUEST = 'POST_MOMENTS_REQUEST'
export const POST_MOMENTS_SUCCESS = 'POST_MOMENTS_SUCCESS'
export const POST_MOMENTS_FAILURE = 'POST_MOMENTS_FAILURE'
const sendMoment = (params) => {
return {
[CALL_API]: {
method: POST,
types: [ POST_MOMENTS_REQUEST, POST_MOMENTS_SUCCESS, POST_MOMENTS_FAILURE ],
endpoint: `users/${params.userId}/moments`,
schema: Schemas.MOMENT,
params: params
}
}
}
export const postMoment = (params) => {
return (dispatch, getState) => {
params = merge(params, { userId: currentUserId })
dispatch(sendMoment(params))
return Promise.resolve()
}
}
<file_sep>import React, { Component } from 'react'
import { connect } from 'react-redux'
import List from '../components/List'
import * as status from '../reducers/paginate'
import filter from 'lodash/filter'
import isEmpty from 'lodash/isEmpty'
import includes from 'lodash/includes'
import union from 'lodash/union'
import { currentUserId } from '../globalData/index'
const mapStateToProps = (state, ownProps) => {
const {
pagination: {
followers: {
ids,
}
}
} = state
return { followerIds: ids }
}
class CommentList extends Component {
renderLike(like) {
return (
<li className="likes-item">
<img src={like.userAvatar} alt={like.userName}/>
</li>
)
}
renderTalk(talk) {
return (
<li className="talks-item">
<p>
<span className="replier">
{talk.userName}
</span>
{ !isEmpty(talk.otherName) ?
(<span className="replier other">{talk.otherName}</span>) : ('')
}
:
{talk.body}
</p>
</li>
)
}
filterUnfollowedComments(comments) {
let ids = this.props.followerIds
ids = union(ids, [currentUserId])
return filter(comments, c => {
const followedReplier = includes(ids, c.userId)
const hasOtherReplier = !!c.otherId
const followedOther = includes(ids, c.otherId)
return followedReplier && (hasOtherReplier && followedOther || !hasOtherReplier)
})
}
render() {
const { renderLike, renderTalk } = this
let { comments } = this.props
comments = this.filterUnfollowedComments(comments)
const talks = filter(comments, c => c.type == 1)
const likes = filter(comments, c => c.type == 2)
if (comments.length == 0)
return (
<div></div>
)
return (
<div className="comments">
<List
renderItem={renderLike}
items={likes}
className={"comments-likes"}
/>
<List
renderItem={renderTalk}
items={talks}
className={"comments-talks"}
/>
</div>
)
}
}
export default connect(
mapStateToProps,
{ }
)(CommentList)
<file_sep>import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as status from '../reducers/paginate'
import { selectUser, updateCurrentPage } from '../actions/page'
import { loadMoments, updateMomentsParams } from '../actions/moments'
import { currentUserId } from '../globalData/index'
const mapStateToProps = (state, ownProps) => {
const {
entities: {
users
},
page: { state: { current, selectUserId } }
} = state
return {
user: users[currentUserId],
current,
selectUserId
}
}
class MyList extends Component {
constructor(props) {
super(props)
this.selectFeed = this.selectFeed.bind(this)
this.selectMe = this.selectMe.bind(this)
}
selectMe() {
const {
user: { id },
selectUser,
loadMoments,
updateMomentsParams,
updateCurrentPage
} = this.props
selectUser(id)
.then(updateMomentsParams)
.then(loadMoments)
.then(() => { updateCurrentPage('user_moment') })
}
selectFeed() {
const { updateCurrentPage, selectUser } = this.props
updateCurrentPage('feeds').then(() => {
// select none user.
selectUser(-1)
})
}
render() {
const {
props: { user }
} = this
// return empty unless user present
if (!user) return ( <div></div> )
return (
<div className={"block my-list"}>
<div className="mylist-header">
</div>
<div className="mylist-main">
<div className="mylist-detail">
<div className="avatar"><img src={user.avatar}/></div>
<div className="name">{user.name}</div>
</div>
<div className="mylist-operations">
<a
href="javascript:;"
onClick={this.selectMe}
className={this.props.selectUserId == currentUserId ? 'selected' : ''}
>
我的moments
</a>
<a
href="javascript:;"
onClick={this.selectFeed}
className={this.props.current == "feeds" ? 'selected' : ''}
>
我的timeline
</a>
</div>
</div>
</div>
)
}
}
export default connect(
mapStateToProps,
{ updateCurrentPage, selectUser, loadMoments, updateMomentsParams }
)(MyList)
<file_sep>export const SELECT_USER = 'SELECT_USER'
export const UPDATE_CURRENT_PAGE = 'UPDATE_CURRENT_PAGE'
export const selectUser = (userId) => {
return (dispatch, getState) => {
dispatch({
type: SELECT_USER,
selectUserId: userId
})
return Promise.resolve()
}
}
export const updateCurrentPage = (current) => {
return (dispatch, getState) => {
dispatch({
type: UPDATE_CURRENT_PAGE,
current
})
return Promise.resolve()
}
}
<file_sep>import { Schema, arrayOf, normalize } from 'normalizr'
const userSchema = new Schema('users', { idAttribute: 'id' })
const momentSchema = new Schema('moments', { idAttribute: 'id' })
const commentSchema = new Schema('comments', { idAttribute: 'id' })
momentSchema.define({
user: arrayOf(userSchema),
comments: arrayOf(commentSchema)
})
commentSchema.define({
moment: momentSchema
})
// Schemas for Moments API responses.
export default {
USER: userSchema,
USER_ARRAY: arrayOf(userSchema),
MOMENT: momentSchema,
MOMENT_ARRAY: arrayOf(momentSchema),
COMMENT: commentSchema,
COMMENT_ARRAY: arrayOf(commentSchema)
}
<file_sep>import merge from 'lodash/merge'
import union from 'lodash/union'
import { combineReducers } from 'redux'
import paginate from './paginate'
import actions from '../actions/actionTypes'
import * as status from './paginate'
import { currentUserId } from '../globalData/index'
import { postMomentHandlers } from './post/moments'
import { updateListReducers } from './updateFollower'
const defaultHandle = (state, action) => {
return Object.assign({}, state, {
params: merge({}, state.params, action.params),
ids: [],
page: 1,
fetchStatus: status.PENDING
})
}
// TODO: avoid hardcoding userId in defaultParams.
export default combineReducers({
followers: paginate({
types: [
actions.FOLLOWERS_REQUEST,
actions.FOLLOWERS_SUCCESS,
actions.FOLLOWERS_FAILURE
],
defaultParams: { userId: currentUserId },
more: merge(updateListReducers, {
[actions.UPDATE_FOLLOWERS_PARAMS]: defaultHandle
})
}),
users: paginate({
types: [
actions.USERS_REQUEST,
actions.USERS_SUCCESS,
actions.USERS_FAILURE
],
defaultParams: {},
more: {
[actions.UPDATE_USERS_PARAMS]: defaultHandle
}
}),
moments: paginate({
types: [
actions.MOMENTS_REQUEST,
actions.MOMENTS_SUCCESS,
actions.MOMENTS_FAILURE
],
defaultParams: { userId: currentUserId },
more: {
[actions.UPDATE_MOMENTS_PARAMS]: defaultHandle
}
}),
feeds: paginate({
types: [
actions.FEEDS_REQUEST,
actions.FEEDS_SUCCESS,
actions.FEEDS_FAILURE
],
defaultParams: { userId: currentUserId },
// TODO: handle last id.
more: merge(postMomentHandlers, {
[actions.UPDATE_FOLLOWERS_PARAMS]: defaultHandle
})
})
})
<file_sep>import action from '../../actions/actionTypes'
import merge from 'lodash/merge'
import union from 'lodash/union'
const deleteCommentReducer = (state, action) => {
const { params: { commentId } } = action
let comment = state.comments[commentId]
comment = merge({}, comment, { '_delete': true })
return merge({}, state, { comments: { [commentId]: comment } })
}
export const postCommentReducers = {
[action.DELETE_COMMENTS_SUCCESS]: deleteCommentReducer
}
<file_sep>import React, { Component } from 'react'
import SelectUser from '../containers/SelectUser'
class Header extends Component {
render() {
return (
<header>
<a className="main-logo" href="/">
Moments
</a>
<div className="options">
<SelectUser />
</div>
</header>
)
}
}
export default Header
<file_sep>import { CALL_API, POST } from '../middleware/api'
import Schemas from '../schemas/index'
import { currentUserId } from '../globalData/index'
import merge from 'lodash/merge'
export const POST_COMMENTS_REQUEST = 'POST_COMMENTS_REQUEST'
export const POST_COMMENTS_SUCCESS = 'POST_COMMENTS_SUCCESS'
export const POST_COMMENTS_FAILURE = 'POST_COMMENTS_FAILURE'
export const DELETE_COMMENTS_REQUEST = 'DELETE_COMMENTS_REQUEST'
export const DELETE_COMMENTS_SUCCESS = 'DELETE_COMMENTS_SUCCESS'
export const DELETE_COMMENTS_FAILURE = 'DELETE_COMMENTS_FAILURE'
const sendComment = (params) => {
return {
[CALL_API]: {
method: POST,
types: [ POST_COMMENTS_REQUEST, POST_COMMENTS_SUCCESS, POST_COMMENTS_FAILURE ],
endpoint: `moments/${params.momentId}/comments`,
schema: Schemas.COMMENT,
params: params
}
}
}
const sendDelteComment = (params) => {
return {
[CALL_API]: {
method: POST,
types: [ DELETE_COMMENTS_REQUEST, DELETE_COMMENTS_SUCCESS, DELETE_COMMENTS_FAILURE ],
endpoint: `moments/${params.momentId}/comments/${params.commentId}/destroy`,
params: params
}
}
}
// type, momentId, userId, (otherId), body
export const postComment = (params) => {
return (dispatch, getState) => {
params = merge(params, { userId: currentUserId })
dispatch(sendComment(params))
return Promise.resolve()
}
}
export const deleteComment = (params) => {
return (dispatch, getState) => {
params = merge(params, { userId: currentUserId })
dispatch(sendDelteComment(params))
return Promise.resolve()
}
}
<file_sep>import React, { Component } from 'react'
import { connect } from 'react-redux'
import MomentItem from './MomentItem'
import List from '../components/List'
import * as status from '../reducers/paginate'
const mapStateToProps = (state, ownProps) => {
const {
entities: {
moments
},
pagination: {
moments: {
fetchStatus,
ids,
failTimes
}
}
} = state
return {
moments: ids.map(id => moments[id]),
fetchStatus,
failTimes
}
}
class MomentList extends Component {
renderMoment(m) {
return (
<MomentItem
moment={m}
/>
)
}
render() {
const { renderMoment, props: { moments } } = this
return (
<div className={"moments"}>
<List
renderItem={renderMoment}
items={moments}
className={"moment-list"}
/>
</div>
)
}
}
export default connect(
mapStateToProps,
{ }
)(MomentList)
<file_sep>import React, { Component } from 'react'
import { connect } from 'react-redux'
import MomentItem from './MomentItem'
import List from '../components/List'
import * as status from '../reducers/paginate'
import { loadFeeds } from '../actions/feeds'
const mapStateToProps = (state, ownProps) => {
const {
entities: {
moments
},
pagination: {
feeds: {
fetchStatus,
ids,
failTimes
}
}
} = state
return {
feeds: ids.map(id => moments[id]),
fetchStatus,
failTimes
}
}
class FeedList extends Component {
componentWillMount() {
if (this.shouldLoad(this.props)) {
this.props.loadFeeds()
}
}
componentWillReceiveProps(nextProps) {
if (this.shouldLoad(nextProps))
this.props.loadFeeds()
}
shouldLoad(props) {
const { feeds, fetchStatus, failTimes } = props
return feeds.length == 0
&& fetchStatus == status.PENDING
&& failTimes < 10
}
renderMoment(m) {
return (
<MomentItem moment={m} />
)
}
render() {
const { renderMoment, props: { feeds } } = this
return (
<div className={"feeds"}>
<List
renderItem={renderMoment}
items={feeds}
className={"moment-list"}
/>
</div>
)
}
}
export default connect(
mapStateToProps,
{ loadFeeds }
)(FeedList)
| 1b9e6530540d4132862975ac2cde12b047c94f34 | [
"Markdown",
"JavaScript"
] | 25 | Markdown | afghl/moments-web | 8085f7df393f694c3331933bc46558c62c3f75cd | 76abd99b8b9e1548bc5ea5272f31ec01168ce657 |
refs/heads/master | <repo_name>joffreydemetz/authentication<file_sep>/src/Authentication.php
<?php
/**
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JDZ\Authentication;
use JDZ\Authentication\Connector\Connector;
/**
* Authentication Base Object
*
* @author <NAME> <<EMAIL>>
*/
class Authentication
{
/**
* Failed request (initial status)
*
* @var constant
*/
const FAILURE = 0;
/**
* Successful response
*
* @var constant
*/
const SUCCESS = 1;
/**
* Missing login
*
* @var constant
*/
const EMPTY_USER = 2;
/**
* Missing password
*
* @var constant
*/
const EMPTY_PASS = 3;
/**
* Account not found
*
* @var constant
*/
const BAD_CREDENTIALS = 4;
/**
* Invalid password
*
* @var constant
*/
const BAD_PASS = 5;
/**
* List of connectors (local|..)
*
* @var array
*/
protected $connectors;
/**
* Constructor
*
* @param array $config Key/value pairs
*/
public function __construct(array $config=[])
{
foreach($config as $key => $value){
$this->{$key} = $value;
}
$this->connectors = [];
}
/**
* Add a connector to the stack
*
* @param Connector $connector Authentication connector instance
* @return void
*/
public function addConnector(Connector $connector)
{
$this->connectors[] = $connector;
}
/**
* Prepare authentication
*
* @param array $credentials Array holding the user credentials
* @return Response
*/
public function authenticate(array $credentials)
{
$response = new AuthenticationResponse();
if ( empty($credentials['username']) ){
$response->status = Authentication::EMPTY_USER;
return $response;
}
if ( empty($credentials['password']) ){
$response->status = Authentication::EMPTY_PASS;
return $response;
}
$connectors = array_reverse($this->connectors);
foreach($connectors as $connector){
if ( $connector->authenticate($credentials, $response) ){
break;
}
}
return $response;
}
}
<file_sep>/src/Connector/BasicConnector.php
<?php
/**
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JDZ\Authentication\Connector;
use JDZ\Authentication\Authentication;
use JDZ\Authentication\AuthenticationResponse;
/**
* Basic connector for authentication
*
* @author <NAME> <<EMAIL>>
*/
class BasicConnector extends Connector
{
/**
* Expected username
*
* @var string
*/
protected $username;
/**
* Expected username
*
* @var string
*/
protected $password;
/**
* Used to authenticate user
*
* @param array $credentials Key/value pairs holding the user credentials
* @param AuthenticationResponse $response Authentication response object
* @return boolean
*/
public function authenticate(array $credentials, AuthenticationResponse &$response)
{
if ( $credentials['username'] === '' ){
$response->status = Authentication::EMPTY_USER;
return false;
}
if ( !isset($this->username) || $this->username === '' || $credentials['username'] !== $this->username ){
$response->status = Authentication::BAD_CREDENTIALS;
return false;
}
$hashed_password = $this->getHashedPassword($credentials);
if ( $hashed_password === '' ){
$response->status = Authentication::BAD_CREDENTIALS;
return false;
}
if ( !$this->checkPassword($credentials, $hashed_password) ){
$response->status = Authentication::BAD_PASS;
return false;
}
$response->type = 'Basic';
$response->status = Authentication::SUCCESS;
return true;
}
/**
* Get the wanted hashed password
*
* @param array $credentials Key/value pairs holding the user credentials
* @return string The user hashed password
*/
protected function getHashedPassword(array $credentials)
{
return isset($this->password) ? $this->password : '';
}
}
<file_sep>/README.md
# authentication
Simple authentication
## Usage
Exemple for a database authentication
1/ Create a DatabaseConnector
```
use JDZ\Authentication\Connector\DatabaseConnector;
/**
* Database connector for authentication
*/
class DboAuthenticator extends DatabaseConnector
{
/**
* Get the user hashed password from the username
*
* @param array $credentials Key/value pairs holding the user credentials
* @return string The user hashed password
*/
protected function getHashedPassword(array $credentials)
{
$dbo = Dbo();
$query = $dbo->getQuery(true);
$query->select($this->tbl_pass_column);
$query->from($this->tbl_name);
$query->where($this->tbl_username_column.'='.$dbo->q($credentials['username']));
$dbo->setQuery($query);
$result = $dbo->loadResult();
return (string)$result;
}
}
```
2/ Authenticate
```
use JDZ\Authentication\Authentication;
use JDZ\Authentication\AuthenticationException;
function authenticate($credentials)
{
$authenticationConnector = new DboAuthenticator([
'tbl_name' => 'users',
'tbl_username_column' => 'email',
'tbl_pass_column' => '<PASSWORD>',
]);
$auth = new Authentication();
$auth->addConnector($authenticationConnector);
$authResponse = $auth->authenticate($credentials, $options);
if ( $authResponse->status !== Authentication::SUCCESS ){
if ( isset($options['silent']) && $options['silent'] ){
return false;
}
switch($authResponse->status){
case Authentication::EMPTY_USER:
$message = 'Missing username in credentials';
break;
case Authentication::EMPTY_PASS:
$message = 'Missing password in credentials';
break;
case Authentication::BAD_PASS:
$message = 'Invalid password';
break;
case Authentication::BAD_CREDENTIALS:
$message = 'Bad credentials';
break;
}
throw new AuthenticationException($message);
}
}
$credentials = [
'username' => 'user',
'password' => '<PASSWORD>',
];
try {
authenticate($credentials);
}
catch(AuthenticationException $e){
die($e->getMessage();
}
```
<file_sep>/src/Connector/ConnectorInterface.php
<?php
/**
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JDZ\Authentication\Connector;
use JDZ\Authentication\AuthenticationResponse;
/**
* Abstract connector for authentication
*
* @author <NAME> <<EMAIL>>
*/
interface ConnectorInterface
{
/**
* Used to authenticate user
*
* @param array $credentials Key/value pairs holding the user credentials
* @param AuthenticationResponse $response Authentication response object
* @return boolean
*/
public function authenticate(array $credentials, AuthenticationResponse &$response);
}
<file_sep>/src/Connector/Connector.php
<?php
/**
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JDZ\Authentication\Connector;
/**
* Abstract connector for authentication
*
* @author <NAME> <<EMAIL>>
*/
abstract class Connector implements ConnectorInterface
{
/**
* Constructor
*
* @param array $config Key/value pairs
*/
public function __construct(array $config=[])
{
foreach($config as $key => $value){
$this->{$key} = $value;
}
}
/**
* Get the user hashed password from the username
*
* @param array $credentials Key/value pairs holding the user credentials
* @return string The user hashed password
*/
abstract protected function getHashedPassword(array $credentials);
/**
* Check the user password
*
* @param array $credentials Key/value pairs holding the user credentials
* @param string $hashed_password The user hashed password
* @return bool True if the passwords are a match.
*/
protected function checkPassword(array $credentials, $hashed_password)
{
return ( password_verify($credentials['password'], $hashed_password) );
}
}
<file_sep>/src/Connector/DatabaseConnector.php
<?php
/**
* THIS SOFTWARE IS PRIVATE
* CONTACT US FOR MORE INFORMATION
* <NAME> <<EMAIL>>
* <https://callisto-framework.com>
*/
namespace JDZ\Authentication\Connector;
use JDZ\Authentication\Authentication;
use JDZ\Authentication\AuthenticationResponse;
/**
* Database connector for authentication
*
* @author <NAME> <<EMAIL>>
*/
abstract class DatabaseConnector extends Connector
{
/**
* Table name
*
* @var string
*/
protected $tbl_name;
/**
* Table username column
*
* @var string
*/
protected $tbl_username_column;
/**
* Table password column
*
* @var string
*/
protected $tbl_pass_column;
/**
* Used to authenticate user
*
* @param array $credentials Key/value pairs holding the user credentials
* @param AuthenticationResponse $response Authentication response object
* @return boolean
*/
public function authenticate(array $credentials, AuthenticationResponse &$response)
{
$hashed_password = $this->getHashedPassword($credentials);
if ( $hashed_password === '' ){
$response->status = Authentication::BAD_CREDENTIALS;
return false;
}
if ( !$this->checkPassword($credentials, $hashed_password) ){
$response->status = Authentication::BAD_PASS;
return false;
}
$response->type = 'Database';
$response->status = Authentication::SUCCESS;
return true;
}
}
<file_sep>/src/AuthenticationResponse.php
<?php
/**
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JDZ\Authentication;
/**
* Authentication response class, provides an object for storing user and error details
*
* @author <NAME> <<EMAIL>>
*/
class AuthenticationResponse
{
/**
* Response status (see status codes)
*
* @var string
*/
public $status;
/**
* The type of authentication that was successful
*
* @var string
*/
public string $type;
/**
* End User email as specified in section 3.4.1 of [RFC2822]
*
* @var string
*/
public $email;
/**
* End User password
*
* @var string
*/
public $password;
/**
* End User full name
*
* @var string
*/
public $fullname;
/**
* End User firstname
*
* @var string
*/
public $firstname;
/**
* End User lastname
*
* @var string
*/
public $lastname;
/**
* End User username
*
* @var string
*/
public $username;
/**
* End User preferred language as specified by ISO639
*
* @var string
*/
public $language;
/**
* Constructor
*/
public function __construct()
{
$this->status = Authentication::FAILURE;
$this->type = '';
$this->email = '';
$this->password = '';
$this->fullname = '';
$this->firstname = '';
$this->lastname = '';
$this->username = '';
$this->language = 'fr-FR';
}
}
| dbc6c4c0e665d0b713f0bd23bac67ef705ac564b | [
"Markdown",
"PHP"
] | 7 | PHP | joffreydemetz/authentication | 791be5f526cf2cc1c4612df4ac0a94a2fb038de6 | 6feefa9ea42552332ae394df47bc9c7b66e9d40a |
refs/heads/main | <repo_name>globalfranck/San-Antonio-quotes<file_sep>/README.md
# San-Antonio-quotes
Quoting <NAME>'s San-Antonio citations using popular fictional characters
<file_sep>/san_antonio.py
# Import random module in order to use the randint method to get a random integer
import random
quotes = [
"Ecoutez-moi, <NAME>, nous avons beau être ou ne pas être, nous sommes ! ",
"On doit pouvoir choisir entre s'écouter parler et se faire entendre"
]
characters = [
"alvin et les chipmunks",
"babar",
"<NAME>",
"calimero",
"casper",
"le chat potté",
"kirikou"
]
# function to obtain a random item from a list
def get_random_item(my_list):
# get a random number from the random library
rand_number = random.randint(0, len(my_list) - 1)
# choose a random item inside of the list (characters or quotes)
item = my_list[rand_number]
return item
# function to capitalize each words (characters are not capitalize)
def capitalize(words):
for word in words:
word.capitalize()
# function to create a message which is comprised of the characters name and its quote
def message(character, quote):
return f"{character.capitalize()} a dit : {quote.capitalize()}"
# First interaction with the user : launching or not the loop
user_answer = input("Tapez entrée pour connaître une autre citation ou B pour quitter le programme.")
# If user enters B => end the program, otherwise launch the program and show a random quote
while user_answer != "B" :
print( message( get_random_item(characters), get_random_item(quotes)) )
user_answer = input("Tapez entrée pour connaître une autre citation ou B pour quitter le programme.")
| 11c8b436d2bcbd92c22f66807822031b5fdbaf26 | [
"Markdown",
"Python"
] | 2 | Markdown | globalfranck/San-Antonio-quotes | 417a8a9bc80b3167d5c0b7539c4b69ca59027dd4 | f34e31270401eed09fec3e418e5638b97aaacc74 |
refs/heads/master | <repo_name>adamheldring/boardgamegoogle<file_sep>/myScript.js
/* My JavaScript function that only has love for board games */
function mySearch() {
var mySearchText = document.getElementById("mySearchField").value;
if (mySearchText == "board games" || mySearchText == "Board games" || mySearchText == "boardgames" || mySearchText == "Boardgames") {
document.getElementById('myHeader').innerHTML = "You searched for \"" + mySearchText + "\"... try these ones!";
document.getElementById("myResultBox").style.visibility = "visible";
}
else {
document.getElementById("myResultBox").style.visibility = "hidden";
document.getElementById('myHeader').innerHTML = "You can search for \"" + mySearchText + "\" any other day.</br></br> Try something fun for once like... board games!" ;
}
}
<file_sep>/README.md
# boardgamegoogle
Board Game Google - My solution for Technigo Coding Challenge.
Enjoy!
/Adam
| b9faeb95e5de3a6a10f127f81005771a639422e3 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | adamheldring/boardgamegoogle | c699136f2b7efcc28fb9ed816c9c634002399ce4 | f8ac9b3794ecd2058d469587b2464c65e6c7f790 |
refs/heads/master | <file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 12/05/2018
* Time: 12:13 PM
*/
namespace App\Services\Impl;
use App\Entities\LandingPage;
use App\Services\LandingPageService;
use App\Services\LandingThemeService;
use App\Services\LandingBannerService;
use App\Repositories\LandingPageRepo;
class LandingPageServiceImpl implements LandingPageService
{
private $theme,$banner,$landingPageRepo;
public function __construct(LandingThemeService $themeService,LandingBannerService $bannerService,LandingPageRepo $landingPageRepo)
{
$this->theme = $themeService;
$this->banner = $bannerService;
$this->landingPageRepo = $landingPageRepo;
}
public function getAllLanding()
{
return $this->landingPageRepo->getAllLanding();
}
public function saveData($data)
{
$landingPage = new LandingPage();
$landingPage->setLandingPageBannerId($this->banner->getBanner($data->get('banner')));
$landingPage->setLandingThemeId($this->theme->getTheme($data->get('theme')));
$landingPage->setTitle($data->get('title'));
$landingPage->setSlug(str_slug($data->get('title'),'-'));
$landingPage->setContent($data->get('content'));
$landingPage->setMetaTitle($data->get('meta-title'));
$landingPage->setMetaKey($data->get('meta-keyword'));
$landingPage->setMetaDescription($data->get('meta-description'));
$landingPage->setAttributes('');
$landingPage->setIsActive(1);
$landingPage->setCreatedAt( new \Datetime());
$landingPage->setUpdatedAt(new \Datetime());
return $this->landingPageRepo->saveData($landingPage);
}
public function updateData($data, $id)
{
$landingPage = $this->landingPageRepo->getLandingPage($id);
$landingPage->setLandingPageBannerId($this->banner->getBanner($data->get('banner')));
$landingPage->setLandingThemeId($this->theme->getTheme($data->get('theme')));
$landingPage->setTitle($data->get('title'));
$landingPage->setSlug(str_slug($data->get('title'),'-'));
$landingPage->setContent($data->get('content'));
$landingPage->setMetaTitle($data->get('meta-title'));
$landingPage->setMetaKey($data->get('meta-keyword'));
$landingPage->setMetaDescription($data->get('meta-description'));
$landingPage->setAttributes('');
$landingPage->setIsActive($data->get('active'));
$landingPage->setCreatedAt( new \Datetime());
$landingPage->setUpdatedAt(new \Datetime());
return $this->landingPageRepo->saveData($landingPage);
}
public function getLandingPage($id)
{
return $this->landingPageRepo->getLandingPage($id);
}
public function getLandingPageBySlug($slug)
{
return $this->landingPageRepo->getLandingPageBySlug($slug);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 13/06/2018
* Time: 4:33 PM
*/
namespace App\Http\Controllers;
use App\Services\VerticalService;
class TagGeneratorController extends Controller
{
public function __construct(VerticalService $solutionTypeService)
{
$this->solutionService=$solutionTypeService;
}
public function tagGenerator()
{
$this->solutionService->tagGenerator();
echo 'Tag Generated SuccessFully............';
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 15/06/2018
* Time: 10:40 AM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="g_product_slug")
*/
class ProductSlug
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\OneToOne(targetEntity="Product", inversedBy="productSlug")
* @ORM\JoinColumn(name="product_id", referencedColumnName="id")
*/
private $productId;
/**
* @ORM\Column(type="string",nullable=true)
*/
private $urlSlug;
/**
* @ORM\Column(type="datetime")
*/
private $updDate;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getProductId()
{
return $this->productId;
}
/**
* @param mixed $productId
*/
public function setProductId($productId)
{
$this->productId = $productId;
}
/**
* @return mixed
*/
public function getUrlSlug()
{
return $this->urlSlug;
}
/**
* @param mixed $urlSlug
*/
public function setUrlSlug($urlSlug)
{
$this->urlSlug = $urlSlug;
}
/**
* @return mixed
*/
public function getUpdDate()
{
return $this->updDate;
}
/**
* @param mixed $updDate
*/
public function setUpdDate($updDate)
{
$this->updDate = $updDate;
}
}<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\AdService;
use App\Services\PageBannerService;
use App\Services\SolutionTypeService;
use App\Services\ProductService;
use App\Services\TagService;
use App\Services\VerticalService;
use App\Services\SolutionService;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;
class SolutionsController extends Controller
{
protected $adService,$pageBannerService,$solutionTypeService,$productService,$verticalService,$solutionService;
protected $route,$page_id,$content,$banner,$solutions,$abouts;
public function __construct(AdService $adService,PageBannerService $pageBannerService,SolutionTypeService $solutionTypeService,ProductService $productService,TagService $tagService, VerticalService $verticalService,SolutionService $solutionService)
{
$this->adService = $adService;
$this->pageBannerService = $pageBannerService;
$this->solutionTypeService = $solutionTypeService;
$this->productService = $productService;
$this->tagService = $tagService;
$this->verticalService = $verticalService;
$this->route = Route::current();
$route_name = strpos($this->route->getName(), ".") !== false?substr($this->route->getName(),0 ,strpos($this->route->getName(), ".")):$this->route->getName();
$this->page_id = $this->pageBannerService->getPageId($route_name);
$this->content = $this->pageBannerService->getPageContent($this->page_id);
$this->banner = $this->pageBannerService->getPageBanner($this->page_id);
$this->solutions = $this->solutionTypeService->getIsActive();
$apage_id = $this->pageBannerService->getPageId('about-GCR');
$this->abouts = $this->pageBannerService->getPageContent($apage_id);
$this->solutionService = $solutionService;
}
public function index(Request $request,$solutionSlug)
{
$solution= $this->solutionService->getSolutionBySolutionSlug($solutionSlug);
$solutionId=$solution->getTitleId()->getId(); //Amit 12-06-2018
$content = $this->content;
//$banner = $this->banner;
$banners = $this->pageBannerService->getVerticalBanner($solutionId);
$banner = json_decode($banners->getImage(),true);
$abouts = $this->abouts;
$sessionSolutions = Session::get('solutions');
$selectedTags = Session::get('solutionTag');
$solutiontags = $this->tagService->getSolutonTagsById($solutionId);
$solutionObject = $this->solutionService->getSolutionParent($solutionId);
$solutionName = $solutionObject->getName();
$solutions = null!=$sessionSolutions?unserialize (serialize ($sessionSolutions)):$this->verticalService->getVertical($solutionId);
$ads = $this->adService->getAdsByPage($this->page_id,2);
$request->session()->put('solutionId', $solutionId);
$request->session()->put('tagId', NULL);
$request->session()->put('solutionSlug',$solutionSlug); //Amit 14-05-18
return view('front-end.catalog',compact('banner','content','solutions','abouts','solutiontags', 'selectedTags','ads','solutionName'));
}
public function product(Request $request,$slug){
$scenarioDetails=$this->verticalService->getScenarioDetailBySlug($slug);
$id=$scenarioDetails->getScenarioId()->getId();
$content = $this->content;
//$banner = $this->banner;
$abouts = $this->abouts;
$producttags = $this->productService->getProductTagsById($id);
$scenarioDetail[] = $id;
$sessionScenarioProducts = Session::get('scenarioProducts');
$selectedTags = Session::get('productTag');
$req['product-filter'] = $selectedTags;
$ads = $this->adService->getAdsByPage($this->page_id,2);
$solutionId = Session::get('solutionId');
$solutionSlug= Session::get('solutionSlug');
$banners = $this->pageBannerService->getVerticalBanner($solutionId);
$banner = json_decode($banners->getImage(),true);
$tagId = Session::get('tagId');
if($request->session()->has('productTag')){
$scenarioDetail[] = $id;
$scenarioProducts = $this->productService->getProductBySolutionDetailInAndProductIn($scenarioDetail, $req);
}else{
$scenarioProducts =$this->productService->getProductBySolutionDetailIn($scenarioDetail);
}
return view('front-end.products',compact('banner','content','abouts', 'scenarioProducts','producttags', 'selectedTags','ads', 'id','solutionId', 'solutionSlug' ,'tagId'));
}
public function filterProduct(Request $request,$id){
return redirect()->route('solution.products', ['id'=>$id])->with(['productTag'=>$request['product-filter']]);
}
public function filterSolution(Request $request,$solutionSlug){
$solution= $this->solutionService->getSolutionBySolutionSlug($solutionSlug);
$id=$solution->gettitleId()->getId();
$solutions = $this->verticalService->getVerticalBySolutionAndSolutionIn($id, $request);
if(in_array('001',$request['solution-tag'])){
return redirect()->route('solution.index', ['id'=>$solutionSlug]);
}else{
return redirect()->route('solution.index', ['id'=>$solutionSlug])->with(['solutions'=>$solutions, 'solutionTag'=>$request['solution-tag']]);
}
}
public function show(Request $request,$slug){
$tagId=$this->tagService->getTagIdBySlug($slug); ////Amit 12-06-2018
$id=$tagId->getId(); //Amit 12-06-2018
$content = $this->content;
$banner = $this->banner;
$abouts = $this->abouts;
$productTag = Session::get('productTag');
if(null==$productTag){
$data['product-filter'][] = $id;
$selectedTags[] = $id;
}else{
$data['product-filter'] = $productTag;
$selectedTags = $productTag;
}
if($request->session()->has('productTag')){
$scenarioProducts = $this->productService->getProductByIdIn($data);
}else {
$scenarioProducts = null != $productTag ? Session::get('scenarioProducts') : $this->productService->getProductByIdIn($data);
}
//$producttags = $this->productService->getProductTags();
$producttags = $this->productService->getRelatedProductTags($id);
$ads = $this->adService->getAdsByPage($this->page_id,2);
$solutionTagName = $this->tagService->getTag($id);
$tagName = $solutionTagName->getTagName();
return view('front-end.productlists',compact('banner','content','scenarioProducts','abouts','producttags', 'selectedTags','ads','tagCategories','id', 'tagId','tagName'));
}
public function showSolution(Request $request,$id){
return redirect()->route('solution.show', ['id'=>$id])->with(['productTag'=>$request['product-filter']]);
}
public function searchFilterSubmit(Request $request){
//return $request->get('slug');die();
return redirect()->route('solution.searchFilter', ['id'=>$request->get('slug')]);
}
public function searchFilter($slug){
$content = $this->content;
$banner = $this->banner;
$abouts = $this->abouts;
$ads = $this->adService->getAdsByPage($this->page_id,2);
$slugDatas = $this->solutionService->searchfilter($slug);
return view('front-end.search-filter',compact('banner','content','abouts','ads','slugDatas','slug'));
}
public function showProduct($slug){
$productDetail=$this->productService->getProductBySlug($slug);
$id=$productDetail->getproductid()->getId();
$content = $this->content;
$banner = $this->banner;
$abouts = $this->abouts;
$ads = $this->adService->getAdsByPage($this->page_id,2);
$scenarioProduct = $this->productService->getProduct($id);
return view('front-end.show-product',compact('banner','content','abouts','ads','scenarioProduct'));
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: MyPc
* Date: 14/02/2018
* Time: 12:55 PM
*/
namespace App\Services\Impl;
use App\Services\QuickLinkService;
use App\Repositories\QuickLinkRepo;
use App\Repositories\QuickLinkPageRepo;
use App\Repositories\PageBannerRepo;
use App\Entities\QuickLink;
use App\Entities\QuickLinkPage;
class QuickLinkServiceImpl implements QuickLinkService
{
private $quickLinkRepo;
private $quickLinkPageRepo;
private $uploadService;
public function __construct(QuickLinkRepo $quickLinkRepo, QuickLinkPageRepo $quickLinkPageRepo, UploadService $uploadService, PageBannerRepo $pageRepo){
$this->quickLinkRepo = $quickLinkRepo;
$this->quickLinkPageRepo = $quickLinkPageRepo;
$this->uploadService = $uploadService;
$this->pageRepo = $pageRepo;
}
public function getAllQuickLinks(){
return $this->quickLinkRepo->findAllQuickLinks();
}
public function getQuickLink($id){
return $this->quickLinkRepo->findQuickLink($id);
}
public function getAllActiveQuickLink(){
return $this->quickLinkRepo->findActiveQuickLinks();
}
public function getQuickLinkByPage($pageId){
return $this->quickLinkPageRepo->findQuickLinksByPage($pageId);
}
public function saveQuickLink($data){
$quickLink = new QuickLink();
$this->populateQuickLink($quickLink, $data);
$quickLink->setCreatedAt(new \DateTime());
return $this->quickLinkRepo->saveOrUpdate($quickLink);
}
public function updateQuickLink($data, $id){
$quickLink = $this->quickLinkRepo->findQuickLink($id);
$this->populateQuickLink($quickLink, $data);
return $this->quickLinkRepo->saveOrUpdate($quickLink);
}
private function populateQuickLink($quickLink, $data){
$mediaUrl = $this->uploadService->UploadFile($data,'file','Quick Link/');
if($mediaUrl){
$quickLink->setMediaUrl($mediaUrl);
}
$quickLink->setMimeType(NULL);
$quickLink->setIsActive(isset($data['active'])?$data['active']:1);
$quickLink->setTitle($data['title']);
if(!$quickLink->getQuickLinkPages()->isEmpty()){
$this->quickLinkPageRepo->removeQuickLinkPages($quickLink->getQuickLinkPages());
}
$pages = $data['pages'];
foreach ($pages as $page) {
$quickLinkPage = new QuickLinkPage();
$quickLinkPage->setPage($this->pageRepo->getPageById($page));
$quickLink->addQuickLinkPages($quickLinkPage);
}
$quickLink->setUpdatedAt(new \DateTime());
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 08/02/2018
* Time: 11:21 AM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="g_scenario_detail")
*/
class ScenarioDetail
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="ScenarioTitle", inversedBy="scenarioDetail")
* @ORM\JoinColumn(name="title_id", referencedColumnName="id")
*/
private $titleId;
/**
* @ORM\Column(type="string")
*/
private $name;
/**
* @ORM\Column(type="text")
*/
private $description;
/**
* @ORM\Column(type="integer")
*/
private $priority;
/**
* @ORM\Column(type="boolean")
*/
private $status;
/**
* @ORM\Column(type="integer")
*/
private $addNo;
/**
* @ORM\Column(type="datetime")
*/
private $addDate;
/**
* @ORM\Column(type="integer")
*/
private $updNo;
/**
* @ORM\Column(type="datetime")
*/
private $updDate;
/**
* @ORM\Column(type="string",nullable=true)
*/
private $urlSlug;
// Amit 13-06-18
/**
* @ORM\OneToOne(targetEntity="ScenarioDetailSlug", mappedBy="scenarioId", fetch="EAGER", cascade={"persist"})
*/
private $scenarioDetailSlug;
/**
* @ORM\OneToMany(targetEntity="ScenarioProduct", mappedBy="scenarioId", fetch="EAGER",cascade={"persist"})
*/
private $scenarioProductId;
/**
* @ORM\OneToMany(targetEntity="TagCategory", mappedBy="scenarioId",cascade={"persist"}, fetch="EAGER")
*/
private $scenarioTagId;
/**
* @return mixed
*/
private $image;
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getTitleId()
{
return $this->titleId;
}
/**
* @param mixed $titleId
*/
public function setTitleId($titleId)
{
$this->titleId = $titleId;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* @param mixed $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* @return mixed
*/
public function getPriority()
{
return $this->priority;
}
/**
* @param mixed $priority
*/
public function setPriority($priority)
{
$this->priority = $priority;
}
/**
* @return mixed
*/
public function getStatus()
{
return $this->status;
}
/**
* @param mixed $status
*/
public function setStatus($status)
{
$this->status = $status;
}
/**
* @return mixed
*/
public function getAddNo()
{
return $this->addNo;
}
/**
* @param mixed $addNo
*/
public function setAddNo($addNo)
{
$this->addNo = $addNo;
}
/**
* @return mixed
*/
public function getAddDate()
{
return $this->addDate;
}
/**
* @param mixed $addDate
*/
public function setAddDate($addDate)
{
$this->addDate = $addDate;
}
/**
* @return mixed
*/
public function getUpdNo()
{
return $this->updNo;
}
/**
* @param mixed $updNo
*/
public function setUpdNo($updNo)
{
$this->updNo = $updNo;
}
/**
* @return mixed
*/
public function getUpdDate()
{
return $this->updDate;
}
/**
* @param mixed $updDate
*/
public function setUpdDate($updDate)
{
$this->updDate = $updDate;
}
/**
* @return mixed
*/
public function getUrlSlug()
{
return $this->urlSlug;
}
/**
* @param mixed $urlSlug
*/
public function setUrlSlug($urlSlug)
{
$this->urlSlug = $urlSlug;
}
/**
* @return mixed
*/
public function getScenarioProductId()
{
return $this->scenarioProductId;
}
/**
* @param mixed $scenarioProductId
*/
public function setScenarioProductId($scenarioProductId)
{
$this->scenarioProductId = $scenarioProductId;
}
/**
* @return mixed
*/
public function getScenarioTagId()
{
return $this->scenarioTagId;
}
/**
* @param mixed $scenarioTagId
*/
public function setScenarioTagId($scenarioTagId)
{
$this->scenarioTagId = $scenarioTagId;
}
public function addScenarioTags(TagCategory $tagCategory){
if(!$this->scenarioTagId->contains($tagCategory)){
$tagCategory->setScenarioId($this);
$this->scenarioTagId->add($tagCategory);
}
}
public function getSelectedTagsByCategory(){
$arr = [];
foreach ($this->scenarioTagId as $category){
$arr [] = $category->getTagId()->getId();
}
return $arr;
}
public function setImage($image){
$this->image = $image;
}
public function getImage(){
return $this->image;
}
public function getScenarioImg(){
foreach ($this->image as $img) {
return $img->getFilePath();
}
}
/**
* @return mixed
*/
public function getScenarioDetailSlug()
{
return $this->scenarioDetailSlug;
}
/**
* @param mixed $scenarioDetailSlug
*/
public function setScenarioDetailSlug($scenarioDetailSlug)
{
$this->scenarioDetailSlug = $scenarioDetailSlug;
}
}<file_sep><?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\CheckPermissionService;
use App\Services\QuickLinkService;
use App\Services\PageBannerService;
use Validator;
class QuickLinkController extends Controller
{
private $checkPermissionService, $quickLinkService;
public function __construct(CheckPermissionService $checkPermissionService, QuickLinkService $quickLinkService, PageBannerService $pages){
$this->checkPermissionService = $checkPermissionService;
$this->quickLinkService = $quickLinkService;
$this->pages = $pages;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(){
$isAuthorize = $this->checkPermissionService->checkPermission();
$quickLinks = $this->quickLinkService->getAllQuickLinks();
return view('admin.quicklinks', compact('quickLinks', 'isAuthorize'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(){
$pages = $this->pages->getAllPages();
return view('admin.quicklink', compact('pages'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request){
Validator::make($request->all(),[
"title" => "required",
"file" => 'required',
"pages" => "required"
]);
$result = $this->quickLinkService->saveQuickLink($request);
if($result){
return redirect()->route('admin.links.index')->with('success-msg', 'Quick Link added successfully.');
}else{
return redirect()->route('admin.links.index')->with('error-msg', 'Please check the form and submit again.');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id){
$pages = $this->pages->getAllPages();
$quickLink = $this->quickLinkService->getQuickLink($id);
return view('admin.quicklink', compact('pages', 'quickLink'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id){
Validator::make($request->all(),[
"title" => "required",
"file" => 'required',
"pages" => "required"
]);
$result = $this->quickLinkService->updateQuickLink($request, $id);
if($result){
return redirect()->route('admin.links.index')->with('success-msg', 'Quick Download Link added successfully.');
}else{
return redirect()->route('admin.links.index')->with('error-msg', 'Please check the form and submit again.');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id){
}
}
<file_sep><?php
namespace App\Entities;
use Doctrine\ORM\Mapping AS ORM;
/**
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="quick_link_page")
**/
class QuickLinkPage{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
**/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Page")
* @ORM\JoinColumn(name="page_id", referencedColumnName="id")
**/
private $page;
/**
* @ORM\ManyToOne(targetEntity="QuickLink", inversedBy="quickLinkPages", fetch="EAGER")
* @ORM\JoinColumn(name="quick_link_id", referencedColumnName="id")
**/
private $quickLink;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getPage()
{
return $this->page;
}
/**
* @param mixed $page
*/
public function setPage($page)
{
$this->page = $page;
}
/**
* @return mixed
*/
public function getQuickLink()
{
return $this->quickLink;
}
/**
* @param mixed $quickLink
*/
public function setQuickLink($quickLink)
{
$this->quickLink = $quickLink;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 10/05/2018
* Time: 3:16 PM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="landing_banner_images")
*/
class LandingBannerImages
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string",length=500)
*/
private $title ;
/**
* @ORM\Column(type="text")
*/
private $description ;
/**
* @ORM\Column(type="text")
*/
private $mediaUrl;
/**
* @ORM\Column(type="boolean")
*/
private $showButton;
/**
* @ORM\Column(type="string")
*/
private $buttonText ;
/**
* @ORM\Column(type="string")
*/
private $buttonUrl;
/**
* @ORM\Column(type="text")
*/
private $attributes;
/**
* @ORM\Column(type="boolean")
*/
private $isActive;
/**
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @ORM\Column(type="datetime")
*/
private $updatedAt;
/**
* @ORM\ManyToOne(targetEntity="LandingBanner", inversedBy="landingBannerImages")
* @ORM\JoinColumn(name="banner_id", referencedColumnName="id")
*/
private $bannerId;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* @param mixed $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* @return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* @param mixed $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* @return mixed
*/
public function getMediaUrl()
{
return $this->mediaUrl;
}
/**
* @param mixed $mediaUrl
*/
public function setMediaUrl($mediaUrl)
{
$this->mediaUrl = $mediaUrl;
}
/**
* @return mixed
*/
public function getShowButton()
{
return $this->showButton;
}
/**
* @param mixed $showButton
*/
public function setShowButton($showButton)
{
$this->showButton = $showButton;
}
/**
* @return mixed
*/
public function getButtonText()
{
return $this->buttonText;
}
/**
* @param mixed $buttonText
*/
public function setButtonText($buttonText)
{
$this->buttonText = $buttonText;
}
/**
* @return mixed
*/
public function getButtonUrl()
{
return $this->buttonUrl;
}
/**
* @param mixed $buttonUrl
*/
public function setButtonUrl($buttonUrl)
{
$this->buttonUrl = $buttonUrl;
}
/**
* @return mixed
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* @param mixed $attributes
*/
public function setAttributes($attributes)
{
$this->attributes = $attributes;
}
/**
* @return mixed
*/
public function getisActive()
{
return $this->isActive;
}
/**
* @param mixed $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
/**
* @return mixed
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param mixed $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return mixed
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param mixed $updatedAt
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
}
/**
* @return mixed
*/
public function getBannerId()
{
return $this->bannerId;
}
/**
* @param mixed $bannerId
*/
public function setBannerId($bannerId)
{
$this->bannerId = $bannerId;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 12/05/2018
* Time: 12:20 PM
*/
namespace App\Repositories;
use App\Entities\LandingTheme;
use Doctrine\ORM\EntityManagerInterface;
class LandingThemeRepo
{
private $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function getAllThemes()
{
return $this->em->getRepository(LandingTheme::class)->findBy();
}
public function getAllActiveThemes()
{
return $this->em->getRepository(LandingTheme::class)->findBy(["isActive"=>1]);
}
public function saveData($data)
{
// TODO: Implement saveData() method.
}
public function updateData($data, $id)
{
// TODO: Implement updateData() method.
}
public function getTheme($id)
{
return $this->em->getRepository(LandingTheme::class)->find($id);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 12/05/2018
* Time: 12:17 PM
*/
namespace App\Services;
interface LandingThemeService
{
public function getAllThemes();
public function getAllActiveThemes();
public function saveData($data);
public function updateData($data,$id);
public function getTheme($id);
}<file_sep><?php
/**
* Created by PhpStorm.
* User: MyPc
* Date: 14/02/2018
* Time: 6:07 PM
*/
namespace App\Services\Impl;
use App\Entities\Product;
use App\Entities\ProductImage;
use App\Entities\ProductSolutionX;
use App\Entities\TagProduct;
use App\Repositories\CountryRepo;
use App\Repositories\ProductRepo;
use App\Repositories\SolutionTypeRepo;
use App\Services\ProductService;
use App\Repositories\SolutionProviderRepo;
use App\Repositories\TagRepo;
use App\Repositories\ProductTagRepo;
use App\Repositories\FileSystemRepo;
use App\Repositories\ProductInquiryRepo;
use App\Repositories\ScenarioProductRepo;
use Doctrine\Common\Collections\ArrayCollection;
class ProductServiceImpl implements ProductService{
private $productRepo, $solutionTypeRepo, $countryRepo, $uploadService,$solutionProvider, $tagRepo, $productTagRepo, $fileSystemRepo, $productInquiryRepo;
public function __construct(ProductRepo $productRepo, SolutionTypeRepo $solutionTypeRepo, CountryRepo $countryRepo, UploadService $uploadService,SolutionProviderRepo $solutionProviderRepo, TagRepo $tagRepo, ProductTagRepo $productTagRepo, ScenarioProductRepo $scenarioProductRepo, FileSystemRepo $fileSystemRepo, ProductInquiryRepo $productInquiryRepo){
$this->productRepo = $productRepo;
$this->solutionTypeRepo = $solutionTypeRepo;
$this->countryRepo = $countryRepo;
$this->uploadService = $uploadService;
$this->solutionProviderRepo = $solutionProviderRepo;
$this->tagRepo = $tagRepo;
$this->productTagRepo = $productTagRepo;
$this->scenarioProductRepo = $scenarioProductRepo;
$this->fileSystemRepo = $fileSystemRepo;
$this->productInquiryRepo = $productInquiryRepo;
}
public function getAllProducts(){
return $this->productRepo->findAll();
}
public function getProduct($productId){
return $this->productRepo->findById($productId);
}
public function saveProduct($data)
{
$product = new Product();
$product->setProductName($data->get('productName'));
$product->setDescription($data->get('description'));
$product->setProductCountryId($this->countryRepo->findById($data->get('country')));
$product->setMetaDescription($data->get('metaDescription'));
$product->setMetaTitle($data->get('metaTitle'));
$product->setMetaKeywords($data->get('metaKeywords'));
$product->setIsActive(1);
$product->setDeleted(0);
$product->setProductProviderId($this->solutionProviderRepo->findById($data->get('solution_provider')));
$product->setCreatedAt(new \DateTime(now()));
$product->setUpdatedAt(new \DateTime(now()));
$productSolutionTypeIds = $data->get('productSolutionTypeId');
foreach ($productSolutionTypeIds as $productSolutionTypeId){
$productSolutionX = new ProductSolutionX();
$productSolutionX->setProductSolutionTypeId($this->solutionTypeRepo->getActiveSolutionType($productSolutionTypeId));
$productSolutionX->setIsActive(1);
$productSolutionX->setDeleted(0);
$productSolutionX->setCreatedAt(new \DateTime(now()));
$product->addProductSolutionX($productSolutionX);
}
$images = $this->uploadService->UploadMulFile($data, 'productImage', 'Product/');
if($images){
foreach ($images as $image){
$productImages = new ProductImage();
$productImages->setCreatedAt(new \DateTime(now()));
$productImages->setUpdatedAt(new \DateTime(now()));
$productImages->setIsActive(1);
$productImages->setDeleted(0);
$productImages->setIsVideo(0);
$productImages->setMediaUrl($image);
$product->addProductImage($productImages);
}
}
return $this->productRepo->saveOrUpdate($product);
}
public function updateProduct($data, $id){
$product = $this->productRepo->findById($id);
$product->setProductName($data->get('productName'));
$product->setDescription($data->get('description'));
$product->setProductCountryId($this->countryRepo->findById($data->get('country')));
$product->setMetaDescription($data->get('metaDescription'));
$product->setMetaTitle($data->get('metaTitle'));
$product->setMetaKeywords($data->get('metaKeywords'));
$product->setIsActive(1);
$product->setUpdatedAt(new \DateTime(now()));
$this->productRepo->removeExistingSolutionType($id);
$productSolutionTypeIds = $data->get('productSolutionTypeId');
foreach ($productSolutionTypeIds as $productSolutionTypeId){
$productSolutionX = new ProductSolutionX();
$productSolutionX->setProductSolutionTypeId($this->solutionTypeRepo->getActiveSolutionType($productSolutionTypeId));
$productSolutionX->setIsActive(1);
$productSolutionX->setDeleted(0);
$productSolutionX->setCreatedAt(new \DateTime(now()));
$product->addProductSolutionX($productSolutionX);
}
$this->productRepo->removeExistingImages($id);
$imageUrls = $data->get('productImageUrl');
if($imageUrls){
foreach ($imageUrls as $imageUrl){
$productImages = new ProductImage();
$productImages->setCreatedAt(new \DateTime(now()));
$productImages->setUpdatedAt(new \DateTime(now()));
$productImages->setIsActive(1);
$productImages->setDeleted(0);
$productImages->setIsVideo(0);
$productImages->setMediaUrl($imageUrl);
$product->addProductImage($productImages);
}
}
$images = $this->uploadService->UploadMulFile($data, 'productImage', 'Product/');
if($images){
foreach ($images as $image){
$productImages = new ProductImage();
$productImages->setCreatedAt(new \DateTime(now()));
$productImages->setUpdatedAt(new \DateTime(now()));
$productImages->setIsActive(1);
$productImages->setDeleted(0);
$productImages->setIsVideo(0);
$productImages->setMediaUrl($image);
$product->addProductImage($productImages);
}
}
return $this->productRepo->saveOrUpdate($product);
}
public function getAllActiveProductsByParentId($id)
{
return $this->productRepo->getAllActiveProductsByParentId($id);
}
public function saveOrUpdateProductTag($productId, $data){
$product = $this->productRepo->findById($productId);
$product->setExtraDescription(strip_tags($data['extra_description']));
$tagIds = $data['tagIds'];
if($product->getProductTagId()->isEmpty()){
$this->populateProductTag($tagIds, $product);
}else{
$existingProductTags = $product->getProductTagId();
$this->productTagRepo->removeTag($existingProductTags);
$this->populateProductTag($tagIds, $product);
}
return $this->productRepo->saveOrUpdate($product);
}
private function populateProductTag($tagIds, $product){
if(!empty($tagIds)) {
foreach ($tagIds as $tagId) {
$productTag = new TagProduct();
$productTag->setTagId($this->tagRepo->findTag($tagId));
$productTag->setStatus(1);
$product->addProductTags($productTag);
}
}
}
public function getProductBySolutionDetailIn($scenarioDetail){
$scenarioProducts = $this->scenarioProductRepo->findByScenarioDetailIn($scenarioDetail);
foreach ($scenarioProducts as $scenarioProduct) {
foreach ($scenarioProduct->getProductId()->getProductAttachment() as $productAttachment) {
if($productAttachment->getType() == 'photo') {
$image = $this->fileSystemRepo->findImage('CloudProductAttachment', $productAttachment->getId());
$productAttachment->setImage($image);
}
}
}
return $scenarioProducts;
}
public function getProductTags(){
$productTagsColl = new ArrayCollection();
$producttags = $this->tagRepo->findProductTags();
foreach ($producttags as $producttag) {
if(!$productTagsColl->contains($producttag->getTagId())){
$productTagsColl->add($producttag->getTagId());
}
}
return $productTagsColl;
}
public function getRelatedProductTags($id){
$productTagsColl = new ArrayCollection();
$producttags = $this->tagRepo->findRelatedProductTags($id);
foreach ($producttags as $producttag) {
if(!$productTagsColl->contains($producttag->getTagId())){
$productTagsColl->add($producttag->getTagId());
}
}
return $productTagsColl;
}
public function getProductTagsById($scenarioId){
$productTagsColl = new ArrayCollection();
$producttags = $this->tagRepo->findProductTagsById($scenarioId);
foreach ($producttags as $producttag) {
if(!$productTagsColl->contains($producttag->getTagId())){
$productTagsColl->add($producttag->getTagId());
}
}
return $productTagsColl;
}
// public function getProductByIdIn($data){
// $scenarioProducts = $this->scenarioProductRepo->findByProductIn($data['product-filter']);
// // dd($scenarioProducts);
// foreach ($scenarioProducts as $scenarioProduct) {
// foreach ($scenarioProduct->getProductId()->getProductAttachment() as $productAttachment) {
// if($productAttachment->getType() == 'photo') {
// $image = $this->fileSystemRepo->findImage('CloudProductAttachment', $productAttachment->getId());
// $productAttachment->setImage($image);
// }
// }
// }
// return $scenarioProducts;
// }
public function getProductByIdIn($data){
$disScenarioProducts = [];
$scenarioProducts = $this->scenarioProductRepo->findByProductIn($data['product-filter']);
foreach ($scenarioProducts as $scenarioProduct) {
foreach ($scenarioProduct->getProductId()->getProductAttachment() as $productAttachment) {
if($productAttachment->getType() == 'photo') {
$image = $this->fileSystemRepo->findImage('CloudProductAttachment', $productAttachment->getId());
$productAttachment->setImage($image);
}
}
}
foreach ($scenarioProducts as $scenarioProduct) {
if($this->checkArray($disScenarioProducts, $scenarioProduct->getProductId()->getId())){
$disScenarioProducts[] = $scenarioProduct;
}
}
// dd($scenarioProducts);
return $disScenarioProducts;
}
public function getProductBySolutionDetailInAndProductIn($scenarioDetail, $data){
$disScenarioProducts = [];
if(null!=$data['product-filter']){
$scenarioProducts = $this->scenarioProductRepo->findByScenarioDetailInAndProductIn($scenarioDetail, $data['product-filter']);
foreach ($scenarioProducts as $scenarioProduct) {
foreach ($scenarioProduct->getProductId()->getProductAttachment() as $productAttachment) {
if($productAttachment->getType() == 'photo') {
$image = $this->fileSystemRepo->findImage('CloudProductAttachment', $productAttachment->getId());
$productAttachment->setImage($image);
}
}
}
}else{
$scenarioProducts = $this->scenarioProductRepo->findByScenarioDetailIn($scenarioDetail);
foreach ($scenarioProducts as $scenarioProduct) {
foreach ($scenarioProduct->getProductId()->getProductAttachment() as $productAttachment) {
if($productAttachment->getType() == 'photo') {
$image = $this->fileSystemRepo->findImage('CloudProductAttachment', $productAttachment->getId());
$productAttachment->setImage($image);
}
}
}
}
// foreach ($scenarioProducts as $scenarioProduct) {
// if($di)
// }
return $scenarioProducts;
}
public function getProductInquiry($inquiryId){
return $this->productInquiryRepo->findOne($inquiryId);
}
private function checkArray($scenarioProducts, $productId){
foreach ($scenarioProducts as $scenarioProduct) {
if($scenarioProduct->getProductId()->getId() == $productId){
return false;
}
}
return true;
}
//Amit 18-06-2018
public function getProductBySlug($slug){
return $this->productRepo->getProductBySlug($slug);
}
//Amit 20-06-2018
public function getAllProductSlug(){
return $this->productRepo->getAllProductSlug();
}
public function getProductSlugById($id){
return $this->productRepo->getProductSlugById($id);
}
}<file_sep><?php
namespace App\Providers;
use App\Shortcodes\ProductShortcode;
use Illuminate\Support\ServiceProvider;
use App\Shortcodes\BoldShortcode;
use Shortcode;
class ShortcodesServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
Shortcode::register('b', BoldShortcode::class);
Shortcode::register('product', ProductShortcode::class);
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 10/05/2018
* Time: 2:09 PM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
* Class Page
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="landing_product_images")
*/
class LandingProductImages
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="LandingProduct", inversedBy="landingProductImages")
* @ORM\JoinColumn(name="product_id", referencedColumnName="id")
*/
private $productId;
/**
* @ORM\Column(type="text")
*/
private $mediaUrl;
/**
* @ORM\Column(type="text")
*/
private $attributes;
/**
* @ORM\Column(type="boolean")
*/
private $isActive;
/**
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @ORM\Column(type="datetime")
*/
private $updatedAt;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getProductId()
{
return $this->productId;
}
/**
* @param mixed $productId
*/
public function setProductId($productId)
{
$this->productId = $productId;
}
/**
* @return mixed
*/
public function getMediaUrl()
{
return $this->mediaUrl;
}
/**
* @param mixed $mediaUrl
*/
public function setMediaUrl($mediaUrl)
{
$this->mediaUrl = $mediaUrl;
}
/**
* @return mixed
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* @param mixed $attributes
*/
public function setAttributes($attributes)
{
$this->attributes = $attributes;
}
/**
* @return mixed
*/
public function getisActive()
{
return $this->isActive;
}
/**
* @param mixed $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
/**
* @return mixed
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param mixed $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return mixed
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param mixed $updatedAt
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 09/02/2018
* Time: 10:41 AM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="g_product_attachment")
*/
class ProductAttachment
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Product", inversedBy="productAttachment")
* @ORM\JoinColumn(name="product_id", referencedColumnName="id")
*/
private $productAttachmentId;
/**
* @ORM\Column(type="integer")
*/
private $priority;
/**
* @ORM\Column(type="string",length=5)
*/
private $type;
/**
* @ORM\Column(type="text")
*/
private $url;
/**
* @ORM\Column(type="integer")
*/
private $addNo;
/**
* @ORM\Column(type="datetime")
*/
private $addDate;
private $image;
// /**
// * @ORM\OneToMany(targetEntity="FileSystem", fetch="EAGER",mappedBy="tableKey",cascade={"persist"})
// */
// private $fileId;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getProductAttachmentId()
{
return $this->productAttachmentId;
}
/**
* @param mixed $productAttachmentId
*/
public function setProductAttachmentId($productAttachmentId)
{
$this->productAttachmentId = $productAttachmentId;
}
/**
* @return mixed
*/
public function getPriority()
{
return $this->priority;
}
/**
* @param mixed $priority
*/
public function setPriority($priority)
{
$this->priority = $priority;
}
/**
* @return mixed
*/
public function getType()
{
return $this->type;
}
/**
* @param mixed $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* @return mixed
*/
public function getUrl()
{
return $this->url;
}
/**
* @param mixed $url
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* @return mixed
*/
public function getAddNo()
{
return $this->addNo;
}
/**
* @param mixed $addNo
*/
public function setAddNo($addNo)
{
$this->addNo = $addNo;
}
/**
* @return mixed
*/
public function getAddDate()
{
return $this->addDate;
}
/**
* @param mixed $addDate
*/
public function setAddDate($addDate)
{
$this->addDate = $addDate;
}
public function setImage($image){
$this->image = $image;
}
public function getImage(){
return $this->image;
}
// /**
// * @return mixed
// */
// public function getFileId()
// {
// return $this->fileId;
// }
//
// /**
// * @param mixed $fileId
// */
// public function setFileId($fileId)
// {
// $this->fileId = $fileId;
// }
public function getScenarioImg(){
if(!empty($this->image)){
foreach ($this->image as $img) {
return $img->getFilePath();
}
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 12/05/2018
* Time: 1:15 PM
*/
namespace App\Repositories;
use App\Entities\LandingPage;
use Doctrine\ORM\EntityManagerInterface;
class LandingPageRepo
{
private $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function getAllLanding()
{
return $this->em->getRepository(LandingPage::class)->findAll();
}
public function saveData($data)
{
$this->em->persist($data);
$this->em->flush();
return true;
}
public function getLandingPage($id){
return $this->em->getRepository(LandingPage::class)->find($id);
}
public function getLandingPageBySlug($slug)
{
return $this->em->getRepository(LandingPage::class)->findOneBy(['slug'=>$slug]);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 07/02/2018
* Time: 4:17 PM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="vertical_images")
*/
class VerticalImages
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\OneToOne(targetEntity="ScenarioTitle", inversedBy="verticalImages")
* @ORM\JoinColumn(name="vertical_id", referencedColumnName="id")
*/
private $verticalId;
/**
* @ORM\Column(type="text")
*/
private $image;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getVerticalId()
{
return $this->verticalId;
}
/**
* @param mixed $verticalId
*/
public function setVerticalId($verticalId)
{
$this->verticalId = $verticalId;
}
/**
* @return mixed
*/
public function getImage()
{
return $this->image;
}
/**
* @param mixed $image
*/
public function setImage($image)
{
$this->image = $image;
}
}<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
//use Illuminate\Foundation\Auth\AuthenticatesUsers;
//use Illuminate\Http\Request;
//use Illuminate\Support\Facades\Auth;
//use Illuminate\Validation\ValidationException;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
//use AuthenticatesUsers;
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = 'admin/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
//$this->middleware('guest:admin')->except('logout');
//$this->middleware('guest:admin', ['except' => 'logout']);
}
public function getLogin()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.login');
}
/**
* Log the user out of the application.
*
* @return \Illuminate\Http\Response
*/
public function getLogout()
{
Auth::logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/admin');
}
/**
* Show the application login form.
*
* @return \Illuminate\Http\Response
public function showLoginForm()
{
return view('admin.login');
}*/
/**
* Log the user out of the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
public function logout(Request $request)
{
$this->guard('admin')->logout();
$request->session()->invalidate();
return redirect('admin/');
}*/
/**
* Get the guard to be used during authentication.
*
* @return \Illuminate\Contracts\Auth\StatefulGuard
protected function authenticated(Request $request)
{
$request->session()->flash('success-msg' , 'Logged In Successfully');
return redirect()->intended($this->redirectPath());
}*/
protected function guard()
{
return Auth::guard('admin');
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 14/02/2018
* Time: 3:04 PM
*/
namespace App\Services;
interface TagService
{
public function tagList();
public function getActiveTags();
public function tagAdd($data);
public function updateTag($data, $id);
public function checkTags($tags);
public function getTag($id);
public static function getSolutionTags();
public function getAllSolutionTags();
public function getParentTags();
public function getSolutonTagsById($solutionId);
public function getTagIdBySlug($slug); ////Amit 12-06-2018
public function tagGenerator($data,$id); //Amit 13-06-2018
}<file_sep><?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\TagService;
use App\Services\CheckPermissionService;
use Validator;
class TagController extends Controller
{
private $tagService,$checkPermissionService;
public function __construct(TagService $tagService,CheckPermissionService $checkPermissionService){
$this->tagService = $tagService;
$this->checkPermissionService = $checkPermissionService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$tags = $this->tagService->tagList();
$isAuthorize = $this->checkPermissionService->checkPermission();
return view('admin.tags', compact('tags','isAuthorize'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$tags = $this->tagService->getParentTags();
return view('admin.tag', compact('tags'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//Amit 21-06-18
$request['tagSlug']=strtolower(preg_replace('/\s+/','-',trim($request->title)));
Validator::make($request->all(),[
"title" => "required"
]);
$result = $this->tagService->tagAdd($request);
if($result){
return redirect()->route('admin.tags.index')->with('success-msg', 'Tag added successfully.');
}else{
return redirect()->route('admin.tags.index')->with('error-msg', 'Please check the form and submit again.');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$tag = $this->tagService->getTag($id);
$tags = $this->tagService->tagList();
return view('admin.tag', compact('tag','tags'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//Amit 21-06-18/
$request['tagSlug']=strtolower(preg_replace('/\s+/','-',trim($request->title)));
Validator::make($request->all(),[
"title" => "required"
]);
$result = $this->tagService->updateTag($request, $id);
if($result){
return redirect()->route('admin.tags.edit', ['tag'=>$id])->with('success-msg', 'Tag updated successfully.');
}else{
return redirect()->route('admin.tags.edit', ['tag'=>$id])->with('error-msg', 'Please check the form and submit again.');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id){
//
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: INTEX
* Date: 14/05/2018
* Time: 12:25 PM
*/
namespace App\Shortcodes;
class BoldShortcode
{
public function register($shortcode, $content)
{
return sprintf('<strong class="%s">%s</strong>', $shortcode->class, $content);
}
}<file_sep>
<ul class="<?php echo e(!$subsolution->getChildren()->isEmpty()?'dropdown-menu':''); ?>">
<?php $__currentLoopData = $subsolution->getChildren(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $children): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<li class="<?php echo e(!$children->getChildren()->isEmpty()?'dropdown-submenu':''); ?>"><a href="<?php echo e(route('solution.show', ['id'=>$children->getId()])); ?>"><?php echo e($children->getTagName()); ?></a>
<?php if(!$children->getChildren()->isEmpty()): ?>
<?php echo view('front-end.component.submenu',['subsolution'=>$children]); ?>
<?php endif; ?>
</li>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
</ul>
<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 09/02/2018
* Time: 10:23 AM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="tag_category_x")
*/
class TagCategory
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="ScenarioDetail", inversedBy="scenarioTagId", fetch="EAGER")
* @ORM\JoinColumn(name="scenario_id", referencedColumnName="id")
*/
private $scenarioId;
/**
* @ORM\ManyToOne(targetEntity="Tag", inversedBy="tagScenarioId", fetch="EAGER")
* @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
*/
private $tagId;
/**
* @ORM\Column(type="boolean",options={"unsigned":true, "default":1})
*/
private $status;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getScenarioId()
{
return $this->scenarioId;
}
/**
* @param mixed $scenarioId
*/
public function setScenarioId($scenarioId)
{
$this->scenarioId = $scenarioId;
}
/**
* @return mixed
*/
public function getTagId()
{
return $this->tagId;
}
/**
* @param mixed $tagId
*/
public function setTagId($tagId)
{
$this->tagId = $tagId;
}
/**
* @return mixed
*/
public function getStatus()
{
return $this->status;
}
/**
* @param mixed $status
*/
public function setStatus($status)
{
$this->status = $status;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 29/03/2018
* Time: 3:38 PM
*/
namespace App\Services;
interface VerticalService
{
public function getAllActiveVerticals();
public function getAllVerticals();
public function getVertical($id);
public function getIsActive();
public function addVertical($data);
public function updateVertical($data,$id);
public function getActiveVerticalById($id);
public function verticalList();
public function getVerticalBySolutionAndSolutionIn($id, $data);
public function getVerticalsBySolution($id);
public function getVerticalsBySolutionIn($id, $data);
public function getScenarioDetailBySlug($slug); // Amit 12-06-18
public function tagGenerator(); //Amit 13-06-18
}<file_sep><?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class NewsRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [
"country" => "required",
"description" => "required",
];
if($this->method() == 'PUT'){
$rules["title"] = "required|unique:App\Entities\News,newsHeading,".$this->id.",id,isActive,1";
}
if ($this->method() != 'PUT'){
$rules["title"] = "required|unique:App\Entities\News,newsHeading,NULL,id,isActive,1";
$rules["thumbimage"] = "required";
$rules["actimage"] = "required";
}
return $rules;
}
public function messages()
{
return [
'country.required' => 'Country is required',
'thumbimage.required' => 'Thumbnail is required',
'actimage.required' => 'Image is required',
'description.required' => 'Description is required',
'actimage.required' => 'News/Events Heading is required',
'title.unique' => 'News/Events Heading is already been taken. Please provide another heading',
];
}
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\ProductService;
use App\Services\ProductNewSchemaService;
use App\Services\CheckPermissionService;
class ProductNewSchemaController extends Controller
{
private $productNewSchemaService,$checkPermissionService, $productService;
public function __construct(ProductNewSchemaService $productNewSchemaService,CheckPermissionService $checkPermissionService, ProductService $productService)
{
$this->productNewSchemaService = $productNewSchemaService;
$this->checkPermissionService = $checkPermissionService;
$this->productService = $productService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$products = $this->productNewSchemaService->getAllProducts();
$isAuthorize = $this->checkPermissionService->checkPermission();
return view('admin.productsnewschema', compact('products','isAuthorize'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
return $id;
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
public function inquiry($id){
$product = $this->productService->getProduct($id);
return view('admin.productinquiries', compact('product'));
}
public function inquiryDetail($id, $inquiryId){
$productInquiry = $this->productService->getProductInquiry($inquiryId);
return view('admin.productinquiriesdetail', compact('productInquiry'));
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 29/03/2018
* Time: 4:22 PM
*/
namespace App\Repositories;
use App\Entities\ScenarioDetail;
use App\Entities\ScenarioTitle;
use App\Entities\ScenarioTitleSlug;
use App\Entities\TagCategory;
use LaravelDoctrine\ORM\Facades\Doctrine;
use Doctrine\ORM\EntityManagerInterface;
class SolutionRepo
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function getAllActiveSolution()
{
// TODO: Implement getAllActiveSolution() method.
}
public function getAllSolution()
{
return $this->em->getRepository(ScenarioDetail::class)->findAll();
}
public function getSolutionById($id)
{
return $this->em->getRepository(ScenarioDetail::class)->find($id);
}
public function getSolutionParent($id)
{
return $this->em->getRepository(ScenarioTitle::class)->find($id);
}
public function saveOrUpdate($data)
{
$this->em->persist($data);
$this->em->flush();
return true;
}
public function findSolutionInSolutionTag($id){
return $this->em->getRepository(TagCategory::class)->findBy(['scenarioId'=>$id]);
}
public function solutionList()
{
// TODO: Implement solutionList() method.
}
public function removeSolutionTags($solutionTags){
foreach ($solutionTags as $solutionTag){
$this->em->remove($solutionTag);
}
$this->em->flush();
return true;
}
public function searchFilter($slug){
$qarr = [];
$query = $this->em->createQuery(
'SELECT p FROM App\Entities\Product p WHERE p.name LIKE :slug'
)
->setParameter('slug','%'.$slug.'%');
$qarr['product'] = $query->getResult();
$query = $this->em->createQuery(
'SELECT n FROM App\Entities\News n WHERE n.newsHeading LIKE :slug'
)
->setParameter('slug','%'.$slug.'%');
$qarr['news'] = $query->getResult();
// dd($qarr);
return $qarr;
}
//Amit 12-06-2018
public function getSolutionBySolutionSlug($solutionSlug)
{
// return $this->em->getRepository(ScenarioTitle::class)->findOneBy(array('urlSlug'=>$solutionSlug));
return $this->em->getRepository(ScenarioTitleSlug::class)->findOneBy(array('urlSlug'=>$solutionSlug));
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 10/05/2018
* Time: 3:34 PM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
* Class Page
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="theme")
*/
class LandingTheme
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string",length=300)
*/
private $name;
/**
* @ORM\Column(type="string",length=300)
*/
private $view;
/**
* @ORM\OneToMany(targetEntity="LandingPage",fetch="EAGER", mappedBy="landingThemeId",cascade={"persist"})
*/
private $landingTheme;
/**
* @ORM\Column(type="text")
*/
private $attributes;
/**
* @ORM\Column(type="boolean")
*/
private $isActive;
/**
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @ORM\Column(type="datetime")
*/
private $updatedAt;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getView()
{
return $this->view;
}
/**
* @param mixed $view
*/
public function setView($view)
{
$this->view = $view;
}
/**
* @return mixed
*/
public function getLandingTheme()
{
return $this->landingTheme;
}
/**
* @param mixed $landingTheme
*/
public function setLandingTheme($landingTheme)
{
$this->landingTheme = $landingTheme;
}
/**
* @return mixed
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* @param mixed $attributes
*/
public function setAttributes($attributes)
{
$this->attributes = $attributes;
}
/**
* @return mixed
*/
public function getisActive()
{
return $this->isActive;
}
/**
* @param mixed $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
/**
* @return mixed
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param mixed $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return mixed
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param mixed $updatedAt
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 11/05/2018
* Time: 2:56 PM
*/
namespace App\Repositories;
use App\Entities\LandingBanner;
use App\Entities\LandingBannerImages;
use Doctrine\ORM\EntityManagerInterface;
class LandingBannerRepo
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em=$em;
}
public function getAllBanners(){
return $this->em->getRepository(LandingBanner::class)->findAll();
}
public function getAllActiveBanners(){
return $this->em->getRepository(LandingBanner::class)->findBy(['isActive'=>1]);
}
public function getBanner($id){
return $this->em->getRepository(LandingBanner::class)->find($id);
}
public function saveOrUpdate($data){
$this->em->persist($data);
$this->em->flush();
return true;
}
public function removeBannerImage($id){
$bannerImages = $this->em->getRepository(LandingBannerImages::class)->findBy(['bannerId'=>$id]);
foreach ($bannerImages as $bannerImage){
$removeImage = $this->em->getRepository(LandingBannerImages::class)->find($bannerImage->getId());
$this->em->remove($removeImage);
$this->em->flush();
}
return true;
}
public function deleteBannerCarousel($id){
$removeImage = $this->em->getRepository(LandingBannerImages::class)->find($id);
$this->em->remove($removeImage);
$this->em->flush();
return true;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 09/02/2018
* Time: 10:23 AM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="g_scenario_product")
*/
class ScenarioProduct
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Product", inversedBy="productScenarioId", fetch="EAGER",cascade={"persist"})
* @ORM\JoinColumn(name="product_id", referencedColumnName="id")
*/
private $productId;
/**
* @ORM\ManyToOne(targetEntity="ScenarioDetail",fetch="EAGER", inversedBy="scenarioProductId",cascade={"persist"})
* @ORM\JoinColumn(name="scenario_id", referencedColumnName="id")
*/
private $scenarioId;
/**
* @ORM\Column(type="integer")
*/
private $addNo;
/**
* @ORM\Column(type="datetime")
*/
private $addDate;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getProductId()
{
return $this->productId;
}
/**
* @param mixed $productId
*/
public function setProductId($productId)
{
$this->productId = $productId;
}
/**
* @return mixed
*/
public function getScenarioId()
{
return $this->scenarioId;
}
/**
* @param mixed $scenarioId
*/
public function setScenarioId($scenarioId)
{
$this->scenarioId = $scenarioId;
}
/**
* @return mixed
*/
public function getAddNo()
{
return $this->addNo;
}
/**
* @param mixed $addNo
*/
public function setAddNo($addNo)
{
$this->addNo = $addNo;
}
/**
* @return mixed
*/
public function getAddDate()
{
return $this->addDate;
}
/**
* @param mixed $addDate
*/
public function setAddDate($addDate)
{
$this->addDate = $addDate;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: MyPc
* Date: 14/02/2018
* Time: 12:55 PM
*/
namespace App\Services\Impl;
use App\Entities\Ads;
use App\Entities\AdsPages;
use App\Entities\Page;
use App\Repositories\AdRepo;
use App\Services\AdService;
use App\Repositories\PageBannerRepo;
class AdServiceImpl implements AdService
{
private $adRepo, $uploadService,$pageRepo;
public function __construct(AdRepo $adRepo, UploadService $uploadService,PageBannerRepo $pageRepo){
$this->adRepo = $adRepo;
$this->uploadService = $uploadService;
$this->pageRepo = $pageRepo;
}
public function getAllAds(){
return $this->adRepo->findAll();
}
public function addAd($data){
$ad = new Ads();
$ad->setTitle($data->get('title'));
$ad->setAddDetail($data->get('addDetail'));
$ad->setDeleted(0);
$ad->setIsActive(1);
$ad->setCreatedAt(new \DateTime());
$ad->setUpdatedAt(new \DateTime());
// add adspage cr
foreach ($data->get('pages') as $page){
$adsPage = new AdsPages();
$adsPage->setPageAds($this->pageRepo->getPageById($page));
$adsPage->setDeleted(0);
$adsPage->setIsActive(1);
$ad->addPageAds($adsPage);
}
$image_url = $this->uploadService->UploadFile($data,'image','Ad/');
if($image_url) {
$ad->setImage($image_url);
}
return $this->adRepo->saveOrUpdate($ad);
}
public function updateAd($data, $id){
$ad = $this->adRepo->findById($id);
$ad->setTitle($data->get('title'));
$ad->setAddDetail($data->get('addDetail'));
$ad->setIsActive($data->get('active'));
$ad->setDeleted(0);
$ad->setUpdatedAt(new \DateTime());
// // add adspage cr
$adspages=$this->adRepo->findAdsById($ad);
foreach ($adspages as $adspage) {
$this->adRepo->removeAdsPage($adspage);
}
foreach ($data->get('pages') as $page){
$adsPage = new AdsPages();
$adsPage->setPageAds($this->pageRepo->getPageById($page));
$adsPage->setDeleted(0);
$adsPage->setIsActive(1);
$ad->addPageAds($adsPage);
}
$image_url = $this->uploadService->UploadFile($data,'image','Testimonial/');
if($image_url){
$ad->setImage($image_url);
}
return $this->adRepo->saveOrUpdate($ad);
}
public function getActiveAd($id){
return $this->adRepo->findById($id);
}
public function topAd($limit)
{
return $this->adRepo->topAd($limit);
}
public function getAdsByPage($page_id,$limit)
{
return $this->adRepo->getAdsByPage($page_id,$limit);
}
}<file_sep><?php
namespace App\Http\Controllers\Admin;
use App\Services\Impl\LandingProductServiceImpl;
use App\Services\LandingProductService;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Services\LandingBannerService;
use App\Services\LandingThemeService;
use App\Services\LandingPageService;
use App\Services\CheckPermissionService;
use App\Repositories\LandingProductRepo;
use App\Http\Requests\LandingPageRequest;
use Validator;
class LandingPageController extends Controller
{
private $landingBannerService,$themeService,$landingPageService,$checkPermissionService;
private static $landingProductRepo;
private static $landingProdService;
public function __construct(LandingBannerService $landingBannerService,LandingThemeService $themeService,LandingPageService $landingPageService,CheckPermissionService $checkPermissionService,LandingProductRepo $landingProductRepo, LandingProductService $landingProductService)
{
$this->landingBannerService = $landingBannerService;
$this->themeService = $themeService;
$this->landingPageService = $landingPageService;
$this->checkPermissionService = $checkPermissionService;
self::$landingProductRepo = $landingProductRepo;
self::$landingProdService = $landingProductService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$landingPages = $this->landingPageService->getAllLanding();
$isAuthorize = $this->checkPermissionService->checkPermission();
return view('admin.landingpages', compact('landingPages','isAuthorize'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$banners = $this->landingBannerService->getAllBanners();
$themes = $this->themeService->getAllActiveThemes();
return view('admin.landingpage',compact('banners','themes'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(LandingPageRequest $request)
{
// $this->validate($request,[
// "title"=>"required",
// "content"=>"required",
// "theme"=>"required",
// "banner"=>"required",
// "meta-title"=>"required",
// "meta-keyword"=>"required",
// "meta-description"=>"required",
// ]);
$result = $this->landingPageService->saveData($request);
if($result){
return redirect()->route('admin.landingpages.index')->with('success-msg', 'Landing Page added successfully.');
}else{
return redirect()->route('admin.landingpages.index')->with('error-msg', 'Please check the form and submit again.');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$banners = $this->landingBannerService->getAllActiveBanners();
$themes = $this->themeService->getAllActiveThemes();
$landingpage = $this->landingPageService->getLandingPage($id);
return view('admin.landingpage',compact('banners','themes','landingpage'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request,[
"title" => "required|unique:App\Entities\LandingPage,title,".$id.",id,isActive,1",
"content"=>"required",
"theme"=>"required",
"banner"=>"required",
"meta-title"=>"required",
"meta-keyword"=>"required",
"meta-description"=>"required",
"active"=>"required",
]);
$result = $this->landingPageService->updateData($request,$id);
if($result){
return redirect()->route('admin.landingpages.edit',['landingpages'=>$id])->with('success-msg', 'Landing Page updated successfully.');
}else{
return redirect()->route('admin.landingpages.edit',['landingpages'=>$id])->with('error-msg', 'Please check the form and submit again.');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
}
public static function getTest($id) {
// $products = self::$landingProductRepo->getAllProducts();
$products = LandingProductServiceImpl::getProducts();
dd($products);
// return view('front-end.component.landingComponent.products');
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: INTEX
* Date: 14/05/2018
* Time: 3:23 PM
*/
namespace App\Shortcodes;
use App\Services\LandingProductService;
use Illuminate\Support\Facades\View;
class ProductShortcode
{
private $landingProductService;
public function __construct(LandingProductService $landingProductService)
{
$this->landingProductService = $landingProductService;
}
public function register($shortcode, $content)
{
$id = $shortcode->id;
$limit = $shortcode->limit;
$order = $shortcode->order;
$products = $this->landingProductService->activeProducts($id, $limit, $order);
// dd($products);
$view = '';
if(is_array($products)) {
foreach ($products as $product) {
$view .= View::make('front-end.component.landingComponent.products', compact('product'));
}
}else{
$product = $products;
$view .= View::make('front-end.component.landingComponent.products', compact('product'));
}
return $view;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 11/05/2018
* Time: 10:12 AM
*/
namespace App\Repositories;
use App\Entities\LandingProduct;
use App\Entities\LandingProductImages;
use Doctrine\ORM\EntityManagerInterface;
class LandingProductRepo{
protected $em;
public function __construct(EntityManagerInterface $em){
$this->em = $em;
}
public function getAllProducts(){
return $this->em->getRepository(LandingProduct::class)->findAll();
}
public function getAllActiveProducts(){
}
public function getProduct($id){
return $this->em->getRepository(LandingProduct::class)->find($id);
}
public function saveOrUpdate(LandingProduct $product){
$this->em->persist($product);
$this->em->flush();
return true;
}
public function removeExistingImages($id){
$existingImages = $this->em->getRepository(LandingProductImages::class)->findBy(['productId'=>$id]);
foreach ($existingImages as $existingImage){
$this->em->remove($existingImage);
}
$this->em->flush();
}
public function findProducts($limit, $order){
return $this->em->getRepository(LandingProduct::class)->findBy(array(), array('id'=>$order), $limit, null);
}
}<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\AdService;
use App\Services\PageBannerService;
use App\Services\SolutionTypeService;
use App\Services\ProductService;
use Illuminate\Support\Facades\Route;
use App\Services\TagService;
use App\Services\VerticalService;
class DisclaimerController extends Controller
{
protected $adService,$pageBannerService,$solutionTypeService,$productService;
protected $route,$page_id,$content,$banner,$solutions,$abouts;
protected $verticalService,$tagService;
public function __construct(AdService $adService,PageBannerService $pageBannerService,SolutionTypeService $solutionTypeService,ProductService $productService,VerticalService $verticalService,TagService $tagService)
{
$this->adService = $adService;
$this->pageBannerService = $pageBannerService;
$this->solutionTypeService = $solutionTypeService;
$this->productService = $productService;
$this->route = Route::current();
$route_name = strpos($this->route->getName(), ".") !== false?substr($this->route->getName(),0 ,strpos($this->route->getName(), ".")):$this->route->getName();
$this->page_id = $this->pageBannerService->getPageId($route_name);
$this->content = $this->pageBannerService->getPageContent($this->page_id);
$this->banner = $this->pageBannerService->getPageBanner($this->page_id);
$this->solutions = $this->solutionTypeService->getIsActive();
$apage_id = $this->pageBannerService->getPageId('about-GCR');
$this->abouts = $this->pageBannerService->getPageContent($apage_id);
}
public function index()
{
$content = $this->content;
$banner = $this->banner;
$solutions = $this->solutions;
$abouts = $this->abouts;
$ads = $this->adService->getAdsByPage($this->page_id,2);
return view('front-end.disclaimer',compact('banner','content','solutions','abouts','ads'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 29/03/2018
* Time: 3:43 PM
*/
namespace App\Repositories;
use App\Entities\ScenarioDetail;
use App\Entities\ScenarioDetailSlug;
use App\Entities\ScenarioTitle;
use App\Entities\VerticalImages;
use App\Entities\TagCategory;
use App\Entities\ScenarioTitleSlug;
use LaravelDoctrine\ORM\Facades\Doctrine;
use Doctrine\ORM\EntityManagerInterface;
class VerticalRepo
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function getAllActiveVerticals()
{
// TODO: Implement getAllActiveVerticals() method.
}
public function getAllVerticals()
{
return $this->em->getRepository(ScenarioTitle::class)->findAll();
}
public function getVertical($id)
{
return $this->em->getRepository(ScenarioTitle::class)->find($id);
}
public function getIsActive()
{
return $this->em->getRepository(ScenarioTitle::class)->findBy(['status' =>1]);
}
public function addVertical($data)
{
// TODO: Implement addVertical() method.
}
public function updateVertical($data, $id)
{
// TODO: Implement updateVertical() method.
}
public function getActiveVerticalById($id)
{
// TODO: Implement getActiveVerticalById() method.
}
public function verticalList()
{
// TODO: Implement verticalList() method.
}
public function getVerticalImageByVerticalId($id){
return $this->em->getRepository(VerticalImages::class)->findBy(['verticalId'=>$id]);
}
public function addOrUpdateVerticalImage($data){
$this->em->persist($data);
$this->em->flush();
return true;
}
public function removeVerticalImage($verticalImage){
$this->em->remove($verticalImage);
$this->em->flush();
return true;
}
public function getScenarioDetail($tagId){
return $this->em->getRepository(TagCategory::class)->findBy(['tagId'=>$tagId]);
}
public function getScenarioDetailByTagIn($tagIdArr){
return $this->em->getRepository(TagCategory::class)->createQueryBuilder('tagcategory')
->select('tagcategories')
->from('App\Entities\TagCategory', 'tagcategories')
->join('tagcategories.tagId','tag')
->where('tagcategories.tagId IN (:tagId)')
->setParameter('tagId', $tagIdArr)
->getQuery()
->getResult();
}
public function saveOrUpdate($datas){
if(is_array($datas)){
foreach ($datas as $data){
$this->em->persist($data);
}
}else {
$this->em->persist($datas);
}
$this->em->flush();
return true;
}
//Amit 12-06-2018
public function getScenarioDetailBySlug($slug){
return $this->em->getRepository(ScenarioDetailSlug::class)->findOneBy(array('urlSlug'=>$slug));
}
//Amit 21-06-2018
public function getscenarioDetailSlugById($scenarioDetailSlugId){
return $this->em->getRepository(ScenarioDetailSlug::class)->find($scenarioDetailSlugId);
}
//Amit 21-06-2018
public function getscenarioTitleDetailsSlugById($verticalTitleSlugId){
return $this->em->getRepository(ScenarioTitleSlug::class)->find($verticalTitleSlugId);
}
}<file_sep><?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\CheckPermissionService;
use App\Services\VerticalService;
use Validator;
class VerticalController extends Controller
{
private $verticalService,$checkPermissionService;
public function __construct(VerticalService $verticalService,CheckPermissionService $checkPermissionService)
{
$this->verticalService = $verticalService;
$this->checkPermissionService = $checkPermissionService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$verticals = $this->verticalService->getAllVerticals();
$isAuthorize = $this->checkPermissionService->checkPermission();
return view('admin.verticals',compact('verticals','isAuthorize'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$vertical = $this->verticalService->getVertical($id);
return view('admin.verticalImage',compact('vertical'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
Validator::make($request->all('files'),[
"image" => "required",
]);
$result = $this->verticalService->updateVertical($request,$id);
if($result){
return redirect()->route('admin.verticals.edit',['verticals'=>$id])->with('success-msg', 'Successfully Done');
}else{
return redirect()->route('admin.verticals.edit',['verticals'=>$id])->with('error-msg', 'Something went wrong.');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 29/03/2018
* Time: 4:17 PM
*/
namespace App\Services;
interface SolutionService
{
public function getAllActiveSolution();
public function getAllSolution();
public function getSolutionById($id);
public function addUpdateSolutionTag($data,$id);
public function findSolutionInSolutionTag($id);
public function solutionList();
public function getSolutionParent($id);
public function searchfilter($slug);
public function getSolutionBySolutionSlug($solutionSlug); //Amit 12-6-18
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 07/02/2018
* Time: 4:17 PM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="g_scenario_title")
*/
class ScenarioTitle
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string",length=50)
*/
private $name;
/**
* @ORM\Column(type="integer", nullable=true)
*/
private $priority;
/**
* @ORM\Column(type="boolean")
*/
private $status;
/**
* @ORM\Column(type="integer")
*/
private $addNo;
/**
* @ORM\Column(type="datetime")
*/
private $addDate;
/**
* @ORM\Column(type="integer")
*/
private $updNo;
/**
* @ORM\Column(type="string",nullable=true)
*/
private $urlSlug;
/**
* @ORM\Column(type="datetime")
*/
private $updDate;
/**
* @ORM\OneToMany(targetEntity="ScenarioDetail", mappedBy="titleId", fetch="EAGER")
*/
private $scenarioDetail;
// Amit 13-06-18
/**
* @ORM\OneToOne(targetEntity="ScenarioTitleSlug", mappedBy="titleId", fetch="EAGER",cascade={"persist"})
*/
private $scenarioTitleSlug;
/**
* @ORM\OneToOne(targetEntity="VerticalImages", mappedBy="verticalId",fetch="EAGER",cascade={"persist"})
*/
private $verticalImages;
//
// /**
// * @ORM\OneToMany(targetEntity="SolutionTypeImageX", mappedBy="solutionTypeImageId")
// * @var ArrayCollection|SolutionTypeImageX[]
// */
// private $solutionImage;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getPriority()
{
return $this->priority;
}
/**
* @param mixed $priority
*/
public function setPriority($priority)
{
$this->priority = $priority;
}
/**
* @return mixed
*/
public function getAddNo()
{
return $this->addNo;
}
/**
* @param mixed $addNo
*/
public function setAddNo($addNo)
{
$this->addNo = $addNo;
}
/**
* @return mixed
*/
public function getAddDate()
{
return $this->addDate;
}
/**
* @param mixed $addDate
*/
public function setAddDate($addDate)
{
$this->addDate = $addDate;
}
/**
* @return mixed
*/
public function getUpdNo()
{
return $this->updNo;
}
/**
* @param mixed $updNo
*/
public function setUpdNo($updNo)
{
$this->updNo = $updNo;
}
/**
* @return mixed
*/
public function getUpdDate()
{
return $this->updDate;
}
/**
* @param mixed $updDate
*/
public function setUpdDate($updDate)
{
$this->updDate = $updDate;
}
/**
* @return mixed
*/
public function getUrlSlug()
{
return $this->urlSlug;
}
/**
* @param mixed $urlSlug
*/
public function setUrlSlug($urlSlug)
{
$this->urlSlug = $urlSlug;
}
/**
* @return mixed
*/
public function getStatus()
{
return $this->status;
}
/**
* @param mixed $status
*/
public function setStatus($status)
{
$this->status = $status;
}
/**
* @return mixed
*/
public function getScenarioDetail()
{
return $this->scenarioDetail;
}
/**
* @param mixed $scenarioDetail
*/
public function setScenarioDetail($scenarioDetail)
{
$this->scenarioDetail = $scenarioDetail;
}
public function removeScenarioDetail($scenarioDetail){
$this->scenarioDetail->removeElement($scenarioDetail);
}
/**
* @return mixed
*/
public function getVerticalImages()
{
return $this->verticalImages;
}
/**
* @param mixed $verticalImages
*/
public function setVerticalImages($verticalImages)
{
$this->verticalImages = $verticalImages;
}
/**
* @return mixed
*/
public function getScenarioTitleSlug()
{
return $this->scenarioTitleSlug;
}
/**
* @param mixed $scenarioTitleSlug
*/
public function setScenarioTitleSlug($scenarioTitleSlug)
{
$this->scenarioTitleSlug = $scenarioTitleSlug;
}
// /**
// * @return mixed
// */
// public function getImage()
// {
// return $this->image;
// }
//
// /**
// * @param mixed $image
// */
// public function setImage($image)
// {
// $this->image = $image;
// }
// /**
// * @return mixed
// */
// public function getProductId()
// {
// return $this->productId;
// }
//
// /**
// * @param mixed $productId
// */
// public function setProductId($productId)
// {
// $this->productId = $productId;
// }
//
// /**
// * @return SolutionTypeImageX[]|ArrayCollection
// */
// public function getSolutionImage()
// {
// return $this->solutionImage;
// }
//
// /**
// * @param SolutionTypeImageX[]|ArrayCollection $solutionImage
// */
// public function setSolutionImage($solutionImage)
// {
// $this->solutionImage = $solutionImage;
// }
}<file_sep><?php
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="g_file_system")
*/
class FileSystem
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string",length=100)
*/
private $path ;
/**
* @ORM\Column(type="string",length=100)
*/
private $originalName ;
/**
* @ORM\Column(type="string",length=100)
*/
private $fileName ;
/**
* @ORM\Column(type="string",length=50)
*/
private $type ;
/**
* @ORM\Column(type="string",length=50)
*/
private $tableName ;
// /**
// * @ORM\ManyToOne(targetEntity="ProductAttachment",fetch="EAGER", inversedBy="fileId")
// * @ORM\JoinColumn(name="table_key", referencedColumnName="id")
// */
/**
* @ORM\Column(type="integer")
*/
private $tableKey ;
/**
* @ORM\Column(type="integer")
*/
private $status;
/**
* @ORM\Column(type="datetime")
*/
private $createDate;
/**
* @ORM\Column(type="string",length=50)
*/
private $mimeType ;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}/**
* @return mixed
*/
public function getPath()
{
return $this->path;
}/**
* @param mixed $path
*/
public function setPath($path)
{
$this->path = $path;
}/**
* @return mixed
*/
public function getOriginalName()
{
return $this->originalName;
}/**
* @param mixed $originalName
*/
public function setOriginalName($originalName)
{
$this->originalName = $originalName;
}/**
* @return mixed
*/
public function getFileName()
{
return $this->fileName;
}/**
* @param mixed $fileName
*/
public function setFileName($fileName)
{
$this->fileName = $fileName;
}/**
* @return mixed
*/
public function getType()
{
return $this->type;
}/**
* @param mixed $type
*/
public function setType($type)
{
$this->type = $type;
}/**
* @return mixed
*/
public function getTableName()
{
return $this->tableName;
}/**
* @param mixed $tableName
*/
public function setTableName($tableName)
{
$this->tableName = $tableName;
}/**
* @return mixed
*/
public function getTableKey()
{
return $this->tableKey;
}/**
* @param mixed $tableKey
*/
public function setTableKey($tableKey)
{
$this->tableKey = $tableKey;
}/**
* @return mixed
*/
public function getStatus()
{
return $this->status;
}/**
* @param mixed $status
*/
public function setStatus($status)
{
$this->status = $status;
}/**
* @return mixed
*/
public function getCreateDate()
{
return $this->createDate;
}/**
* @param mixed $createDate
*/
public function setCreateDate($createDate)
{
$this->createDate = $createDate;
}/**
* @return mixed
*/
public function getMimeType()
{
return $this->mimeType;
}/**
* @param mixed $mimeType
*/
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
}
public function getFilePath(){
$url = '/var/www/nas/'.$this->path.'/'.$this->fileName;
if(file_exists($url)){
$img = file_get_contents($url);
$url_info = pathinfo($url);
$src = 'data:image/'. $url_info['extension'] .';base64,'. base64_encode($img);
}else{
$src="noimage";
}
echo $src;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 13/06/2018
* Time: 11:15 AM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="g_scenario_title_slug")
*/
class ScenarioTitleSlug
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\OneToOne(targetEntity="ScenarioTitle", inversedBy="scenarioTitleSlug")
* @ORM\JoinColumn(name="title_id", referencedColumnName="id")
*/
private $titleId;
/**
* @ORM\Column(type="string",nullable=true)
*/
private $urlSlug;
/**
* @ORM\Column(type="datetime")
*/
private $updDate;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getTitleId()
{
return $this->titleId;
}
/**
* @param mixed $titleId
*/
public function setTitleId($titleId)
{
$this->titleId = $titleId;
}
/**
* @return mixed
*/
public function getUrlSlug()
{
return $this->urlSlug;
}
/**
* @param mixed $urlSlug
*/
public function setUrlSlug($urlSlug)
{
$this->urlSlug = $urlSlug;
}
/**
* @return mixed
*/
public function getUpdDate()
{
return $this->updDate;
}
/**
* @param mixed $updDate
*/
public function setUpdDate($updDate)
{
$this->updDate = $updDate;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 11/05/2018
* Time: 10:08 AM
*/
namespace App\Services\Impl;
use App\Entities\LandingProduct;
use App\Entities\LandingProductImages;
use App\Services\LandingProductService;
use App\Services\Impl\UploadService;
use App\Repositories\LandingProductRepo;
class LandingProductServiceImpl implements LandingProductService{
protected $uploadService;
private static $landingProductRepo;
public function __construct(UploadService $uploadService,LandingProductRepo $landingProductRepo){
$this->uploadService = $uploadService;
self::$landingProductRepo = $landingProductRepo;
}
public function getAllProducts(){
return self::$landingProductRepo->getAllProducts();
}
public function getAllActiveProducts(){
// TODO: Implement getAllActiveProducts() method.
}
public function getProduct($id){
return self::$landingProductRepo->getProduct($id);
}
public function saveProduct($data)
{
$product = new LandingProduct();
$product->setName($data->get('name'));
$product->setAttributes('');
$product->setVendor($data->get('vendor'));
$product->setDescription($data->get('description'));
$product->setIsActive(1);
$product->setCreatedAt(new \DateTime());
$product->setUpdatedAt(new \DateTime());
$images = $this->uploadService->UploadMulFile($data, 'productImage', 'LandingProduct/');
if($images){
foreach ($images as $image){
$productImages = new LandingProductImages();
$productImages->setCreatedAt(new \DateTime());
$productImages->setUpdatedAt(new \DateTime());
$productImages->setIsActive(1);
//$productImages->setDeleted(0);
$productImages->setAttributes('');
$productImages->setMediaUrl($image);
$product->addProductImage($productImages);
}
}
return self::$landingProductRepo->saveOrUpdate($product);
}
public function updateProduct($data, $id){
$product = self::$landingProductRepo->getProduct($id);
$product->setName($data->get('name'));
$product->setAttributes('');
$product->setVendor($data->get('vendor'));
$product->setDescription($data->get('description'));
$product->setIsActive($data->get('active'));
$product->setCreatedAt(new \DateTime());
$product->setUpdatedAt(new \DateTime());
self::$landingProductRepo->removeExistingImages($id);
$imageUrls = $data->get('productImageUrl');
if($imageUrls){
foreach ($imageUrls as $imageUrl){
$productImages = new LandingProductImages();
$productImages->setCreatedAt(new \DateTime());
$productImages->setUpdatedAt(new \DateTime());
$productImages->setIsActive(1);
$productImages->setAttributes('');
$productImages->setMediaUrl($imageUrl);
$product->addProductImage($productImages);
}
}
$images = $this->uploadService->UploadMulFile($data, 'productImage', 'LandingProduct/');
if($images){
foreach ($images as $image){
$productImages = new LandingProductImages();
$productImages->setCreatedAt(new \DateTime());
$productImages->setUpdatedAt(new \DateTime());
$productImages->setIsActive(1);
$productImages->setAttributes('');
$productImages->setMediaUrl($image);
$product->addProductImage($productImages);
}
}
return self::$landingProductRepo->saveOrUpdate($product);
}
public static function getProducts()
{
return self::$landingProductRepo->getAllProducts();
}
public function activeProducts($id, $limit, $order)
{
if($id != null){
return self::$landingProductRepo->getProduct($id);
}else{
return self::$landingProductRepo->findProducts($limit, $order);
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 10/05/2018
* Time: 3:14 PM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="landing_banner")
*/
class LandingBanner
{
public function __construct()
{
$this->landingBannerImages = new ArrayCollection();
}
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string",length=500)
*/
private $title ;
/**
* @ORM\Column(type="text")
*/
private $description ;
/**
* @ORM\Column(type="text")
*/
private $attributes;
/**
* @ORM\Column(type="boolean")
*/
private $isActive;
/**
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @ORM\Column(type="datetime")
*/
private $updatedAt;
/**
* @ORM\OneToMany(targetEntity="LandingBannerImages",fetch="EAGER", mappedBy="bannerId",cascade={"persist"})
*/
private $landingBannerImages;
/**
* @ORM\OneToMany(targetEntity="LandingPage",fetch="EAGER", mappedBy="landingPageBannerId",cascade={"persist"})
*/
private $landingPageBanner;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* @param mixed $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* @return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* @param mixed $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* @return mixed
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* @param mixed $attributes
*/
public function setAttributes($attributes)
{
$this->attributes = $attributes;
}
/**
* @return mixed
*/
public function getisActive()
{
return $this->isActive;
}
/**
* @param mixed $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
/**
* @return mixed
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param mixed $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return mixed
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param mixed $updatedAt
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
}
/**
* @return mixed
*/
public function getLandingBannerImages()
{
return $this->landingBannerImages;
}
/**
* @param mixed $landingBannerImages
*/
public function setLandingBannerImages($landingBannerImages)
{
$this->landingBannerImages = $landingBannerImages;
}
/**
* @return mixed
*/
public function getLandingPageBanner()
{
return $this->landingPageBanner;
}
/**
* @param mixed $landingPageBanner
*/
public function setLandingPageBanner($landingPageBanner)
{
$this->landingPageBanner = $landingPageBanner;
}
public function addBannerImage(LandingBannerImages $landingBannerImages){
if(!$this->landingBannerImages->contains($landingBannerImages)){
$landingBannerImages->setBannerId($this);
$this->landingBannerImages->add($landingBannerImages);
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 13/06/2018
* Time: 11:40 AM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="g_scenario_detail_slug")
*/
class ScenarioDetailSlug
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\OneToOne(targetEntity="ScenarioDetail", inversedBy="scenarioDetailSlug")
* @ORM\JoinColumn(name="scenario_id", referencedColumnName="id")
*/
private $scenarioId;
/**
* @ORM\Column(type="string",nullable=true)
*/
private $urlSlug;
/**
* @ORM\Column(type="datetime")
*/
private $updDate;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getScenarioId()
{
return $this->scenarioId;
}
/**
* @param mixed $scenarioId
*/
public function setScenarioId($scenarioId)
{
$this->scenarioId = $scenarioId;
}
/**
* @return mixed
*/
public function getUrlSlug()
{
return $this->urlSlug;
}
/**
* @param mixed $urlSlug
*/
public function setUrlSlug($urlSlug)
{
$this->urlSlug = $urlSlug;
}
/**
* @return mixed
*/
public function getUpdDate()
{
return $this->updDate;
}
/**
* @param mixed $updDate
*/
public function setUpdDate($updDate)
{
$this->updDate = $updDate;
}
}<file_sep><?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Services\CheckPermissionService;
use App\Services\LandingBannerService;
class LandingBanner extends Controller
{
private $landingBannerService,$checkPermissionService;
public function __construct(CheckPermissionService $checkPermissionService,LandingBannerService $landingBannerService)
{
$this->landingBannerService = $landingBannerService;
$this->checkPermissionService = $checkPermissionService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$banners = $this->landingBannerService->getAllBanners();
$isAuthorize = $this->checkPermissionService->checkPermission();
return view('admin.landingbanners', compact('banners','isAuthorize'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.landingbanner');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
"title" =>"required",
"bannerimage-title" =>"required",
"description" =>"required",
"image" =>"required",
"banner_image_description" =>"required",
]);
$result = $this->landingBannerService->saveData($request);
if($result){
return redirect()->route('admin.landingbanners.index')->with('success-msg', 'Carousal added successfully.');
}else{
return redirect()->route('admin.landingbanners.index')->with('error-msg', 'Please check the form and submit again.');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$banner = $this->landingBannerService->getBanner($id);
return view('admin.landingbanner',compact('banner'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request,[
"title" =>"required",
"bannerimage-title" =>"required",
"description" =>"required",
]);
$result = $this->landingBannerService->updateData($request,$id);
if($result){
return redirect()->route('admin.landingbanners.edit',['landingbanners'=>$id])->with('success-msg', 'Carousal added successfully.');
}else{
return redirect()->route('admin.landingbanners.edit',['landingbanners'=>$id])->with('error-msg', 'Please check the form and submit again.');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$result = $this->landingBannerService->deleteBannerCarousel($id);
if($result){
$resp = ['title'=>'Success','text'=>'Carousel Deleted Successfully'];
}else {
$resp = ['title'=>'Error','text'=>'Something Went Wrong'];
}
echo json_encode($resp);
}
public function dynamicForm(){
return view('admin.Form.landingBannerForm');
}
}
<file_sep><?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class LandingPageRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [
"content"=>"required",
"theme"=>"required",
"banner"=>"required",
"meta-title"=>"required",
"meta-keyword"=>"required",
"meta-description"=>"required",
];
if($this->method() == 'PUT'){
//$rules["title"] = "required|unique:App\Entities\LandingPage,title,".$this->id.",id,isActive,1";
$rules["title"] = "required|unique:App\Entities\LandingPage,title,".$this->id.",id,isActive,1";
}
if ($this->method() != 'PUT'){
$rules["title"] = "required|unique:App\Entities\LandingPage,title,NULL,id,isActive,1";
}
return $rules;
}
}
<file_sep>(function ( $ ) {
$.fn.scrollify = function() {
function visuallyWrap(el){
var ul = $(el)
ul.addClass('jq-scroller-mover');
ul.wrap('<div class="jq-scroller-wrapper"><div class="jq-scroller"></div></div>');
var prevNextBtn = '<i class="fa fa-arrow-circle-left jq-scroller-prev"></i><i class="fa fa-arrow-circle-right jq-scroller-next"></i>'
var overlay = '<div class="jq-scroller-overlay"><div class="jq-overlay-item"><i class="jq-overlay-close fa fa-times-circle"></i><i class="fa fa-arrow-circle-left jq-scroller-overlay-prev"></i><i class="fa fa-arrow-circle-right jq-scroller-overlay-next"></i><div class="jq-overlay-content"></div></div></div>';
var wrapper = ul.parents('.jq-scroller-wrapper')
wrapper.append(prevNextBtn)
wrapper.append(overlay)
$(el).find('li').each(function(index, elem){
var li = $(elem)
var a = li.find('a').first();
a.addClass('jq-scroller-preview')
li.addClass('jq-scroller-item');
a.attr('style', 'background-image:url('+a.children('img').attr('src')+');')
li.append('<div class="jq-scroller-caption">'+a.attr('data-title')+'</div>')
})
}
function attachEventHandlers(el){
var wrapper = $(el).parents('.jq-scroller-wrapper')
var nextBtn = wrapper.find('.jq-scroller-next')
var prevBtn = wrapper.find('.jq-scroller-prev')
var mover = wrapper.find('.jq-scroller-mover')
var overlay = wrapper.find('.jq-scroller-overlay')
var items = wrapper.find('.jq-scroller-item')
var overlayContent = wrapper.find('.jq-overlay-content')
var overlayN = wrapper.find('.jq-scroller-overlay-next')
var overlayP = wrapper.find('.jq-scroller-overlay-prev')
var w = $(items[0]).outerWidth()+"px";
var animN = function(){
var l = $(items).last().offset().left + $(items).last().width();
var m = $(wrapper).offset().left + $(wrapper).width();
if ( l >= m){
return {left: "-="+w}
} else {
return {left: "-="+0}
}
};
var animP = function(){
if ($(mover).position().left == 0){
return {left: "+="+0}
} else {
return {left: "+="+w}
}
};
var animDur = {duration: "medium"}
var indexOfCurrentItem;
$(nextBtn).click( function(){
mover.animate(animN(),animDur)
console.log($(mover).position().left);
})
$(prevBtn).click( function(){
mover.animate(animP(),animDur)
console.log();
})
$(overlay).click( function(){
overlay.removeClass('active')
overlayContent.empty();
});
$(items).click( function(event){
event.preventDefault();
overlayContent.empty();
indexOfCurrentItem = items.index(this)
var contentLink = $(this).children('.jq-scroller-preview')
var contentImageSrc = contentLink.attr('href')
var caption = contentLink.attr('data-title')
var maxHeight = ($(document).height() - 200)+"px";
if (contentLink.attr('data-type') == 'iframe'){
var content = $('<iframe src="'+contentImageSrc+'" frameborder="0" allowfullscreen></iframe><p>'+caption+'</p>');
} else {
var content = $('<img src="'+contentImageSrc+'" style="max-height:'+maxHeight+';"/><p>'+caption+'</p>');
}
content.appendTo(overlayContent);
overlay.addClass('active')
})
$(overlayN).click( function(event){
event.stopPropagation();
if($(items[indexOfCurrentItem+1]).attr('data-rel')===$(items[indexOfCurrentItem]).attr('data-rel')){
$(items[indexOfCurrentItem+1]).trigger('click');
}
})
$(overlayP).click( function(event){
event.stopPropagation();
if($(items[indexOfCurrentItem-1]).attr('data-rel')===$(items[indexOfCurrentItem]).attr('data-rel')){
$(items[indexOfCurrentItem-1]).trigger('click');
}
})
}
visuallyWrap(this);
attachEventHandlers(this)
return this;
}
}( jQuery ));<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 29/03/2018
* Time: 3:42 PM
*/
namespace App\Services\Impl;
use App\Entities\ProductSlug;
use App\Entities\ScenarioTitleSlug;
use App\Entities\Tag;
use App\Services\TagService;
use App\Entities\VerticalImages;
use App\Services\VerticalService;
use App\Services\FileSystemService;
use App\Repositories\VerticalRepo;
use App\Services\Impl\UploadService;
use App\Repositories\ProductRepo;
use App\Entities\ScenarioDetailSlug;
use Doctrine\Common\Collections\ArrayCollection;
use App\Services\ProductService;
class VerticalServiceImpl implements VerticalService
{
private $uploadService,$fileSystemService,$tagService;
private static $verticalRepo;
public function __construct(VerticalRepo $verticalRepo,ProductRepo $productRepo,ProductService $productService,UploadService $uploadService, TagService $tagService ,FileSystemService $fileSystemService)
{
self::$verticalRepo = $verticalRepo;
$this->uploadService = $uploadService;
$this->fileSystemService = $fileSystemService;
$this->tagService=$tagService;
$this->productService=$productService; //18-06-18
}
public function getAllActiveVerticals()
{
// TODO: Implement getAllActiveVerticals() method.
}
public function getAllVerticals()
{
return self::$verticalRepo->getAllVerticals();
}
public function getVertical($id)
{
$vertical = self::$verticalRepo->getVertical($id);
foreach ($vertical->getScenarioDetail() as $scenarioDetail) {
$imageUrl = $this->fileSystemService->getImages('CloudScenarioDetail', $scenarioDetail->getId());
$scenarioDetail->setImage($imageUrl);
}
return $vertical;
}
public function getVerticalBySolutionAndSolutionIn($id, $data){
$vertical = self::$verticalRepo->getVertical($id);
if(null!=$data['solution-tag']){
foreach ($vertical->getScenarioDetail() as $scenarioDetail) {
if($this->checkTag($scenarioDetail, $data['solution-tag'])){
$imageUrl = $this->fileSystemService->getImages('CloudScenarioDetail', $scenarioDetail->getId());
$scenarioDetail->setImage($imageUrl);
}else{
$vertical->removeScenarioDetail($scenarioDetail);
}
}
}
return $vertical;
}
public function getVerticalsBySolution($id){
$tagCategories = self::$verticalRepo->getScenarioDetail($id);
foreach ($tagCategories as $tagCategory) {
$imageUrl = $this->fileSystemService->getImages('CloudScenarioDetail', $tagCategory->getScenarioId()->getId());
$tagCategory->getScenarioId()->setImage($imageUrl);
}
return $tagCategories;
}
private function checkTag($scenarioDetail, $tagArr){
if(!$scenarioDetail->getScenarioTagId()->isEmpty()){
foreach ($scenarioDetail->getScenarioTagId() as $scenarioTag) {
if(in_array($scenarioTag->getTagId()->getId(), $tagArr)){
return true;
}
}
}
return false;
}
public function getIsActive()
{
return self::$verticalRepo->getIsActive();
}
public static function getActiveVerticals(){
return self::$verticalRepo->getIsActive();
}
public function addVertical($data)
{
// TODO: Implement addVertical() method.
}
public function updateVertical($data, $id)
{
$vertical = self::$verticalRepo->getVertical($id);
$verticalImage = $vertical->getVerticalImages();
if(null!=$verticalImage){
self::$verticalRepo->removeVerticalImage($verticalImage);
}
$newVerticalImage = new VerticalImages();
$image_url = $this->uploadService->UploadFile($data,'image','Vertical/');
$m_image_url = $this->uploadService->UploadFile($data,'m-image','Vertical/Banner/');
$tiles_image = $image_url?$image_url:$data->get('image-txt');
$banner_image = $m_image_url?$m_image_url:$data->get('m-image-txt');
$img_arr = ['tiles'=>$tiles_image,'banner'=>$banner_image];
$JSON_IMAGE_URL = json_encode($img_arr,JSON_UNESCAPED_SLASHES);
//$image_url?$newVerticalImage->setImage($JSON_IMAGE_URL):'';
$newVerticalImage->setImage($JSON_IMAGE_URL);
$newVerticalImage->setVerticalId($vertical);
$vertical->setVerticalImages($newVerticalImage);
return self::$verticalRepo->saveOrUpdate($vertical);
}
public function getActiveVerticalById($id)
{
// TODO: Implement getActiveVerticalById() method.
}
public function verticalList()
{
// TODO: Implement verticalList() method.
}
public function getVerticalsBySolutionIn($id, $data){
if(null!=$data['solution-tag']){
$tagCategoriesColl = new ArrayCollection();
$tagCategories = self::$verticalRepo->getScenarioDetailByTagIn($data['solution-tag']);
foreach ($tagCategories as $tagCategory) {
if($this->checkDataInCollection($tagCategoriesColl, $tagCategory->getScenarioId())){
$imageUrl = $this->fileSystemService->getImages('CloudScenarioDetail', $tagCategory->getScenarioId()->getId());
$tagCategory->getScenarioId()->setImage($imageUrl);
$tagCategoriesColl->add($tagCategory);
}
}
return $tagCategoriesColl;
}else{
$this->getVerticalsBySolution($id);
}
}
private function checkDataInCollection($collectionArr, $data){
foreach ($collectionArr as $collection) {
if($collection->getScenarioId()==$data){
return false;
}
}
return true;
}
//Amit 12-06-18
public function getScenarioDetailBySlug($slug){
return self::$verticalRepo->getScenarioDetailBySlug($slug);
}
//Amit 20-06-2018
public function clean($string) {
$string = str_replace(' ', '-', trim($string)); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9-]/', '', $string); // Removes special chars.
return strtolower(preg_replace('/-+/', '-', $string)); // Replaces multiple hyphens with single one.
}
//Amit 13-06-18
public function tagGenerator(){
//To Generate Product Slug
$products = $this->productService->getAllProducts();
foreach($products as $product){
if($product->getproductSlug()!=null) {
$productSlugId = $product->getproductSlug()->getId();
$productSlug = $this->productService->getProductSlugById($productSlugId);
}else{
$productSlug = new ProductSlug();
}
$productSlug->setProductId($product);
// $productSlug->setUrlSlug(strtolower(preg_replace('/\s+/','-',trim($product->getName ()))));
$productSlug->setUrlSlug($this->clean($product->getName()));
$productSlug->setUpdDate(new \DateTime());
self::$verticalRepo->saveOrUpdate($productSlug);
}
// To generate Tags Slug
$activeTagsLists = $this->tagService->getActiveTags();
foreach($activeTagsLists as $activeTagsList){
if($activeTagsList->getUrlSlug()==null){
$tagList = $this->tagService->getTag($activeTagsList->getId());
$tagList->setUrlSlug(strtolower(preg_replace('/\s+/','-',trim($activeTagsList->getTagName ()))));
self::$verticalRepo->saveOrUpdate($tagList);
}
}
$verticals = self::$verticalRepo->getAllVerticals();
foreach($verticals as $vertical){
foreach($vertical->getscenarioDetail() as $de){
//To generate ScenarioDetailSlug
if($de->getscenarioDetailSlug()!=null){
$scenarioDetailSlugId=$de->getscenarioDetailSlug()->getId();
$verticalDetailSlug=self::$verticalRepo->getscenarioDetailSlugById($scenarioDetailSlugId);
}else{
$verticalDetailSlug=new ScenarioDetailSlug();
}
$verticalDetailSlug->setUrlSlug(strtolower(preg_replace('/\s+/','-',trim($de->getName()))));
$verticalDetailSlug->setScenarioId($de);
$verticalDetailSlug->setUpdDate(new \DateTime());
$de->setscenarioDetailSlug($verticalDetailSlug);
//To generate ProductSlug
// foreach($de->getscenarioProductId() as $product){
//
// if($product->getproductId()->getproductSlug()==null){
// $productSlug = new ProductSlug();
// $productSlug->setProductId($product->getProductId());
// $productSlug->setUrlSlug(strtolower(preg_replace('/\s+/','-',trim($product->getproductId()->getName ()))));
// $productSlug->setUpdDate(new \DateTime());
// $product->getproductId()->setproductSlug($productSlug);
//
// }
// }
}
//To generate ScenarioTitleSlug
if($vertical->getscenarioTitleSlug()!=null){
$verticalTitleSlugId=$vertical->getscenarioTitleSlug()->getId();
$verticalTitleSlug=self::$verticalRepo->getscenarioTitleDetailsSlugById($verticalTitleSlugId);
}else{
$verticalTitleSlug = new ScenarioTitleSlug();
}
$verticalTitleSlug->setTitleId($vertical);
$verticalTitleSlug->setUpdDate(new \DateTime());
$verticalTitleSlug->setUrlSlug(strtolower(preg_replace('/\s+/','-',trim($vertical->getName()))));
$vertical->setscenarioTitleSlug($verticalTitleSlug);
}
return self::$verticalRepo->saveOrUpdate($verticals);
}
}<file_sep><?php
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="quick_link")
**/
class QuickLink{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
**/
private $id;
/**
* @ORM\Column(type="string", name="media_url")
**/
private $mediaUrl;
/**
* @ORM\Column(type="string", nullable=true, name="mime_type")
**/
private $mimeType;
/**
* @ORM\Column(type="string", length=200, name="title")
**/
private $title;
/**
* @ORM\Column(type="boolean", name="is_active")
**/
private $isActive;
/**
* @ORM\OneToMany(targetEntity="QuickLinkPage", mappedBy="quickLink", cascade={"persist"}, fetch="EAGER")
**/
private $quickLinkPages;
/**
* @ORM\Column(type="datetime", name="created_at")
*/
private $createdAt;
/**
* @ORM\Column(type="datetime", name="updated_at")
*/
private $updatedAt;
public function __construct(){
$this->quickLinkPages = new ArrayCollection();
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getMediaUrl()
{
return $this->mediaUrl;
}
/**
* @param mixed $mediaUrl
*/
public function setMediaUrl($mediaUrl)
{
$this->mediaUrl = $mediaUrl;
}
/**
* @param mixed $mimeType
*/
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
}
/**
* @return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* @param mixed $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* @return mixed
*/
public function getQuickLinkPages()
{
return $this->quickLinkPages;
}
/**
* @param mixed $quickLinkPages
*/
public function setQuickLinkPages($quickLinkPages)
{
$this->quickLinkPages = $quickLinkPages;
}
/**
* @return mixed
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param mixed $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return mixed
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param mixed $updatedAt
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
}
/**
* @return mixed
*/
public function getisActive()
{
return $this->isActive;
}
/**
* @param mixed $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
public function addQuickLinkPages(QuickLinkPage $quickLinkPage){
if(!$this->quickLinkPages->contains($quickLinkPage)){
$quickLinkPage->setQuickLink($this);
$this->quickLinkPages->add($quickLinkPage);
}
}
public function getSelectedPages(){
$selectedPages = [];
foreach ($this->quickLinkPages as $quickLinkPage) {
$selectedPages[] = $quickLinkPage->getPage()->getId();
}
return $selectedPages;
}
public function getPages(){
$selectedPageNames = [];
foreach ($this->quickLinkPages as $quickLinkPage) {
$selectedPageNames[] = $quickLinkPage->getPage()->getName();
}
return implode(',', $selectedPageNames);
}
public function getFileThumbNail()
{
$fileThumbNail = 'fa fa-file fa-2x';
// $fileThumbNail = "";
// $mimeType = mime_content_type($this->mediaUrl);
// switch($mimeType){
// case 'application/pdf':
// $fileThumbNail = 'fa fa-file-pdf-o fa-2x';
// break;
// default:
// $fileThumbNail = 'images/pdf_icon.png';
// break;
// }
return $fileThumbNail;
}
}<file_sep><?php
namespace App\Repositories;
use App\Entities\Tag;
use App\Entities\TagCategory;
use App\Entities\TagProduct;
use Doctrine\ORM\EntityManager;
class TagRepo
{
private $em;
public function __construct(EntityManager $em){
$this->em = $em;
}
public function tagList(){
return $this->em->getRepository(Tag::class)->findAll();
}
public function findActiveTags(){
return $this->em->getRepository(Tag::class)->findBy(array('isActive'=>1));
}
public function tagAdd($data){
$this->em->persist($data);
$this->em->flush();
return true;
}
public function findTag($id){
return $this->em->getRepository(Tag::class)->find($id);
}
public function findSolutionTags(){
return $this->em->getRepository(TagCategory::class)->createQueryBuilder('solution')
->select('DISTINCT solutiontags')
->from('App\Entities\TagCategory', 'solutiontags')
->getQuery()
->getResult();
}
public function findSolutionTagsById($solutionId){
return $this->em->getRepository(TagCategory::class)->createQueryBuilder('solution')
->select('DISTINCT solutiontags')
->from('App\Entities\TagCategory', 'solutiontags')
->join('solutiontags.scenarioId', 'scenariodetails')
->where('scenariodetails.titleId = :titleId')
->setParameter('titleId',$solutionId)
->getQuery()
->getResult();
}
public function findProductTags(){
return $this->em->getRepository(TagProduct::class)->createQueryBuilder('product')
->select('DISTINCT producttags')
->from('App\Entities\TagProduct', 'producttags')
->getQuery()
->getResult();
}
public function findRelatedProductTags($id){
$tags=[];
$parentId = $this->em->getRepository(Tag::class)->find($id);
if(null!=$parentId->getParent()) {
foreach ($parentId->getParent()->getChildren() as $parent){
$tags[] = $parent->getId();
}
}
return $this->em->getRepository(TagProduct::class)->createQueryBuilder('product')
->select('DISTINCT producttags')
->from('App\Entities\TagProduct', 'producttags')
->where('producttags.tagId IN (:tags)')->setParameter('tags',$tags)
->getQuery()
->getResult();
}
public function findProductTagsById($scenarioId){
return $this->em->getRepository(TagProduct::class)->createQueryBuilder('product')
->select('DISTINCT producttags')
->from('App\Entities\TagProduct', 'producttags')
->join('producttags.productId', 'products')
->join('products.productScenarioId', 'scenarioproduct')
->where('scenarioproduct.scenarioId = :scenarioId')
->setParameter('scenarioId', $scenarioId)
->getQuery()
->getResult();
}
public function findParentTags(){
return $this->em->getRepository(Tag::class)->findBy(['parent'=>NULL]);
}
//Amit 12-06-2018
public function findTagIdBySlug($slug){
return $this->em->getRepository(Tag::class)->findOneBy(array('urlSlug'=>$slug));
}
}
?><file_sep><?php
namespace DoctrineProxies\__CG__\App\Entities;
/**
* DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR
*/
class Product extends \App\Entities\Product implements \Doctrine\ORM\Proxy\Proxy
{
/**
* @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with
* three parameters, being respectively the proxy object to be initialized, the method that triggered the
* initialization process and an array of ordered parameters that were passed to that method.
*
* @see \Doctrine\Common\Persistence\Proxy::__setInitializer
*/
public $__initializer__;
/**
* @var \Closure the callback responsible of loading properties that need to be copied in the cloned object
*
* @see \Doctrine\Common\Persistence\Proxy::__setCloner
*/
public $__cloner__;
/**
* @var boolean flag indicating if this object was already initialized
*
* @see \Doctrine\Common\Persistence\Proxy::__isInitialized
*/
public $__isInitialized__ = false;
/**
* @var array properties to be lazy loaded, with keys being the property
* names and values being their default values
*
* @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties
*/
public static $lazyPropertiesDefaults = [];
/**
* @param \Closure $initializer
* @param \Closure $cloner
*/
public function __construct($initializer = null, $cloner = null)
{
$this->__initializer__ = $initializer;
$this->__cloner__ = $cloner;
}
/**
*
* @return array
*/
public function __sleep()
{
if ($this->__isInitialized__) {
return ['__isInitialized__', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'id', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'name', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'description', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'extra_description', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'vender', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'add_no', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'upd_no', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'status', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'addDate', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'updDate', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'productScenarioId', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'productInquiryId', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'productTagId', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'productAttachment'];
}
return ['__isInitialized__', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'id', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'name', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'description', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'extra_description', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'vender', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'add_no', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'upd_no', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'status', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'addDate', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'updDate', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'productScenarioId', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'productInquiryId', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'productTagId', '' . "\0" . 'App\\Entities\\Product' . "\0" . 'productAttachment'];
}
/**
*
*/
public function __wakeup()
{
if ( ! $this->__isInitialized__) {
$this->__initializer__ = function (Product $proxy) {
$proxy->__setInitializer(null);
$proxy->__setCloner(null);
$existingProperties = get_object_vars($proxy);
foreach ($proxy->__getLazyProperties() as $property => $defaultValue) {
if ( ! array_key_exists($property, $existingProperties)) {
$proxy->$property = $defaultValue;
}
}
};
}
}
/**
*
*/
public function __clone()
{
$this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', []);
}
/**
* Forces initialization of the proxy
*/
public function __load()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, '__load', []);
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __isInitialized()
{
return $this->__isInitialized__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitialized($initialized)
{
$this->__isInitialized__ = $initialized;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitializer(\Closure $initializer = null)
{
$this->__initializer__ = $initializer;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __getInitializer()
{
return $this->__initializer__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setCloner(\Closure $cloner = null)
{
$this->__cloner__ = $cloner;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific cloning logic
*/
public function __getCloner()
{
return $this->__cloner__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
* @static
*/
public function __getLazyProperties()
{
return self::$lazyPropertiesDefaults;
}
/**
* {@inheritDoc}
*/
public function getId()
{
if ($this->__isInitialized__ === false) {
return (int) parent::getId();
}
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', []);
return parent::getId();
}
/**
* {@inheritDoc}
*/
public function setId($id)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setId', [$id]);
return parent::setId($id);
}
/**
* {@inheritDoc}
*/
public function getName()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getName', []);
return parent::getName();
}
/**
* {@inheritDoc}
*/
public function setName($name)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setName', [$name]);
return parent::setName($name);
}
/**
* {@inheritDoc}
*/
public function getDescription()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getDescription', []);
return parent::getDescription();
}
/**
* {@inheritDoc}
*/
public function setDescription($description)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setDescription', [$description]);
return parent::setDescription($description);
}
/**
* {@inheritDoc}
*/
public function getExtraDescription()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getExtraDescription', []);
return parent::getExtraDescription();
}
/**
* {@inheritDoc}
*/
public function setExtraDescription($extra_description)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setExtraDescription', [$extra_description]);
return parent::setExtraDescription($extra_description);
}
/**
* {@inheritDoc}
*/
public function getVender()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getVender', []);
return parent::getVender();
}
/**
* {@inheritDoc}
*/
public function setVender($vender)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setVender', [$vender]);
return parent::setVender($vender);
}
/**
* {@inheritDoc}
*/
public function getAddNo()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getAddNo', []);
return parent::getAddNo();
}
/**
* {@inheritDoc}
*/
public function setAddNo($add_no)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setAddNo', [$add_no]);
return parent::setAddNo($add_no);
}
/**
* {@inheritDoc}
*/
public function getUpdNo()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getUpdNo', []);
return parent::getUpdNo();
}
/**
* {@inheritDoc}
*/
public function setUpdNo($upd_no)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setUpdNo', [$upd_no]);
return parent::setUpdNo($upd_no);
}
/**
* {@inheritDoc}
*/
public function getStatus()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getStatus', []);
return parent::getStatus();
}
/**
* {@inheritDoc}
*/
public function setStatus($status)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setStatus', [$status]);
return parent::setStatus($status);
}
/**
* {@inheritDoc}
*/
public function getAddDate()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getAddDate', []);
return parent::getAddDate();
}
/**
* {@inheritDoc}
*/
public function setAddDate($addDate)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setAddDate', [$addDate]);
return parent::setAddDate($addDate);
}
/**
* {@inheritDoc}
*/
public function getUpdDate()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getUpdDate', []);
return parent::getUpdDate();
}
/**
* {@inheritDoc}
*/
public function setUpdDate($updDate)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setUpdDate', [$updDate]);
return parent::setUpdDate($updDate);
}
/**
* {@inheritDoc}
*/
public function addProductScenario(\App\Entities\ScenarioProduct $scenarioProduct)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'addProductScenario', [$scenarioProduct]);
return parent::addProductScenario($scenarioProduct);
}
/**
* {@inheritDoc}
*/
public function getProductScenarioId()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getProductScenarioId', []);
return parent::getProductScenarioId();
}
/**
* {@inheritDoc}
*/
public function setProductScenarioId($productScenarioId)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setProductScenarioId', [$productScenarioId]);
return parent::setProductScenarioId($productScenarioId);
}
/**
* {@inheritDoc}
*/
public function getProductInquiryId()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getProductInquiryId', []);
return parent::getProductInquiryId();
}
/**
* {@inheritDoc}
*/
public function setProductInquiryId($productInquiryId)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setProductInquiryId', [$productInquiryId]);
return parent::setProductInquiryId($productInquiryId);
}
/**
* {@inheritDoc}
*/
public function getProductTagId()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getProductTagId', []);
return parent::getProductTagId();
}
/**
* {@inheritDoc}
*/
public function getProductTagIds()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getProductTagIds', []);
return parent::getProductTagIds();
}
/**
* {@inheritDoc}
*/
public function getProductTag()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getProductTag', []);
return parent::getProductTag();
}
/**
* {@inheritDoc}
*/
public function setProductTagId($productTagId)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setProductTagId', [$productTagId]);
return parent::setProductTagId($productTagId);
}
/**
* {@inheritDoc}
*/
public function addProductTags(\App\Entities\TagProduct $productTag)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'addProductTags', [$productTag]);
return parent::addProductTags($productTag);
}
/**
* {@inheritDoc}
*/
public function getProductAttachment()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getProductAttachment', []);
return parent::getProductAttachment();
}
/**
* {@inheritDoc}
*/
public function setProductAttachment($productAttachment)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setProductAttachment', [$productAttachment]);
return parent::setProductAttachment($productAttachment);
}
/**
* {@inheritDoc}
*/
public function addProductImage(\App\Entities\ProductAttachment $productAttachment)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'addProductImage', [$productAttachment]);
return parent::addProductImage($productAttachment);
}
/**
* {@inheritDoc}
*/
public function getProductParent()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getProductParent', []);
return parent::getProductParent();
}
/**
* {@inheritDoc}
*/
public function getAttachments()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getAttachments', []);
return parent::getAttachments();
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 12/05/2018
* Time: 12:12 PM
*/
namespace App\Services;
interface LandingPageService
{
public function getAllLanding();
public function saveData($data);
public function updateData($data,$id);
public function getLandingPage($id);
public function getLandingPageBySlug($slug);
}<file_sep><?php $__env->startSection('banner-image',asset($banner->getImage())); ?>
<?php $__env->startSection('content'); ?>
<div class="container">
<!--<div class="flt">-->
<!-- <h2>Solutions</h2>-->
<!--<hr>-->
<!--</div>-->
<div class="row">
<div class="col-md-2 col-xs-12"></div>
<div class="col-md-8 col-xs-12">
<div class="brdCum">
<ul>
<li><a href="<?php echo e(route('home')); ?>">Home</a>/</li>
<li>Solutions</li>
</ul>
</div></div>
<div class="col-md-2 col-xs-12"></div>
</div>
<div class="">
<div class="col-md-2 col-sm-3 col-md-12">
<?php if(!$solutiontags->isEmpty()): ?>
<form class="form-horizontal" role="form" id="filterForm" action="<?php echo e(isset($solutions)&&!empty($solutions)?route('solution.filtersolutions',['id'=>$solutions->getId()]):''); ?>" method="POST">
<?php echo e(csrf_field()); ?>
<div class="leftDrop">
<h3>Refine by</h3>
<div class="pdn">
<h4>Solution</h4>
<?php $__currentLoopData = $solutiontags; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $solutiontag): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<div class="checkbox">
<label>
<input type="checkbox" value="<?php echo e($solutiontag->getId()); ?>" name="solution-tag[]" <?php echo e(isset($selectedTags)&&in_array($solutiontag->getId(), $selectedTags)?'checked':''); ?>>
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>
<?php echo e($solutiontag->getTagName()); ?>
</label>
</div>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
</div>
</div>
<div class="filtr-btn">
<button type="submit" class="btn btn-sm btn-primary pull-right">Search</button>
</div>
</form>
<?php endif; ?>
</div>
<div class="col-md-8 col-sm-8 col-md-12">
<div class="row"><div class="col-md-12"><h4><?php echo e($solutions->getName()); ?></h4></div></div>
<div class="row">
<?php if($solutions->getScenarioDetail()): ?>
<?php $__currentLoopData = $solutions->getScenarioDetail(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $scenarioDetail): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<a href="<?php echo e(route('solution.products',['id'=>$scenarioDetail->getId()])); ?>">
<div class="col-md-4 col-md-12">
<div class="solInerTab">
<div class="divImg"><img src="<?php echo e(asset('images/solution-1.jpg')); ?>" class="img-responsive" alt="solution-1"></div> <h1><?php echo e($scenarioDetail->getName()); ?></h1>
<p><?php echo e($scenarioDetail->getDescription()); ?></p>
</div>
</div>
</a>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
<?php else: ?>
<p>No solutions found..</p>
<?php endif; ?>
</div>
</div>
<div class="col-md-2 col-md-12 hidden-sm hidden-xs">
<?php $__env->startComponent('front-end.component.ads',['ads'=>$ads]); ?>
<?php echo $__env->renderComponent(); ?>
</div>
</div>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('front-end.layouts.frontLayout', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?><file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 07/02/2018
* Time: 6:30 PM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="g_product")
*/
class Product
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string",length=30)
*/
private $name;
/**
* @ORM\Column(type="text")
*/
private $description;
/**
* @ORM\Column(type="text")
*/
private $extra_description;
/**
* @ORM\Column(type="string",length=50)
*/
private $vender;
/**
* @ORM\Column(type="integer")
*/
private $add_no;
/**
* @ORM\Column(type="integer")
*/
private $upd_no;
/**
* @ORM\Column(type="boolean",options={"unsigned":true, "default":1})
*/
private $status;
/**
* @ORM\Column(type="datetime")
*/
private $addDate;
/**
* @ORM\Column(type="datetime")
*/
private $updDate;
// Amit 15-06-18
/**
* @ORM\OneToOne(targetEntity="ProductSlug", mappedBy="productId", fetch="EAGER",cascade={"persist"})
*/
private $productSlug;
//
// /**
// * @ORM\OneToMany(targetEntity="ProductIndustryX", mappedBy="productId")
// */
// private $productX;
/**
* @ORM\OneToMany(targetEntity="ScenarioProduct",fetch="EAGER", mappedBy="productId",cascade={"persist"})
*/
private $productScenarioId;
/**
* @ORM\OneToMany(targetEntity="ProductInquiry", mappedBy="productId",cascade={"persist"}, fetch="EAGER")
*/
private $productInquiryId;
/**
*
* @ORM\OneToMany(targetEntity="TagProduct", mappedBy="productId",cascade={"persist"}, fetch="EAGER")
*/
private $productTagId;
/**
* @ORM\Column(type="integer")
*/
private $deleted;
// /**
// * @ORM\OneToMany(targetEntity="ProductSolutionX", mappedBy="productProductTypeId")
// */
// private $productTypeX;
//
//
// /**
// * @ORM\OneToMany(targetEntity="ProductDetails", mappedBy="product")
// */
// private $productDetails;
/**
* @ORM\OneToMany(targetEntity="ProductAttachment", fetch="EAGER",mappedBy="productAttachmentId",cascade={"persist"})
*/
private $productAttachment;
public function __construct()
{
$this->productScenarioId= new ArrayCollection();
$this->productAttachment = new ArrayCollection();
$this->productTagId = new ArrayCollection();
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* @param mixed $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* @return mixed
*/
public function getExtraDescription()
{
return $this->extra_description;
}
/**
* @param mixed $extra_description
*/
public function setExtraDescription($extra_description)
{
$this->extra_description = $extra_description;
}
/**
* @return mixed
*/
public function getVender()
{
return $this->vender;
}
/**
* @param mixed $vender
*/
public function setVender($vender)
{
$this->vender = $vender;
}
/**
* @return mixed
*/
public function getAddNo()
{
return $this->add_no;
}
/**
* @param mixed $add_no
*/
public function setAddNo($add_no)
{
$this->add_no = $add_no;
}
/**
* @return mixed
*/
public function getUpdNo()
{
return $this->upd_no;
}
/**
* @param mixed $upd_no
*/
public function setUpdNo($upd_no)
{
$this->upd_no = $upd_no;
}
/**
* @return mixed
*/
public function getStatus()
{
return $this->status;
}
/**
* @param mixed $status
*/
public function setStatus($status)
{
$this->status = $status;
}
/**
* @return mixed
*/
public function getAddDate()
{
return $this->addDate;
}
/**
* @param mixed $addDate
*/
public function setAddDate($addDate)
{
$this->addDate = $addDate;
}
/**
* @return mixed
*/
public function getUpdDate()
{
return $this->updDate;
}
/**
* @param mixed $updDate
*/
public function setUpdDate($updDate)
{
$this->updDate = $updDate;
}
public function addProductScenario(ScenarioProduct $scenarioProduct)
{
if(!$this->productScenarioId->contains($scenarioProduct)) {
$scenarioProduct->setProductId($this);
$this->productScenarioId->add($scenarioProduct);
}
}
/**
* @return mixed
*/
public function getProductScenarioId()
{
return $this->productScenarioId;
}
/**
* @param mixed $productScenarioId
*/
public function setProductScenarioId($productScenarioId)
{
$this->productScenarioId = $productScenarioId;
}
/**
* @return mixed
*/
public function getProductInquiryId()
{
return $this->productInquiryId;
}
/**
* @param mixed $productInquiryId
*/
public function setProductInquiryId($productInquiryId)
{
$this->productInquiryId = $productInquiryId;
}
/**
* @return mixed
*/
public function getProductTagId()
{
return $this->productTagId;
}
public function getProductTagIds(){
$productTagIdArr = [];
foreach ($this->productTagId as $productTagId) {
$productTagIdArr[] = $productTagId->getTagId()->getId();
}
return $productTagIdArr;
}
public function getProductTag(){
$productTag = [];
foreach ($this->productTagId as $productTagId) {
$productTag[] = $productTagId->getTagId()->getTagName();
}
return implode(',', $productTag);
}
/**
* @param mixed $productTagId
*/
public function setProductTagId($productTagId)
{
$this->productTagId = $productTagId;
}
public function addProductTags(TagProduct $productTag)
{
if(!$this->productTagId->contains($productTag)) {
$productTag->setProductId($this);
$this->productTagId->add($productTag);
}
}
/**
* @return mixed
*/
public function getProductAttachment()
{
return $this->productAttachment;
}
/**
* @param mixed $productAttachment
*/
public function setProductAttachment($productAttachment)
{
$this->productAttachment = $productAttachment;
}
public function addProductImage(ProductAttachment $productAttachment)
{
if(!$this->productAttachment->contains($productAttachment)) {
$productAttachment->setProductAttachmentId($this);
$this->productAttachment->add($productAttachment);
}
}
public function getProductParent(){
$productScenario=[];
foreach ($this->productScenarioId as $scenarioId){
$productScenario[] = $scenarioId->getScenarioId()->getName();
}
return implode(',',$productScenario);
}
public function getAttachments(){
$attachments=[];
foreach ($this->productAttachment as $attachment){
$attachments[]=$attachment->getId();
}
return implode(',',$attachments);
}
/**
* @return mixed
*/
public function getProductSlug()
{
return $this->productSlug;
}
/**
* @param mixed $productSlug
*/
public function setProductSlug($productSlug)
{
$this->productSlug = $productSlug;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 29/03/2018
* Time: 4:20 PM
*/
namespace App\Services\Impl;
use App\Entities\TagCategory;
use App\Services\SolutionService;
use App\Repositories\SolutionRepo;
use App\Repositories\TagRepo;
class SolutionServiceImpl implements SolutionService
{
private $solutionRepo,$tagRepo;
public function __construct(SolutionRepo $solutionRepo,TagRepo $tagRepo)
{
$this->solutionRepo = $solutionRepo;
$this->tagRepo = $tagRepo;
}
public function getAllActiveSolution()
{
// TODO: Implement getAllActiveSolution() method.
}
public function getAllSolution()
{
return $this->solutionRepo->getAllSolution();
}
public function getSolutionById($id)
{
return $this->solutionRepo->getSolutionById($id);
}
public function getSolutionParent($id)
{
return $this->solutionRepo->getSolutionParent($id);
}
public function addUpdateSolutionTag($data, $id)
{
$solution = $this->solutionRepo->getSolutionById($id);
$solutionTags = $solution->getScenarioTagId();
if(!$solutionTags->isEmpty()){
$this->solutionRepo->removeSolutionTags($solutionTags);
}
foreach ($data->get('tags') as $tag){
$tagCat = new TagCategory();
$tagCat->setScenarioId($this->solutionRepo->getSolutionById($id));
$tagCat->setTagId($this->tagRepo->findTag($tag));
$tagCat->setStatus(1);
$solution->addScenarioTags($tagCat);
}
return $this->solutionRepo->saveOrUpdate($solution);
}
public function solutionList()
{
// TODO: Implement solutionList() method.
}
public function findSolutionInSolutionTag($id)
{
return $this->solutionRepo->findSolutionInSolutionTag($id);
}
public function searchfilter($slug)
{
return $this->solutionRepo->searchFilter($slug);
}
//Amit12-06-2018
public function getSolutionBySolutionSlug($solutionSlug)
{
return $this->solutionRepo->getSolutionBySolutionSlug($solutionSlug);
}
}<file_sep><?php
namespace App\Http\Controllers;
use App\Services\PageBannerService;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Services\LandingPageService;
class LandingController extends Controller
{
protected $pageBannerService;
public function __construct(LandingPageService $landingPageService,PageBannerService $pageBannerService)
{
$this->landingPageService = $landingPageService;
$this->pageBannerService = $pageBannerService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
public function showLandingPage($slug){
$apage_id = $this->pageBannerService->getPageId('about-GCR');
$abouts = $this->pageBannerService->getPageContent($apage_id);
$page = $this->landingPageService->getLandingPageBySlug($slug);
$content = $page->getContent();
$view = $page->getLandingThemeId()->getView();
return view('front-end.landingPage.'.$view, compact('content', 'page','abouts'))->withShortcodes();
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 29/06/2018
* Time: 12:35 PM
*/
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\UserService;
use Illuminate\Support\Facades\Hash;
class ChangePasswordController extends Controller
{
private $userService;
public function __construct(UserService $userService){
$this->userService = $userService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('admin.changepassword',compact('session'));
}
public function chkoldPass(Request $request){
$id = $request['id'];
$res = $this->userService->getUserById($id);
$hashedPassword=$res->getpassword();
$oldPassword = $request['old<PASSWORD>'];
if (Hash::check($oldPassword, $hashedPassword))
{
echo 1;
}else{
echo 0;
}
exit;
}
public function update(Request $request){
$this->validate($request,[
"newPass" => "<PASSWORD>|required_with:cNewPass|same:cNewPass",
"cNewPass"=>"<PASSWORD>",
]);
$result = $this->userService->changepassword($request);
if($result){
return redirect()->route('admin.changepassword')->with('success-msg', ' Password updated successfully.');
}else{
return redirect()->route('admin.changepassword')->with('error-msg', 'Something went wrong.');
}
exit;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 12/05/2018
* Time: 12:17 PM
*/
namespace App\Services\Impl;
use App\Entities\LandingPage;
use App\Entities\LandingTheme;
use App\Services\LandingThemeService;
use App\Repositories\LandingThemeRepo;
class LandingThemeServiceImpl implements LandingThemeService
{
private $landingThemeRepo;
public function __construct(LandingThemeRepo $landingThemeRepo)
{
$this->landingThemeRepo = $landingThemeRepo;
}
public function getAllThemes()
{
return $this->landingThemeRepo->getAllThemes();
}
public function getAllActiveThemes()
{
return $this->landingThemeRepo->getAllActiveThemes();
}
public function saveData($data)
{
}
public function updateData($data, $id)
{
}
public function getTheme($id)
{
return $this->landingThemeRepo->getTheme($id);
}
}<file_sep><?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\ProductService;
use App\Services\TagService;
class ProductTagController extends Controller
{
private $productService;
private $tagService;
public function __construct(ProductService $productService, TagService $tagService){
$this->productService = $productService;
$this->tagService = $tagService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$product = $this->productService->getProduct($id);
$tags = $this->tagService->getActiveTags();
return view('admin.product-tag', compact('product','tags'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$result = $this->productService->saveOrUpdateProductTag($id, $request);
if($result){
return redirect()->route('admin.products.index')->with('success-msg', 'Product tag updated successfully.');
}else{
return redirect()->route('admin.produtstags.edit',['product-id'=>$id])->with('error-msg', 'Something went wrong.');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: MyPc
* Date: 14/02/2018
* Time: 12:55 PM
*/
namespace App\Repositories;
use App\Entities\ScenarioProduct;
use Doctrine\ORM\EntityManager;
class ScenarioProductRepo
{
private $em;
public function __construct(EntityManager $em){
$this->em = $em;
}
public function findByScenarioDetailIn($scenarioDetail){
return $this->em->getRepository(ScenarioProduct::class)->createQueryBuilder('products')
->select('scenarioproduct')
->from('App\Entities\ScenarioProduct', 'scenarioproduct')
->join('scenarioproduct.scenarioId', 'scenariodetail')
->join('scenarioproduct.productId','prdct')
->where('scenariodetail.id IN (:scenariodetail)')
->setParameter('scenariodetail', $scenarioDetail)
->orderBy("prdct.vender",'asc')
->getQuery()
->getResult();
}
public function findByScenarioDetailInAndProductIn($scenariodetail, $productTag){
return $this->em->getRepository(ScenarioProduct::class)->createQueryBuilder('products')
->select('scenarioproduct')
->from('App\Entities\ScenarioProduct', 'scenarioproduct')
->join('scenarioproduct.scenarioId', 'scenariodetail')
->join('scenarioproduct.productId', 'product')
->join('product.productTagId', 'productTag')
->where('scenariodetail.id IN (:scenariodetail)')
->andWhere('productTag.tagId IN (:producttag)')
->setParameter('scenariodetail', $scenariodetail)
->setParameter('producttag', $productTag)
->orderBy("product.vender",'asc')
->getQuery()
->getResult();
}
public function findByProductIn($productTag){
return $this->em->getRepository(ScenarioProduct::class)->createQueryBuilder('products')
->select('scenarioproduct')
->from('App\Entities\ScenarioProduct', 'scenarioproduct')
->join('scenarioproduct.scenarioId', 'scenariodetail')
->join('scenarioproduct.productId', 'product')
->join('product.productTagId', 'productTag')
->where('productTag.tagId IN (:producttag)')
->setParameter('producttag', $productTag)
->orderBy("product.vender",'asc')
->getQuery()
->getResult();
}
}<file_sep><?php
namespace App\Services\Impl;
class UploadService
{
public function UploadFile($data,$fileName,$dir){
$data->file($fileName);
if($data->hasFile($fileName)){
$file = $data->$fileName->getClientOriginalName();
//Storage::move('old/file1.jpg', 'new/file1.jpg');
// Request::file('img_filename')->move($updir, $img_name);
//Storage::disk('local')->put('file.txt', 'Contents');
if($data->file($fileName)->move('storage/'.$dir,time().$file)){
$url = 'storage/'.$dir.time().$file;
return $url;
}else{
return false;
}
}else{
return false;
}
}
public function UploadMulFile($data,$fileName,$dir){
if($data->file($fileName)){
$url =[];
foreach ($data->file($fileName) as $key => $file) {
$origName = $file->getClientOriginalName();
$file->move('storage/'.$dir,time().$origName);
$url[]= 'storage/'.$dir.'/'.time().$origName;
}
return $url;
}
}
public function UploadMultipleFileReturnShazUrl($data,$fileName,$dir){
if($data->file($fileName)){
$url =[];
foreach ($data->file($fileName) as $key => $file) {
$origName = $file->getClientOriginalName();
$file->move('storage/'.$dir,time().$origName);
$url[$key]= 'storage/'.$dir.'/'.time().$origName;
}
return $url;
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 10/05/2018
* Time: 3:25 PM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="landing_page")
*/
class LandingPage
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string",length=500)
*/
private $title ;
/**
* @ORM\Column(type="string",length=500)
*/
private $slug ;
/**
* @ORM\Column(type="string",length=500)
*/
private $metaKey ;
/**
* @ORM\Column(type="string",length=500)
*/
private $metaTitle ;
/**
* @ORM\Column(type="string",length=500)
*/
private $metaDescription ;
/**
* @ORM\Column(type="text")
*/
private $content ;
/**
* @ORM\Column(type="text")
*/
private $attributes;
/**
* @ORM\Column(type="boolean")
*/
private $isActive;
/**
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @ORM\Column(type="datetime")
*/
private $updatedAt;
/**
* @ORM\ManyToOne(targetEntity="LandingBanner",fetch="EAGER", inversedBy="landingPageBanner")
* @ORM\JoinColumn(name="banner_id", referencedColumnName="id")
*/
private $landingPageBannerId;
/**
* @ORM\ManyToOne(targetEntity="LandingTheme",fetch="EAGER", inversedBy="landingTheme")
* @ORM\JoinColumn(name="theme_id", referencedColumnName="id")
*/
private $landingThemeId;
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* @param mixed $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* @return mixed
*/
public function getSlug()
{
return $this->slug;
}
/**
* @param mixed $slug
*/
public function setSlug($slug)
{
$this->slug = $slug;
}
/**
* @return mixed
*/
public function getMetaKey()
{
return $this->metaKey;
}
/**
* @param mixed $metaKey
*/
public function setMetaKey($metaKey)
{
$this->metaKey = $metaKey;
}
/**
* @return mixed
*/
public function getMetaTitle()
{
return $this->metaTitle;
}
/**
* @param mixed $metaTitle
*/
public function setMetaTitle($metaTitle)
{
$this->metaTitle = $metaTitle;
}
/**
* @return mixed
*/
public function getMetaDescription()
{
return $this->metaDescription;
}
/**
* @param mixed $metaDescription
*/
public function setMetaDescription($metaDescription)
{
$this->metaDescription = $metaDescription;
}
/**
* @return mixed
*/
public function getContent()
{
return $this->content;
}
/**
* @param mixed $content
*/
public function setContent($content)
{
$this->content = $content;
}
/**
* @return mixed
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* @param mixed $attributes
*/
public function setAttributes($attributes)
{
$this->attributes = $attributes;
}
/**
* @return mixed
*/
public function getisActive()
{
return $this->isActive;
}
/**
* @param mixed $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
/**
* @return mixed
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param mixed $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return mixed
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param mixed $updatedAt
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
}
/**
* @return mixed
*/
public function getLandingPageBannerId()
{
return $this->landingPageBannerId;
}
/**
* @param mixed $landingPageBannerId
*/
public function setLandingPageBannerId($landingPageBannerId)
{
$this->landingPageBannerId = $landingPageBannerId;
}
/**
* @return mixed
*/
public function getLandingThemeId()
{
return $this->landingThemeId;
}
/**
* @param mixed $landingThemeId
*/
public function setLandingThemeId($landingThemeId)
{
$this->landingThemeId = $landingThemeId;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 11/05/2018
* Time: 2:51 PM
*/
namespace App\Services\Impl;
use App\Entities\LandingBanner;
use App\Entities\LandingBannerImages;
use App\Repositories\LandingBannerRepo;
use App\Services\LandingBannerService;
use App\Services\Impl\UploadService;
use Illuminate\Support\Facades\Input;
class LandingBannerServiceImpl implements LandingBannerService
{
private $landingBannerRepo,$uploadService;
public function __construct(LandingBannerRepo $landingBannerRepo,UploadService $uploadService)
{
$this->landingBannerRepo = $landingBannerRepo;
$this->uploadService = $uploadService;
}
public function getAllBanners()
{
return $this->landingBannerRepo->getAllBanners();
}
public function getAllActiveBanners()
{
return $this->landingBannerRepo->getAllActiveBanners();
}
public function getBanner($id){
return $this->landingBannerRepo->getBanner($id);
}
public function saveData($data)
{
$arr_length = count($data->get('bannerimage-title'));
$input_array = Input::all();
$banner = new LandingBanner();
$banner->setAttributes('');
$banner->setDescription($data->get('description'));
$banner->setTitle($data->get('title'));
$banner->setIsActive(1);
$banner->setUpdatedAt(new \DateTime());
$banner->setCreatedAt(new \DateTime());
$mulImage = $this->uploadService->UploadMulFile($data,'image','LandingBanner');
for($i=0; $i<$arr_length;$i++){
$bannerImage = new LandingBannerImages();
$bannerImage->setTitle($input_array['bannerimage-title'][$i]);
if($mulImage[$i]==''){
$bannerImage->setMediaUrl($input_array['url'][$i]);
}else{
$bannerImage->setMediaUrl($mulImage[$i]);
}
$bannerImage->setDescription($input_array['banner_image_description'][$i]);
isset($input_array['showButton'][$i])?$bannerImage->setShowButton($input_array['showButton'][$i]):$bannerImage->setShowButton(0);
$bannerImage->setButtonText($input_array['anchor_text'][$i]);
$bannerImage->setButtonUrl($input_array['anchor_url'][$i]);
$bannerImage->setAttributes('');
$bannerImage->setIsActive(1);
$bannerImage->setCreatedAt(new \DateTime());
$bannerImage->setUpdatedAt(new \DateTime());
$banner->addBannerImage($bannerImage);
}
return $this->landingBannerRepo->saveOrUpdate($banner);
}
public function updateData($data, $id)
{
$result = $this->removeBannerImage($id);
if($result){
$arr_length = count($data->get('bannerimage-title'));
$input_array = Input::all();
$banner = $this->landingBannerRepo->getBanner($id);
$banner->setAttributes('');
$banner->setDescription($data->get('description'));
$banner->setTitle($data->get('title'));
$banner->setIsActive($data->get('active'));
$banner->setUpdatedAt(new \DateTime());
$banner->setCreatedAt(new \DateTime());
$mulImage = $this->uploadService->UploadMultipleFileReturnShazUrl($data,'image','LandingBanner');
for($i=0; $i<$arr_length;$i++){
$bannerImage = new LandingBannerImages();
$bannerImage->setTitle($input_array['bannerimage-title'][$i]);
if(!isset($input_array['image'][$i])){
$bannerImage->setMediaUrl($input_array['url'][$i]);
}else{
//dd($mulImage[$i]);
$bannerImage->setMediaUrl($mulImage[$i]);
}
$bannerImage->setDescription($input_array['banner_image_description'][$i]);
isset($input_array['showButton'][$i])?$bannerImage->setShowButton($input_array['showButton'][$i]):$bannerImage->setShowButton(0);
$bannerImage->setButtonText($input_array['anchor_text'][$i]);
$bannerImage->setButtonUrl($input_array['anchor_url'][$i]);
$bannerImage->setAttributes('');
$bannerImage->setIsActive(1);
$bannerImage->setCreatedAt(new \DateTime());
$bannerImage->setUpdatedAt(new \DateTime());
$banner->addBannerImage($bannerImage);
}
return $this->landingBannerRepo->saveOrUpdate($banner);
}
}
public function removeBannerImage($id)
{
return $this->landingBannerRepo->removeBannerImage($id);
}
public function deleteBannerCarousel($id)
{
return $this->landingBannerRepo->deleteBannerCarousel($id);
}
}<file_sep><?php $__env->startSection('banner-image',asset($banner->getImage())); ?>
<?php $__env->startSection('content'); ?>
<div class="container">
<!--<div class="flt">-->
<!-- <h2>Products</h2>-->
<!--<hr>-->
<!--</div>-->
<div class="row">
<div class="col-md-2 col-sm-2 col-xs-12"></div>
<div class="col-md-8 col-sm-3 col-xs-12">
<div class="brdCum">
<ul>
<li><a href="<?php echo e(route('home')); ?>">Home</a>/</li>
<li> Products</li>
</ul>
</div></div>
<div class="col-md-2 col-sm-2 col-xs-12"></div>
</div>
<div class="">
<div class="col-md-2 col-sm-3 col-md-12">
<?php if(!$producttags->isEmpty()): ?>
<form class="form-horizontal" role="form" id="filterForm" action="<?php echo e(route('solution.filter',['id'=>$id])); ?>" method="POST">
<?php echo e(csrf_field()); ?>
<div class="leftDrop">
<h3>Refine by</h3>
<div class="pdn">
<h4>Product</h4>
<?php $__currentLoopData = $producttags; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $producttag): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<div class="checkbox">
<label>
<input type="checkbox" value="<?php echo e($producttag->getId()); ?>" name="product-filter[]" <?php echo e(isset($selectedTags)&&in_array($producttag->getId(), $selectedTags)?'checked':''); ?>>
<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>
<?php echo e($producttag->getTagName()); ?>
</label>
</div>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
</div>
</div>
<div class="filtr-btn">
<button type="submit" class="btn btn-sm btn-primary pull-right">Search</button>
</div>
</form>
<?php endif; ?>
</div>
<div class="col-md-8 col-sm-8 col-md-12">
<?php if($scenarioProducts): ?>
<?php $__currentLoopData = $scenarioProducts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $scenarioProduct): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<div class="row Products">
<div class="col-md-4 col-sm-4 col-md-12">
<div class="Products">
<img src="<?php echo e(asset('images/solution-4.jpg')); ?>" class="img-responsive" alt="solution-4">
</div>
</div>
<div class="col-md-8 col-sm-8 col-md-12">
<h1><?php echo e($scenarioProduct->getProductId()->getName()); ?></h1>
<h2>By <?php echo e($scenarioProduct->getProductId()->getVender()); ?></h2>
<p><?php echo \Illuminate\Support\Str::words($scenarioProduct->getProductId()->getDescription(), 40,' ...'); ?>... <button type="button" class="btn btn-primary more-btn" data-attr="<?php echo e($scenarioProduct->getProductId()->getDescription()); ?>">more</button> </p>
<div>
<button type="button" class="btn btn-primary inquire-btn" data-pid="<?php echo e($scenarioProduct->getProductId()->getId()); ?>">Inquire Now</button>
</div>
</div>
</div>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
<?php else: ?>
<div class="row">
<p>No products found..</p>
</div>
<?php endif; ?>
</div>
<div class="col-md-2 col-md-12 hidden-sm hidden-xs">
<?php $__env->startComponent('front-end.component.ads',['ads'=>$ads]); ?>
<?php echo $__env->renderComponent(); ?>
</div>
</div>
</div>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('front-end.layouts.frontLayout', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?><file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 11/05/2018
* Time: 10:07 AM
*/
namespace App\Services;
interface LandingProductService
{
public function getAllProducts();
public function getAllActiveProducts();
public function getProduct($id);
public function saveProduct($data);
public function updateProduct($data, $id);
public function activeProducts($id, $limit, $order);
// public static function getProducts();
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 11/05/2018
* Time: 2:50 PM
*/
namespace App\Services;
interface LandingBannerService
{
public function getAllBanners();
public function getAllActiveBanners();
public function saveData($data);
public function updateData($data,$id);
public function getBanner($id);
public function deleteBannerCarousel($id);
}<file_sep><?php
namespace App\Http\Controllers;
use App\Services\VerticalService;
use Illuminate\Http\Request;
use App\Services\AdService;
use App\Services\PageBannerService;
use App\Services\SolutionTypeService;
use Illuminate\Support\Facades\Route;
use App\Services\VideosService;
use App\Services\ClientTestimonialService;
use App\Services\SolutionPartnerService;
use App\Services\TagService;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
private $adService,$solutionPartnerService,$clientTestimonialService,$videoService,$solutionService,$pageBannerService;
public function __construct(AdService $adService,PageBannerService $pageBannerService,VerticalService $solutionTypeService,VideosService $videosService,ClientTestimonialService $clientTestimonialService,SolutionPartnerService $solutionPartnerService,TagService $tagService)
{
$this->adService = $adService;
$this->pageBannerService = $pageBannerService;
$this->solutionService = $solutionTypeService;
$this->videoService = $videosService;
$this->clientTestimonialService = $clientTestimonialService;
$this->solutionPartnerService = $solutionPartnerService;
$this->tagService = $tagService;
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$route = Route::current();
$page_id = $this->pageBannerService->getPageId($route->getName());
$content = $this->pageBannerService->getPageContent($page_id);
$banner = $this->pageBannerService->getPageBanner($page_id);
$ads = $this->adService->getAdsByPage($page_id,2);
$solutions = $this->solutionService->getIsActive();
$videos = $this->videoService->getActiveCorporateVideos();
$testimonials = $this->clientTestimonialService->getAllActiveTestimonial();
$partners= $this->solutionPartnerService->getAllActiveSolutionPartner();
$page_id = $this->pageBannerService->getPageId('about-GCR');
$abouts = $this->pageBannerService->getPageContent($page_id);
return view('front-end.home',compact('ads','banner','content','solutions','videos','testimonials','partners','abouts'));
}
public function tagGenerator()
{
//Scenario Table
$verticals = $this->solutionService->getAllVerticals();
foreach($verticals as $vertical){
$id=$vertical->getId();
$data['verticalSlug']=strtolower(preg_replace('/\s+/','-',trim($vertical->getName())));
$result=$this->solutionService->tagGenerator($data,$id);
}
echo 'Vertical Slug Generator SuccessFully.......';
//Tag Table
$tags = $this->tagService->getActiveTags();
foreach($tags as $tag){
$id=$tag->getId();
$data['tagSlug']=strtolower(preg_replace('/\s+/','-',trim($tag->getTagName())));
$result=$this->tagService->tagGenerator($data,$id);
}
echo 'Tag Slug Generator SuccessFully.......';
}
}
<file_sep>$(window).load(function() {
$(".loader").fadeOut("slow");
});
$(document).ready(function() {
var owl = $('.owl-carousel');
owl.owlCarousel({
items: 6,
loop: true,
margin: 5,
autoplay: true,
autoplayTimeout: 2500,
autoplaySpeed: 1500,
smartSpeed: 1000,
fluidSpeed: 1000,
autoplayHoverPause: true,
responsive:{
0:{
items:2,
loop:true
},
414:{
items:3,
loop:true
},
480:{
items:3,
loop:true
},
684:{
items:4,
loop:true
},
667:{
items:4,
loop:true
},
736:{
items:5,
loop:true
},
768:{
items:5,
loop:true
},
1200:{
items:6,
loop:true
}
}
});
$('body').on('click','.more-btn', function(){
if($(this).hasClass('m')){
$(this).parent(".PDesc").children("p").html($(this).attr('data-attr'));
$(this).removeClass("m").addClass('l');
$(this).html("... less");
}
else{
$(this).parent(".PDesc").children("p").html($(this).attr('data-attrshort'));
$(this).removeClass("l").addClass('m');
$(this).html("... more");
}
// $('#popup .modal-title').html($(this).parent().parent().find('h1').html());
// $('#popup .modal-body').html($(this).attr('data-attr'));
// $('#popup').modal('show');
});
$('body').on('click','.inquire-btn', function(){
var pid = $(this).data('pid');
$("#pid").val(pid);
$('#inquiry-form').modal('show');
});
})
$(document).ready(function(){
$("")
$('.left-scroll,.vc_list').slick({
vertical: true,
autoplay: true,
autoplaySpeed: 500,
speed: 1500
});
});
$(window).load(function() {
// if(sessionStorage.getItem('dropnav')==1){
$(".DropNav").show();
// sessionStorage.setItem('dropnav',0);
//}
$("#flexiselDemo1").flexisel();
$("#flexiselDemo2").flexisel({
enableResponsiveBreakpoints: true,
responsiveBreakpoints: {
portrait: {
changePoint:480,
visibleItems: 1
},
landscape: {
changePoint:640,
visibleItems: 2
},
tablet: {
changePoint:768,
visibleItems: 3
}
}
});
$("#flexiselDemo3").flexisel({
visibleItems: 5,
animationSpeed: 1000,
autoPlay: true,
autoPlaySpeed: 3000,
pauseOnHover: true,
enableResponsiveBreakpoints: true,
responsiveBreakpoints: {
portrait: {
changePoint:480,
visibleItems: 1
},
landscape: {
changePoint:640,
visibleItems: 2
},
tablet: {
changePoint:768,
visibleItems: 3
}
}
});
$("#flexiselDemo4").flexisel({
clone:false
});
$(".secon").click(function(){
$("#show").show();
});
$("#flexiselDemo7").flexisel({
visibleItems: 5,
animationSpeed: 1000,
autoPlay: true,
autoPlaySpeed: 3000,
pauseOnHover: true,
enableResponsiveBreakpoints: true,
responsiveBreakpoints: {
portrait: {
changePoint:480,
visibleItems: 1
},
landscape: {
changePoint:640,
visibleItems: 2
},
tablet: {
changePoint:768,
visibleItems: 3
}
}
});
$(function(){
$(".leftSlider").scrollText({
'duration': 2000
});
});
});
$( document ).ready(function() {
$(".alertifyshaz").delay(3000).fadeOut(1000);
new Vue({
el: '#example',
data: {
slides: 5
},
components: {
'carousel-3d': Carousel3d.Carousel3d,
'slide': Carousel3d.Slide
}
});
$("body").on("submit","form",function(){
var $flag = true;
var $required = $(this).find(".required");
$required.each(function(){
if($.trim($(this).val())==''){
$(this).addClass('error');
$(this).siblings(".red").children("small").html("Field is mendatory.")
$flag = false;
}else{
$(this).siblings(".red").children("small").html("")
$(this).removeClass('error');
}
});
if(!$flag){
$('html, body').animate({
scrollTop: $(".error").first().offset().top - 250
}, 1000);
return $flag;
}
});
$('form > .required').keyup(function() {
var empty = false;
$('form > .required').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('input[type=submit]').attr('disabled', 'disabled');
} else {
$('input[type=submit]').removeAttr('disabled');
}
});
});
$(document).on('ready', function() {
$(".center").slick({
dots: true,
autoPlay: true,
infinite: true,
centerMode: true,
slidesToShow: 5,
slidesToScroll: 3
});
$(".variable").slick({
dots: true,
infinite: true,
autoPlay: true,
variableWidth: true
});
$(".lazy").slick({
lazyLoad: 'ondemand', // ondemand progressive anticipated
infinite: true,
autoPlay: true,
});
//DropMenu
$('#main-nav ul li a').click(function(){
$("#main-nav ul li a").removeClass("active-4");
$(this).addClass("active-4");
});
//Solution
$('.bxslider').bxSlider({
minSlides: 1,
maxSlides: 8,
slideWidth: 157,
slideMargin: 0,
ticker: true,
speed: 15000,
});
});
$(function(){
$("body").on("click",".closePopUp",function(){
$(".popupcontact").hide();
});
setTimeout(function(){
var key = sessionStorage.getItem('popupKey');
if(key!=1){
$.ajax({
url:'/GCR29-5/contact-popup-form',
dataType:'html',
cache:false,
success:function(html){
$("#popTemp").modal("hide");
$("#popup-form").find(".modal-body").html(html);
$("#popup-form").modal("show");
}
})
}
},30000);
setTimeout(function() {
$("#popTemp").modal("hide");
},5000);
setTimeout(function() {
$("#popTemp").modal("show");
},100);
$("body").on("click",".close-btn",function(){
$("#popTemp").modal("hide");
})
$("body").on("click",".partnerspop",function(){
var route = $(this).data('route');
var id = $(this).data('id');
$.ajax({
url:route+'/'+id,
type:'get',
dataType:'html',
cache:false,
success:function(html){
$("#myModal-partner").find(".modal-body").html(html);
$("#myModal-partner").modal("show");
}
});
});
});
$(function () {
$('#demo5').scrollbox({
direction: 'h',
distance: 134
});
$('#demo5-backward').click(function () {
$('#demo5').trigger('backward');
});
$('#demo5-forward').click(function () {
$('#demo5').trigger('forward');
});
});
$(function(){
$('#news-container').vTicker({
speed: 500,
pause: 3000,
animation: 'fade',
mousePause: true,
showItems: 5,
});
});
$(document).ready(function(){
$(".collapsed").click(function(){
$('.navbar-collapse').slideToggle(1500);
});
});
// $(document).ready(function() {
// var nice = $("html").niceScroll(); // The document page (body)
// $("#div1").html($("#div1").html()+' '+nice.version);
// $("#boxscroll").niceScroll({cursorborder:"",cursorcolor:"#be0807",boxzoom:true}); // First scrollable DIV
// });
$(document).ready(function() {
//var nice = $("html").niceScroll(); // The document page (body)
//$("#div1").html($("#div1").html()+' '+nice.version);
//$("#boxscroll").niceScroll({cursorborder:"",cursorcolor:"#fff"}); // First scrollable DIV
$('.scroller').scrollify();
});
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<file_sep><?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\SolutionService;
use App\Services\CheckPermissionService;
use App\Services\TagService;
use Validator;
class SolutionController extends Controller
{
protected $solutionService,$checkPermissionService,$tagService;
public function __construct(SolutionService $solutionService,CheckPermissionService $checkPermissionService,TagService $tagService)
{
$this->solutionService = $solutionService;
$this->checkPermissionService = $checkPermissionService;
$this->tagService = $tagService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$solutions = $this->solutionService->getAllSolution();
$isAuthorize = $this->checkPermissionService->checkPermission();
return view('admin.solutions',compact('solutions','isAuthorize'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$stag = $this->solutionService->getSolutionById($id);
$linkedTag = $this->solutionService->findSolutionInSolutionTag($id);
$tags = $this->tagService->getActiveTags();
return view('admin.solutionTags',compact('stag','tags','linkedTag'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
Validator::make($request->all(),[
"tags"=>"required",
"solution"=>"required"
]);
$result = $this->solutionService->addUpdateSolutionTag($request,$id);
if($result){
return redirect()->route('admin.solutions.index')->with('success-msg', 'Tags Added successfully.');
}else{
return redirect()->route('admin.solutions.index')->with('error-msg', 'Please check the form and submit again.');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 07/02/2018
* Time: 6:24 PM
*/
namespace App\Entities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping AS ORM;
/**
*
* @package App\Entities
* @ORM\Entity
* @ORM\Table(name="tags")
*/
class Tag
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string")
*/
private $tagName;
/**
* @ORM\Column(type="string",nullable=true)
*/
private $urlSlug;
/**
* @var ArrayCollection|Tag[]
* @ORM\OneToMany(targetEntity="Tag", mappedBy="parent", fetch="EAGER")
*/
private $children;
/**
* @var Tag
* @ORM\ManyToOne(targetEntity="Tag", inversedBy="children", fetch="EAGER")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
private $parent;
/**
* @ORM\Column(type="string",options={"unsigned":true, "default":0})
*/
private $deleted;
/**
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @ORM\Column(type="datetime")
*/
private $updatedAt;
/**
* @ORM\OneToMany(targetEntity="TagProduct", mappedBy="tagId",cascade={"persist"})
*/
private $tagProductId;
/**
* @ORM\OneToMany(targetEntity="TagCategory", mappedBy="tagId",cascade={"persist"})
*/
private $tagScenarioId;
/**
* @ORM\Column(type="boolean")
*/
private $isActive;
public function __construct(){
$this->children = new ArrayCollection();
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getTagName()
{
return $this->tagName;
}
/**
* @param mixed $tagName
*/
public function setTagName($tagName)
{
$this->tagName = $tagName;
}
/**
* @return mixed
*/
public function getUrlSlug()
{
return $this->urlSlug;
}
/**
* @param mixed $urlSlug
*/
public function setUrlSlug($urlSlug)
{
$this->urlSlug = $urlSlug;
}
/**
* @return mixed
*/
public function getDeleted()
{
return $this->deleted;
}
/**
* @param mixed $deleted
*/
public function setDeleted($deleted)
{
$this->deleted = $deleted;
}
/**
* @return mixed
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param mixed $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return mixed
*/
public function getUpdatedAt()
{
return $this->createdAt;
}
/**
* @param mixed $createdAt
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
}
/**
* @return mixed
*/
public function getTagProductId()
{
return $this->tagProductId;
}
/**
* @param mixed $tagProductId
*/
public function setTagProductId($tagProductId)
{
$this->tagProductId = $tagProductId;
}
/**
* @return mixed
*/
public function getTagScenarioId()
{
return $this->tagScenarioId;
}
/**
* @param mixed $tagScenarioId
*/
public function setTagScenarioId($tagScenarioId)
{
$this->tagScenarioId = $tagScenarioId;
}
/**
* @return Tag[]|ArrayCollection
*/
public function getChildren()
{
return $this->children;
}
/**
* @param Tag[]|ArrayCollection $children
*/
public function setChildren($children)
{
$this->children = $children;
}
/**
* @return Tag
*/
public function getParent()
{
return $this->parent;
}
/**
* @param Tag $parent
*/
public function setParent($parent)
{
$this->parent = $parent;
}
public function addChildren(Tag $tag){
if(!$this->children->contains($tag)){
$category->setParent($this);
$this->children->add($tag);
}
}
/**
* @return mixed
*/
public function getisActive()
{
return $this->isActive;
}
/**
* @param mixed $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Android
* Date: 14/02/2018
* Time: 3:05 PM
*/
namespace App\Services\Impl;
use App\Services\TagService;
use App\Repositories\TagRepo;
use App\Entities\Tag;
use App\Entities\TagCategory;
use App\Services\ProductTypeService;
use App\Services\SolutionTypeService;
use App\Services\IndustryService;
use Doctrine\Common\Collections\ArrayCollection;
class TagServiceImpl implements TagService
{
protected static $tagRepo;
protected $ind;
protected $pt;
protected $st;
public function __construct(TagRepo $tagRepo,IndustryService $ind,SolutionTypeService $st,ProductTypeService $pt)
{
self::$tagRepo = $tagRepo;
$this->ind = $ind;
$this->st = $st;
$this->pt =$pt;
}
public function tagList()
{
return self::$tagRepo->tagList();
}
public function getActiveTags(){
$tagColl = new ArrayCollection();
$tags = self::$tagRepo->findActiveTags();
foreach ($tags as $tag) {
if(!$tagColl->contains($tag) && $tag->getChildren()->isEmpty()){
$tagColl->add($tag);
}
}
return $tagColl;
}
public function tagAdd($data)
{
$tag = new Tag();
$tag->setTagName($data['title']);
if(isset($data['parent-tag']) && $data['parent-tag']!=""){
$tag->setParent(self::$tagRepo->findTag($data['parent-tag']));
}
$tag->setIsActive(1);
$tag->setCreatedAt(new \DateTime());
$tag->setUpdatedAt(new \DateTime());
$tag->setDeleted(0);
$tag->setUrlSlug($data['tagSlug']);
return self::$tagRepo->tagAdd($tag);
}
// /**
// * Sync up the list of tags in the database. Add Tag if not exist.
// */
public function checkTags($tags)
{
// $tag = explode(',',$tags);
// $currentListTag = $this->tagRepo->tagList();
// $currentListST = $this->st->STList();
// $currentListIND = $this->ind->INDList();
// $currentListPT = $this->pt->PTList();
// $currentListArray=[];
// foreach ($currentListTag as $tagsArray){
// $currentListArray[] = $tagsArray->getTagName();
// }
// foreach ($currentListIND as $tagsArrayInd){
// $currentListArray[] = $tagsArrayInd->getIndustryName();
// }
// foreach ($currentListST as $tagsArraySt){
// $currentListArray[] = $tagsArraySt->getName();
// }
// foreach ($currentListPT as $tagsArrayPt){
// $currentListArray[] = $tagsArrayPt->getName();
// }
// $newTags = array_diff($tag, $currentListArray);
// foreach ($newTags as $newTag)
// {
// $this->tagAdd($newTag);
// }
// return true;
}
public function getTag($id){
return self::$tagRepo->findTag($id);
}
public function updateTag($data, $id){
$tag = self::$tagRepo->findTag($id);
$tag->setTagName($data['title']);
if(isset($data['parent-tag']) && $data['parent-tag']!=""){
$tag->setParent(self::$tagRepo->findTag($data['parent-tag']));
}else{
$tag->setParent(NULL);
}
if(isset($data['tagSlug']) && $data['tagSlug']!=""){
$tag->setUrlSlug($data['tagSlug']);
}else{
$tag->setUrlSlug(NULL);
}
$tag->setIsActive($data['active']);
$tag->setUpdatedAt(new \DateTime());
$tag->setDeleted(0);
return self::$tagRepo->tagAdd($tag);
}
public static function getSolutionTags(){
// $_this = new self;
// $solutionTags =self::$tagRepo->findSolutionTags();
$solutionTags = self::$tagRepo->findProductTags();
$tagsList = new ArrayCollection();
foreach ($solutionTags as $solutionTag) {
$tag = $solutionTag->getTagId();
while(null!=$tag->getParent()){
$tag = $tag->getParent();
}
if(!$tagsList->contains($tag)){
$tagsList->add($tag);
}
}
//sort ascending order with tagname.
$iterator = $tagsList->getIterator();
$iterator->uasort(function ($a, $b) {
return ($a->getTagName() < $b->getTagName()) ? -1 : 1;
});
$collection = new ArrayCollection(iterator_to_array($iterator));
//dd($collection);
return $collection;
}
public function getAllSolutionTags(){
$solutionTagsColl = new ArrayCollection();
$solutionTags =self::$tagRepo->findSolutionTags();
foreach ($solutionTags as $solutionTag) {
if(!$solutionTagsColl->contains($solutionTag->getTagId())){
$solutionTagsColl->add($solutionTag->getTagId());
}
}
return $solutionTagsColl;
}
public function getSolutonTagsById($solutionId){
$solutionTagsColl = new ArrayCollection();
$solutionTags =self::$tagRepo->findSolutionTagsById($solutionId);
foreach ($solutionTags as $solutionTag) {
if(!$solutionTagsColl->contains($solutionTag->getTagId())){
$solutionTagsColl->add($solutionTag->getTagId());
}
}
return $solutionTagsColl;
}
public function getParentTags(){
return self::$tagRepo->findParentTags();
}
//Amit 12-06-2018
public function getTagIdBySlug($slug){
return self::$tagRepo->findTagIdBySlug($slug);
}
//Amit 13-06-2018
public function tagGenerator($data,$id){
$tag = self::$tagRepo->findTag($id);
if(isset($data['tagSlug']) && $data['tagSlug']!=""){
$tag->setUrlSlug($data['tagSlug']);
}else{
$tag->setUrlSlug(NULL);
}
$tag->setUpdatedAt(new \DateTime());
return self::$tagRepo->tagAdd($tag);
}
}
| 24899ba130e5b51abe4c41edcde7dd1d63b47b0b | [
"JavaScript",
"PHP"
] | 71 | PHP | amitalgo/GCR_5.1 | 1a62d3c934e9c9e7763e6d61638a4b28665896e3 | 01980aa6e4cf8197b60cfdb39976954fe71ba5ab |
refs/heads/master | <file_sep>#include <RBDdimmer.h>
dimmerLamp dim4(4); //initialase port for dimmer: name(PinNumber);
int buttonRed = 0;
void setup() {
dim4.begin(NORMAL_MODE, ON); //dimmer initialisation: name.begin(MODE, STATE)
dim4.setPower(50);
pinMode(14, INPUT);
}
void loop() {
buttonRed = digitalRead(14);
if (buttonRed == 1)
{
delay(10);
dim4.setState(ON); //name.setState(ON/OFF);
}
if (buttonRed == 0)
{
delay(10);
dim4.setState(OFF); //name.setState(ON/OFF);
}
}
<file_sep>#include <RBDdimmer.h>//
dimmerLamp dimmer(4); //initialase port for dimmer: name(PinNumber);
int outVal = 0;
void setup() {
Serial.begin(9600);
dimmer.begin(NORMAL_MODE, ON); //dimmer initialisation: name.begin(MODE, STATE)
Serial.println("Dimmer Program is starting...");
Serial.println("Set value");
}
void printSpace(int val)
{
if ((val / 100) == 0) Serial.print(" ");
if ((val / 10) == 0) Serial.print(" ");
}
void loop() {
int preVal = outVal;
if (Serial.available())
{
int buf = Serial.parseInt();
if (buf != 0) outVal = buf;
delay(200);
}
dimmer.setPower(outVal); // setPower(0-100%);
if (preVal != outVal)
{
Serial.print("% lampValue -> ");
printSpace(dimmer.getPower());
Serial.print(dimmer.getPower());
}
delay(50);
}
<file_sep>#include <RBDdimmer.h>
dimmerLamp dimmer(4); //initialase port for dimmer: name(PinNumber);
void setup() {
Serial.begin(9600);
dimmer.begin(TOGGLE_MODE, OFF); //dimmer initialisation: name.begin(MODE, STATE)
Serial.println("--- Toggle dimmer example ---");
dimmer.toggleSettings(0, 100); //Name.toggleSettings(MIN, MAX);
dimmer.setState(ON); // state: dimmer1.setState(ON/OFF);
pinMode(14, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
}
<file_sep>#include <RBDdimmer.h>
dimmerLamp dimmer1(4); //initialase port for dimmer: name(PinNumber);
void setup() {
Serial.begin(9600);
dimmer1.begin(NORMAL_MODE, OFF); //dimmer initialisation: name.begin(MODE, STATE)
Serial.println("--- Simple dimmer example ---");
dimmer1.setPower(50); // setPower(0-100%);
dimmer1.setState(ON); // setState(ON/OFF);
pinMode(5, INPUT);
}
void loop() {
if (digitalRead(5) == 1)
{
dimmer1.changeState(); //changes state on the opposite: name.changeState();
}
Serial.print("Dimmer state: ");
Serial.println(dimmer1.getState());
delay(1000);
}
<file_sep>#include <RBDdimmer.h>
dimmerLamp dimmer(4); //initialase port for dimmer: name(PinNumber);
int outVal = 0;
void setup() {
Serial.begin(9600);
dimmer.begin(NORMAL_MODE, ON); //dimmer initialisation: name.begin(MODE, STATE)
}
void loop()
{
outVal = map(analogRead(0), 1, 1024, 100, 0); // analogRead(analog_pin), min_analog, max_analog, 100%, 0%);
Serial.println(outVal);
dimmer.setPower(outVal); // name.setPower(0%-100%)
}
| fc8f9135b5976a78f0a873c2f633febc798a4083 | [
"C++"
] | 5 | C++ | jirmjos/AC-Light-Dimmer-Module-1-Channel-3.3V-5V-logic-AC-50-60hz-220V-110V | 45a5cc46375e492eb647c4e0640955bc67348601 | 138404c81272c248cc89ea3fc81353fed80499cb |
refs/heads/main | <file_sep><body id="page-top">
<div class="container-fluid">
<div class="box">
<div class="box-header">
<h1 class="h4 mb-0 text-gray-800">Add Pegawai</h1>
<div align="right">
<a href="<?=site_url('perangkat_desa')?>" class="btn btn-warning btn-flat">
<i class="fa fa-undo"></i> Back </a>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-md-4 col-md-offset-4">
</div>
<?php // echo validation_errors() ; ?>
<form action="" method="post">
<div class="form-group <?=form_error('name') ? 'has-error' : null ?>">
<label>Nama *</label>
<input type="text" name="nama" value="<?= set_value('name')?>" class="form-control">
<?=form_error('name')?>
</div>
<div class="form-group <?=form_error('username') ? 'has-error' : null ?>">
<label>NIK *</label>
<input type="text" name="nik" value="<?= set_value('username')?>" class="form-control">
<?=form_error('username')?>
</div>
<div class="form-group <?=form_error('password') ? 'has-error' : null ?>">
<label>Jabatan *</label>
<input type="text" name="jabatan" value="<?= set_value('password')?>" class="form-control">
<?=form_error('password')?>
</div>
<div class="form-group <?=form_error('address') ? 'has-error' : null ?>">
<label>Devisi *</label>
<textarea name="divisi" value="<?= set_value('address')?>" class="form-control"> </textarea>
<?=form_error('divisi')?>
</div>
<div class="form-group <?=form_error('level') ? 'has-error' : null ?>">
<label>Status</label>
<input type="text" name="status" value="<?= set_value('Level')?>" class="form-control">
<?=form_error('status')?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-flat"><i class="fa fa-paper-plane"></i> Save</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</form>
</div>
</div>
<file_sep> <!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">Tambah Surat Internal</h1>
<div class="row">
<div onclick="href('surat_tugas')" style="cursor: pointer;" class="col-xl-3 col-md-6 mb-4">
<div class="card shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
</div>
<div class="h5 mb-0 font-weight-bold text-gray-800">Surat Tugas</div>
</div>
<div class="col-auto">
<i class="fas fa-envelope fa-2x text-gray-300"></i>
</div>
</div>
</div>
</div>
</div>
<div onclick="href('surat_undangan')" style="cursor: pointer;" class="col-xl-3 col-md-6 mb-4">
<div class="card shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
</div>
<div class="h5 mb-0 font-weight-bold text-gray-800">Surat Undangan</div>
</div>
<div class="col-auto">
<i class="fas fa-envelope fa-2x text-gray-300"></i>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<script>
function href(loc) {
if (loc == 'surat_tugas') {
window.location = '<?= base_url('PembuatanSurat/surat_tugas')?>'
}else{
window.location = '<?= base_url('PembuatanSurat/surat_undangan')?>'
}
}
</script><file_sep><body id="page-top">
<div class="container-fluid">
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800"><?php echo $title ?></h1>
</div>
<div class="card mb-3">
<div class="card-header bg-primary text-white">
Filter Data Laporan Keluar
</div>
<div class="card-body">
<form method="POST" class="form-inline" action="<?php echo base_url('laporankeluar/print') ?>">
<div class="form-group mb-2">
<label for="staticEmail2">Bulan:</label>
<select id="bulan" class="form-control ml-3" required name="bulan">
<option value="">--Pilih Bulan--</option>
<option value="01">Januari</option>
<option value="02">Februari</option>
<option value="03">Maret</option>
<option value="04">April</option>
<option value="05">Mei</option>
<option value="06">Juni</option>
<option value="07">Juli</option>
<option value="08">Agustus</option>
<option value="09">September</option>
<option value="10">Oktober</option>
<option value="11">November</option>
<option value="12">Desember</option>
</select>
</div>
<div class="form-group mb-2 ml-5">
<label for="staticEmail2">Tahun:</label>
<select id="tahun" class="form-control ml-3" required name="tahun">
<option value="">--Pilih Tahun--</option>
<?php $tahun = date('Y');
for($i=2020;$i<$tahun+5;$i++){ ?>
<option value="<?php echo $i ?>"> <?php echo $i ?></option>
<?php } ?>
</select>
</div>
<button id="tampil_data" type="button" class="btn btn-primary mb-2 ml-auto"><i class="fas fa-eye"></i>Tampilkan Data</button>
<button href="submit" class="btn btn-success mb-2 ml-3"><i class="fas fa-print"></i>Cetak Laporan</button>
</form>
<table id="datatable_surat_keluar" class="table table-striped display nowrap table-sm" style="width: 100%;" id="table1" align="center">
<thead>
<tr>
<th>No</th>
<th>No. Surat</th>
<th>Tanggal</th>
<th>Jenis Surat</th>
</tr>
</thead>
<tbody id="records_table">
</tbody>
</table>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#datatable_surat_keluar').hide();
$('#tampil_data').on('click', function () {
$('#records_table').html('');
var bulan = $('#bulan').val()
var tahun = $('#tahun').val()
$.ajax({
type: "POST",
url: "<?php echo site_url('LaporanKeluar/data_surat_keluar') ?>",
dataType: "JSON",
data: {
bulan: bulan,
tahun: tahun
},
success: function(data) {
var trHTML = '';
$.each(data, function (i, item) {
trHTML += `
<tr>
<td>${item.no}</td>
<td>${item.no_surat}</td>
<td>${item.tanggal}</td>
<td>${(item.jenis_surat !=null) ? item.jenis_surat : '-'}</td>
</tr>
`
});
$('#records_table').append(trHTML);
$('#datatable_surat_keluar').show();
}
});
})
});
</script>
<file_sep><?php
if (!function_exists('sasi')) {
function sasi($ss){
switch($ss){
case 1:
return "Januari";
break;
case 2:
return "Februari";
break;
case 3:
return "Maret";
break;
case 4:
return "April";
break;
case 5:
return "Mei";
break;
case 6:
return "Juni";
break;
case 7:
return "Juli";
break;
case 8:
return "Agustus";
break;
case 9:
return "September";
break;
case 10:
return "Oktober";
break;
case 11:
return "November";
break;
case 12:
return "Desember";
break;
default:
$ss = date('F');
break;
}
return $ss;
}
}
if (!function_exists('bulan')) {
function bulan(){
$bulan = date('m') ;
switch($bulan){
case 1:
return "Januari";
break;
case 2:
return "Februari";
break;
case 3:
return "Maret";
break;
case 4:
return "April";
break;
case 5:
return "Mei";
break;
case 6:
return "Juni";
break;
case 7:
return "Juli";
break;
case 8:
return "Agustus";
break;
case 9:
return "September";
break;
case 10:
return "Oktober";
break;
case 11:
return "November";
break;
case 12:
return "Desember";
break;
default:
$bulan = date('F');
break;
}
return $bulan;
}
}
// fungsi untuk mencetak tanggal dalam format tanggal indonesia
if(!function_exists('tanggal')){
function tanggal(){
$tanggal = date('d')." ".bulan()." ".date('Y');
return $tanggal;
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
include 'SuratPengantar.php';
class PembuatanSurat extends CI_Controller {
var $ttd_img;
function __construct(){
parent::__construct();
$this->load->model('m_keluar');
check_not_login();
$this->load->library('form_validation');
$this->load->helper('my_helper');
$this->load->library('form_validation');
$this->ttd_img = [
'Camat' => 'media\surat\ttd2.jpg',
'Sekretaris Camat' => 'media\surat\ttd3.jpg',
'Admin' => 'media\surat\ttd.jpg',
];
}
public function surat_internal()
{
$data = [
'row' => $this->m_keluar->get(),
'title' => "Surat Internal",
'data_surat' => $this->m_keluar->get_surat_internal()
];
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('pembuatan_surat/surat_internal/index', $data);
$this->load->view('template_admin/footer');
}
public function surat_internal_add()
{
$data = [
'row' => $this->m_keluar->get(),
'title' => "Surat Undangan"
];
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('pembuatan_surat/surat_internal/surat_internal_add', $data);
$this->load->view('template_admin/footer');
}
public function surat_undangan()
{
if ($this->input->server('REQUEST_METHOD') == 'POST'){
$ttd = explode("%",$this->input->post('ttd'));
$nama_ttd = $ttd[0];
$jabatan_ttd = $ttd[1];
$data =[
'no_surat' => $this->input->post('no_surat'),
'nama_ttd' => $nama_ttd,
'jabatan_ttd' => $jabatan_ttd,
'jenis_surat' => $this->input->post('jenis_surat'),
'kepada' => $this->input->post('kepada'),
'kontent' => $this->input->post('kontent'),
];
$this->form_validation->set_rules('no_surat', 'No_surat', 'required|is_unique[surat_undangan.no_surat]');
if ($this->form_validation->run() == true){
if($this->db->insert('surat_undangan', $data)){
$data['ttd_img'] = $this->ttd_img[$jabatan_ttd];
$data['tanggal_surat'] = $this->input->post('tanggal_surat');
$this->load->view('print/surat_undangan.php', $data);
}
}
}else{
$data = [
'row' => $this->m_keluar->get(),
'title' => "Surat Undangan",
'no_surat' => no_surat_internal('undangan')
];
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('pembuatan_surat/surat_internal/s_undangan', $data);
$this->load->view('template_admin/footer');
}
}
public function surat_tugas()
{
if ($this->input->server('REQUEST_METHOD') == 'POST'){
$ttd = explode("%",$this->input->post('ttd'));
$nama_ttd = $ttd[0];
$jabatan_ttd = $ttd[1];
$data = [
'jenis_surat' => $this->input->post('jenis_surat'),
'no_surat' => $this->input->post('no_surat'),
'id_perangkat_desa' => $this->input->post('id_perangkat_desa'),
'kontent' => $this->input->post('kontent'),
'tanggal_surat' => $this->input->post('tanggal_surat'),
'nama_ttd' => $nama_ttd,
'jabatan_ttd' => $jabatan_ttd,
];
$this->form_validation->set_rules('no_surat', 'No_surat', 'required|is_unique[surat_tugas.no_surat]');
if ($this->form_validation->run() == true){
if($this->db->insert('surat_tugas', $data)){
$data['perangkat_desa'] = $this->db->get_where('perangkat_desa', ['id' => $this->input->post('id_perangkat_desa') ])->row_array();
$data['ttd_img'] = $this->ttd_img[$jabatan_ttd];
$data['tanggal_surat'] = $this->input->post('tanggal_surat');
$this->load->view('print/surat_tugas.php', $data);
}
}
}else {
$data = [
'row' => $this->m_keluar->get(),
'title' => "Surat Tugas",
'data_perangkat_desa' => $this->db->get('perangkat_desa')->result(),
'no_surat' => no_surat_internal('tugas')
];
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('pembuatan_surat/surat_internal/s_tugas', $data);
$this->load->view('template_admin/footer');
}
}
public function cetak()
{
$id_surat = $this->uri->segment(3);
$jenis_surat = $this->uri->segment(4);
$data_surat = null;
$template = null;
$data = null;
if ($jenis_surat == 'Surat_Undangan') {
$data_surat = $this->db->get_where('surat_undangan', ['id' => $id_surat])->row_array();
$template = 'print\surat_undangan.php';
$data =[
'no_surat' => $data_surat['no_surat'],
'nama_ttd' => $data_surat['nama_ttd'],
'jabatan_ttd' => $data_surat['jabatan_ttd'],
'jenis_surat' => $data_surat['jenis_surat'],
'kontent' => $data_surat['kontent'],
'tanggal' => $data_surat['tanggal']
];
}else {
$data_surat = $this->db->get_where('surat_tugas', ['id' => $id_surat])->row_array();
$template = 'print\surat_tugas.php';
$data = [
'jenis_surat' => $data_surat['jenis_surat'],
'no_surat' => $data_surat['no_surat'],
'id_perangkat_desa' => $data_surat['id_perangkat_desa'],
'kontent' => $data_surat['kontent'],
'nama_ttd' => $data_surat['nama_ttd'],
'jabatan_ttd' => $data_surat['jabatan_ttd'],
'tanggal' => $data_surat['tanggal'],
'perangkat_desa' => $this->db->get_where('perangkat_desa', ['id' => $data_surat['id_perangkat_desa'] ])->row_array()
];
}
if ($data_surat != null) {
$this->load->view($template, $data);
}else {
redirect('pembuatanSurat/surat_internal');
}
}
public function del()
{
$id_surat = $this->uri->segment(3);
$jenis_surat = $this->uri->segment(4);
if ($jenis_surat == 'Surat_Undangan') {
if($this->db->delete('surat_undangan', ['id' => $id_surat])){
echo "<script> alert('Data berhasil dihapus');</script>";
echo "<script>window.location='".site_url('pembuatanSurat/surat_internal')."';</script>";
} else {
echo "<script> alert('Data tidak ditemukan');</script>";
echo "<script>window.location='".site_url('pembuatanSurat/surat_internal')."';</script>";
}
}else {
if ($this->db->delete('surat_tugas', ['id' => $id_surat])){
echo "<script> alert('Data berhasil dihapus');</script>";
echo "<script>window.location='".site_url('pembuatanSurat/surat_internal')."';</script>";
}
echo "<script> alert('Data tidak ditemukan');</script>";
echo "<script>window.location='".site_url('pembuatanSurat/surat_internal')."';</script>";
}
}
}
?><file_sep> <!-- Page Wrapper -->
<div id="wrapper">
<!-- Sidebar -->
<ul class="navbar-nav bg-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<!-- Sidebar - Brand -->
<a class="sidebar-brand d-flex align-items-center justify-content-center" href="#">
<div class="sidebar-brand-icon rotate-n-15">
<i class="fas fa-file-archive"></i>
</div>
<div class="sidebar-brand-text mx-3">ADMINISTRASI SURAT</sup></div>
</a>
<!-- Divider -->
<hr class="sidebar-divider">
<li class="nav-item">
<!-- Heading -->
<!-- Nav Item - Dashboard -->
<li class="nav-item">
<a class="nav-link pb-0" href="<?= base_url('Dashboard') ?>">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Dashboard</span></a>
</li>
<!-- Divider -->
<hr class="sidebar-divider">
<!-- Heading -->
<div class="sidebar-heading">
Staff
</div>
<!-- <?php if($this->fungsi->user_login()->level == 1) { ?>
<li class="nav-item">
<a class="nav-link pb-0" href="<?= base_url('Penduduk') ?>">
<i class="fas fa-fw fa-user"></i>
<span>Warga</span></a>
<?php } ?>
</li>
-->
<!---<?php if($this->fungsi->user_login()->level == 1) { ?>
<li class="nav-item">
<a class="nav-link pb-0" href="<?= base_url('PerangkatDesa') ?>">
<i class="fas fa-fw fa-user"></i>
<span>Perangkat Desa</span></a>
<?php } ?>
</li>!--->
<?php if($this->fungsi->user_login()->level == 1) { ?>
<li class="nav-item">
<a class="nav-link pb-0 collapsed" href="#" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<i class="fas fa-fw fa-mail-bulk"></i>
<span>Transaksi Surat</span></a>
<div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<a class="collapse-item" href="<?= base_url('suratmasuk') ?>">Surat Masuk</a>
<a class="collapse-item" href="<?= base_url('pembuatanSurat/surat_internal') ?>">Surat Internal</a>
<a class="collapse-item" href="<?= base_url('suratkeluar') ?>">Surat Keluar</a>
</div>
</div>
<?php } ?>
</li>
<!--<?php if($this->fungsi->user_login()->level == 2) { ?>
<li class="nav-item">
<a class="nav-link pb-0 collapsed" href="#" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<i class="fas fa-fw fa-mail-bulk"></i>
<span>Transaksi Surat</span></a>
<div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<a class="collapse-item" href="<?= base_url('lurahmasuk') ?>">Surat Masuk</a>
<a class="collapse-item" href="<?= base_url('lurahkeluar') ?>">Surat Keluar</a>
</div>
</div>
<?php } ?>
</li>
<!-- Nav Item - Pages Collapse Menu Blog Sekdes-->
<!--<?php if($this->fungsi->user_login()->level == 3) { ?>
<li class="nav-item">
<a class="nav-link pb-0 collapsed" href="#" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<i class="fas fa-fw fa-mail-bulk"></i>
<span>Transaksi Surat</span></a>
<div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<a class="collapse-item" href="<?= base_url('sekdesmasuk') ?>">Surat Masuk</a>
<a class="collapse-item" href="<?= base_url('sekdeskeluar') ?>">Surat Keluar</a>
</div>
</div>
<?php } ?>
</li>!-->
<!-- Nav Item - Pages Collapse Menu Blog -->
<?php if($this->fungsi->user_login()->level == 1) { ?>
<li class="nav-item">
<a class="nav-link pb-0 collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
<i class="fas fa-fw fa-book "></i>
<span>Laporan</span></a>
<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<a class="collapse-item" href="<?= base_url('laporanMasuk') ?>">Surat Masuk</a>
<a class="collapse-item" href="<?= base_url('laporanKeluar') ?>">Surat Keluar</a>
</div>
</div>
<?php } ?>
</li>
<!-- Nav Item - Pages Collapse Menu Blog -->
<?php if($this->fungsi->user_login()->level == 1) { ?>
<li class="nav-item">
<a class="nav-link pb-0 collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo1" aria-expanded="true" aria-controls="collapseTwo">
<i class="fas fa-user-cog"></i>
<span>Setting</span></a>
<div id="collapseTwo1" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<a class="collapse-item" href="<?= base_url('user'); ?>">User</a>
<a class="collapse-item" href="<?= base_url('perangkat_desa') ?>">Pegawai</a>
</div>
</div>
<?php } ?>
</li>
<li class="nav-item">
<a class="nav-link collapsed" href="<?php echo base_url('auth/logout') ?>">
<i class="fas fa-sign-out-alt"></i>
<span>Logout</span>
</a>
</li>
<!-- Sidebar Toggler (Sidebar) -->
<div class="text-center d-none d-md-inline">
<button class="rounded-circle border-0" id="sidebarToggle"></button>
</div>
</ul>
<!-- End of Sidebar -->
<!-- Content Wrapper -->
<div id="content-wrapper" class="d-flex flex-column">
<!-- Main Content -->
<div id="content">
<!-- Topbar -->
<nav class="navbar navbar-expand navbar-danger bg-light topbar mb-4 static-top shadow">
<!-- Sidebar Toggle (Topbar)
<img src="<?php echo base_url();?>assets/img/Kelurahan.png" width="40" hight="40"><br>
<h5 style="color:dark"> Kantor <NAME></h5>-->
<marquee behavior='alternate' direction='left' scrollamount='3' scrolldelay='40'><p align="center" style="font-family: monospace; font-size: 130%; color: dark; font-weight: bold; line-height: 18px;">Selamat Datang di Sistem Administrasi Surat Kecamatan Cipari</p></marquee>
<!-- Topbar Navbar -->
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown no-arrow">
</ul>
</nav>
<!-- End of Topbar --><file_sep><body id="page-top">
<div class="container-fluid">
<div class="box">
<div class="box-header">
<i class="fa fa-envelope"></i>
<h3 class="box-title">TAMBAH SURAT KELUAR</h3>
<!-- tools box -->
</div>
<section class="content">
<!-- quick email widget -->
<div class="row">
<div class="col-xl-6 col-sm-12 mb-3">
<div class="card text-black o-hidden h-100">
<div class="card-body">
<div class="card-body-icon">
<i class=""></i>
</div>
<div class="mr-5">SURAT KETERANGAN</div>
</div>
<a class="card-footer text-black clearfix small z-1" href="<?= base_url('surat/surat/s_keterangan'); ?>">
<span class="float-left">Tambah Surat</span>
<span class="float-right">
<i class="fas fa-angle-right"></i>
</span>
</a>
</div>
</div>
<div class="col-xl-6 col-sm-12 mb-3">
<div class="card text-black o-hidden h-100">
<div class="card-body">
<div class="card-body-icon">
<i class=""></i>
</div>
<div class="mr-5">SURAT PERNYATAAN</div>
</div>
<a class="card-footer text-black clearfix small z-1" href="<?= base_url('surat/surat/s_pernyataan'); ?>">
<span class="float-left">Tambah Surat</span>
<span class="float-right">
<i class="fas fa-angle-right"></i>
</span>
</a>
</div>
</div>
<!---<div class="col-xl-6 col-sm-12 mb-3">
<div class="card text-black o-hidden h-100">
<div class="card-body">
<div class="card-body-icon">
<i class=""></i>
</div>
<div class="mr-5">SURAT UNDANGAN</div>
</div>
<a class="card-footer text-black clearfix small z-1" href="<?= base_url('surat/surat/s_undangan'); ?>">
<span class="float-left">Tambah Surat</span>
<span class="float-right">
<i class="fas fa-angle-right"></i>
</span>
</a>
</div>
</div>!--->
</section>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends CI_Controller {
public function index()
{
$this->load->view('formLogin');
}
public function process(){
$post = $this->input->post(null,TRUE);
if(isset($post['auth'])){
$this->load->model('m_user');
$user = $post['username'];
$pw = <PASSWORD>($post['password']);
$query = $this->m_user->login($user,$pw);
if($query->num_rows() > 0){
$row = $query->row();
$params =array(
'id' => $row->id
);
$this->session->set_userdata($params);
echo "<script> alert('Selamat, login berhasil'); window.location='".site_url('dashboard')."'; </script>";
} else {
echo "<script> alert('Login gagal'); window.location='".site_url('auth')."'; </script>";
}
}
} public function logout(){
$params = array('id');
$this->session->unset_userdata($params);
redirect('auth');
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dashboarduser extends CI_Controller {
public function index()
{
$this->load->view('template_user/header');
$this->load->view('template_user/topbar');
$this->load->view('user penduduk/dashboard');
$this->load->view('template_user/footer');
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Surat extends CI_Controller {
function __construct(){
parent::__construct();
//$this->load->model('m_masuk');
//$this->load->helper(array('url','download'));
check_not_login();
$this->load->library('form_validation');
}
public function index()
{
$data = [
//'row' => $this->m_masuk->get(),
'title' => "Surat Masuk"
];
//$data['row'] = $this->m_masuk->get();
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('eksternal_surat/s_warga', $data);
$this->load->view('template_admin/footer', $data);
}
public function s_keterangan()
{
$jenis_surat = $this->uri->segment(4);
$id_surat = $this->uri->segment(5);
$data_surat = $this->db->get_where('penduduk', ['id' => $id_surat])->row_array();
if ($jenis_surat == 'Surat_Kelahiran') {
$data_surat = $this->db->select('*')->from('surat_kelahiran')->join('penduduk', 'penduduk.id=surat_kelahiran.id_penduduk')->where(['surat_kelahiran.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat_Keterangan_Usaha') {
$data_surat = $this->db->select('*')->from('surat_sku')->join('penduduk', 'penduduk.id=surat_sku.id_penduduk')->where(['surat_sku.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat_Kematian') {
$data_surat = $this->db->select('*')->from('surat_kematian')->join('penduduk', 'penduduk.id=surat_kematian.id_penduduk')->where(['surat_kematian.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat_Nikah') {
$data_surat = $this->db->select('*')->from('surat_nikah')->join('penduduk', 'penduduk.id=surat_nikah.id_penduduk')->where(['surat_nikah.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat_Pindah_Daerah') {
$data_surat = $this->db->select('*')->from('surat_pindah_domisili')->join('penduduk', 'penduduk.id=surat_pindah_domisili.id_penduduk')->where(['surat_pindah_domisili.id' => $id_surat])->get()->row_array();
}
$data = [
'data_surat' => $data_surat,
'title' => "Surat Keluar"
];
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('eksternal_surat/s_keterangan', $data);
$this->load->view('template_admin/footer', $data);
}
public function s_pernyataan()
{
$data = [
//'row' => $this->m_masuk->get(),
'title' => "Surat Masuk"
];
//$data['row'] = $this->m_masuk->get();
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('eksternal_surat/s_pernyataan', $data);
$this->load->view('template_admin/footer', $data);
}
public function s_undangan()
{
$data = [
//'row' => $this->m_masuk->get(),
'title' => "Surat Masuk"
];
//$data['row'] = $this->m_masuk->get();
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('eksternal_surat/s_undangan', $data);
$this->load->view('template_admin/footer', $data);
}
public function cetak_pdf(){
$id_surat = $this->input->post('id_surat');
$jenis_surat = $this->input->post('jenis_surat');
$ttd = explode("%",$this->input->post('ttd'));
$template_surat = null;
$nama_ttd = $ttd[0];
$jabatan_ttd = $ttd[1];
$proses_surat = 'Finish';
$data_surat = null;
if ($jenis_surat == 'Surat_Kelahiran') {
$template_surat = "print/surat_kelahiran.php";
$data_surat = $this->db->select('*')->from('surat_kelahiran')->join('penduduk', 'penduduk.id=surat_kelahiran.id_penduduk')->where(['surat_kelahiran.id' => $id_surat])->get()->row_array();
if ($data_surat['proses_surat'] != $proses_surat){
$this->db->update('surat_kelahiran', ['proses_surat' => $proses_surat, 'jabatan_ttd' => $jabatan_ttd, 'nama_ttd' => $nama_ttd], ['id' => $id_surat]);
}
// send email
if ($data_surat['send_notif'] == 0) {
$this->send_email(
array(
'receiver' => $data_surat['email'],
'subject' => 'Pengajuan Surat Kelurahan Gandrungmangu',
'message' => "Assalamu'alaikum Wr. Wb <br>
Pengajuan surat anda telah disetujui dan telah dicetak, silakan mengambilnya di Kelurahan Gandrungmangu, Terimakasih. <br>
<br>
Hormat kami, <br>
<NAME><br>"
)
);
// update send_notif
$this->db->update('surat_kelahiran', ['send_notif' => 1], ['id' => $id_surat]);
}
}elseif ($jenis_surat == 'Surat_Keterangan_Usaha') {
$template_surat = "print/surat_sku.php";
$data_surat = $this->db->select('*')->from('surat_sku')->join('penduduk', 'penduduk.id=surat_sku.id_penduduk')->where(['surat_sku.id' => $id_surat])->get()->row_array();
if ($data_surat['proses_surat'] != $proses_surat){
$this->db->update('surat_sku', ['proses_surat' => $proses_surat, 'jabatan_ttd' => $jabatan_ttd, 'nama_ttd' => $nama_ttd], ['id' => $id_surat]);
}
// send email
if ($data_surat['send_notif'] == 0) {
$this->send_email(
array(
'receiver' => $data_surat['email'],
'subject' => 'Pengajuan Surat Kelurahan Gandrungmangu',
'message' => "Assalamu'alaikum Wr. Wb <br>
Pengajuan surat anda telah disetujui dan telah dicetak, silakan mengambilnya di Kelurahan Gandrungmangu, Terimakasih. <br>
<br>
Hormat kami, <br>
<NAME><br>"
)
);
// update send_notif
$this->db->update('surat_sku', ['send_notif' => 1], ['id' => $id_surat]);
}
}elseif ($jenis_surat == 'Surat_Kematian') {
$template_surat = "print/surat_kematian.php";
$data_surat = $this->db->select('*')->from('surat_kematian')->join('penduduk', 'penduduk.id=surat_kematian.id_penduduk')->where(['surat_kematian.id' => $id_surat])->get()->row_array();
if ($data_surat['proses_surat'] != $proses_surat){
$this->db->update('surat_kematian', ['proses_surat' => $proses_surat, 'jabatan_ttd' => $jabatan_ttd, 'nama_ttd' => $nama_ttd], ['id' => $id_surat]);
}
// send email
if ($data_surat['send_notif'] == 0) {
$this->send_email(
array(
'receiver' => $data_surat['email'],
'subject' => 'Pengajuan Surat Kelurahan Gandrungmangu',
'message' => "Assalamu'alaikum Wr. Wb <br>
Pengajuan surat anda telah disetujui dan telah dicetak, silakan mengambilnya di Kelurahan Gandrungmangu, Terimakasih. <br>
<br>
Hormat kami, <br>
<NAME><br>"
)
);
// update send_notif
$this->db->update('surat_kematian', ['send_notif' => 1], ['id' => $id_surat]);
}
}elseif ($jenis_surat == 'Surat_Nikah') {
$template_surat = "print/surat_nikah.php";
$data_surat = $this->db->select('*')->from('surat_nikah')->join('penduduk', 'penduduk.id=surat_nikah.id_penduduk')->where(['surat_nikah.id' => $id_surat])->get()->row_array();
if ($data_surat['proses_surat'] != $proses_surat){
$this->db->update('surat_nikah', ['proses_surat' => $proses_surat, 'jabatan_ttd' => $jabatan_ttd, 'nama_ttd' => $nama_ttd], ['id' => $id_surat]);
}
// send email
if ($data_surat['send_notif'] == 0) {
$this->send_email(
array(
'receiver' => $data_surat['email'],
'subject' => 'Pengajuan Surat Kelurahan Gandrungmangu',
'message' => "Assalamu'alaikum Wr. Wb <br>
Pengajuan surat anda telah disetujui dan telah dicetak, silakan mengambilnya di Kelurahan Gandrungmangu, Terimakasih. <br>
<br>
Hormat kami, <br>
<NAME><br>"
)
);
// update send_notif
$this->db->update('surat_nikah', ['send_notif' => 1], ['id' => $id_surat]);
}
}elseif ($jenis_surat == 'Surat_Pindah_Daerah') {
$template_surat = "print/surat_pindah_daerah.php";
$data_surat = $this->db->select('*')->from('surat_pindah_domisili')->join('penduduk', 'penduduk.id=surat_pindah_domisili.id_penduduk')->where(['surat_pindah_domisili.id' => $id_surat])->get()->row_array();
if ($data_surat['proses_surat'] != $proses_surat){
$this->db->update('surat_pindah_domisili', ['proses_surat' => $proses_surat, 'jabatan_ttd' => $jabatan_ttd, 'nama_ttd' => $nama_ttd], ['id' => $id_surat]);
}
// send email
if ($data_surat['send_notif'] == 0) {
$this->send_email(
array(
'receiver' => $data_surat['email'],
'subject' => 'Pengajuan Surat Kelurahan Gandrungmangu',
'message' => "Assalamu'alaikum Wr. Wb <br>
Pengajuan surat anda telah disetujui dan telah dicetak, silakan mengambilnya di Kelurahan Gandrungmangu, Terimakasih. <br>
<br>
Hormat kami, <br>
<NAME><br>"
)
);
// update send_notif
$this->db->update('surat_pindah_domisili', ['send_notif' => 1], ['id' => $id_surat]);
}
}
$month = explode("-",$data_surat['tanggal']);
$dateObj = DateTime::createFromFormat('!m', $month[1]);
$monthName = $dateObj->format('F'); // March
$str_month = $month[1] . ' ' . $monthName . ' ' . $month[0];
$data_surat['tanggal'] = $str_month;
$data = [
"data_surat" =>$data_surat,
"nama_ttd" => $ttd[0],
"jabatan_ttd" => $ttd[1]
];
$this->load->view($template_surat, $data);
}
private function send_email($data)
{
// Konfigurasi email
$config = [
'mailtype' => 'html',
'charset' => 'utf-8',
'protocol' => 'smtp',
'smtp_host' => 'smtp.gmail.com',
'smtp_user' => '<EMAIL>', // Email gmail
'smtp_pass' => '<PASSWORD>', // Password gmail
'smtp_crypto' => 'ssl',
'smtp_port' => 465,
'crlf' => "\r\n",
'newline' => "\r\n"
];
// Load library email dan konfigurasinya
$this->load->library('email', $config);
// Email dan nama pengirim
$this->email->from('<EMAIL>', '<NAME>');
// Email penerima
$this->email->to($data['receiver']); // Ganti dengan email tujuan
// Subject email
$this->email->subject($data['subject']);
// Isi email
$this->email->message($data['message']);
$this->email->send();
}
}
?><file_sep><body id="page-top">
<div class="container-fluid">
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800">Tambah Data</h1>
</div>
<form action="<?= base_url('penduduk/proses'); ?>" method="post">
<div class="form-group">
<label for="form_name">Nama *</label>
<input value="<?=$row->id?>" id="form_name" type="hidden" name="id" class="form-control" placeholder="Silahkan masukkan nama anda *" required="required" data-error="Nama harus diisi!.">
<input value="<?=$row->nama?>" id="form_name" type="text" name="nama" class="form-control" placeholder="Silahkan masukkan nama anda *" required="required" data-error="Nama harus diisi!.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_lastname">NIK *</label>
<input value="<?=$row->NIK?>" id="form_lastname" type="text" name="NIK" class="form-control" placeholder="Silahkan masukkan NIK anda *" required="required" data-error="NIK Harus diisi!.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_wa">Jenis Kelamin *</label>
<select value="<?=$row->jk?>" name="jk" class="form-control" id="sel1" required>
<option value="" selected disabled>Choose...</option>
<?php
if ($row->jk == 'Laki-laki') {
echo '<option selected value="Laki-laki">Laki-laki</option>';
echo '<option value="Perempuan">Perempuan</option>';
}else{
echo '<option value="Laki-laki">Laki-laki</option>';
echo '<option selected value="Perempuan">Perempuan</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="form_alamat">Alamat *</label>
<textarea value="<?=$row->alamat?>" required name="alamat" class="form-control" rows="3" id="comment" placeholder="Silahkan masukkan alamat anda" ><?=$row->alamat?></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_wa">Agama *</label>
<input type="text" value="<?=$row->agama?>" required name="agama" class="form-control" id="sel1">
</input>
</div>
<div class="form-group">
<label for="form_wa">Tempat tanggal lahir *</label>
<input value="<?=$row->tempat_tgl_lahir?>" id="form_wa" type="text" name="tempat_tgl_lahir" class="form-control" placeholder="Silahkan masukkan tempat tanggal lahir anda *" required="required" data-error="Format no salah.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_wa">Email </label>
<input value="<?=$row->email?>" id="form_wa" type="email" name="email" class="form-control" placeholder="silakan kosongi jika tidak ada data email" data-error="Format no salah.">
<SMALL>
Ketik email yang aktif karena notifikasi akan dikirim melalui email.
</SMALL>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_wa">Pekerjaan</label>
<input value="<?=$row->pekerjaan?>" id="form_wa" type="text" name="pekerjaan" class="form-control" placeholder="Silahkan masukkan pekerjaan anda *" required="required" data-error="Format no salah.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_wa">Status perkawinan</label>
<select value="<?=$row->status?>" required name="status" class="form-control" id="sel1">
<option value="" selected disabled>Choose...</option>
<?php
if ($row->jk == 'Kawin') {
echo '<option selected value="Kawin">Kawin</option>';
echo '<option value="Belum Kawin">Belum Kawin</option>';
}else{
echo '<option value="Kawin">Kawin</option>';
echo '<option selected value="Belum Kawin">Belum Kawin</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="form_wa">Whatsapp</label>
<input value="<?=$row->wa?>" id="form_wa" type="text" name="wa" class="form-control" placeholder="Silahkan masukkan nomor whatsapp anda *" required="required" data-error="Format no salah.">
</div>
<div class="form-group">
<button type="submit" name="<?=$page?>" class="btn btn-success btn-flat">
<i class="fa fa-paper-plane"></i> Save</button>
</div>
</form>
</div>
<file_sep><?php
class M_dashboard extends CI_Model{
public function GetStatistikSuratKeluar($bulan){
$sql = "
SELECT COUNT(id) AS `jumlah_surat` FROM (
SELECT surat_kematian.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, surat_nikah ,null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_kematian JOIN penduduk ON surat_kematian.id_penduduk=penduduk.id
UNION ALL
SELECT surat_nikah.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, ktp_ortu, kk, null as surat_nikah ,null as surat_keterangan_rs, ktp, akta_kelahiran, ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_nikah JOIN penduduk ON surat_nikah.id_penduduk=penduduk.id
UNION ALL
SELECT surat_pindah_domisili.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_pindah_domisili JOIN penduduk ON surat_pindah_domisili.id_penduduk=penduduk.id
UNION ALL
SELECT surat_sku.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_sku JOIN penduduk ON surat_sku.id_penduduk=penduduk.id
) AS surat_keluar
WHERE surat_keluar.proses_surat='Finish' AND MONTH(surat_keluar.tanggal)=$bulan
";
return $this->db->query($sql)->row_array();
}
public function GetStatistikSuratMasuk($bulan)
{
$sql = "
SELECT COUNT(no) AS `jumlah_surat` FROM tb_masuk
WHERE MONTH(tgl_terima)=$bulan
";
return $this->db->query($sql)->row_array();
}
public function CountSuratKeluar()
{
$sql = "
SELECT COUNT(id) AS `jumlah_surat` FROM (
SELECT surat_kematian.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, surat_nikah ,null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_kematian JOIN penduduk ON surat_kematian.id_penduduk=penduduk.id
UNION ALL
SELECT surat_nikah.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, ktp_ortu, kk, null as surat_nikah ,null as surat_keterangan_rs, ktp, akta_kelahiran, ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_nikah JOIN penduduk ON surat_nikah.id_penduduk=penduduk.id
UNION ALL
SELECT surat_pindah_domisili.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_pindah_domisili JOIN penduduk ON surat_pindah_domisili.id_penduduk=penduduk.id
UNION ALL
SELECT surat_sku.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_sku JOIN penduduk ON surat_sku.id_penduduk=penduduk.id
) AS surat_keluar
WHERE surat_keluar.proses_surat='Finish'
";
return $this->db->query($sql)->row_array();
}
}
?>
<file_sep><div class="container-fluid">
<div class="table-responsive">
<div class="card mb-3">
<div class="card-header">
<i class=""></i>
Surat Tugas
</div>
<form method='post' action=''>
<div class="container-fluid"></br>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>Jenis Surat : </label>
<input type="text" width="50%" name="jenis_surat" class="form-control" value="Surat Tugas" readonly required/>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Nomor Surat :</label>
<input type="text" name="no_surat" class="form-control" placeholder="Nomor Surat" value="<?=$no_surat?>" readonly required />
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Tanggal Surat :</label>
<input id="tanggal_surat" type="date" name="tanggal_surat" class="form-control" placeholder="Nomor Surat" value="" required />
</div>
</div>
</div>
</br>
<div class="table-responsive">
<div class="card mb-3">
<div class="card-header">
<i class=""></i>
Data Perangkat Desa
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>No</th>
<th>Pilih</th>
<th>NIK</th>
<th>Nama</th>
<th>Jabatan</th>
<th>Divisi</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php $id = 1;;
foreach ($data_perangkat_desa as $data) { ?>
<tr>
<td><?= $id++ ?>.</td>
<td><input required type='radio' name='id_perangkat_desa' value='<?= $data->id; ?>' />
</td>
<td><?= $data->nik ?></td>
<td><?= $data->nama ?></td>
<td><?= $data->jabatan ?></td>
<td><?= $data->divisi ?></td>
<td><?= $data->status ?></td>
</tr>
<?php
} ?>
</tbody>
</table>
</div>
</div>
</div>
<small id="emailHelp" class="form-text text-muted">Silakan ganti titik(........) sesuai dengan kebutuhan anda.</small>
<textarea rows="10" name="kontent" id="textarea" class="form-control">
Untuk mengikuti kegiatan<strong> ......................</strong> yang akan dilaksanakan pada :
<table id="tabel" style="margin-left: 100px;" width="55%">
<tr>
<td width="15%">Tanggal</td>
<td width="2%"> : </td>
<td width="40%"></td>
</tr>
<tr>
<td>Waktu</td>
<td> : </td>
<td ></td>
</tr>
<tr>
<td>Tempat</td>
<td> : </td>
<td></td>
</tr>
<tr>
<td>Acara</td>
<td> : </td>
<td></td>
</tr>
<tr>
<td>Catatan</td>
<td> : </td>
<td></td>
</tr>
</table>
</textarea>
</div></br>
<select name="ttd" class="form-control" required >
<option value="">---Pilih TTD---</option>
<option value="Ahmad Husin%Camat">Camat</option>
<option value="Suyatno%Sekretaris Camat">Sekretaris Camat</option>
</select></br>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
<button type="submit" class="btn btn-primary">Buat</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- /.content-wrapper -->
</div>
<!-- /#wrapper -->
<script src="<?= base_url() ?>plugins/tinymce/tinymce.min.js"></script>
<script>
tinymce.init({
selector: "#textarea",theme: "modern",height: 220,
plugins: [
"advlist autolink link image lists charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars insertdatetime media nonbreaking",
"table contextmenu directionality emoticons paste textcolor"
],
toolbar1: "undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | styleselect",
toolbar2: "| link unlink anchor | image media | forecolor backcolor | print preview code ",
image_advtab: true ,
});
// config tanggal surat
$('#tanggal_surat').on('change', function(){
var tgl_surat = $('#tanggal_surat').val()
var arr_tgl = tgl_surat.split("-")
var bulan = ['Januari', 'Februari', 'Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
var html = `
Untuk mengikuti kegiatan<strong> ......................</strong> yang akan dilaksanakan pada :
<table id="tabel" style="margin-left: 100px;" width="55%">
<tr>
<td width="15%">Tanggal</td>
<td width="2%"> : </td>
<td width="40%">${arr_tgl[2]}, ${bulan[parseInt(arr_tgl[1])]} ${arr_tgl[0]}</td>
</tr>
<tr>
<td>Waktu</td>
<td> : </td>
<td ></td>
</tr>
<tr>
<td>Tempat</td>
<td> : </td>
<td></td>
</tr>
<tr>
<td>Acara</td>
<td> : </td>
<td></td>
</tr>
<tr>
<td>Catatan</td>
<td> : </td>
<td></td>
</tr>
</table>
`
tinymce.activeEditor.setContent(html);
})
</script><file_sep><body id="page-top">
<div class="container-fluid">
<div class="box">
<div class="box-header">
<h1 class="h4 mb-0 text-gray-800">Tambah Data</h1>
<div align="right">
<a href="<?=site_url('suratmasuk')?>" class="btn btn-warning btn-flat">
<i class="fa fa-undo"></i> Back </a>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-md-4 col-md-offset-4">
</div>
<form action="<?= base_url('suratmasuk/proses2'); ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>No. Surat</label>
<input type="hidden" name="no" value="<?=$row->no?>">
<input type="text" name="no_surat" value="<?= $row->no_surat?>" class="form-control" required>
</div>
<div class="form-group">
<label>Pengirim</label>
<input type="text" name="pengirim" value="<?= $row->pengirim?>" class="form-control" required>
</div>
<div class="form-group">
<label>Tanggal Surat</label>
<input type="date" name="tgl_surat" value="<?= $row->tgl_surat?>" class="form-control" required>
</div>
<div class="form-group">
<label>Tanggal Terima</label>
<input type="date" name="tgl_terima" value="<?= $row->tgl_terima?>" class="form-control" required>
</div>
<div class="form-group">
<label>Keterangan</label>
<textarea name="keterangan" class="form-control"><?php echo $row->keterangan;?></textarea>
</div>
<div class="form-group">
<label>File Surat</label>
<input type="file" name="file_surat" class="form-control"><?php echo $row->file_surat;?>
<small class="text-sm text-info">Format file yang diizinkan .jpg, .png, .pdf, .doc dan ukuran maks 1 MB!</small>
</div>
<div class="form-group">
<button type="submit" name="<?=$page?>" class="btn btn-success btn-flat">
<i class="fa fa-paper-plane"></i> Save</button>
<!---<button type="reset" class="btn btn-flat">Reset</button>!--->
</div>
</div>
</form>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class SuratPengantar extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('m_suratpengantar');
$this->load->library('form_validation');
$this->load->helper('my_helper');
}
public function index()
{
$data['ambil_data']= $this->m_suratpengantar->get()->result_array();
$this->load->view('template_user/header', $data);
$this->load->view('template_user/topbar', $data);
//$this->load->view('user penduduk/layanan', $data);
$this->load->view('template_user/footer', $data);
}
public function add_surat_general()
{
$nama = $this->input->post('nama');
$NIK = $this->input->post('NIK');
$email = $this->input->post('email');
$penduduk = null;
$checkPenduduk = $this->db->get_where('penduduk', ['NIK' => $NIK, 'nama' => $nama])->num_rows();
// check user penduduk
if ($checkPenduduk >= 1) {
$penduduk = $this->db->get_where('penduduk', ['NIK' => $NIK, 'nama' => $nama])->row_array();
if ($email != '') {
$this->db->update('penduduk', ['email' => $email], ['NIK' => $NIK, 'nama' => $nama]);
}
}else{
// Insert data to penduduk
$dataInfoPenduduk = array();
$dataInfoSurat = array();
foreach (array_keys($_POST) as $key) {
$dataInfoPenduduk[$key] = $this->input->post($key);
}
unset($dataInfoPenduduk['jenis_surat']);
unset($dataInfoPenduduk['keterangan']);
if ($this->input->post('jenis_surat') == 'Surat Pindah Daerah') {
unset($dataInfoPenduduk['alamat_pindah']);
unset($dataInfoPenduduk['alasan_pindah']);
unset($dataInfoPenduduk['pengikut']);
} else if ($this->input->post('jenis_surat') == 'Surat Kematian') {
unset($dataInfoPenduduk['hari_meninggal']);
unset($dataInfoPenduduk['jam_meninggal']);
} else if ($this->input->post('jenis_surat') == 'Surat Keterangan Usaha') {
unset($dataInfoPenduduk['nama_usaha']);
}
$this->db->insert('penduduk', $dataInfoPenduduk);
$penduduk = $this->db->get_where('penduduk', ['NIK' => $NIK, 'nama' => $nama])->row_array();
}
// insert data to surat general
$this->load->library('upload');
$this->upload->initialize($this->set_upload_options());
foreach (array_keys($_FILES) as $key) {
if ( ! $this->upload->do_upload($key)){
$error = array('error' => $this->upload->display_errors());
print_r($error);
}else{
$dataInfoSurat[$key] = $this->upload->data('file_name');
}
}
$dataInfoSurat['tanggal'] = Date('Y-m-d');
$dataInfoSurat['keterangan'] = $this->input->post('keterangan');
$dataInfoSurat['id_penduduk'] = $penduduk['id'];
if ($this->input->post('jenis_surat') == 'Surat Pindah Daerah') {
$dataInfoSurat['alamat_pindah'] = $this->input->post('alamat_pindah');
$dataInfoSurat['alasan_pindah'] = $this->input->post('alasan_pindah');
$dataInfoSurat['pengikut'] = $this->input->post('pengikut');
$this->db->insert('surat_pindah_domisili', $dataInfoSurat);
} else if ($this->input->post('jenis_surat') == 'Surat Nikah') {
$this->db->insert('surat_nikah', $dataInfoSurat);
} else if ($this->input->post('jenis_surat') == 'Surat Kematian') {
$dataInfoSurat['hari_meninggal'] = $this->input->post('hari_meninggal');
$dataInfoSurat['jam_meninggal'] = $this->input->post('jam_meninggal');
$this->db->insert('surat_kematian', $dataInfoSurat);
} else if ($this->input->post('jenis_surat') == 'Surat Keterangan Usaha') {
$dataInfoSurat['nama_usaha'] = $this->input->post('nama_usaha');
$this->db->insert('surat_sku', $dataInfoSurat);
}
echo "<script> alert('Data berhasil disimpan');</script>";
echo "<script>window.location='".site_url('DashboardUser')."';</script>";
}
private function set_upload_options()
{
$config = array();
$config['upload_path'] = './media/surat';
$config['allowed_types'] = 'jpeg|jpg|png|pdf|doc';
$config['max_size'] = 3000;
return $config;
}
public function add(){
$data = [
'row' => $this->m_suratpengantar->get(),
//'row' => $pengantar,
'title' => "Permintaan Surat"
];
$pengantar = new stdClass();
$pengantar->nama = null;
$pengantar->NIK = null;
$pengantar->alamat = null;
$pengantar->whatsapp = null;
$pengantar->keperluan = null;
$pengantar->keterangan = null;
$pengantar->file_surat = null;
if ($this->form_validation->run() == FALSE){
$post = $this->input->post(null, TRUE);
$this->m_suratpengantar->add($post);
if($this->db->affected_rows() > 0 ){
echo "<script> alert('Data berhasil disimpan');</script>";
}
echo "<script>window.location='".site_url('suratPengantar')."';</script>";
}
}
public function permintaan_surat_datatabel(){
$list = $this->m_suratpengantar->get_datatables();
$data = array();
$no = $_POST['start'];
$type=$this->input->get('type');
foreach ($list as $field) {
$jenis_surat = "'".$field->jenis_surat."'";
$nama = "'".$field->nama."'";
$nik = "'".$field->nik."'";
$proses_surat = "'".$field->proses_surat."'";
$JenisSurat = str_replace(' ', '_', $field->jenis_surat);
$tombol_proses_surat = '<a onClick="proses_button('.$field->id.','.$jenis_surat.','.$nama.','.$nik.','.$proses_surat.')" class="btn btn-danger btn-xs" onclick="konfirmasi()" >Process</a>';
$tombol_buat_surat = '<a href="../surat/Surat/'.$field->id.'" class="btn btn-primary disabled btn-xs" >Buat Surat</a> ';
if ($field->proses_surat == 'Accepted') {
$tombol_buat_surat = '<a href="../surat/Surat/s_keterangan/'.$JenisSurat.'/'.$field->id.'" class="btn btn-primary btn-xs" >Buat Surat</a> ';
$tombol_proses_surat = '<a onClick="proses_button('.$field->id.','.$jenis_surat.','.$nama.','.$nik.','.$proses_surat.')" class="btn btn-success btn-xs" onclick="konfirmasi()" >Accepted</a>';
}else if($field->proses_surat == 'Rejected'){
$tombol_proses_surat = '<a onClick="proses_button('.$field->id.','.$jenis_surat.','.$nama.','.$nik.','.$proses_surat.')" class="btn btn-warning btn-xs" onclick="konfirmasi()" >Rejected</a>';
}else if($field->proses_surat == 'Finish'){
$tombol_proses_surat = '<a onClick="proses_button('.$field->id.','.$jenis_surat.','.$nama.','.$nik.','.$proses_surat.')" class="btn btn-success btn-xs" onclick="konfirmasi()" >Finish</a>';
}
$no++;
$row = array();
$row['no'] = $no;
$row['NIK'] = $field->nik;
$row['nama'] = $field->nama;
$row['alamat'] = $field->alamat;
$row['email'] = $field->email;
$row['jenis_surat'] = $field->jenis_surat;
$row['keterangan'] = $field->keterangan;
$row['proses_surat'] = $tombol_proses_surat;
$row['kk'] = $field->kk;
$row['kode_surat'] = $field->kode_surat;
$row['ktp'] = $field->ktp;
$row['ktp_ortu'] = $field->ktp_ortu;
$row['no_surat'] = $field->no_surat;
$row['surat_keterangan_rs'] = $field->surat_keterangan_rs;
$row['surat_nikah'] = $field->surat_nikah;
$row['surat_rt_rw'] = $field->surat_rt_rw;
$row['tanggal'] = $field->tanggal;
$row['akta_kelahiran'] = $field->akta_kelahiran;
$row['ijazah'] = $field->ijazah;
$row['aksi'] = $tombol_buat_surat;
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->m_suratpengantar->count_all(),
"recordsFiltered" => $this->m_suratpengantar->count_filtered(),
"data" => $data,
);
echo json_encode($output);
}
public function permintaan(){
$data = [
'row' => $this->m_suratpengantar->get()->result(),
'title' => "Permintaan Surat"
];
$this->load->view('template_admin/header',$data);
$this->load->view('template_admin/sidebar');
$this->load->view('permintaan_surat/permintaan',$data);
$this->load->view('template_admin/footer',$data);
}
public function proses_permintaan_surat(){
$id = $this->input->post('id');
$jenis_surat = $this->input->post('jenis_surat');
$proses_surat = $this->input->post('proses_surat');
$no_surat = no_surat_keterangan();
$alasan = $this->input->post('alasan');
// print_r($no_surat);
// die;
$pesan = null;
if ($jenis_surat == 'Surat Kematian') {
if($proses_surat == 'Accepted' ){
$this->db->update('surat_kematian', ['proses_surat' => $proses_surat, 'no_surat' => $no_surat], ['id' => $id]);
}
if ($alasan != '') {
$this->db->update('surat_kematian', ['proses_surat' => $proses_surat, 'alasan_reject' => $alasan], ['id' => $id]);
}
$data_surat = $this->db->select('*')->from('surat_kematian')->join('penduduk', 'penduduk.id=surat_kematian.id_penduduk')->where(['surat_kematian.id' => $id])->get()->row_array();
if ($data_surat['alasan_reject'] != '') {
$this->send_email(
array(
'receiver' => $data_surat['email'],
'subject' => 'Pengajuan Surat Kelurahan Gandrungmangu',
'message' => sprintf("Assalamu'alaikum Wr. Wb <br>
Maaf Pengajuan surat anda ditolak dengan alasan <strong>%s</strong>, silakan melakukan permintaan surat kembali dengan pengisian data lebih cermat, Terimakasih. <br>
<br>
Hormat kami, <br>
<NAME><br>", $data_surat['alasan_reject'] )
)
);
}
}elseif ($jenis_surat == 'Surat Kelahiran') {
if($proses_surat == 'Accepted' ){
$this->db->update('surat_kelahiran', ['proses_surat' => $proses_surat, 'no_surat' => $no_surat], ['id' => $id]);
}
if ($alasan != '') {
$this->db->update('surat_kelahiran', ['proses_surat' => $proses_surat, 'alasan_reject' => $alasan], ['id' => $id]);
}
$data_surat = $this->db->select('*')->from('surat_kelahiran')->join('penduduk', 'penduduk.id=surat_kelahiran.id_penduduk')->where(['surat_kelahiran.id' => $id])->get()->row_array();
if ($data_surat['alasan_reject'] != '') {
$this->send_email(
array(
'receiver' => $data_surat['email'],
'subject' => 'Pengajuan Surat Kelurahan Gandrungmangu',
'message' => sprintf("Assalamu'alaikum Wr. Wb <br>
Maaf Pengajuan surat anda ditolak dengan alasan <strong>%s</strong>, silakan melakukan permintaan surat kembali dengan pengisian data lebih cermat, Terimakasih. <br>
<br>
Hormat kami, <br>
<NAME><br>", $data_surat['alasan_reject'] )
)
);
}
}elseif ($jenis_surat == 'Surat Nikah') {
if($proses_surat == 'Accepted' ){
$this->db->update('surat_nikah', ['proses_surat' => $proses_surat, 'no_surat' => $no_surat], ['id' => $id]);
}
if ($alasan != '') {
$this->db->update('surat_nikah', ['proses_surat' => $proses_surat, 'alasan_reject' => $alasan], ['id' => $id]);
}
$data_surat = $this->db->select('*')->from('surat_nikah')->join('penduduk', 'penduduk.id=surat_nikah.id_penduduk')->where(['surat_nikah.id' => $id])->get()->row_array();
if ($data_surat['alasan_reject'] != '') {
$this->send_email(
array(
'receiver' => $data_surat['email'],
'subject' => 'Pengajuan Surat Kelurahan Gandrungmangu',
'message' => sprintf("Assalamu'alaikum Wr. Wb <br>
Maaf Pengajuan surat anda ditolak dengan alasan <strong>%s</strong>, silakan melakukan permintaan surat kembali dengan pengisian data lebih cermat, Terimakasih. <br>
<br>
Hormat kami, <br>
<NAME><br>", $data_surat['alasan_reject'] )
)
);
}
}elseif ($jenis_surat == 'Surat Pindah Daerah') {
if($proses_surat == 'Accepted' ){
$this->db->update('surat_pindah_domisili', ['proses_surat' => $proses_surat, 'no_surat' => $no_surat], ['id' => $id]);
}
if ($alasan != '') {
$this->db->update('surat_pindah_domisili', ['proses_surat' => $proses_surat, 'alasan_reject' => $alasan], ['id' => $id]);
}
$data_surat = $this->db->select('*')->from('surat_pindah_domisili')->join('penduduk', 'penduduk.id=surat_pindah_domisili.id_penduduk')->where(['surat_pindah_domisili.id' => $id])->get()->row_array();
if ($data_surat['alasan_reject'] != '') {
$this->send_email(
array(
'receiver' => $data_surat['email'],
'subject' => 'Pengajuan Surat Kelurahan Gandrungmangu',
'message' => sprintf("Assalamu'alaikum Wr. Wb <br>
Maaf Pengajuan surat anda ditolak dengan alasan <strong>%s</strong>, silakan melakukan permintaan surat kembali dengan pengisian data lebih cermat, Terimakasih. <br>
<br>
Hormat kami, <br>
<NAME><br>", $data_surat['alasan_reject'] )
)
);
}
}elseif ($jenis_surat == 'Surat Keterangan Usaha') {
if($proses_surat == 'Accepted' ){
$this->db->update('surat_sku', ['proses_surat' => $proses_surat, 'no_surat' => $no_surat], ['id' => $id]);
}
if ($alasan != '') {
$this->db->update('surat_sku', ['proses_surat' => $proses_surat, 'alasan_reject' => $alasan], ['id' => $id]);
}
$data_surat = $this->db->select('*')->from('surat_sku')->join('penduduk', 'penduduk.id=surat_sku.id_penduduk')->where(['surat_sku.id' => $id])->get()->row_array();
if ($data_surat['alasan_reject'] != '') {
$this->send_email(
array(
'receiver' => $data_surat['email'],
'subject' => 'Pengajuan Surat Kelurahan Gandrungmangu',
'message' => sprintf("Assalamu'alaikum Wr. Wb <br>
Maaf Pengajuan surat anda ditolak dengan alasan <strong>%s</strong>, silakan melakukan permintaan surat kembali dengan pengisian data lebih cermat, Terimakasih. <br>
<br>
Hormat kami, <br>
<NAME><br>", $data_surat['alasan_reject'] )
)
);
}
}
$output = array(
"proses_permintaan_surat" => $jenis_surat,
);
echo json_encode($output);
}
private function send_email($data)
{
// Konfigurasi email
$config = [
'mailtype' => 'html',
'charset' => 'utf-8',
'protocol' => 'smtp',
'smtp_host' => 'smtp.gmail.com',
'smtp_user' => '<EMAIL>', // Email gmail
'smtp_pass' => '<PASSWORD>', // Password gmail
'smtp_crypto' => 'ssl',
'smtp_port' => 465,
'crlf' => "\r\n",
'newline' => "\r\n"
];
// Load library email dan konfigurasinya
$this->load->library('email', $config);
// Email dan nama pengirim
$this->email->from('<EMAIL>', '<NAME>');
// Email penerima
$this->email->to($data['receiver']); // Ganti dengan email tujuan
// Subject email
$this->email->subject($data['subject']);
// Isi email
$this->email->message($data['message']);
$this->email->send();
}
}
?><file_sep><body id="page-top">
<div class="container-fluid">
<div class="box">
<div class="box-header">
<h1 class="h4 mb-0 text-gray-800"></h1>
<div align="right">
<a href="<?=site_url('suratpengantar/permintaan')?>" class="btn btn-warning btn-flat">
<i class="fa fa-undo"></i> Back </a>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-md-4 col-md-offset-4">
</div>
<form action="<?= base_url('multiple/proses'); ?>" method="post">
<div class="form-group">
<div class="form-group">
<label>Proses Surat</label>
<select id="form_need" name="proses_surat" class="form-control" required="required" data-error="Pilih jenis surat yang anda perlukan">
<option value=""></option>
<option value="a">Process</option>
<option value="b">Finish</option>
</select>
</div>
<div class="form-group">
<button type="submit" name="" class="btn btn-success btn-flat" >
<i class="fa fa-paper-plane"></i> Save</button>
<!---<button type="reset" class="btn btn-flat">Reset</button>!--->
</div>
</div>
</form>
</div>
<file_sep> <section class="page-section about-heading">
<div class="container">
<img class="img-fluid rounded about-heading-img mb-3 mb-lg-0" src="img/kelurahan.png" alt="">
<div class="about-heading-content">
<div class="row">
<div class="col-xl-9 col-lg-10 mx-auto">
<div class="bg-faded rounded p-5">
<div class="dropdown show">
<a class="btn btn-info dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fa fa-list"></i> Layanan Surat Online
</a>
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="<?= base_url('pindahDomisili') ?>">Surat Pindah Daerah</a>
<a class="dropdown-item" href="#">Surat Pindah RT/RW</a>
<a class="dropdown-item" href="#">Surat Nikah</a>
<a class="dropdown-item" href="#">Surat Cerai</a>
<a class="dropdown-item" href="#">Surat Kelahiran</a>
<a class="dropdown-item" href="#">Surat Kematian</a>
<a class="dropdown-item" href="#">Surat Keterangan Usaha</a>
<a class="dropdown-item" href="#">Surat Kehilangan STNK</a>
<a class="dropdown-item" href="#">Surat Kehilangan KTP</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section><file_sep><section class="page-section about-heading">
<div class="container">
<img class="img-fluid rounded about-heading-img mb-3 mb-lg-0" src="img/kelurahan.png" alt="">
<div class="about-heading-content">
<div class="row">
<div class="col-xl-9 col-lg-10 mx-auto">
<div class="bg-faded rounded p-5">
<h2 class="section-heading mb-4">
<h1 align="center"><p>Pelayanan Surat Online</p>
<a href="https://Semarapurakaja.desa.id">Desa gandrungmangu</a>
</h1>
<p id="judul_cek_nik" class="lead">Silahkan validasi NIK anda dibawah ini</p>
<form id="form_cek_nik" class="form-inline" action="">
<div class="form-group">
<label for="nik_input"> </label>
<input type="nik_input" placeholder="Masukan NIK anda" class="form-control" id="nik_input">
</div>
<button type="submit" class="btn btn-primary">CEK</button>
</form>
<form id="contact-form" method="post" action="<?= base_url('suratPengantar/add_surat_general') ?>" role="form" enctype="multipart/form-data">
<p class="lead">Silahkan lengkapi semua isian sesuai dengan data yang diperlukan</p>
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-10">
<div class="form-group">
<label for="form_name">Nama *</label>
<input id="nama" type="text" name="nama" class="form-control" placeholder="Silahkan masukkan nama anda *" required="required" data-error="Nama harus diisi!.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="form_lastname">NIK *</label>
<input id="nik" type="text" name="NIK" class="form-control" placeholder="Silahkan masukkan NIK anda *" required="required" data-error="NIK Harus diisi!.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-10">
<div class="form-group">
<label for="form_wa">Jenis Kelamin *</label>
<select name="jk" class="form-control" id="jk" required>
<option value="" selected disabled>Choose...</option>
<option value="Laki-laki">Laki-laki</option>
<option value="Perempuan">Perempuan</option>
</select>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="form_alamat">Alamat *</label>
<textarea required name="alamat" class="form-control" rows="3" id="alamat" placeholder="Silahkan masukkan alamat anda" ></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="form_wa">Agama *</label>
<select required name="agama" class="form-control" id="agama">
<option value="" selected disabled>Choose...</option>
<option value="Islam">Islam</option>
<option value="Protestan">Protestan</option>
<option value="Katolik">Katolik</option>
<option value="Hindu">Hindu</option>
<option value="Buddha">Buddha</option>
<option value="Khonghucu">Khonghucu</option>
</select>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="form_wa">Tempat tanggal lahir *</label>
<input id="ttl" type="text" name="tempat_tgl_lahir" class="form-control" placeholder="Silahkan masukkan tempat tanggal lahir anda *" required="required" data-error="Format no salah.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="form_wa">Email *</label>
<input id="email" type="email" name="email" class="form-control" placeholder="Silahkan masukkan email anda *" required="required" data-error="Format no salah.">
<SMALL>
Ketik email yang aktif karena notifikasi akan dikirim melalui email.
</SMALL>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="form_wa">Pekerjaan</label>
<input id="pekerjaan" type="text" name="pekerjaan" class="form-control" placeholder="Silahkan masukkan pekerjaan anda *" required="required" data-error="Format no salah.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="form_wa">Status perkawinan</label>
<select required name="status" class="form-control" id="status">
<option value="" selected disabled>Choose...</option>
<option value="Kawin">Kawin</option>
<option value="Belum Kawin">Belum Kawin</option>
</select>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="form_wa">Whatsapp</label>
<input id="wa" type="text" name="wa" class="form-control" placeholder="Silahkan masukkan nomor whatsapp anda *" required="required" data-error="Format no salah.">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="form_wa">Jenis Surat</label>
<input type="text" width="50%" name="jenis_surat" class="form-control" value="Surat Kelahiran" readonly required >
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="form_wa">Nama Ayah</label>
<input id="form_wa" type="text" name="nama_ayah" class="form-control" placeholder="Silahkan masukkan nama ayah anda *" required="required" data-error="Format no salah.">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="form_wa">Nama Ibu</label>
<input id="form_wa" type="text" name="nama_ibu" class="form-control" placeholder="Silahkan masukkan nama ibu anda *" required="required" data-error="Format no salah.">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="form_wa">Anak ke</label>
<input id="form_wa" type="text" name="anak_ke" class="form-control" placeholder="Silahkan masukkan anak keberapa dari saudara anda *" required="required" data-error="Format no salah.">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label>Surat Pengantar RT/RW*</label>
<div class="custom-file">
<input required name="surat_rt_rw" type="file" class="custom-file-input" id="surat_rt_rw">
<label class="custom-file-label" for="surat_rt_rw">Choose file</label>
</div>
<SMALL>
Upload dalam file .png, .jpg, .pdf, .doc maksimal 3MB
</SMALL>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label>E-KTP kedua Orang Tua*</label>
<div class="custom-file">
<input required name="ktp_ortu" type="file" class="custom-file-input" id="ktp_ortu">
<label class="custom-file-label" for="ktp">Choose file</label>
</div>
<SMALL>
Upload dalam file .png, .jpg, .pdf, .doc maksimal 3MB
</SMALL>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label>Kartu Keluarga (KK)*</label>
<div class="custom-file">
<input required name="kk" type="file" class="custom-file-input" id="kk">
<label class="custom-file-label" for="ktp">Choose file</label>
</div>
<SMALL>
Upload dalam file .png, .jpg, .pdf, .doc maksimal 3MB
</SMALL>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label>Surat Nikah Orang Tua*</label>
<div class="custom-file">
<input required name="surat_nikah" type="file" class="custom-file-input" id="surat_nikah">
<label class="custom-file-label" for="ktp">Choose file</label>
</div>
<SMALL>
Upload dalam file .png, .jpg, .pdf, .doc maksimal 3MB
</SMALL>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label>Surat Keterangan Lahir dari RS*</label>
<div class="custom-file">
<input required name="surat_keterangan_rs" type="file" class="custom-file-input" id="surat_keterangan_rs">
<label class="custom-file-label" for="kk">Choose file</label>
</div>
<SMALL>
Upload dalam file .png, .jpg, .pdf, .doc maksimal 3MB
</SMALL>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="comment">Keterangan:</label>
<textarea name="keterangan" class="form-control" rows="3" id="comment" placeholder="Isi jika ada keterangan"></textarea>
</div>
</div>
<div class="col-md-6" >
<input type="submit" class="btn btn-success btn-send">
</div>
<div class="col-md-6">
<input type="button" class="btn btn-danger btn-send" value="Kembali" onclick="window.history.back()" />
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted">
<strong>*</strong> Harus diisi
</p>
</div>
</div>
</div>
</form>
</div>
<!-- /.10 -->
</div>
<!-- /.row-->
</div>
<!-- /.container-->
</section>
<script>
$('#contact-form').hide()
$(document).ready(function() {
$('#form_cek_nik').on('submit', function(e){
e.preventDefault();
var nik = $('#nik_input').val()
console.log(nik)
if (nik) {
$.ajax({
type: "POST",
url: "<?php echo site_url('layananSurat/cek_nik') ?>",
dataType: "JSON",
data: {
nik: nik,
},
success: function(data) {
if (data != null) {
$('#nama').val(data.nama)
$('#nik').val(data.NIK)
$('#jk').val(data.jk)
$('#alamat').val(data.alamat)
$('#agama').val(data.agama)
$('#ttl').val(data.tempat_tgl_lahir)
if(data.email != null){
$('#email').val(data.email)
}
$('#pekerjaan').val(data.pekerjaan)
$('#status').val(data.status)
$('#wa').val(data.wa)
$('#contact-form').show()
$('#form_cek_nik').hide()
$('#judul_cek_nik').hide()
} else{
alert('data anda tidak ditemukan silakan menghubungi admin atau datang ke balai desa, terimakasih.')
}
}
});
}
})
});
</script>
<script>
$('#surat_rt_rw').on('change',function(){
//get the file name
var fileName = $(this).val();
text = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length);
$(this).next('.custom-file-label').html(text);
})
$('#surat_nikah').on('change',function(){
//get the file name
var fileName = $(this).val();
text = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length);
$(this).next('.custom-file-label').html(text);
})
$('#kk').on('change',function(){
//get the file name
var fileName = $(this).val();
text = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length);
$(this).next('.custom-file-label').html(text);
})
$('#ktp_ortu').on('change',function(){
//get the file name
var fileName = $(this).val();
text = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length);
$(this).next('.custom-file-label').html(text);
})
$('#kk').on('change',function(){
//get the file name
var fileName = $(this).val();
text = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length);
$(this).next('.custom-file-label').html(text);
})
$('#surat_keterangan_rs').on('change',function(){
//get the file name
var fileName = $(this).val();
text = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length);
$(this).next('.custom-file-label').html(text);
})
</script>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
include 'SuratPengantar.php';
class Suratkeluar extends CI_Controller {
var $ttd_img;
function __construct(){
parent::__construct();
$this->load->model('m_keluar');
check_not_login();
$this->load->library('form_validation');
$this->load->helper('my_helper');
$this->ttd_img = [
'Camat' => '..\..\media\surat\ttd2.jpg',
'Sekretaris Camat' => '..\..\media\surat\ttd3.jpg',
'Admin' => '..\..\media\surat\ttd.jpg',
];
}
public function index()
{
$data = [
'row' => $this->m_keluar->get(),
'title' => "Surat Keluar"
];
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('suratkeluar/suratkeluar_data', $data);
$this->load->view('template_admin/footer');
}
public function permintaan_surat_datatabel(){
$list = $this->m_keluar->get_datatables();
$data = array();
$no = $_POST['start'];
$type=$this->input->get('type');
$count = $this->m_keluar->count_all();
// $count = $count['jumlah_surat'];
foreach ($list as $field) {
$jenis_surat = "'".$field->jenis_surat."'";
$nama = "'".$field->nama."'";
$nik = "'".$field->nik."'";
$proses_surat = "'".$field->proses_surat."'";
$JenisSurat = str_replace(' ', '_', $field->jenis_surat);
$no++;
$row = array();
$row['no'] = $no;
$row['id'] = $field->id;
$row['NIK'] = $field->nik;
$row['nama'] = $field->nama;
$row['alamat'] = $field->alamat;
$row['email'] = $field->email;
$row['jenis_surat'] = $field->jenis_surat;
$row['keterangan'] = $field->keterangan;
$row['kk'] = $field->kk;
$row['kode_surat'] = $field->kode_surat;
$row['ktp'] = $field->ktp;
$row['ktp_ortu'] = $field->ktp_ortu;
$row['no_surat'] = $field->no_surat;
$row['surat_keterangan_rs'] = $field->surat_keterangan_rs;
$row['surat_nikah'] = $field->surat_nikah;
$row['surat_rt_rw'] = $field->surat_rt_rw;
$row['tanggal'] = tanggal_indo(date('Y-n-d', strtotime($field->tanggal)));
$row['akta_kelahiran'] = $field->akta_kelahiran;
$row['ijazah'] = $field->ijazah;
$row['aksi'] = array('id' => $field->id, 'jenis_surat' => $field->jenis_surat);
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $count,
"recordsFiltered" => $count,
"data" => $data,
);
echo json_encode($output);
}
public function deleteSurat()
{
$id = $this->input->post('id');
$jenis_surat = $this->input->post('jenis_surat');
if ($jenis_surat == 'Surat Kematian') {
if($this->db->delete('surat_kematian', ['id' => $id])){
$pesan = 'berhasil';
}
}elseif ($jenis_surat == 'Surat Kelahiran') {
if($this->db->delete('surat_kelahiran', ['id' => $id])){
$pesan = 'berhasil';
}
}elseif ($jenis_surat == 'Surat Nikah') {
if($this->db->delete('surat_nikah', ['id' => $id])){
$pesan = 'berhasil';
}
}elseif ($jenis_surat == 'Surat Pindah Daerah') {
if($this->db->delete('surat_pindah_domisili', ['id' => $id])){
$pesan = 'berhasil';
}
}elseif ($jenis_surat == 'Surat Keterangan Usaha') {
if($this->db->delete('surat_sku', ['id' => $id])){
$pesan = 'berhasil';
}
}elseif ($jenis_surat == 'Surat Tugas') {
if($this->db->delete('surat_tugas', ['id' => $id])){
$pesan = 'berhasil';
}
}elseif ($jenis_surat == 'Surat Undangan') {
if($this->db->delete('surat_undangan', ['id' => $id])){
$pesan = 'berhasil';
}
}
$output = array(
'respon' => $pesan,
'jenis_surat' => $jenis_surat
);
echo json_encode($output);
}
public function add(){
$suratkeluar = new stdClass();
$suratkeluar->no = null;
$suratkeluar->no_surat = null;
$suratkeluar->perihal = null;
$suratkeluar->tgl_surat = null;
$suratkeluar->NIK = null;
$suratkeluar->nama = null;
$data = array(
'page' => 'add',
'row' => $suratkeluar,
'title' => "Surat Keluar"
);
$this->load->view('template_admin/header');
$this->load->view('template_admin/sidebar');
$this->load->view('suratkeluar/suratkeluar_form', $data);
$this->load->view('template_admin/footer');
}
public function edit($no){
$query = $this->m_keluar->get($no);
if($query->num_rows() > 0){
$suratkeluar = $query->row();
$data = array(
'page' => 'edit',
'row' => $suratkeluar,
'title' => "Surat Keluar"
);
$this->load->view('template_admin/header',$data);
$this->load->view('template_admin/sidebar');
$this->load->view('suratkeluar/suratkeluar_form', $data);
$this->load->view('template_admin/footer',$data);
}else{
echo "<script> alert('Data tidak ditemukan');</script>";
echo "<script>window.location='".site_url('suratkeluar')."';</script>";
}
}
public function proses(){
$post = $this->input->post(null, TRUE);
if(isset($_POST['add'])){
$config['upload_path'] ='./uploads/';
$config['allowed_types'] ='pdf|doc|jpg|png';
$config['max_size'] = 2000;
$config['file_name'] = 'laporan-'.date('ymd').'-'.substr(md5(rand()), 0,10);
$this->load->library('upload', $config);
if(@$_POST['lampiran'] ['name'] != null){
if($this->upload->do_upload('lampiran')){
$post['lampiran'] = $this->upload->data('file_name');
$this->m_keluar->add($post);
if($this->db->affected_rows() > 0) {
$this->session->set_flashdata('success', 'Data berhasil di simpan');
}
redirect('suratkeluar');
}else{
$error = $this->upload->display_error();
$this->session->set_flashdata('error', $error);
redirect('suratkeluar/add');
}
}else{
$post['lampiran'] = null;
$this->m_keluar->add($post);
if($this->db->affected_rows() > 0) {
$this->session->set_flashdata('success', 'Data berhasil di simpan');
}
redirect('suratkeluar');
}
}else if (isset($_POST['edit'])) {
$this->m_keluar->edit($post);
}
if($this->db->affected_rows() > 0){
echo "<script> alert('Data berhasil disimpan');</script>";
}
echo "<script>window.location='".site_url('suratkeluar')."';</script>";
}
public function del($no){
$this->m_keluar->del($no);
if($this->db->affected_rows() > 0){
echo "<script> alert('Data berhasil dihapus');</script>";
}
echo "<script>window.location='".site_url('suratkeluar')."';</script>";
}
public function download($no){
$this->load->helper('download');
$fileinfo = $this->m_keluar->download($no);
$keluar = './assets/upload/'.$fileinfo['file_surat'];
force_download($keluar, NULL);
}
public function cetak_pdf(){
$template_surat = null;
$jenis_surat = $this->uri->segment(3);
$id_surat = $this->uri->segment(4);
$data_surat = null;
if ($jenis_surat == 'Surat_Kelahiran') {
$template_surat = "print/surat_kelahiran.php";
$data_surat = $this->db->select('*')->from('surat_kelahiran')->join('penduduk', 'penduduk.id=surat_kelahiran.id_penduduk')->where(['surat_kelahiran.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat_Keterangan_Usaha') {
$template_surat = "print/surat_sku.php";
$data_surat = $this->db->select('*')->from('surat_sku')->join('penduduk', 'penduduk.id=surat_sku.id_penduduk')->where(['surat_sku.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat_Kematian') {
$template_surat = "print/surat_kematian.php";
$data_surat = $this->db->select('*')->from('surat_kematian')->join('penduduk', 'penduduk.id=surat_kematian.id_penduduk')->where(['surat_kematian.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat_Nikah') {
$template_surat = "print/surat_nikah.php";
$data_surat = $this->db->select('*')->from('surat_nikah')->join('penduduk', 'penduduk.id=surat_nikah.id_penduduk')->where(['surat_nikah.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat_Pindah_Daerah') {
$template_surat = "print/surat_pindah_daerah.php";
$data_surat = $this->db->select('*')->from('surat_pindah_domisili')->join('penduduk', 'penduduk.id=surat_pindah_domisili.id_penduduk')->where(['surat_pindah_domisili.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat_Undangan') {
$data_surat = $this->db->get_where('surat_undangan', ['id' => $id_surat])->row_array();
$template_surat = 'print\surat_undangan.php';
$data =[
'no_surat' => $data_surat['no_surat'],
'nama_ttd' => $data_surat['nama_ttd'],
'jabatan_ttd' => $data_surat['jabatan_ttd'],
'jenis_surat' => $data_surat['jenis_surat'],
'kontent' => $data_surat['kontent'],
'tanggal' => $data_surat['tanggal'],
'ttd_img' => $this->ttd_img[$data_surat['jabatan_ttd']],
];
}elseif($jenis_surat == 'Surat_Tugas'){
$data_surat = $this->db->get_where('surat_tugas', ['id' => $id_surat])->row_array();
$template_surat = 'print\surat_tugas.php';
$data = [
'jenis_surat' => $data_surat['jenis_surat'],
'no_surat' => $data_surat['no_surat'],
'id_perangkat_desa' => $data_surat['id_perangkat_desa'],
'kontent' => $data_surat['kontent'],
'nama_ttd' => $data_surat['nama_ttd'],
'jabatan_ttd' => $data_surat['jabatan_ttd'],
'tanggal' => $data_surat['tanggal'],
'ttd_img' => $this->ttd_img[$data_surat['jabatan_ttd']],
'perangkat_desa' => $this->db->get_where('perangkat_desa', ['id' => $data_surat['id_perangkat_desa'] ])->row_array()
];
}
if ($jenis_surat != 'Surat_Undangan' && $jenis_surat != 'Surat_Tugas') {
$month = explode("-",$data_surat['tanggal']);
$dateObj = DateTime::createFromFormat('!m', $month[1]);
$monthName = $dateObj->format('F'); // March
$str_month = $month[1] . ' ' . $monthName . ' ' . $month[0];
$data_surat['tanggal'] = $str_month;
$data = [
"data_surat" =>$data_surat,
"nama_ttd" => $data_surat['nama_ttd'],
"jabatan_ttd" => $data_surat['jabatan_ttd']
];
}
$this->load->view($template_surat, $data);
}
}
?><file_sep><div class="box box-info">
<section class="content">
<div class="row">
<div class="col-lg-8">
<div class="box-header">
<div class="container-fluid">
<div class="table-responsive">
<div class="card mb-3">
<div class="card-header">
<i class=""></i>
Surat Keterangan </div>
<form method ='post' action='<?= base_url('surat/Surat/cetak_pdf') ?>'>
<div class="container-fluid"></br>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>Jenis Surat : </label>
<input type="text" name="no_surat" class="form-control" placeholder="Nomor Surat" value="<?= $data_surat['jenis_surat']?>" readonly required/>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Nomor Surat :</label>
<input type="text" name="no_surat" class="form-control" placeholder="Nomor Surat" value="<?= $data_surat['no_surat']?>" readonly required/>
<input type="hidden" name="nosu" class="form-control" placeholder="Nomor Surat" value="" readonly required/>
</div>
</div>
</div>
</br>
<table cellpadding="2" cellspacing="4" style="font-size: 15px;">
<tr>
<b>
Data warga:
</b>
</tr>
<tr>
<td width="150px">Nama </td>
<td>:</td>
<td><?= $data_surat['nama']?></td>
</tr>
<tr>
<td>Tempat, tanggal lahir</td>
<td>:</td>
<td><?= $data_surat['tempat_tgl_lahir']?></td>
</tr>
<tr>
<td>Status perkawinan</td>
<td>:</td>
<td><?= $data_surat['status']?></td>
</tr>
<tr>
<td>Agama</td>
<td>:</td>
<td><?= $data_surat['agama']?></td>
</tr>
<tr>
<td>Jenis kelamin</td>
<td>:</td>
<td><?= $data_surat['jk']?></td>
</tr>
<tr>
<td>Pekerjaan</td>
<td>:</td>
<td><?= $data_surat['pekerjaan']?></td>
</tr>
<tr>
<td>Alamat</td>
<td>:</td>
<td><?= $data_surat['alamat']?></td>
</tr>
</table>
<br>
<select name="ttd" class="form-control" required >
<option selected disabled value="">---Pilih TTD---</option>
<option value="Antoni Budiarso%Kepala Desa">Kepala Desa</option>
<option value="Ninuk Winarsih%Sekretaris Desa">Sekretaris Desa</option>
</select></br>
<input type="hidden" name="jenis_surat" value="<?=$this->uri->segment(4)?>">
<input type="hidden" name="id_surat" value="<?=$this->uri->segment(5)?>">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
<button target="_blank" type="submit" class="btn btn-primary">Buat</button>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class LayananSurat extends CI_Controller {
function __construct(){
parent::__construct();
//$this->load->model('m_suratpengantar');
$this->load->library('form_validation');
}
public function index()
{
//$data['ambil_data']= $this->m_suratpengantar->get();
$this->load->view('template_user/header');
$this->load->view('template_user/topbar');
$this->load->view('user penduduk/layanan');
$this->load->view('template_user/footer');
}
public function pindahdomisili()
{
//$data['ambil_data']= $this->m_suratpengantar->get();
$this->load->view('template_user/header');
$this->load->view('template_user/topbar');
$this->load->view('user penduduk/layanan_pindahdomisili');
$this->load->view('template_user/footer');
}
public function nikah()
{
//$data['ambil_data']= $this->m_suratpengantar->get();
$this->load->view('template_user/header');
$this->load->view('template_user/topbar');
$this->load->view('user penduduk/layanan_nikah');
$this->load->view('template_user/footer');
}
public function kematian()
{
//$data['ambil_data']= $this->m_suratpengantar->get();
$this->load->view('template_user/header');
$this->load->view('template_user/topbar');
$this->load->view('user penduduk/layanan_kematian');
$this->load->view('template_user/footer');
}
public function kelahiran()
{
//$data['ambil_data']= $this->m_suratpengantar->get();
$this->load->view('template_user/header');
$this->load->view('template_user/topbar');
$this->load->view('user penduduk/layanan_kelahiran');
$this->load->view('template_user/footer');
}
public function sku()
{
//$data['ambil_data']= $this->m_suratpengantar->get();
$this->load->view('template_user/header');
$this->load->view('template_user/topbar');
$this->load->view('user penduduk/layanan_keteranganusaha');
$this->load->view('template_user/footer');
}
public function cek_nik()
{
$nik = $this->input->post('nik');
$data_warga = null;
if ($nik) {
$data_warga = $this->db->get_where('penduduk' ,['NIK' => $nik])->row_array();
}
echo json_encode($data_warga);
}
}
?>
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class LaporanMasuk extends CI_Controller {
var $ttd_img;
public function __construct()
{
parent::__construct();
check_not_login();
$this->load->model('m_laporanmasuk');
$this->ttd_img = [
'Camat' => 'media\surat\ttd2.jpg',
'Sekretaris Camat' => 'media\surat\ttd3.jpg',
'Admin' => 'media\surat\ttd.jpg',
];
}
public function index()
{
$data['title'] = "Laporan Masuk";
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('laporanMasuk/laporanMasuk', $data);
$this->load->view('template_admin/footer');
}
public function data_surat_masuk()
{
$bulan = $this->input->post('bulan');
$tahun = $this->input->post('tahun');
$list = $this->m_laporanmasuk->filterbybulan($bulan,$tahun);
$no = 0;
foreach ($list as $field) {
$no++;
$row = array();
$row['no'] = $no;
$row['no_surat'] = $field->no_surat;
$row['tanggal'] = $field->tgl_surat;
$row['keterangan'] = $field->keterangan;
$data[] = $row;
}
echo json_encode($data);
}
function print(){
$bulan = $this->input->post('bulan');
$tahun = $this->input->post('tahun');
$data['datafilter'] = $this->m_laporanmasuk->filterbybulan($bulan,$tahun);
$data['ttd_img'] = $this->ttd_img['Admin'];
$this->load->view('LaporanMasuk/v_Laporan', $data);
}
}
<file_sep><body id="page-top">
<div class="container-fluid">
<div class="box">
<div class="box-header">
<h1 class="h4 mb-0 text-gray-800">Silahkan edit data</h1>
<div align="right">
<a href="<?=site_url('user')?>" class="btn btn-warning btn-flat">
<i class="fa fa-undo"></i> Back </a>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-md-4 col-md-offset-4">
</div>
<form action="" method="post">
<div class="form-group <?=form_error('name') ? 'has-error' : null ?>">
<label>Nama *</label>
<input type="hidden" name="id" value="<?=$row->id?>">
<input type="text" name="name" value="<?=$this->input->post('name') ?? $row->name ?>" class="form-control">
<?=form_error('name')?>
</div>
<div class="form-group <?=form_error('username') ? 'has-error' : null ?>">
<label>Username *</label>
<input type="text" name="username" value="<?=$this->input->post('username') ?? $row->username ?>" class="form-control">
<?=form_error('username')?>
</div>
<div class="form-group <?=form_error('password') ? 'has-error' : null ?>">
<label>Password</label> <SMALL>(Biarkan kosong jika tidak diganti)</SMALL>
<input type="password" name="password" value="<?=$this->input->post('password') ?>" class="form-control">
<?=form_error('password')?>
</div>
<div class="form-group <?=form_error('address') ? 'has-error' : null ?>">
<label>Address *</label>
<textarea name="address" class="form-control"> <?=$this->input->post('address') ?? $row->address ?></textarea>
<?=form_error('address')?>
</div>
<div class="form-group <?=form_error('address') ? 'has-error' : null ?>">
<label>Level *</label>
<textarea name="level" class="form-control"> <?=$this->input->post('level') ?? $row->level ?></textarea>
<?=form_error('level')?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-flat"><i class="fa fa-paper-plane"></i> Save</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</form>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Penduduk extends CI_Controller {
function __construct(){
parent::__construct();
check_not_login();
$this->load->model('m_penduduk');
$this->load->library('form_validation');
}
public function index()
{
$data = [
'row' => $this->m_penduduk->get(),
'title' => "Penduduk"
];
$data['row'] = $this->m_penduduk->get();
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('penduduk/penduduk_data', $data);
$this->load->view('template_admin/footer', $data);
}
public function user_datatabel(){
$list = $this->m_penduduk->get_datatables();
$data = array();
$no = $_POST['start'];
$type=$this->input->get('type');
foreach ($list as $field) {
$no++;
$row = array();
$row['no'] = $no;
$row['NIK'] = $field->NIK;
$row['nama'] = $field->nama;
$row['jk'] = $field->jk;
$row['tempat_tgl_lahir'] = $field->tempat_tgl_lahir;
$row['agama'] = $field->agama;
$row['status'] = $field->status;
$row['pekerjaan'] = $field->pekerjaan;
$row['alamat'] = $field->alamat;
$row['aksi'] = '<a href="penduduk/edit/'.$field->id.'" class="btn btn-primary btn-xs" ><i class="fas fa-pencil-alt"></i> Update</a> <a href="penduduk/del/'.$field->id.'" class="btn btn-danger btn-xs" onclick="konfirmasi()" ><i class="fa fa-trash"> </i> Delete</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->m_penduduk->count_all(),
"recordsFiltered" => $this->m_penduduk->count_filtered(),
"data" => $data,
);
echo json_encode($output);
}
public function add(){
$penduduk = new stdClass();
$penduduk->id = null;
$penduduk->nama = null;
$penduduk->NIK = null;
$penduduk->jk = null;
$penduduk->tempat_tgl_lahir = null;
$penduduk->agama = null;
$penduduk->status = null;
$penduduk->pekerjaan = null;
$penduduk->alamat = null;
$penduduk->email = null;
$penduduk->wa = null;
$data = array(
'page' => 'add',
'row' => $penduduk,
'title' => "penduduk"
);
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('penduduk/penduduk_form', $data);
$this->load->view('template_admin/footer',$data);
}
public function edit($id){
$query = $this->m_penduduk->get($id);
if($query->num_rows() > 0){
$penduduk = $query->row();
$data = array(
'page' => 'edit',
'row' => $penduduk,
'title' => "penduduk"
);
$this->load->view('template_admin/header',$data);
$this->load->view('template_admin/sidebar');
$this->load->view('penduduk/penduduk_form', $data);
$this->load->view('template_admin/footer',$data);
}else{
echo "<script> alert('Data tidak ditemukan');</script>";
echo "<script>window.location='".site_url('penduduk')."';</script>";
}
}
public function proses(){
$post = $this->input->post(null, TRUE);
if(isset($_POST['add'])){
$this->m_penduduk->add($post);
}else if (isset($_POST['edit'])) {
$this->m_penduduk->edit($post);
}
if($this->db->affected_rows() > 0){
echo "<script> alert('Data berhasil disimpan');</script>";
}
echo "<script>window.location='".site_url('penduduk')."';</script>";
}
public function del($id){
$this->m_penduduk->del($id);
if($this->db->affected_rows() > 0){
echo "<script> alert('Data berhasil dihapus');</script>";
}
echo "<script>window.location='".site_url('penduduk')."';</script>";
}
}
?><file_sep><!DOCTYPE html>
<html><style type="text/css">
body{
padding: 5px 50px 70px 30px;
font-family: TimesNewRoman, "Times New Roman", Times, Baskerville, Georgia, serif;
font-size: 12;
}
header { position: fixed; top: 30px; left: 40px; right: 40px; height: auto;}
footer { position: fixed; bottom: -60px; left: 0px; right: 0px;height: 120px; padding: 0px 40px 0px 50px;}
</style>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Surat Keterangan</title>
<center>
<table width="100%">
<tr>
<td align="center" ><img src="<?php echo base_url()?>assets/img/logo.png" width="45%" ></td>
<td align="right" width="60%">
<table style="margin-top:0%">
<tr>
<td><center>PEMERINTAH JAWA TENGAH</center></td>
</tr>
<tr>
<td><center>KECAMATAN GANDRUNGMANGU</center></td>
</tr>
<tr style="font-size: 14; font-weight: bold">
<td><center>KANTOR KEPALA DESA GANDRUNG</center></td>
</tr>
<tr style="font-size: 10">
<td><center>Jln. Wilis No.5 Desa Gandrung, Kec. Gandrung Kode Pos 63263</center></td>
</tr>
</table>
</td>
</tr>
<tr><u>--------------------------------------------------------------------------------------------------------</u></tr>
</table>
</center>
</head>
<body>
<style type="text/css">
.left { text-align: left;}
.right { text-align: right;}
.center { text-align: center;}
.justify { text-align: justify;}
</style>
<center>
<u><strong style="font-size:12; line-height: 10px;"><?php echo strtoupper ($tampil['jenis_surat']) ?></strong></u><br>
<u><p style="font-size:10;">No : <?php echo $tampil['no_surat'] ?></p></u>
</center>
<br/><br/>
<p class="justify"> Yang bertanda tangan dibawah ini saya Kepala Desa Gandrung Kecamatan Gandrung Kabupaten Gandrung.</p>
<br>
Dengan ini menerangkan :
<!-- text input -->
<table cellpadding="3" width="600px">
<tr >
<td width="150px">NIK</td>
<td width="10px">:</td>
<td width="440px"><?php echo $tampil['NIK'] ?></td>
</tr>
<tr >
<td>Nama</td>
<td>:</td>
<td><?php echo $tampil['nama'] ?></td>
</tr>
<tr >
<td>Jenis Kelamin</td>
<td>:</td>
<td><?php echo $tampil['jk']?></td>
</tr>
<tr >
<td>Tempat/Tgl. Lahir</td>
<td>:</td>
<td><?php echo $tampil['tempat_tgl_lahir'] ?></td>
</tr>
<tr >
<td>Agama</td>
<td>:</td>
<td><?php echo $tampil['agama']?></td>
</tr>
<tr >
<td>Status Perkawinan</td>
<td>:</td>
<td><?php echo $tampil['status']?></td>
</tr>
<tr >
<td>Pekerjaan</td>
<td>:</td>
<td><?php echo $tampil['pekerjaan']?></td>
</tr>
<tr >
<td>Alamat</td>
<td>:</td>
<td><?php echo $tampil['alamat']?></td>
</tr>
<tr >
<td>Keterangan</td>
<td>:</td>
</tr>
</table>
<p class="justify"><?php echo $tampil['keterangan']?></p>
<br/><br/>
<br/>
<p class="justify">Demikian Surat Keterangan ini dibuat dan diberikan kepada yang bersangkutan untuk dapat dipergunakan sebagaimana mestinya.</p>
<br/><br/><br/>
<table width="100%">
<tr>
<td width="30%">
</td>
<td></td>
<td width="40%">
Mendiro, <?php echo tgl($tampil['tanggal']) ?>
<br/>
<?php
if($tampil['ttd'] == '<NAME>'){
echo "Kepala Desa Mendiro";
}else{
echo "Sekretaris Desa Mendiro";
}
?>
<br/><br/><br/><br/>
<strong><?php echo $tampil['ttd'] ?></strong>
</td>
</tr>
</table>
<footer>
<table width="100%">
<tr>
<td></td>
</tr>
</table>
</footer>
</body></html>
<file_sep><?php
class M_suratpengantar extends CI_Model{
var $table = 'surat_kelahiran'; //nama tabel dari database
var $column_order = array('nama', 'nik', 'alamat', 'email', 'jenis_surat', 'keterangan', 'proses_surat', 'no_surat', 'kode_surat', 'tanggal'); //field yang ada di table user
var $column_search = array('nama', 'nik', 'alamat', 'email', 'jenis_surat', 'keterangan', 'proses_surat', 'no_surat', 'kode_surat', 'tanggal'); //field yang diizin untuk pencarian
var $order = array('id' => 'asc'); // default order
public function __construct()
{
parent::__construct();
$this->load->database();
}
private function CustomDataTabel()
{
$sql = "
SELECT * FROM (
SELECT surat_kematian.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, surat_nikah ,null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_kematian JOIN penduduk ON surat_kematian.id_penduduk=penduduk.id
UNION ALL
SELECT surat_nikah.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, ktp_ortu, kk, null as surat_nikah ,null as surat_keterangan_rs, ktp, akta_kelahiran, ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_nikah JOIN penduduk ON surat_nikah.id_penduduk=penduduk.id
UNION ALL
SELECT surat_pindah_domisili.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_pindah_domisili JOIN penduduk ON surat_pindah_domisili.id_penduduk=penduduk.id
UNION ALL
SELECT surat_sku.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_sku JOIN penduduk ON surat_sku.id_penduduk=penduduk.id
) AS surat_keluar
ORDER BY surat_keluar.no_surat DESC
LIMIT ". $_POST['length']." OFFSET ". $_POST['start'] ."
";
if($_POST['search']['value']){
$tgl = $_POST['search']['value'];
$sql = "
SELECT * FROM (
SELECT surat_kematian.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, surat_nikah ,null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_kematian JOIN penduduk ON surat_kematian.id_penduduk=penduduk.id
UNION ALL
SELECT surat_nikah.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, ktp_ortu, kk, null as surat_nikah ,null as surat_keterangan_rs, ktp, akta_kelahiran, ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_nikah JOIN penduduk ON surat_nikah.id_penduduk=penduduk.id
UNION ALL
SELECT surat_pindah_domisili.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_pindah_domisili JOIN penduduk ON surat_pindah_domisili.id_penduduk=penduduk.id
UNION ALL
SELECT surat_sku.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_sku JOIN penduduk ON surat_sku.id_penduduk=penduduk.id
) AS surat_keluar
WHERE surat_keluar.nama LIKE'%".$tgl."%' OR surat_keluar.nik LIKE'%".$tgl."%' OR surat_keluar.jenis_surat LIKE'%".$tgl."%' OR surat_keluar.no_surat LIKE'%".$tgl."%' OR surat_keluar.tanggal LIKE'%".$tgl."%'
";
return $this->db->query($sql)->result();
}
if($_POST['length'] != -1);
return $this->db->query($sql)->result();
}
function get_datatables()
{
$query = $this->CustomDataTabel();
return $query;
}
function count_filtered()
{
$sql = "
SELECT COUNT(id) AS `jumlah_surat` FROM (
SELECT surat_kematian.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, surat_nikah ,null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_kematian JOIN penduduk ON surat_kematian.id_penduduk=penduduk.id
UNION ALL
SELECT surat_nikah.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, ktp_ortu, kk, null as surat_nikah ,null as surat_keterangan_rs, ktp, akta_kelahiran, ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_nikah JOIN penduduk ON surat_nikah.id_penduduk=penduduk.id
UNION ALL
SELECT surat_pindah_domisili.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_pindah_domisili JOIN penduduk ON surat_pindah_domisili.id_penduduk=penduduk.id
UNION ALL
SELECT surat_sku.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_sku JOIN penduduk ON surat_sku.id_penduduk=penduduk.id
) AS surat_keluar
";
$data = $this->db->query($sql)->row_array();
return $data['jumlah_surat'];
}
public function count_all()
{
$sql = "
SELECT COUNT(id) AS `jumlah_surat` FROM (
SELECT surat_kematian.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, surat_nikah ,null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_kematian JOIN penduduk ON surat_kematian.id_penduduk=penduduk.id
UNION ALL
SELECT surat_nikah.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, ktp_ortu, kk, null as surat_nikah ,null as surat_keterangan_rs, ktp, akta_kelahiran, ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_nikah JOIN penduduk ON surat_nikah.id_penduduk=penduduk.id
UNION ALL
SELECT surat_pindah_domisili.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_pindah_domisili JOIN penduduk ON surat_pindah_domisili.id_penduduk=penduduk.id
UNION ALL
SELECT surat_sku.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_sku JOIN penduduk ON surat_sku.id_penduduk=penduduk.id
) AS surat_keluar
";
$data = $this->db->query($sql)->row_array();
return $data['jumlah_surat'];
}
public function get(){
$sql =
"SELECT surat_kematian.id as id, nama, nik, alamat, email, `jenis_surat`, `surat_rt_rw`, null as `ktp_ortu`, `kk`, `surat_nikah` ,null as `surat_keterangan_rs`, `ktp`, null as `akta_kelahiran`, null as `ijazah`, `keterangan`, `proses_surat`, `no_surat`, `kode_surat`, `tanggal` FROM surat_kematian JOIN penduduk ON surat_kematian.id_penduduk=penduduk.id WHERE
tanggal
UNION ALL
SELECT surat_nikah.id as id, nama, nik, alamat, email, `jenis_surat`, `surat_rt_rw`, `ktp_ortu`, `kk`, null as `surat_nikah` ,null as `surat_keterangan_rs`, `ktp`, `akta_kelahiran`, `ijazah`, `keterangan`, `proses_surat`, `no_surat`, `kode_surat`, `tanggal` FROM surat_nikah JOIN penduduk ON surat_nikah.id_penduduk=penduduk.id WHERE
tanggal
UNION ALL
SELECT surat_pindah_domisili.id as id, nama, nik, alamat, email, `jenis_surat`, `surat_rt_rw`, null as `ktp_ortu`, `kk`, null as `surat_nikah` , null as `surat_keterangan_rs`, `ktp`, null as `akta_kelahiran`, null as `ijazah`, `keterangan`, `proses_surat`, `no_surat`, `kode_surat`, `tanggal` FROM surat_pindah_domisili JOIN penduduk ON surat_pindah_domisili.id_penduduk=penduduk.id WHERE
tanggal
UNION ALL
SELECT surat_sku.id as id, nama, nik, alamat, email, `jenis_surat`, `surat_rt_rw`, null as `ktp_ortu`, null as `kk`, null as `surat_nikah` , null as `surat_keterangan_rs`, `ktp`, null as `akta_kelahiran`, null as `ijazah`, `keterangan`, `proses_surat`, `no_surat`, `kode_surat`, `tanggal` FROM surat_sku JOIN penduduk ON surat_sku.id_penduduk=penduduk.id WHERE
tanggal";
$hsl = $this->db->query($sql);
return $hsl;
}
function add($post){
$params = [
'nama' => $post['nama'],
'NIK' => $post['NIK'],
'alamat' => $post['alamat'],
'whatsapp' => $post['whatsapp'],
'keperluan' => $post['keperluan'],
'keterangan' => empty($post['keterangan']) ? null : $post['keterangan'],
//'file_surat' => $post['file_surat'],
];
$this->db->insert('suratpengantar', $params);
}
public function get_penduduk(){
$this->db->query('select nama, nik, alamat from penduduk');
$query = $this->db->get();
return $query;
}
public function ambil_data($id = null)
{
$this->db->select('*');
$this->db->from('suratpengantar');
if($id != null){
$this->db->where('id',$id);
}
$query = $this->db->get();
return $query;
}
}
?><file_sep><?php
function tgl_indo($tgl){
$tanggal = substr($tgl,8,2);
$bulan = getBulan(substr($tgl,5,2));
$tahun = substr($tgl,0,4);
return $tanggal.' '.$bulan.' '.$tahun;
}
function hari_ini($w){
$seminggu = array("Minggu","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu");
$hari_ini = $seminggu[$w];
return $hari_ini;
}
function getBulan($bln){
switch ($bln){
case 1:
return "Jan";
break;
case 2:
return "Feb";
break;
case 3:
return "Mar";
break;
case 4:
return "Apr";
break;
case 5:
return "Mei";
break;
case 6:
return "Jun";
break;
case 7:
return "Juli";
break;
case 8:
return "Agu";
break;
case 9:
return "Sep";
break;
case 10:
return "Okt";
break;
case 11:
return "Nov";
break;
case 12:
return "Des";
break;
}
}
function tanggal_indo($tanggal){
$bulan = array (
1 => 'Januari',
'Februari',
'Maret',
'April',
'Mei',
'Juni',
'Juli',
'Agustus',
'September',
'Oktober',
'November',
'Desember'
);
$pecahkan = explode('-', $tanggal);
// variabel pecahkan 0 = tanggal
// variabel pecahkan 1 = bulan
// variabel pecahkan 2 = tahun
$str = $pecahkan[2] . ' ' . $bulan[ (int)$pecahkan[1] ] . ' ' . $pecahkan[0];
return $str;
}<file_sep><body id="page-top">
<div class="container-fluid">
<div class="row">
<div class="col">
<h1 class="judul h3 text-gray-800">Daftar <?= $title ?></h1>
<div class="card shadow mb-0">
<div class="card-header py-3">
<a href="<?= base_url('suratmasuk/add'); ?>" class="btn btn-primary"><i class="fa fa-user-plus"></i>Tambah Data</a>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table table-bordered table-striped" id="dataTable">
<thead>
<tr align="center" class="bg-primary" style = "color: white;">
<th>No</th>
<th>No. Surat</th>
<th>SKPD/Intansi</th>
<th>Tanggal Surat</th>
<th>Tanggal Terima</th>
<th>Perihal</th>
<th>File</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php $no = 1;;
foreach($row->result() as $key => $data) { ?>
<tr align="center">
<td><?=$no++?>.</td>
<td><?=$data->no_surat?></td>
<td><?=$data->pengirim?></td>
<td><?php echo tanggal_indo(date('Y-m-d ', strtotime ($data->tgl_surat)))?></td>
<td><?php echo tanggal_indo(date('Y-m-d ', strtotime ($data->tgl_terima)))?></td>
<!--<td><?=$data->tgl_terima?></td>!-->
<td><?=$data->keterangan?></td>
<td><a href="<?php echo base_url().'suratmasuk/download/'.$data->no; ?>" href=<?= base_url('./assets/upload/')?>> <?=$data->file_surat?> </a> </a></td>
<td class="text-center">
<a href="<?=site_url('suratmasuk/edit/'.$data->no)?>" class="btn btn-info btn-xs" >
<i class="fas fa-edit"></i></a>
<a href="<?= base_url('suratmasuk/openfile/' .$data->file_surat )?>" class="btn btn-success btn-xs" >
<i class="fa fa-eye"> </i></a>
<a class="btn btn-danger btn-xs" data-toggle="modal" data-target="#deleteModal" onclick="delete_data(<?=$data->no?>)"><i class="fa fa-trash"> </i></a>
</td>
</tr>
<?php
} ?>
</tbody>
</table>
</div>
<!-- Modal Delete-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Hapus Data</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method ='post' action="<?php echo base_url().'suratmasuk/hapusdata'; ?>">
<input type="hidden" name="no">
<div class="form-group">
<p><b>Apakah Anda Yakin Menghapus Data Ini?</b></p>
</div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
<button type="submit" class="btn btn-danger">Hapus</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
function delete_data(id) {
$('input[name=no]').val(id);
}
</script>
<file_sep><!DOCTYPE html>
<!-- Created by pdf2htmlEX (https://github.com/coolwanglu/pdf2htmlex) -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<link href="<?php echo base_url()?>/assets/print_assets/surat_kelahiran/base.min.css" rel="stylesheet">
<link href="<?php echo base_url()?>/assets/print_assets/surat_kelahiran/fancy.min.css" rel="stylesheet">
<link href="<?php echo base_url()?>/assets/print_assets/surat_kelahiran/main.css" rel="stylesheet">
<script src="<?php echo base_url()?>/assets/print_assets/surat_kelahiran/compatibility.min.js"></script>
<script src="<?php echo base_url()?>/assets/print_assets/surat_kelahiran/theViewer.min.js"></script>
<script>
try{
theViewer.defaultViewer = new theViewer.Viewer({});
}catch(e){}
</script>
<title>Surat Keterangan Kelahiran</title>
</head>
<body>
<div id="sidebar">
<div id="outline"></div>
</div>
<div id="page-container">
<div id="pf1" class="pf w0 h0" data-page-no="1">
<div class="pc pc1 w0 h0">
<img class="bi x0 y0 w0 h0" alt="" src="<?php echo base_url()?>assets/print_assets/surat_kelahiran/bg1.png">
<div class="c x1 y1 w1 h1">
<div class="t m0 x2 h2 y2 ff1 fs0 fc0 sc0 ls0 ws0">PEMERINTAH KABUPATEN CILACAP</div>
<div class="t m0 x3 h2 y3 ff1 fs0 fc0 sc0 ls0 ws0">KECAMATAN GANDRUNGMANGU</div>
<div class="t m0 x4 h2 y4 ff1 fs0 fc0 sc0 ls0 ws0">KELURAHAN GANDRUNGMANGU</div>
</div>
<div class="t m0 x5 h3 y5 ff2 fs1 fc0 sc0 ls0 ws0">Alamat: Jalan Infra 14/15 Bumi Dipasena Abadi Kode Pos 34675</div>
<div class="t m0 x6 h3 y6 ff2 fs1 fc0 sc0 ls0 ws0">Website<span class="fc1">: https://semarapurakaja.desa.id/</span> Email: <EMAIL></div>
<div class="t m0 x7 h4 y7 ff1 fs2 fc0 sc0 ls0 ws0">SURAT KETERANGAN KELAHIRAN</div>
<div class="t m0 x8 h5 y8 ff2 fs2 fc0 sc0 ls0 ws0">Nomor<span class="_ _0"> </span>: <?=$data_surat['no_surat']?></div>
<div class="t m0 x9 h5 y9 ff2 fs2 fc0 sc0 ls0 ws0">Yang <span class="_ _1"> </span>bertanda <span class="_ _1"> </span>tangan <span class="_ _1"> </span>di <span class="_ _1"> </span>bawah <span class="_ _1"> </span>ini <span class="_ _1"> </span>Kepala <span class="_ _1"> </span>Desa <span class="_ _1"> </span>Gandrungmangu <span class="_ _1"> </span>Kecamatan </div>
<div class="t m0 x9 h5 ya ff2 fs2 fc0 sc0 ls0 ws0">Gandrungmangu menerangkan dengan sesungguhnya bahwa : </div>
<div class="t m0 xa h5 yb ff2 fs2 fc0 sc0 ls0 ws0">N a m a<span class="_ _2"> </span>: <?=$data_surat['nama']?></div>
<div class="t m0 xa h5 yc ff2 fs2 fc0 sc0 ls0 ws0">Tempat, tanggal lahir<span class="_ _3"> </span>: <?=$data_surat['tempat_tgl_lahir']?></div>
<div class="t m0 xa h5 yd ff2 fs2 fc0 sc0 ls0 ws0">A g a m a<span class="_ _4"> </span>: <?=$data_surat['agama']?></div>
<div class="t m0 xa h5 ye ff2 fs2 fc0 sc0 ls0 ws0"> </div>
<div class="t m0 xa h5 yf ff2 fs2 fc0 sc0 ls0 ws0">Jenis kelamin<span class="_ _5"> </span>: <?=$data_surat['jk']?></div>
<div class="t m0 xa h5 y10 ff2 fs2 fc0 sc0 ls0 ws0">Pekerjaan<span class="_ _6"> </span>: <?=$data_surat['pekerjaan']?></div>
<div class="t m0 xa h5 y11 ff2 fs2 fc0 sc0 ls0 ws0">Alamat<span class="_ _7"> </span>: <?=$data_surat['alamat']?></div>
<div class="t m0 x9 h5 y12 ff2 fs2 fc0 sc0 ls0 ws0">Adalah anak dari: </div>
<div class="t m0 xa h5 y13 ff2 fs2 fc0 sc0 ls0 ws0">Nama <NAME><span class="_ _8"> </span>: <?=$data_surat['nama_ayah']?></div>
<div class="t m0 xa h5 y14 ff2 fs2 fc0 sc0 ls0 ws0">Nama Ibu Kandung<span class="_ _9"> </span>: <?=$data_surat['nama_ibu']?></div>
<div class="t m0 xa h5 y15 ff2 fs2 fc0 sc0 ls0 ws0">Anak Ke<span class="_ _a"> </span>: <?=$data_surat['anak_ke']?></div>
<div class="t m0 xa h5 y16 ff2 fs2 fc0 sc0 ls0 ws0"> </div>
<div class="t m0 x9 h5 y17 ff2 fs2 fc0 sc0 ls0 ws0">Demikianlah <span class="_ _b"></span>surat <span class="_ _b"></span>keterangan <span class="_ _b"></span>ini <span class="_ _b"></span>dibuat <span class="_ _b"></span>untuk <span class="_ _b"></span>dapat <span class="_ _b"></span>dipergunakan <span class="_ _b"></span>sebagaimana <span class="_ _b"></span>mestinya. </div>
<div class="t m0 x9 h5 y18 ff2 fs2 fc0 sc0 ls0 ws0">Atas kerja samanya diucapkan terima kasih.</div>
<div class="t m0 xb h5 y19 ff2 fs2 fc0 sc0 ls0 ws0"> <span class="_ _c"> </span>Gandrungmangu, <?=$data_surat['tanggal']?></div>
<div class="t m0 x9 h5 y1a ff2 fs2 fc0 sc0 ls0 ws0"> <span class="_ _d"> </span><span class="fs1"> </span></div>
<div class="t m0 xc h5 y1b ff2 fs2 fc0 sc0 ls0 ws0"> <span class="_ _e"> </span> <?=$jabatan_ttd?></div>
<div class="t m0 xd h5 y1c ff2 fs2 fc0 sc0 ls0 ws0"> </div>
<div class="t m0 xd h4 y1d ff1 fs2 fc0 sc0 ls0 ws0"> <span class="_ _f"> </span> <?=$nama_ttd?></div>
</div>
<div class="pi" data-data='{"ctm":[1.000000,0.000000,0.000000,1.000000,0.000000,0.000000]}'></div>
</div>
</div>
<div class="loading-indicator">
</div>
</body>
</html>
<script>
window.onload = function () {
window.print();
path = location.pathname.split("/")
if (path[2] == 'suratkeluar') {
window.onafterprint = function(){
console.log("Printing completed...");
location.replace("<?= base_url('suratkeluar')?>")
}
}else{
window.onafterprint = function(){
console.log("Printing completed...");
location.replace("<?= base_url('suratPengantar/permintaan')?>")
}
}
};
</script><file_sep>*********
Note
*********
- Download Project dengan format .zip [pengarsipan.zip](https://github.com/fflah/pengarsipan/archive/refs/heads/main.zip)
- Extract pengarsipan.zip kemudian copy and paste di xampp/htdocs
- Replace atau ganti DB di folder db/pengarsipan.sql
- Run!
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Perangkat_desa extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('m_perangkat_desa');
check_not_login();
$this->load->library('form_validation');
}
public function index()
{
$data = [
'row' => $this->m_perangkat_desa->get(),
'title' => "Setting"
];
$data['row'] = $this->m_perangkat_desa->get();
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('perangkat_desa/user_data', $data);
$this->load->view('template_admin/footer', $data);
}
public function add(){
$data = [
'row' => $this->m_perangkat_desa->get(),
'title' => "Setting"
];
$this->form_validation->set_rules('nama', 'Nama', 'required');
$this->form_validation->set_rules('nik', 'Nik', 'required');
$this->form_validation->set_rules('jabatan', 'Jabatan', 'required');
$this->form_validation->set_rules('divisi', 'Divisi', 'required');
$this->form_validation->set_rules('status', 'Status', 'required');
$this->form_validation->set_message('required' , '%s masih kosong, silahkan isi');
$this->form_validation->set_error_delimiters('<span class="help-block">', '</span>');
if ($this->form_validation->run() == FALSE){
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('perangkat_desa/user_form_add', $data);
$this->load->view('template_admin/footer', $data);
}else {
$post = $this->input->post(null, TRUE);
$this->m_perangkat_desa->add($post);
if($this->db->affected_rows() > 0 ){
echo "<script> alert('Data berhasil disimpan');</script>";
}
echo "<script>window.location='".site_url('perangkat_desa')."';</script>";
}
}
public function edit($id){
$data = [
'row' => $this->m_perangkat_desa->get(),
'title' => "Setting"
];
$this->form_validation->set_rules('nama', 'Nama', 'required');
$this->form_validation->set_rules('nik', 'Nik', 'required');
$this->form_validation->set_rules('jabatan', 'Jabatan', 'required');
$this->form_validation->set_rules('divisi', 'Divisi', 'required');
$this->form_validation->set_rules('status', 'Status', 'required');
$this->form_validation->set_message('required' , '%s masih kosong, silahkan isi');
$this->form_validation->set_error_delimiters('<span class="help-block">', '</span>');
if ($this->form_validation->run() == FALSE){
$query = $this->m_perangkat_desa->get($id);
if($query->num_rows() > 0){
$data['row'] = $query->row();
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('perangkat_desa/user_form_edit', $data);
$this->load->view('template_admin/footer', $data);
}else{
echo "<script> alert('Data tidak ditemukan');</script>";
echo "<script>window.location='".site_url('perangkat_desa')."';</script>";
}
}else {
$post = $this->input->post(null, TRUE);
$this->m_perangkat_desa->edit($post);
if($this->db->affected_rows() > 0 ){
echo "<script> alert('Data berhasil disimpan');</script>";
}
echo "<script>window.location='".site_url('perangkat_desa')."';</script>";
}
}
public function hapusdata(){
$id = $this->input->post("id");
$where = array('id' => $id);
$this->m_perangkat_desa->deleteData('perangkat_desa', $where);
redirect ('perangkat_desa');
}
}
?><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Surat Tugas</title>
<style>
body{
padding: 0;
margin: 0;
}
.content {
max-width: 793px;
margin: auto;
}
th, td {
padding: 0px;
}
.logo{
width: 70.79px;
height: 95.05px;
display: block;
margin-left: auto;
margin-right: auto;
}
.kop-judul{
font-weight: bold;
font-size: x-large;
text-align: center;
}
.kop-sub{
font-size: x-small;
text-align: center;
}
hr.solid {
border-top: 4px solid rgb(17, 17, 17);
}
</style>
</head>
<body>
<center>
<div class="content">
<table width="593">
<tr>
<td rowspan="2"><img class="logo" alt="" src="<?=base_url('assets\img\image1.png')?>" title=""></td>
<td class="kop-judul">PEMERINTAH KABUPATEN CILACAP <br>
KECAMATAN CIPARI <br>
</td>
</tr>
<tr>
<td class="kop-sub">Alamat: <NAME> No 42, Kode Pos 53262, Telp. (0280) 523412</td>
</tr>
<tr>
<td style="padding: -3px;" colspan="2">
<hr class="solid">
</td>
</tr>
<tr>
<td align="center" colspan="2">
<b><u> SURAT TUGAS</u></b>
</td>
</tr>
<tr>
<td style="padding-bottom: 20px;" align="center" colspan="2">
Nomor :<?= $no_surat?>
</td>
</tr>
<tr>
<td align="left" colspan="2">
Yang bertanda tangan di bawah ini Kepala Kecamatan Cipari menerangkan dengan sesungguhnya bahwa :
</td>
</tr>
<tr>
<td align="left" colspan="2">
<table style="margin-left: 100px;" width="55%">
<tr>
<td width="15%">Nama</td>
<td width="2%"> : </td>
<td width="40%"><?=$perangkat_desa['nama']?></td>
</tr>
<tr>
<td>NIK</td>
<td>:</td>
<td><?=$perangkat_desa['nik']?></td>
</tr>
<tr>
<td>Jabatan</td>
<td>:</td>
<td><?=$perangkat_desa['jabatan']?></td>
</tr>
<tr>
<td>Devisi</td>
<td>:</td>
<td><?=$perangkat_desa['divisi']?></td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="padding-top:20px;" align="left" colspan="2">
<?=$kontent?>
</td>
</tr>
<tr>
<td align="left" colspan="2">
Demikianlah surat tugas ini dibuat untuk dapat dipergunakan sebagaimana mestinya. Atas kerja samanya diucapkan terima kasih.
</td>
</tr>
<tr>
<td colspan="2">
<table style="margin-left:300px; margin-top: 100px;">
<tr>
<td align="center">Cipari, <?=date("d F Y ")?></td>
</tr>
<tr>
<td align="center" ><?=$jabatan_ttd?></td>
</tr>
<tr>
<td><center><img width="100" height="100" src="..\<?=$ttd_img?>" alt=""></center></td>
</tr>
<tr>
<td align="center" style="padding-bottom: 10px;" ><?= $nama_ttd?></td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</center>
</body>
</html>
<script>
window.onload = function () {
window.print();
path = location.pathname.split("/")
window.onafterprint = function(){
console.log("Printing completed...");
location.replace("<?= base_url('suratkeluar')?>")
}
};
</script>
<file_sep><body id="page-top">
<div class="container-fluid">
<div class="box">
<div class="box-header">
<h1 class="h4 mb-0 text-gray-800">Silahkan edit data</h1>
<div align="right">
<a href="<?=site_url('user')?>" class="btn btn-warning btn-flat">
<i class="fa fa-undo"></i> Back </a>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-md-4 col-md-offset-4">
</div>
<form action="" method="post">
<div class="form-group <?=form_error('nama') ? 'has-error' : null ?>">
<label>Nama *</label>
<input type="hidden" name="id" value="<?=$row->id?>">
<input type="text" name="nama" value="<?=$this->input->post('nama') ?? $row->nama ?>" class="form-control">
<?=form_error('nama')?>
</div>
<div class="form-group <?=form_error('nik') ? 'has-error' : null ?>">
<label>NIK *</label>
<input type="text" name="nik" value="<?=$this->input->post('nik') ?? $row->nik ?>" class="form-control">
<?=form_error('nik')?>
</div>
<div class="form-group <?=form_error('jabatan') ? 'has-error' : null ?>">
<label>Jabatan</label>
<input type="text" name="jabatan" value="<?=$this->input->post('jabatan') ?? $row->jabatan ?>" class="form-control">
<?=form_error('jabatan')?>
</div>
<div class="form-group <?=form_error('divisi') ? 'has-error' : null ?>">
<label>Devisi *</label>
<textarea name="divisi" class="form-control"> <?=$this->input->post('divisi') ?? $row->divisi ?></textarea>
<?=form_error('divisi')?>
</div>
<div class="form-group <?=form_error('status') ? 'has-error' : null ?>">
<label>Status *</label>
<textarea name="status" class="form-control"> <?=$this->input->post('status') ?? $row->status ?></textarea>
<?=form_error('status')?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-flat"><i class="fa fa-paper-plane"></i> Save</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</form>
</div>
</div>
<file_sep><?php
class M_penduduk extends CI_Model{
// Get data peduduk using datatabel
var $table = 'penduduk'; //nama tabel dari database
var $column_order = array('id', 'NIk', 'nama', 'jk', 'tempat_tgl_lahir', 'agama', 'status', 'pekerjaan', 'alamat'); //field yang ada di table user
var $column_search = array('id', 'NIk', 'nama', 'jk', 'tempat_tgl_lahir', 'agama', 'status', 'pekerjaan', 'alamat'); //field yang diizin untuk pencarian
var $order = array('id' => 'asc'); // default order
public function __construct()
{
parent::__construct();
$this->load->database();
}
private function _get_datatables_query()
{
$this->db->select(['id', 'NIK', 'nama', 'jk', 'tempat_tgl_lahir', 'agama', 'status', 'pekerjaan', 'alamat']);
$this->db->from('penduduk');
$i = 0;
foreach ($this->column_search as $item) // looping awal
{
if($_POST['search']['value']) // jika datatable mengirimkan pencarian dengan metode POST
{
if($i===0) // looping awal
{
$this->db->group_start();
$this->db->like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i)
$this->db->group_end();
}
$i++;
}
if(isset($_POST['order']))
{
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
// echo $this->db->last_query();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
public function get($id = null){
$this->db->from('penduduk');
if($id != null){
$this->db->where('id', $id);
}
$query = $this->db->get();
return $query;
}
function add($post){
$params = [
'nama' => $post['nama'],
'NIK' => $post['NIK'],
'jk' => $post['jk'],
'tempat_tgl_lahir' => $post['tempat_tgl_lahir'],
'agama' => $post['agama'],
'status' => $post['status'],
'pekerjaan' => $post['pekerjaan'],
'alamat' => $post['alamat'],
'email' => $post['email'],
'wa' => $post['wa']
];
$this->db->insert('penduduk', $params);
}
function edit($post){
$params = [
'nama' => $post['nama'],
'NIK' => $post['NIK'],
'jk' => $post['jk'],
'tempat_tgl_lahir' => $post['tempat_tgl_lahir'],
'agama' => $post['agama'],
'status' => $post['status'],
'pekerjaan' => $post['pekerjaan'],
'alamat' => $post['alamat'],
'email' => $post['email'],
'wa' => $post['wa']
];
$this->db->where('id', $post['id']);
$this->db->update('penduduk', $params);
}
public function del($id){
$this->db->where('id', $id);
$this->db->delete('penduduk');
}
public function find($id)
{
$this->db->select('*');
$this->db->order_by('NIK');
$this->db->from('');
$this->db->where('penduduk',$id);
$query = $this->db->get();
return $query->row();
}
public function find2($NIK)
{
$this->db->select('penduduk');
$this->db->from('penduduk');
///$this->db->join('desa','penduduk.id_desa = desa.id_desa', 'LEFT');
$this->db->where('penduduk.NIK',$NIK);
$query = $this->db->get();
return $query->result();
}
// public function find3($NIK)
////{
//$this->db->select('penduduk.*, desa.desa');
//$this->db->from('penduduk');
//$this->db->join('desa','penduduk.id_desa = desa.id_desa', 'LEFT');
//$this->db->where('penduduk.nik_penduduk',$nik_penduduk);
//$query = $this->db->get();
///return $query->row();
//}
}
?>
<file_sep><style>
td.details-control {
background: url('../assets/icon/plus-square-solid.png') no-repeat center center;
cursor: pointer;
margin: 3px;
padding: 5px;
fill: Dodgerblue;
}
tr.shown td.details-control {
background: url('../assets/icon/minus-square-solid.png') no-repeat center center;
}
</style>
<body id="page-top">
<div class="container-fluid">
<div class="row">
<div class="col">
<h1 class="judul h3 text-gray-800">Daftar <?= $title ?></h1>
<div class="card shadow mb-4">
<div class="card-body">
<div class="table-responsive">
<table id="datatable-permintaan-surat" class="table table-striped display nowrap" style="width: 100%;" id="table1">
<thead>
<tr>
<th></th>
<th>#</th>
<th>NIK</th>
<th>Nama</th>
<th>Email</th>
<th>Jenis Surat</th>
<th>Status Surat</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</>
<!-- Modal -->
<div class="modal fade" id="prosesData" tabindex="-1" aria-labelledby="prosesDataLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="prosesDataLabel">Proses surat</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="proses_surat_form">
<input type="hidden" name="id" class="form-control" id="id_proses" aria-describedby="emailHelp">
<input type="hidden" name="jenis_surat" class="form-control" id="jenis_surat" aria-describedby="emailHelp">
<div class="form-group">
<label for="exampleInputEmail1">Nama</label>
<input readonly id="nama" type="text" class="form-control" aria-describedby="emailHelp">
</div>
<div class="form-group">
<label for="exampleInputEmail1">NIK</label>
<input readonly id="nik" type="text" class="form-control" aria-describedby="emailHelp">
</div>
<div class="form-group">
<label for="exampleFormControlSelect2">Proses surat</label>
<select class="form-control" id="proses_surat_val">
<option selected disabled>Choose...</option>
<option value="Accepted">Accepted</option>
<option value="Rejected">Rejected</option>
</select>
</div>
<div id="comp_alasan_rejected" class="form-group">
<label for="exampleInputEmail1">Alasan</label>
<textarea placeholder="alasan permintaan surat direject" id="alasan" type="text" class="form-control" aria-describedby="emailHelp"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
<!-- End Modal -->
<script>
$(document).ready(function() {
function format(d){
var result = null
var no_surat_new = '-'
if (d.no_surat != null ) {
no_surat_new = d.no_surat
}
if(d.jenis_surat == 'Surat Kelahiran'){
result = '<table cellpadding="5" cellspacing="0" class="table table-striped "'+
'<tr>'+
'<td> Keterangan</td>'+
'<td>'+d.keterangan+'</td>'+
'<tr>'+
'<tr>'+
'<td> Alamat</td>'+
'<td>'+d.alamat+'</td>'+
'<tr>'+
'<tr>'+
'<td> No Surat</td>'+
'<td>'+no_surat_new +'</td>'+
'<tr>'+
'<tr>'+
'<td> Surat Pengantar RT/RW</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.surat_rt_rw+'>'+d.surat_rt_rw+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> E-KTP kedua Orang Tua</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.ktp_ortu+'>'+d.ktp_ortu+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> Kartu Keluarga (KK)</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.ktp_ortu+'>'+d.ktp_ortu+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> Surat Nikah Orang Tua</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.surat_nikah+'>'+d.surat_nikah+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> Surat Keterangan Lahir dari RS</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.surat_keterangan_rs+'>'+d.surat_keterangan_rs+'</a></td>'+
'<tr>'+
'<table>';
}else if(d.jenis_surat == 'Surat Kematian'){
result = '<table cellpadding="5" cellspacing="0" class="table table-striped "'+
'<tr>'+
'<td> Keterangan</td>'+
'<td>'+d.keterangan+'</td>'+
'<tr>'+
'<tr>'+
'<td> Alamat</td>'+
'<td>'+d.alamat+'</td>'+
'<tr>'+
'<tr>'+
'<td> No Surat</td>'+
'<td>'+no_surat_new +'</td>'+
'<tr>'+
'<tr>'+
'<td> Surat Pengantar RT/RW</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.surat_rt_rw+'>'+d.surat_rt_rw+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> E-KTP</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.ktp+'>'+d.ktp+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> Kartu Keluarga (KK)</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.kk+'>'+d.kk+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> Surat Nikah</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.surat_nikah+'>'+d.surat_nikah+'</a></td>'+
'<tr>'+
'<table>';
}else if(d.jenis_surat == 'Surat Nikah'){
result = '<table cellpadding="5" cellspacing="0" class="table table-striped "'+
'<tr>'+
'<td> Keterangan</td>'+
'<td>'+d.keterangan+'</td>'+
'<tr>'+
'<tr>'+
'<td> Alamat</td>'+
'<td>'+d.alamat+'</td>'+
'<tr>'+
'<tr>'+
'<td> No Surat</td>'+
'<td>'+no_surat_new +'</td>'+
'<tr>'+
'<tr>'+
'<td> Surat Pengantar RT/RW</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.surat_rt_rw+'>'+d.surat_rt_rw+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> Akta Kelahiran</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.akta_kelahiran+'>'+d.akta_kelahiran+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> Ijazah Terakhir</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.ijazah+'>'+d.ijazah+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> KTP</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.ktp+'>'+d.ktp+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> Kartu Keluarga (KK)</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.kk+'>'+d.kk+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> KTP Orang Tua</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.ktp_ortu+'>'+d.ktp_ortu+'</a></td>'+
'<tr>'+
'<table>';
}else if(d.jenis_surat == 'Surat Pindah Daerah'){
result = '<table cellpadding="5" cellspacing="0" class="table table-striped "'+
'<tr>'+
'<td> Keterangan</td>'+
'<td>'+d.keterangan+'</td>'+
'<tr>'+
'<tr>'+
'<td> Alamat</td>'+
'<td>'+d.alamat+'</td>'+
'<tr>'+
'<tr>'+
'<td> No Surat</td>'+
'<td>'+no_surat_new +'</td>'+
'<tr>'+
'<tr>'+
'<td> Surat Pengantar RT/RW</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.surat_rt_rw+'>'+d.surat_rt_rw+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> E-KTP </td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.ktp+'>'+d.ktp+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> Kartu Keluarga (KK)</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.kk+'>'+d.kk+'</a></td>'+
'<tr>'+
'<table>';
}else if(d.jenis_surat == 'Surat Keterangan Usaha'){
result = '<table cellpadding="5" cellspacing="0" class="table table-striped "'+
'<tr>'+
'<td> Keterangan</td>'+
'<td>'+d.keterangan+'</td>'+
'<tr>'+
'<tr>'+
'<td> Alamat</td>'+
'<td>'+d.alamat+'</td>'+
'<tr>'+
'<tr>'+
'<td> No Surat</td>'+
'<td>'+no_surat_new +'</td>'+
'<tr>'+
'<tr>'+
'<td> Surat Pengantar RT/RW</td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.surat_rt_rw+'>'+d.surat_rt_rw+'</a></td>'+
'<tr>'+
'<tr>'+
'<td> E-KTP </td>'+
'<td><a target="_blank" href=<?= base_url('./media/surat/')?>'+d.ktp+'>'+d.ktp+'</a></td>'+
'<tr>'+
'<table>';
}
return result
}
var table = $('#datatable-permintaan-surat').DataTable( {
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
"url": "<?php echo site_url('/suratPengantar/permintaan_surat_datatabel')?>",
"type": "POST"
},
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent":''
},
{ "data": "no" },
{ "data": "NIK" },
{ "data": "nama" },
{ "data": "email" },
{ "data": "jenis_surat" },
{ "data": "proses_surat" },
{ "data": "aksi" },
]
});
//detail data
$('#datatable-permintaan-surat tbody').on('click', 'td.details-control', function(){
var tr = $(this).closest('tr');
var row = table.row(tr);
var col = tr.find('td:eq(6)').text();
if (row.child.isShown()){
row.child.hide();
tr.removeClass('shown');
}else{
row.child(format(row.data()) ).show();
tr.addClass('shown');
}
});
});
</script>
<script>
$(document).ready(function(){
$('#comp_alasan_rejected').hide();
$("#proses_surat_val").change(function(){
var selectedReject = $(this).children("option:selected").val();
console.log(selectedReject)
if (selectedReject == 'Rejected') {
$('#comp_alasan_rejected').show();
}else{
$('#comp_alasan_rejected').hide();
}
});
});
</script>
<script>
function konfirmasi(){
return confirm('Apakah Anda yakin?')
}
</script>
<script>
function proses_button(id, jenis_surat, nama, nik, proses_surat) {
if (proses_surat == 'Finish' || proses_surat == 'Accepted') {
$('#id_proses').val(id)
$('#jenis_surat').val(jenis_surat)
$('#nama').val(nama)
$('#nik').val(nik)
$('#proses_surat_val').find('option')
.remove()
.end()
.append(`<option value="" selected disabled>${proses_surat}</option>`)
.val("");
$('#prosesData').modal('show')
}else if(proses_surat == ''){
$('#id_proses').val(id)
$('#jenis_surat').val(jenis_surat)
$('#nama').val(nama)
$('#nik').val(nik)
$('#proses_surat_val').find('option')
.remove()
.end()
.append(` <option selected disabled>Choose...</option>`)
.append(`<option value="Accepted">Accepted</option>`)
.append(`<option value="Rejected">Rejected</option>`)
$('#prosesData').modal('show')
}else{
}
}
$('#proses_surat_form').on("submit", function(e){
e.preventDefault();
console.log(1)
var id = $('#id_proses').val();
var jenis_surat = $('#jenis_surat').val();
var jenis_surat = $('#jenis_surat').val();
var proses_surat = $('#proses_surat_val').val();
var alasan = $('#alasan').val();
console.log(proses_surat)
if (id && jenis_surat) {
$.ajax({
type: "POST",
url: "<?php echo site_url('/suratPengantar/proses_permintaan_surat')?>",
data: {
'id' : id,
'jenis_surat' : jenis_surat,
'proses_surat' : proses_surat,
'alasan' : alasan
},
dataType: 'JSON',
success: function(data){
$('#proses_surat_val').val("Choose...");
$('#prosesData').modal('hide');
$('#datatable-permintaan-surat').DataTable().ajax.reload()
// location.reload()
$('.alert').addClass( "alert-success" );
$('.alert').append( '<span id="text-alert"><i class="fa fa-check"></i> <strong>Success!</strong> Data berhasil ditambahkan !!</span>' );
$('.alert').slideDown("slow").show();
setTimeout(function(){
$('.alert').slideUp(700, function(){ $(this).hide() });
$('#text-alert').remove()
}, 3000);
}
});
}
});
</script>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sur<NAME></title>
<style>
body{
padding: 0;
margin: 0;
}
.content {
max-width: 793px;
margin: auto;
}
th, td {
padding: 0px;
}
.logo{
width: 70.79px;
height: 95.05px;
display: block;
margin-left: auto;
margin-right: auto;
}
.kop-judul{
font-weight: bold;
font-size: x-large;
text-align: center;
}
.kop-sub{
font-size: x-small;
text-align: center;
}
hr.solid {
border-top: 4px solid rgb(17, 17, 17);
}
</style>
</head>
<body>
<center>
<div class="content">
<table border="0" width="593">
<tr>
<td rowspan="2"><img class="logo" alt="" src="<?=base_url('assets\img\image1.png')?>" title=""></td>
<td class="kop-judul">PEMERINTAH KABUPATEN CILACAP <br>
KECAMATAN CIPARI</td>
</tr>
<tr>
<td class="kop-sub">Alamat: Jalan J<NAME>ani No 42, Kode Pos 53262, Telp. (0280) 523412</td>
</tr>
<tr>
<td style="padding: -3px;" colspan="2">
<hr class="solid">
</td>
</tr>
<tr>
<td colspan="2">
Cipari, <?=date("d F Y ") ?>
</td>
</tr>
</table>
<table border="0" width="593">
<?=$kontent?>
<tr>
<td colspan="2">
<table style="margin-left:300px; margin-top: 100px;">
<tr>
<td align="center" style="padding-bottom: 10px;">Cipari, <?=date("d F Y ")?></td>
</tr>
<tr>
<td align="center" ><?=$jabatan_ttd?></td>
</tr>
<tr>
<td><center><img width="100" height="100" src="..\<?=$ttd_img?>" alt=""></center></td>
</tr>
<tr>
<td align="center" style="padding-bottom: 10px;" ><?= $nama_ttd?></td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</center>
</body>
</html>
<script>
window.onload = function () {
window.print();
path = location.pathname.split("/")
window.onafterprint = function(){
console.log("Printing completed...");
location.replace("<?= base_url('suratkeluar')?>")
}
};
</script><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_laporanmasuk extends CI_Model {
function filterbybulan($bulan = null, $tahun = null){
$query = $this->db->query("SELECT * from tb_masuk where MONTH(tgl_surat) = '$bulan' AND YEAR(tgl_surat) = '$tahun' ORDER BY tgl_surat ASC ");
return $query->result();
}
function filterbytahun($tahun){
$query = $this->db->query("SELECT * from tb_masuk where YEAR(tgl_surat) = '$tahun' ORDER BY tgl_surat ASC ");
return $query->result();
}
}
/* End of file Barang_model.php */
/* Location: ./application/models/Barang_model.php */<file_sep> <section class="page-section about-heading">
<div class="container">
<img class="img-fluid rounded about-heading-img mb-3 mb-lg-0">
<div class="about-heading-content">
<div class="row">
<div class="col-xl-9 col-lg-10 mx-auto">
<div class="bg-faded rounded p-5">
<h2 class="section-heading mb-4">
<h1>Selamat Datang di Website Ajuan Surat Pengantar Online </h1>
<p> Untuk <b>proses surat yang anda ajukan,</b> file surat akan dikirim ke <b>NO WHATSAPP</b> anda atau dapat mengambil langsung ke Kantor Kelurahan.</p>
<p>Jika anda sudah memahami prosedur pendaftaran ajuan surat, silahkan klik tombol <b>Daftar</b> dibawah ini untuk melakukan <b>Pendaftaran!</b> atau anda bisa klik tombol <b>Surat Online!</b> pada halaman menu.</p>
<p><a class="btn btn-primary btn-lg" href="<?php echo site_url('suratPengantar');?>" role="button">Daftar</a></p>
</h2>
</div>
</div>
</div>
</div>
</div>
</section><file_sep><script type="text/javascript">
function show_modal(id) {
$.ajax({
type : 'GET',
url : '<?= base_url()?>surat/dashboard/show_dataw/'+id,
dataType : 'json',
success : function(data){
console.log(data);
$('#1').text(data.NIK);
$('#2').text(data.nama);
$('#3').text(data.alamat);
$('#4').text(data.tempat_tgl_lahir);
$('#5').text(data.agama);
$('#6').text(data.status);
$('#7').text(data.agama);
$('#8').text(data.pekerjaan);
$('#9').text(data.alamat);
}
});
}
</script><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_laporankeluar extends CI_Model {
function filterbybulan($bulan = null, $tahun = null){
$sql = "
SELECT * FROM (
SELECT surat_kematian.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, surat_nikah ,null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_kematian JOIN penduduk ON surat_kematian.id_penduduk=penduduk.id
UNION ALL
SELECT surat_nikah.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, ktp_ortu, kk, null as surat_nikah ,null as surat_keterangan_rs, ktp, akta_kelahiran, ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_nikah JOIN penduduk ON surat_nikah.id_penduduk=penduduk.id
UNION ALL
SELECT surat_pindah_domisili.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_pindah_domisili JOIN penduduk ON surat_pindah_domisili.id_penduduk=penduduk.id
UNION ALL
SELECT surat_tugas.id as id, null as nama, null as nik, null as alamat, null as email, null as jk, null as agama, jenis_surat, null as surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, null as ktp, null as akta_kelahiran, null as ijazah, null as keterangan, proses_surat, no_surat, null as kode_surat, tanggal FROM surat_tugas
UNION ALL
SELECT surat_undangan.id as id, null as nama, null as nik, null as alamat, null as email, null as jk, null as agama, jenis_surat, null as surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, null as ktp, null as akta_kelahiran, null as ijazah, null as keterangan, proses_surat, no_surat, null as kode_surat, tanggal FROM surat_undangan
UNION ALL
SELECT surat_sku.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_sku JOIN penduduk ON surat_sku.id_penduduk=penduduk.id
) AS surat_keluar
WHERE surat_keluar.proses_surat='Finish' AND MONTH(surat_keluar.tanggal)=$bulan AND YEAR(surat_keluar.tanggal) = $tahun
";
return $this->db->query($sql)->result();
}
function filterbytahun($tahun){
$query = $this->db->query("SELECT * from tb_keluar where YEAR(tgl_surat) = '$tahun' ORDER BY tgl_surat ASC ");
return $query->result();
}
}
/* End of file Barang_model.php */
/* Location: ./application/models/Barang_model.php */<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_perangkat_desa extends CI_Model{
public function login($user,$pw)
{
$this->db->where('username', $user);
$this->db->where('password', $pw);
$query = $this->db->get('users');
return $query;
}
public function get($id = null){
$this->db->from('perangkat_desa');
if($id != null){
$this->db->where('id', $id);
}
$query = $this->db->get();
return $query;
}
public function add($post){
$params['nama'] = $post['nama'];
$params['nik'] = $post['nik'];
$params['jabatan'] = $post['jabatan'];
$params['divisi'] = $post['divisi'];
$params['status'] = $post['status'];
$this->db->insert('perangkat_desa', $params);
}
public function edit($post){
$params['nama'] = $post['nama'];
$params['nik'] = $post['nik'];
$params['jabatan'] = $post['jabatan'];
$params['divisi'] = $post['divisi'];
$params['status'] = $post['status'];
$this->db->where('id', $post['id']);
$this->db->update('perangkat_desa', $params);
}
public function deleteData($table,$where){
$this->db->delete($table,$where);
}
}
?><file_sep> <section class="page-section about-heading">
<div class="container">
<img class="img-fluid rounded about-heading-img mb-3 mb-lg-0" src="img/kelurahan.png" alt="">
<div class="about-heading-content">
<div class="row">
<div class="col-xl-9 col-lg-10 mx-auto">
<div class="bg-faded rounded p-5">
<h2 class="section-heading mb-4">
<h1 align="center"><p>Pelayanan Surat Online</p>
<a href="https://Semarapurakaja.desa.id">Desa Kalongan</a>
</h1>
<p class="lead">Silahkan lengkapi semua isian sesuai dengan data yang diperlukan</p>
<form id="contact-form" method="post" action="<?= base_url('suratPengantar/add') ?>" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">Nama *</label>
<input id="form_name" type="text" name="nama" class="form-control" placeholder="Silahkan masukkan nama anda *" required="required" data-error="Nama harus diisi!.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">NIK *</label>
<input id="form_lastname" type="text" name="NIK" class="form-control" placeholder="Silahkan masukkan NIK anda *" required="required" data-error="NIK Harus diisi!.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_alamat">Alamat *</label>
<input id="form_alamat" type="text" name="alamat" class="form-control" placeholder="Silahkan masukkan alamat anda *" required="required" data-error="Format alamat salah.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_wa">No Whatsapp *</label>
<input id="form_wa" type="text" name="whatsapp" class="form-control" placeholder="Silahkan masukkan no whatsapp anda *" required="required" data-error="Format no salah.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_need">Pilih Jenis Surat *</label>
<select id="form_need" name="keperluan" class="form-control" required="required" data-error="Pilih jenis surat yang anda perlukan">
<option value=""></option>
<option value="Surat Keterangan Usaha">Surat Keterangan Usaha</option>
<option value="Surat Keterangan Tidak Mampu">Surat Keterangan Tidak Mampu</option>
<option value="Surat Keterangan Miskin">Surat Keterangan Miskin</option>
<option value="Surat Keterangan Belum Pernah Menikah">Surat Keterangan Belum Pernah Menikah</option>
<option value="Surat Keterangan Kelahiran">Surat Keterangan Kelahiran</option>
<option value="Surat Keterangan Kematian">Surat Keterangan Kematian</option>
<option value="Surat Keterangan Beda Nama">Surat Keterangan Beda Nama</option>
<option value="Surat Keterangan Penghasilan">Surat Keterangan Penghasilan</option>
<option value="Surat Keterangan Harga Tanah">Surat Keterangan Harga Tanah</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Pesan *</label>
<textarea id="form_message" name="keterangan" class="form-control" placeholder="Silahkan isi keperluan atau keterangan lainnya disini *" rows="4" required="required" data-error="Silahkan isi pesan atau keterangan anda."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<input type="submit" class="btn btn-success btn-send"><a href=<?= base_url('suratPengantar/add') ?>>
</a>
</div>
<div class="col-md-6">
<input type="button" class="btn btn-danger btn-send" value="Kembali" onclick="window.history.back()" />
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted">
<strong>*</strong> Harus diisi
</p>
</div>
</div>
</div>
</form>
</div>
<!-- /.8 -->
</div>
<!-- /.row-->
</div>
<!-- /.container-->
</section>
<file_sep><style>
td.details-control {
background: url('assets/icon/plus-square-solid.png') no-repeat center center;
cursor: pointer;
margin: 3px;
padding: 5px;
fill: Dodgerblue;
}
tr.shown td.details-control {
background: url('assets/icon/minus-square-solid.png') no-repeat center center;
}
</style>
<body id="page-top">
<div class="container-fluid">
<div class="row">
<div class="col">
<h1 class="judul h3 text-gray-800">Daftar <?= $title ?></h1>
<div class="card shadow mb-4">
<div class="card-header py-3">
<a href="<?= base_url('penduduk/add'); ?>" class="btn btn-primary mb-3">Tambah Data</a>
</div>
<div class="card-body">
<div class="table-responsive">
<table id="datatable-penduduk" class="table table-striped display nowrap" style="width: 100%;" id="table1">
<thead>
<tr>
<th></th>
<th>#</th>
<th>NIK</th>
<th>Nama Lengkap</th>
<th>Status</th>
<th>Jenis Kelamin</th>
<th>Pekerjaan</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script>
$(document).ready(function() {
function format(d){
result = '<table cellpadding="5" cellspacing="0" class="table table-striped "'+
'<tr>'+
'<td> Tempat, tanggal lahir</td>'+
'<td>'+d.tempat_tgl_lahir+'</td>'+
'<tr>'+
'<tr>'+
'<td> Agama</td>'+
'<td>'+d.agama+'</td>'+
'<tr>'+
'<tr>'+
'<td> Alamat</td>'+
'<td>'+d.alamat+'</td>'+
'<tr>'+
'<table>';
return result
}
var table = $('#datatable-penduduk').DataTable( {
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
"url": "<?php echo site_url('/Penduduk/user_datatabel')?>",
"type": "POST"
},
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent":''
},
{ "data": "no" },
{ "data": "NIK" },
{ "data": "nama" },
{ "data": "status" },
{ "data": "jk" },
{ "data": "pekerjaan" },
{ "data": "aksi" },
]
});
//detail data
$('#datatable-penduduk tbody').on('click', 'td.details-control', function(){
var tr = $(this).closest('tr');
var row = table.row(tr);
var col = tr.find('td:eq(6)').text();
if (row.child.isShown()){
row.child.hide();
tr.removeClass('shown');
}else{
row.child(format(row.data()) ).show();
tr.addClass('shown');
}
});
});
</script>
<script>
function konfirmasi(){
return confirm('Apakah Anda yakin?')
}
</script>
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class LaporanKeluar extends CI_Controller {
var $ttd_img;
public function __construct()
{
parent::__construct();
check_not_login();
$this->load->model('m_laporankeluar');
$this->ttd_img = [
'Kepala Desa' => 'media\surat\ttd2.jpg',
'Sekretaris Desa' => 'media\surat\ttd3.jpg',
'Admin' => 'media\surat\ttd.jpg',
];
}
public function index()
{
$data['title'] = "Laporan Keluar";
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('laporanKeluar/laporanKeluar', $data);
$this->load->view('template_admin/footer');
}
public function data_surat_keluar()
{
$bulan = $this->input->post('bulan');
$tahun = $this->input->post('tahun');
$list = $this->m_laporankeluar->filterbybulan($bulan,$tahun);
$no = 0;
foreach ($list as $field) {
$no++;
$row = array();
$row['no'] = $no;
$row['no_surat'] = $field->no_surat;
$row['tanggal'] = $field->tanggal;
$row['jenis_surat'] = $field->jenis_surat;
$data[] = $row;
}
echo json_encode($data);
}
function print(){
$bulan = $this->input->post('bulan');
$tahun = $this->input->post('tahun');
$data['datafilter'] = $this->m_laporankeluar->filterbybulan($bulan,$tahun);
$data['ttd_img'] = $this->ttd_img['Admin'];
$this->load->view('LaporanKeluar/v_Laporan', $data);
}
}
<file_sep><script src="<?= base_url('assets/') ?>vendor/chart.js/Chart.min.js"></script>
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Modal Dialog berhasil login-->
<div class="alert alert-success alert-dismissible fade show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>Login</strong> berhasil, selamat datang <strong><?= ucfirst($this->fungsi->user_login()->username) ?></strong>.
</div>
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800">Dashboard</h1>
</div>
<!-- Content Row -->
<div class="row">
<!-- Earnings (Monthly) Card Example -->
<div style="cursor:pointer" title="klik untuk detail data" onclick="data_surat_masuk()" class="col-xl-3 col-md-6 mb-4">
<div class="card border-left-danger shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-danger text-uppercase mb-1">
Data Surat Masuk</div>
<div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $masuk ?></div>
</div>
<div class="col-auto">
<i class="fas fa-paper-plane"></i>
</div>
</div>
</div>
</div>
</div>
<!-- Earnings (Monthly) Card Example -->
<div style="cursor:pointer" title="klik untuk detail data" onclick="data_surat_keluar()" class="col-xl-3 col-md-6 mb-4">
<div class="card border-left-warning shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
Data Surat Keluar</div>
<div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $keluar ?></div>
</div>
<div class="col-auto">
<i class="fas fa-paper-plane"></i>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div id="data_surat_masuk" class="col-xl-12 col-lg-12">
<div class="card shadow mb-4">
<!-- Card Header - Dropdown -->
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Data Surat Masuk</h6>
<div class="dropdown no-arrow">
<a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
</a>
</div>
</div>
<!-- Card Body -->
<div class="card-body">
<div class="table-responsive">
<table id="datatable-surat-masuk" class="table table-striped display nowrap table-sm" style="width: 100%;" id="table1" align="center">
<thead>
<tr align="center" class="bg-primary" style = "color: white;">
<th></th>
<th>No</th>
<th>No. Surat</th>
<th>Pengirim</th>
<th>Keterangan</th>
<th>Action</th>
</tr>
</thead>
<tbody align="center">
</tbody>
</table>
</div>
</div>
</div>
</div>
<div id="data_surat_keluar" class="col-xl-12 col-lg-12">
<div class="card shadow mb-4">
<!-- Card Header - Dropdown -->
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Data Surat Keluar</h6>
<div class="dropdown no-arrow">
<a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
</a>
</div>
</div>
<!-- Card Body -->
<div class="card-body">
<div class="table-responsive">
<table id="datatable-surat-keluar" class="table table-striped display nowrap table-sm" style="width: 100%;" id="table1" align="center">
<thead>
<tr align="center" class="bg-primary" style = "color: white;">
<th></th>
<th>No</th>
<th>No. Surat</th>
<th>Jenis Surat</th>
<th>Tanggal Surat</th>
<th>NIK</th>
<th>Nama</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- End of Main Content -->
<!-- Modal detail data -->
<div class="modal fade" id="detailData" tabindex="-1" role="dialog" aria-labelledby="detailDataLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="detailData">Detail data </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="deleteSurat" action="">
<div class="modal-body">
<span id="tabel_detail_data">
</span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
</div>
</form>
</div>
</div>
</div>
<!-- End modal detail data -->
<script>
$(document).ready(function() {
$('#data_surat_keluar').hide()
$('#data_surat_masuk').hide()
var table = $('#datatable-surat-keluar').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
"url": "<?php echo site_url('/dashboard/permintaan_surat_datatabel') ?>",
"type": "POST"
},
"columns": [{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{"data": "no"},
{"data": "no_surat"},
{"data": "jenis_surat"},
{"data": "tanggal"},
{"data": "NIK",
"render": function(data){
if (data != null) {
return data
}else{
return '-'
}
}
},
{
"data": "nama",
"render": function(data){
if (data != null) {
return data
}else{
return '-'
}
}
},
{"data": "aksi",
"render": function(data) {
var jenis_surat = data.jenis_surat.replace(/ /g, "_")
return `
<a onclick="detailSurat(${data.id},'${data.jenis_surat}')" class="btn btn-info btn-icon-split">
<span class="icon text-white-50">
<i class="fas fa-info-circle"></i>
</span>
<span class="text">detail data</span>
</a>
`
}
},
]
});
var table_masuk = $('#datatable-surat-masuk').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
"url": "<?php echo site_url('/dashboard/get_surat_masuk') ?>",
"type": "POST"
},
"columns": [{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{"data": "no"},
{"data": "no_surat"},
{"data": "pengirim"},
{"data": "keterangan",
"render": function (data) {
if (data != '') {
return data
}else{
return '-'
}
}
},
{"data": "aksi",
"render": function(data) {
return `
<a onclick="detailSuratMasuk(${data.no})" class="btn btn-info btn-icon-split">
<span class="icon text-white-50">
<i class="fas fa-info-circle"></i>
</span>
<span class="text">detail data</span>
</a>
`
}
},
]
});
});
</script>
<script>
function detailSuratMasuk(id) {
$.ajax({
type: "POST",
url: "<?php echo site_url('Dashboard/detail_surat_masuk') ?>",
dataType: "JSON",
data: {
id: id,
},
success: function(data) {
console.log(data.data_surat.no)
$('#detailData').modal('show');
var html = `
<table cellpadding="2" cellspacing="4" style="font-size: 15px;" >
<tr>
<td width="150px">No Surat </td>
<td>:</td>
<td>${data.data_surat.no_surat}</td>
</tr>
<tr>
<td>Pengirim</td>
<td>:</td>
<td>${data.data_surat.pengirim}</td>
</tr>
<tr>
<td>Tanggal Surat</td>
<td>:</td>
<td>${data.data_surat.tgl_surat}</td>
</tr>
<tr>
<td>Tanggal Terima</td>
<td>:</td>
<td>${data.data_surat.tgl_terima}</td>
</tr>
<tr>
<td>Keterangan</td>
<td>:</td>
<td>${data.data_surat.keterangan ? data.data_surat.keterangan : '-'}</td>
</tr>
<tr>
<td>File Surat</td>
<td>:</td>
<td><a href="<?=base_url('suratmasuk/download/')?>${data.data_surat.no}">${data.data_surat.file_surat}</a></td>
</tr>
</table>
`
$('#tabel_detail_data').html(html);
}
})
}
</script>
<script>
function detailSurat(id, jenis_surat) {
$.ajax({
type: "POST",
url: "<?php echo site_url('Dashboard/detail_surat') ?>",
dataType: "JSON",
data: {
id: id,
jenis_surat: jenis_surat
},
success: function(data) {
$('#detailData').modal('show');
jenis_surat = data.data_surat.jenis_surat;
console.log(data.data_surat)
var html = `
<table cellpadding="2" cellspacing="4" style="font-size: 15px;">
<tr>
<td width="150px">Nama </td>
<td>:</td>
<td>${data.data_surat.nama}</td>
</tr>
<tr>
<td>Tempat, tanggal lahir</td>
<td>:</td>
<td>${data.data_surat.tempat_tgl_lahir}</td>
</tr>
<tr>
<td>Status perkawinan</td>
<td>:</td>
<td>${data.data_surat.status}</td>
</tr>
<tr>
<td>Agama</td>
<td>:</td>
<td>${data.data_surat.agama}</td>
</tr>
<tr>
<td>No Surat</td>
<td>:</td>
<td>${data.data_surat.no_surat}</td>
</tr>
<tr>
<td>Tanggal Surat</td>
<td>:</td>
<td>${data.data_surat.tanggal}</td>
</tr>
<tr>
<td>Alamat</td>
<td>:</td>
<td>${data.data_surat.alamat}</td>
</tr>
</table>
`
if (jenis_surat == 'Surat Keterangan Usaha') {
var html = `
<table cellpadding="2" cellspacing="4" style="font-size: 15px;">
<tr>
<td width="150px">Nama </td>
<td>:</td>
<td>${data.data_surat.nama}</td>
</tr>
<tr>
<td>Tempat, tanggal lahir</td>
<td>:</td>
<td>${data.data_surat.tempat_tgl_lahir}</td>
</tr>
<tr>
<td>Status perkawinan</td>
<td>:</td>
<td>${data.data_surat.status}</td>
</tr>
<tr>
<td>Agama</td>
<td>:</td>
<td>${data.data_surat.agama}</td>
</tr>
<tr>
<td>No Surat</td>
<td>:</td>
<td>${data.data_surat.no_surat}</td>
</tr>
<tr>
<td>Tanggal Surat</td>
<td>:</td>
<td>${data.data_surat.tanggal}</td>
</tr>
<tr>
<td>Alamat</td>
<td>:</td>
<td>${data.data_surat.alamat}</td>
</tr>
<tr>
<td>Nama Usaha</td>
<td>:</td>
<td>${data.data_surat.nama_usaha}</td>
</tr>
</table>
`
}else if(jenis_surat == 'Surat Pindah Daerah'){
var html = `
<table cellpadding="2" cellspacing="4" style="font-size: 15px;">
<tr>
<td width="150px">Nama </td>
<td>:</td>
<td>${data.data_surat.nama}</td>
</tr>
<tr>
<td>Tempat, tanggal lahir</td>
<td>:</td>
<td>${data.data_surat.tempat_tgl_lahir}</td>
</tr>
<tr>
<td>Status perkawinan</td>
<td>:</td>
<td>${data.data_surat.status}</td>
</tr>
<tr>
<td>Agama</td>
<td>:</td>
<td>${data.data_surat.agama}</td>
</tr>
<tr>
<td>No Surat</td>
<td>:</td>
<td>${data.data_surat.no_surat}</td>
</tr>
<tr>
<td>Tanggal Surat</td>
<td>:</td>
<td>${data.data_surat.tanggal}</td>
</tr>
<tr>
<td>Alamat</td>
<td>:</td>
<td>${data.data_surat.alamat}</td>
</tr>
<tr>
<td>Alamat Pindah</td>
<td>:</td>
<td>${data.data_surat.alamat_pindah}</td>
</tr>
<tr>
<td>Alasan Pindah</td>
<td>:</td>
<td>${data.data_surat.alasan_pindah}</td>
</tr>
<tr>
<td>Pengikut</td>
<td>:</td>
<td>${data.data_surat.pengikut}</td>
</tr>
</table>
`
}else if(jenis_surat == 'Surat Kelahiran'){
var html = `
<table cellpadding="2" cellspacing="4" style="font-size: 15px;">
<tr>
<td width="150px">Nama </td>
<td>:</td>
<td>${data.data_surat.nama}</td>
</tr>
<tr>
<td>Tempat, tanggal lahir</td>
<td>:</td>
<td>${data.data_surat.tempat_tgl_lahir}</td>
</tr>
<tr>
<td>Status perkawinan</td>
<td>:</td>
<td>${data.data_surat.status}</td>
</tr>
<tr>
<td>Agama</td>
<td>:</td>
<td>${data.data_surat.agama}</td>
</tr>
<tr>
<td>No Surat</td>
<td>:</td>
<td>${data.data_surat.no_surat}</td>
</tr>
<tr>
<td>Tanggal Surat</td>
<td>:</td>
<td>${data.data_surat.tanggal}</td>
</tr>
<tr>
<td>Alamat</td>
<td>:</td>
<td>${data.data_surat.alamat}</td>
</tr>
<tr>
<td>Nama Ayah</td>
<td>:</td>
<td>${data.data_surat.nama_ayah}</td>
</tr>
<tr>
<td>Nama Ibu</td>
<td>:</td>
<td>${data.data_surat.nama_ibu}</td>
</tr>
<tr>
<td>Anak Ke </td>
<td>:</td>
<td>${data.data_surat.anak_ke}</td>
</tr>
</table>
`
}else if(jenis_surat == 'Surat Kematian'){
var html = `
<table cellpadding="2" cellspacing="4" style="font-size: 15px;">
<tr>
<td width="150px">Nama </td>
<td>:</td>
<td>${data.data_surat.nama}</td>
</tr>
<tr>
<td>Tempat, tanggal lahir</td>
<td>:</td>
<td>${data.data_surat.tempat_tgl_lahir}</td>
</tr>
<tr>
<td>Status perkawinan</td>
<td>:</td>
<td>${data.data_surat.status}</td>
</tr>
<tr>
<td>Agama</td>
<td>:</td>
<td>${data.data_surat.agama}</td>
</tr>
<tr>
<td>No Surat</td>
<td>:</td>
<td>${data.data_surat.no_surat}</td>
</tr>
<tr>
<td>Tanggal Surat</td>
<td>:</td>
<td>${data.data_surat.tanggal}</td>
</tr>
<tr>
<td>Alamat</td>
<td>:</td>
<td>${data.data_surat.alamat}</td>
</tr>
<tr>
<td>Hari Meninggal</td>
<td>:</td>
<td>${data.data_surat.hari_meninggal}</td>
</tr>
<tr>
<td>Jam Meninggal</td>
<td>:</td>
<td>${data.data_surat.jam_meninggal}</td>
</tr>
</table>
`
}else if(jenis_surat == 'Surat Tugas'){
var html = `
<table cellpadding="2" cellspacing="4" style="font-size: 15px;">
<tr>
<td width="150px">Nama </td>
<td>:</td>
<td>${data.data_surat.nama}</td>
</tr>
<tr>
<td width="150px">NIK </td>
<td>:</td>
<td>${data.data_surat.nik}</td>
</tr>
<tr>
<td width="150px">Jabatan </td>
<td>:</td>
<td>${data.data_surat.jabatan}</td>
</tr>
<tr>
<td width="150px">Devisi </td>
<td>:</td>
<td>${data.data_surat.divisi}</td>
</tr>
<tr>
<td width="150px">Jenis Surat</td>
<td>:</td>
<td>${data.data_surat.jenis_surat}</td>
</tr>
<tr>
<td>No Surat</td>
<td>:</td>
<td>${data.data_surat.no_surat}</td>
</tr>
<tr>
<td>Tanggal Surat</td>
<td>:</td>
<td>${data.data_surat.tanggal}</td>
</tr>
</table>
`
}else if(jenis_surat == 'Surat Undangan'){
var html = `
<table cellpadding="2" cellspacing="4" style="font-size: 15px;">
<tr>
<td width="150px">Jenis Surat </td>
<td>:</td>
<td>${data.data_surat.jenis_surat}</td>
</tr>
<tr>
<td>No Surat</td>
<td>:</td>
<td>${data.data_surat.no_surat}</td>
</tr>
<tr>
<td>Tanggal Surat</td>
<td>:</td>
<td>${data.data_surat.tanggal}</td>
</tr>
</table>
`
}
$('#tabel_detail_data').html(html);
}
});
}
</script>
<script>
function data_surat_keluar() {
$('#card_surat_masuk').hide()
$('#card_surat_keluar').hide()
$('#data_surat_masuk').hide()
$('#data_surat_keluar').show()
}
</script>
<script>
function data_surat_masuk() {
$('#card_surat_masuk').hide()
$('#card_surat_keluar').hide()
$('#data_surat_keluar').hide()
$('#data_surat_masuk').show()
}
</script>
<file_sep><?php
class M_keluar extends CI_Model{
public function __construct()
{
parent::__construct();
$this->load->database();
}
private function CustomDataTabel()
{
$sql = "
SELECT * FROM (
SELECT surat_kematian.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, surat_nikah ,null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_kematian JOIN penduduk ON surat_kematian.id_penduduk=penduduk.id
UNION ALL
SELECT surat_nikah.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, ktp_ortu, kk, null as surat_nikah ,null as surat_keterangan_rs, ktp, akta_kelahiran, ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_nikah JOIN penduduk ON surat_nikah.id_penduduk=penduduk.id
UNION ALL
SELECT surat_pindah_domisili.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_pindah_domisili JOIN penduduk ON surat_pindah_domisili.id_penduduk=penduduk.id
UNION ALL
SELECT surat_tugas.id as id, nama, nik, null as alamat, null as email, null as jk, null as agama, jenis_surat, null as surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, null as ktp, null as akta_kelahiran, null as ijazah, null as keterangan, proses_surat, no_surat, null as kode_surat, tanggal FROM surat_tugas JOIN perangkat_desa ON surat_tugas.id_perangkat_desa=perangkat_desa.id
UNION ALL
SELECT surat_undangan.id as id, kepada as nama, null as nik, null as alamat, null as email, null as jk, null as agama, jenis_surat, null as surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, null as ktp, null as akta_kelahiran, null as ijazah, null as keterangan, proses_surat, no_surat, null as kode_surat, tanggal FROM surat_undangan
UNION ALL
SELECT surat_sku.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_sku JOIN penduduk ON surat_sku.id_penduduk=penduduk.id
) AS surat_keluar
WHERE surat_keluar.proses_surat='Finish' ORDER BY surat_keluar.no_surat ASC
LIMIT ". $_POST['length']." OFFSET ". $_POST['start'] ."
";
if($_POST['search']['value']){
$tgl = $_POST['search']['value'];
$sql = "
SELECT * FROM (
SELECT surat_kematian.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, surat_nikah ,null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_kematian JOIN penduduk ON surat_kematian.id_penduduk=penduduk.id
UNION ALL
SELECT surat_nikah.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, ktp_ortu, kk, null as surat_nikah ,null as surat_keterangan_rs, ktp, akta_kelahiran, ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_nikah JOIN penduduk ON surat_nikah.id_penduduk=penduduk.id
UNION ALL
SELECT surat_pindah_domisili.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_pindah_domisili JOIN penduduk ON surat_pindah_domisili.id_penduduk=penduduk.id
UNION ALL
SELECT surat_tugas.id as id, nama, nik, null as alamat, null as email, null as jk, null as agama, jenis_surat, null as surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, null as ktp, null as akta_kelahiran, null as ijazah, null as keterangan, proses_surat, no_surat, null as kode_surat, tanggal FROM surat_tugas JOIN perangkat_desa ON surat_tugas.id_perangkat_desa=perangkat_desa.id
UNION ALL
SELECT surat_undangan.id as id, kepada as nama, null as nik, null as alamat, null as email, null as jk, null as agama, jenis_surat, null as surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, null as ktp, null as akta_kelahiran, null as ijazah, null as keterangan, proses_surat, no_surat, null as kode_surat, tanggal FROM surat_undangan
UNION ALL
SELECT surat_sku.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_sku JOIN penduduk ON surat_sku.id_penduduk=penduduk.id
) AS surat_keluar
WHERE surat_keluar.proses_surat = 'Finish' AND surat_keluar.nama LIKE'%".$tgl."%' OR surat_keluar.nik LIKE'%".$tgl."%' OR surat_keluar.jenis_surat LIKE'%".$tgl."%' OR surat_keluar.no_surat LIKE'%".$tgl."%' OR surat_keluar.tanggal LIKE'%".$tgl."%'
";
return $this->db->query($sql)->result();
}
if($_POST['length'] != -1);
return $this->db->query($sql)->result();
}
function get_datatables()
{
$query = $this->CustomDataTabel();
return $query;
}
function count_filtered()
{
$sql = "
SELECT COUNT(id) AS `jumlah_surat` FROM (
SELECT surat_kematian.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, surat_nikah ,null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_kematian JOIN penduduk ON surat_kematian.id_penduduk=penduduk.id
UNION ALL
SELECT surat_nikah.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, ktp_ortu, kk, null as surat_nikah ,null as surat_keterangan_rs, ktp, akta_kelahiran, ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_nikah JOIN penduduk ON surat_nikah.id_penduduk=penduduk.id
UNION ALL
SELECT surat_pindah_domisili.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_pindah_domisili JOIN penduduk ON surat_pindah_domisili.id_penduduk=penduduk.id
UNION ALL
SELECT surat_tugas.id as id, nama, nik, null as alamat, null as email, null as jk, null as agama, jenis_surat, null as surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, null as ktp, null as akta_kelahiran, null as ijazah, null as keterangan, proses_surat, no_surat, null as kode_surat, tanggal FROM surat_tugas JOIN perangkat_desa ON surat_tugas.id_perangkat_desa=perangkat_desa.id
UNION ALL
SELECT surat_undangan.id as id, null as nama, null as nik, null as alamat, null as email, null as jk, null as agama, jenis_surat, null as surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, null as ktp, null as akta_kelahiran, null as ijazah, null as keterangan, proses_surat, no_surat, null as kode_surat, tanggal FROM surat_undangan
UNION ALL
SELECT surat_sku.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_sku JOIN penduduk ON surat_sku.id_penduduk=penduduk.id
) AS surat_keluar
WHERE surat_keluar.proses_surat='Finish'
";
$data = $this->db->query($sql)->row_array();
return $data['jumlah_surat'];
}
public function count_all()
{
$sql = "
SELECT COUNT(id) AS `jumlah_surat` FROM (
SELECT surat_kematian.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, surat_nikah ,null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_kematian JOIN penduduk ON surat_kematian.id_penduduk=penduduk.id
UNION ALL
SELECT surat_nikah.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, ktp_ortu, kk, null as surat_nikah ,null as surat_keterangan_rs, ktp, akta_kelahiran, ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_nikah JOIN penduduk ON surat_nikah.id_penduduk=penduduk.id
UNION ALL
SELECT surat_pindah_domisili.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_pindah_domisili JOIN penduduk ON surat_pindah_domisili.id_penduduk=penduduk.id
UNION ALL
SELECT surat_tugas.id as id, nama, nik, null as alamat, null as email, null as jk, null as agama, jenis_surat, null as surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, null as ktp, null as akta_kelahiran, null as ijazah, null as keterangan, proses_surat, no_surat, null as kode_surat, tanggal FROM surat_tugas JOIN perangkat_desa ON surat_tugas.id_perangkat_desa=perangkat_desa.id
UNION ALL
SELECT surat_undangan.id as id, null as nama, null as nik, null as alamat, null as email, null as jk, null as agama, jenis_surat, null as surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, null as ktp, null as akta_kelahiran, null as ijazah, null as keterangan, proses_surat, no_surat, null as kode_surat, tanggal FROM surat_undangan
UNION ALL
SELECT surat_sku.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_sku JOIN penduduk ON surat_sku.id_penduduk=penduduk.id
) AS surat_keluar
WHERE surat_keluar.proses_surat='Finish'
";
$data = $this->db->query($sql)->row_array();
return $data['jumlah_surat'];
}
public function get($no = null){
$this->db->from('tb_keluar');
if($no != null){
$this->db->where('no', $no);
}
//$this->db->order_by('no_surat', 'asc');
$query = $this->db->get();
return $query;
}
function proses(){
$config['upload_path'] = './assets/upload/';
$config['allowed_types'] = 'gif|jpg|png|pdf|doc';
$config['overwrite'] = true;
$config['max_size'] = 1024; // 1MB
$this->load->library('upload', $config);
if ($this->upload->do_upload('nama')) {
return $this->upload->data("file_name");
}else {
return $this->upload->display_errors();
}
}
function add($post){
$upload = $this->proses();
$params = [
'no_surat' => $post['no_surat'],
'perihal' => $post['perihal'],
'tgl_surat' => $post['tgl_surat'],
'NIK' => $post['NIK'],
'nama' => $upload
];
$this->db->insert('tb_keluar', $params);
}
function edit($post){
$upload = $this->proses();
$params = [
'no_surat' => $post['no_surat'],
'perihal' => $post['perihal'],
'tgl_surat' => $post['tgl_surat'],
'NIK' => $post['NIK'],
'nama' => $upload
];
$this->db->where('no', $post['no']);
$this->db->update('tb_keluar', $params);
}
public function del($no){
$this->db->where('no', $no);
$this->db->delete('tb_keluar');
}
public function download($no){
$query = $this->db->get_where('tb_keluar',array('no'=>$no));
return $query->row_array();
}
public function get_surat_internal()
{
$sql = "SELECT * FROM(
SELECT surat_tugas.id as id, nama, nik, jabatan, divisi, jenis_surat, no_surat, tanggal, nama_ttd, jabatan_ttd, kontent FROM surat_tugas JOIN perangkat_desa ON surat_tugas.id_perangkat_desa=perangkat_desa.id
UNION ALL
SELECT surat_undangan.id as id, null, null, null, null, jenis_surat, no_surat, tanggal, nama_ttd, jabatan_ttd, kontent FROM surat_undangan
) AS surat_internal;";
return $this->db->query($sql)->result();
}
}
?>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
function no_surat_keterangan( ){
$CI = &get_instance();
$nomor = $CI->db->query("SELECT *FROM kategori_surat WHERE id_kategori = '1' ")->row();
$count_surat = $CI->db->query("
SELECT COUNT(id) AS `jumlah_surat` FROM (
SELECT surat_kematian.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, surat_nikah ,null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_kematian JOIN penduduk ON surat_kematian.id_penduduk=penduduk.id
UNION ALL
SELECT surat_nikah.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, ktp_ortu, kk, null as surat_nikah ,null as surat_keterangan_rs, ktp, akta_kelahiran, ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_nikah JOIN penduduk ON surat_nikah.id_penduduk=penduduk.id
UNION ALL
SELECT surat_pindah_domisili.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_pindah_domisili JOIN penduduk ON surat_pindah_domisili.id_penduduk=penduduk.id
UNION ALL
SELECT surat_sku.id as id, nama, nik, alamat, email, jk, agama, jenis_surat, surat_rt_rw, null as ktp_ortu, null as kk, null as surat_nikah , null as surat_keterangan_rs, ktp, null as akta_kelahiran, null as ijazah, keterangan, proses_surat, no_surat, kode_surat, tanggal FROM surat_sku JOIN penduduk ON surat_sku.id_penduduk=penduduk.id
) AS surat_keluar
WHERE surat_keluar.proses_surat='Finish' OR surat_keluar.proses_surat='Accepted'
")->row_array();
$no_surat = $count_surat['jumlah_surat']+1;
$kode_surat = '01';
if ($no_surat < 10) {
$no_surat = '000'.$no_surat;
}elseif ($no_surat < 100) {
$no_surat = '00'.$no_surat;
}elseif ($no_surat < 1000) {
$no_surat = '0'.$no_surat;
}else{
$no_surat = $no_surat;
}
$no_surat_fix = $no_surat.'/'.$kode_surat.'/'.'404.306.13'.'/'.tgl_romawi(date('m')).'/'.date('Y');
return $no_surat_fix;
}
function no_surat_pernyataan( ){
$CI = &get_instance();
$nomor = $CI->db->query("SELECT *FROM kategori_surat WHERE id_kategori = '2' ")->row();
$no_surat = $nomor->no_surat;
$kode_surat = $nomor->kode_surat;
if ($no_surat < 10) {
$no_surat = '000'.$no_surat;
}elseif ($no_surat < 100) {
$no_surat = '00'.$no_surat;
}elseif ($no_surat < 1000) {
$no_surat = '0'.$no_surat;
}else{
$no_surat = $no_surat;
}
$no_surat_fix = $no_surat.'/'.$kode_surat.'/'.'404.306.13'.'/'.tgl_romawi(date('m')).'/'.date('Y');
return $no_surat_fix;
}
function no_surat_internal($surat){
$CI = &get_instance();
if ($surat == 'undangan') {
$no_surat = $CI->db->get('surat_undangan')->num_rows()+1;
$kode_surat = '02';
} elseif ($surat == 'tugas') {
$no_surat = $CI->db->get('surat_tugas')->num_rows()+1;
$kode_surat = '03';
}
if ($no_surat < 10) {
$no_surat = '000'.$no_surat;
}elseif ($no_surat < 100) {
$no_surat = '00'.$no_surat;
}elseif ($no_surat < 1000) {
$no_surat = '0'.$no_surat;
}else{
$no_surat = $no_surat;
}
$no_surat_fix = $no_surat.'/'.$kode_surat.'/'.'404.306.13'.'/'.tgl_romawi(date('m')).'/'.date('Y');
return $no_surat_fix;
}
if (!function_exists('tgl_romawi')) {
function tgl_romawi($bulan_awal) {
$bulan = array (
1 => 'I',
2 => 'II',
3 => 'III',
4 => 'IV',
5 => 'V',
6 => 'VI',
7 => 'VII',
8 => 'VIII',
9 => 'IX',
10 => 'X',
11 => 'XI',
12 => 'XII'
);
return $bulan[(int)$bulan_awal];
}
}
if (!function_exists('tgl')) {
function tgl($date){
$BulanIndo = array("Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember");
$tahun = substr($date, 0, 4);
$bulan = substr($date, 5, 2);
$tgl = substr($date, 8, 2);
$result = $tgl . " " . $BulanIndo[(int)$bulan-1]. " ". $tahun;
return($result);
}
}
<file_sep> <!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">Tambah Surat Undangan</h1>
<div class="row">
<div class="col-lg-12">
<div class="card mb-4">
<div class="card-header">
Default Card Example
</div>
<div class="card-body">
<form action="" method="post">
<textarea name="content" id="ckeditor" required></textarea>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<script src="<?php echo base_url('assets/ckeditor/ckeditor.js');?>"></script>
<script type="text/javascript">
$(function () {
CKEDITOR.replace('ckeditor',{
filebrowserImageBrowseUrl : '<?php echo base_url('assets/kcfinder/browse.php');?>',
height: '400px'
});
});
</script><file_sep><div class="container-fluid">
<div class="table-responsive">
<div class="card mb-3">
<div class="card-header">
<i class=""></i>
Surat Undangan
</div>
<form method='post' action=''>
<div class="container-fluid"></br>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>Jenis Surat : </label>
<input type="text" width="50%" name="jenis_surat" class="form-control" value="Surat Undangan" readonly required/>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Nomor Surat :</label>
<input type="text" name="no_surat" class="form-control" placeholder="Nomor Surat" value="<?= $no_surat ?>" readonly required />
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Kepada :</label>
<input type="text" id="kepada" name="kepada" required class="form-control"/>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Tanggal :</label>
<input type="date" id="tanggal_surat" name="tanggal_surat" required class="form-control"/>
</div>
</div>
<div class="col-lg-12">
<div class="form-group">
<label>Kontent Surat :</label>
<small id="emailHelp" class="form-text text-muted">Silakan ganti titik(........) sesuai dengan kebutuhan anda.</small>
<textarea rows="30" name="kontent" id="textarea" class="form-control">
<table width="593">
<tr>
<td style="padding-bottom: 20px;" colspan="2">
<table width="55%">
<tr>
<td width="15%">No</td>
<td width="2%"> : </td>
<td width="40%"><?= $no_surat ?></td>
</tr>
<tr>
<td>Perihal</td>
<td>:</td>
<td>........</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2">
Kepada <br>
Yth ........ <br>
di Tempat <br>
</td>
</tr>
<tr>
<td align="left" colspan="2">
<b><i> Assalamu’alaikum Wr. Wb </i></b> <br> <br>
<p align="justify"> Segala Puja Puji hanya milik Allah yang memberi Rahmat dan Taufiknya kepada kita. Sholawat serta salam kita sampaikan kepada Baginda Nabi Besar Muhammad SAW, beserta sahabatnya, semoga kita selalu dalam lindungan Allah SWT, Amin. Bersama ini kami mengundang ........ dalam acara ........ Tingkat desa yang InsyaAllah akan dilaksanakan pada: </p>
</td>
</tr>
<tr>
<td align="left" colspan="2">
<table style="margin-left: 80px;" width="55%">
<tr>
<td width="25%">Tanggal</td>
<td width="2%"> : </td>
<td width="40%">........</td>
</tr>
<tr>
<td>Pukul</td>
<td>:</td>
<td>........</td>
</tr>
<tr>
<td>Tempat</td>
<td>:</td>
<td>........</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="left" colspan="2">
Demikianlah surat tugas ini dibuat untuk dapat dipergunakan sebagaimana mestinya. Atas kerja samanya diucapkan terima kasih.
<br>
<br>
<b><i> Wassalamu’alaikum Wr. Wb</i></b>
</td>
</tr>
</table>
</textarea>
</div>
</div>
</div>
</br>
<select name="ttd" class="form-control" required>
<option value="">---Pilih TTD---</option>
<option value="A<NAME>%Camat">Camat</option>
<option value="Suyatno%Sekretaris Camat">Sekretaris Camat</option>
</select></br>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
<button type="submit" class="btn btn-primary">Buat</button>
</div>
</form>
</div>
</div>
</div>
<script src="<?= base_url() ?>plugins/tinymce/tinymce.min.js"></script>
<script>
tinymce.init({
selector: "#textarea",theme: "modern",height: 220,
plugins: [
"advlist autolink link image lists charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars insertdatetime media nonbreaking",
"table contextmenu directionality emoticons paste textcolor"
],
toolbar1: "undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | styleselect",
toolbar2: "| link unlink anchor | image media | forecolor backcolor | print preview code ",
image_advtab: true ,
});
// config tanggal surat
$('#tanggal_surat').on('change', function(){
var tgl_surat = $('#tanggal_surat').val()
console.log(tgl_surat)
var arr_tgl = tgl_surat.split("-")
var bulan = ['Januari', 'Februari', 'Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
var no_surat = `<?= $no_surat ?>`
var kepada =$('#kepada').val();
var html = `
<table width="593">
<tr>
<td style="padding-bottom: 20px;" colspan="2">
<table width="55%">
<tr>
<td width="15%">No</td>
<td width="2%"> : </td>
<td width="40%">${no_surat}</td>
</tr>
<tr>
<td>Perihal</td>
<td>:</td>
<td>........</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2">
Kepada <br>
Yth ${kepada} <br>
di Tempat <br>
</td>
</tr>
<tr>
<td align="left" colspan="2">
<b><i> Assalamu’alaikum Wr. Wb </i></b> <br> <br>
<p align="justify"> Segala Puja Puji hanya milik Allah yang memberi Rahmat dan Taufiknya kepada kita. Sholawat serta salam kita sampaikan kepada Baginda Nabi Besar Muhammad SAW, beserta sahabatnya, semoga kita selalu dalam lindungan Allah SWT, Amin. Bersama ini kami mengundang ........ dalam acara ........ Tingkat desa yang InsyaAllah akan dilaksanakan pada: </p>
</td>
</tr>
<tr>
<td align="left" colspan="2">
<table style="margin-left: 80px;" width="55%">
<tr>
<td width="25%">Tanggal</td>
<td width="2%"> : </td>
<td width="40%">${arr_tgl[2]}, ${bulan[parseInt(arr_tgl[1])]} ${arr_tgl[0]}</td>
</tr>
<tr>
<td>Pukul</td>
<td>:</td>
<td>........</td>
</tr>
<tr>
<td>Tempat</td>
<td>:</td>
<td>........</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="left" colspan="2">
Demikianlah surat tugas ini dibuat untuk dapat dipergunakan sebagaimana mestinya. Atas kerja samanya diucapkan terima kasih.
<br>
<br>
<b><i> Wassalamu’alaikum Wr. Wb</i></b>
</td>
</tr>
</table>
`
tinymce.activeEditor.setContent(html);
})
</script><file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jun 10, 2021 at 01:46 PM
-- Server version: 10.4.13-MariaDB
-- PHP Version: 7.2.31
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `pengarsipan2`
--
-- --------------------------------------------------------
--
-- Table structure for table `kategori_surat`
--
CREATE TABLE `kategori_surat` (
`id_kategori` int(100) NOT NULL,
`kategori surat` varchar(100) NOT NULL,
`kode_surat` varchar(100) NOT NULL,
`no_surat` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `kategori_surat`
--
INSERT INTO `kategori_surat` (`id_kategori`, `kategori surat`, `kode_surat`, `no_surat`) VALUES
(1, 'surat_keterangan', '01', NULL),
(2, 'surat_undangan', '02', NULL),
(3, 'surat_tugas', '03', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `penduduk`
--
CREATE TABLE `penduduk` (
`id` int(11) NOT NULL,
`NIK` bigint(11) DEFAULT NULL,
`nama` varchar(100) DEFAULT NULL,
`jk` varchar(100) DEFAULT NULL,
`tempat_tgl_lahir` varchar(100) DEFAULT NULL,
`agama` varchar(100) DEFAULT NULL,
`status` varchar(50) DEFAULT NULL,
`pekerjaan` varchar(30) DEFAULT NULL,
`alamat` varchar(40) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`wa` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `penduduk`
--
INSERT INTO `penduduk` (`id`, `NIK`, `nama`, `jk`, `tempat_tgl_lahir`, `agama`, `status`, `pekerjaan`, `alamat`, `email`, `wa`) VALUES
(1, 123, 'falah', 'Laki-laki', 'simo', 'Islam', 'Belum Kawin', 'Developer', 'semarang', '<EMAIL>', '+6285647358986'),
(2, 123, 'zulfa', 'Laki-laki', 'slo', 'Islam', 'Kawin', 'Developer', 'solo', '<EMAIL>', '09090909'),
(4, 123, 'joko', 'Laki-laki', 'solo. 12 januari 1999', 'Islam', 'Belum Kawin', 'Developer', 'solo', '<EMAIL>', '12344213'),
(6, 9090, 'falah', 'Laki-laki', 'Semarang, 21 Januari 1998', 'Islam', 'Kawin', 'Developer', 'Semarang', '<EMAIL>', '980909990'),
(7, 9090, 'ewewe', 'Laki-laki', 'sasa', 'sasa', 'Belum Kawin', 'asa', 'sa', '', 'sasa'),
(8, 0, 'falahsasas', 'Perempuan', 'sasa', 'sasa', 'Kawin', 'sasas', 'sasasa', '<EMAIL>', 'sasa'),
(9, 0, 'dsds', 'Perempuan', 'dsds', 'dsds', 'Belum Kawin', 'dsds', 'dsds', '<EMAIL>', 'ds');
-- --------------------------------------------------------
--
-- Table structure for table `perangkat_desa`
--
CREATE TABLE `perangkat_desa` (
`id` int(11) NOT NULL,
`nama` varchar(255) DEFAULT NULL,
`nik` varchar(100) DEFAULT NULL,
`jabatan` varchar(255) DEFAULT NULL,
`divisi` varchar(255) DEFAULT NULL,
`status` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `surat`
--
CREATE TABLE `surat` (
`id` int(20) NOT NULL,
`whatsapp` varchar(20) NOT NULL,
`keperluan` varchar(100) NOT NULL,
`keterangan` text DEFAULT NULL,
`proses_surat` varchar(100) NOT NULL,
`id_penduduk` int(11) NOT NULL,
`id_ketegori_surat` int(11) NOT NULL,
`no_surat` varchar(50) NOT NULL,
`kode_surat` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `surat`
--
INSERT INTO `surat` (`id`, `whatsapp`, `keperluan`, `keterangan`, `proses_surat`, `id_penduduk`, `id_ketegori_surat`, `no_surat`, `kode_surat`) VALUES
(29, 'sas', 'asasa', 'sasa', 'sasa', 2, 3, 'sas', 'sasa');
-- --------------------------------------------------------
--
-- Table structure for table `surat_kematian`
--
CREATE TABLE `surat_kematian` (
`id` int(11) NOT NULL,
`surat_rt_rw` varchar(255) NOT NULL,
`ktp` varchar(100) NOT NULL,
`kk` varchar(100) NOT NULL,
`surat_nikah` varchar(100) NOT NULL,
`id_penduduk` int(11) NOT NULL,
`keterangan` varchar(255) DEFAULT NULL,
`proses_surat` varchar(50) DEFAULT NULL,
`no_surat` varchar(50) DEFAULT NULL,
`kode_surat` varchar(50) DEFAULT NULL,
`tanggal` date DEFAULT current_timestamp(),
`jenis_surat` varchar(50) NOT NULL DEFAULT 'Surat Kematian',
`hari_meninggal` varchar(255) DEFAULT NULL,
`jam_meninggal` varchar(255) DEFAULT NULL,
`send_notif` int(11) NOT NULL DEFAULT 0,
`alasan_reject` varchar(255) DEFAULT NULL,
`nama_ttd` varchar(50) DEFAULT NULL,
`jabatan_ttd` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `surat_nikah`
--
CREATE TABLE `surat_nikah` (
`id` int(11) NOT NULL,
`surat_rt_rw` varchar(100) NOT NULL,
`akta_kelahiran` varchar(100) NOT NULL,
`ijazah` varchar(100) NOT NULL,
`ktp` varchar(100) NOT NULL,
`kk` varchar(100) NOT NULL,
`ktp_ortu` varchar(100) NOT NULL,
`id_penduduk` int(11) NOT NULL,
`keterangan` varchar(255) DEFAULT NULL,
`proses_surat` varchar(50) DEFAULT NULL,
`no_surat` varchar(50) DEFAULT NULL,
`kode_surat` varchar(50) DEFAULT NULL,
`tanggal` date DEFAULT current_timestamp(),
`jenis_surat` varchar(50) NOT NULL DEFAULT 'Surat Nikah',
`send_notif` int(11) NOT NULL DEFAULT 0,
`alasan_reject` varchar(255) DEFAULT NULL,
`nama_ttd` varchar(50) DEFAULT NULL,
`jabatan_ttd` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `surat_pindah_domisili`
--
CREATE TABLE `surat_pindah_domisili` (
`id` int(11) NOT NULL,
`surat_rt_rw` varchar(255) NOT NULL,
`ktp` varchar(255) NOT NULL,
`kk` varchar(255) NOT NULL,
`id_penduduk` int(11) NOT NULL,
`keterangan` varchar(255) DEFAULT NULL,
`proses_surat` varchar(50) DEFAULT NULL,
`no_surat` varchar(50) DEFAULT NULL,
`kode_surat` varchar(50) DEFAULT NULL,
`tanggal` date DEFAULT current_timestamp(),
`jenis_surat` varchar(50) NOT NULL DEFAULT 'Surat Pindah Daerah',
`alamat_pindah` varchar(255) DEFAULT NULL,
`alasan_pindah` varchar(255) DEFAULT NULL,
`pengikut` varchar(50) DEFAULT NULL,
`send_notif` int(11) NOT NULL DEFAULT 0,
`alasan_reject` varchar(255) DEFAULT NULL,
`nama_ttd` varchar(50) DEFAULT NULL,
`jabatan_ttd` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `surat_sku`
--
CREATE TABLE `surat_sku` (
`id` int(11) NOT NULL,
`surat_rt_rw` varchar(255) NOT NULL,
`ktp` varchar(255) NOT NULL,
`id_penduduk` int(11) NOT NULL,
`keterangan` varchar(255) DEFAULT NULL,
`proses_surat` varchar(50) DEFAULT NULL,
`no_surat` varchar(50) DEFAULT NULL,
`kode_surat` varchar(50) DEFAULT NULL,
`tanggal` date DEFAULT NULL,
`jenis_surat` varchar(50) NOT NULL DEFAULT 'Surat Keterangan Usaha',
`nama_usaha` varchar(255) DEFAULT NULL,
`send_notif` int(11) NOT NULL DEFAULT 0,
`alasan_reject` varchar(255) DEFAULT NULL,
`nama_ttd` varchar(50) DEFAULT NULL,
`jabatan_ttd` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `surat_tugas`
--
CREATE TABLE `surat_tugas` (
`id` int(11) NOT NULL,
`id_perangkat_desa` int(11) DEFAULT NULL,
`kontent` text DEFAULT NULL,
`nama_ttd` varchar(100) DEFAULT NULL,
`jabatan_ttd` varchar(100) DEFAULT NULL,
`jenis_surat` varchar(100) DEFAULT NULL,
`no_surat` varchar(100) DEFAULT NULL,
`tanggal` date DEFAULT current_timestamp(),
`proses_surat` varchar(100) NOT NULL DEFAULT 'Finish',
`tanggal_surat` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `surat_undangan`
--
CREATE TABLE `surat_undangan` (
`id` int(11) NOT NULL,
`no_surat` varchar(100) DEFAULT NULL,
`nama_ttd` varchar(100) DEFAULT NULL,
`jabatan_ttd` varchar(100) DEFAULT NULL,
`jenis_surat` varchar(100) DEFAULT NULL,
`tanggal` date DEFAULT current_timestamp(),
`kontent` text DEFAULT NULL,
`proses_surat` varchar(100) NOT NULL DEFAULT 'Finish',
`kepada` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `tb_keluar`
--
CREATE TABLE `tb_keluar` (
`no` int(10) NOT NULL,
`no_surat` int(100) NOT NULL,
`perihal` varchar(100) NOT NULL,
`tgl_surat` date NOT NULL,
`NIK` varchar(100) NOT NULL,
`nama` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `tb_masuk`
--
CREATE TABLE `tb_masuk` (
`no` int(100) NOT NULL,
`no_surat` varchar(100) NOT NULL,
`pengirim` varchar(100) NOT NULL,
`tgl_surat` date NOT NULL,
`perihal` varchar(100) NOT NULL,
`tgl_terima` date NOT NULL,
`keterangan` varchar(100) NOT NULL,
`file_surat` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `tb_masuk`
--
INSERT INTO `tb_masuk` (`no`, `no_surat`, `pengirim`, `tgl_surat`, `perihal`, `tgl_terima`, `keterangan`, `file_surat`) VALUES
(10, 'sasa', 'asasa', '2021-01-04', 'asasa', '2021-02-18', 'sasa', 'laporan-210227-290976e808.jpg'),
(12, '12121', 'asasa', '2021-06-07', 'tes', '2021-06-07', 'asasa', 'laporan-210607-9c12325349.PNG');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(20) NOT NULL,
`username` varchar(100) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
`name` varchar(100) DEFAULT NULL,
`address` varchar(100) DEFAULT NULL,
`level` varchar(100) DEFAULT NULL COMMENT '1. admin, 2. kepalakelurahan, 3. sekdes,\r\n4. adminpengantar'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `username`, `password`, `name`, `address`, `level`) VALUES
(1, 'admin', '<PASSWORD>', 'Risa', ' <PASSWORD>', ' 1');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `kategori_surat`
--
ALTER TABLE `kategori_surat`
ADD PRIMARY KEY (`id_kategori`);
--
-- Indexes for table `penduduk`
--
ALTER TABLE `penduduk`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `perangkat_desa`
--
ALTER TABLE `perangkat_desa`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `surat`
--
ALTER TABLE `surat`
ADD PRIMARY KEY (`id`),
ADD KEY `id_penduduk` (`id_penduduk`),
ADD KEY `id_ketegori_surat` (`id_ketegori_surat`);
--
-- Indexes for table `surat_kematian`
--
ALTER TABLE `surat_kematian`
ADD PRIMARY KEY (`id`),
ADD KEY `id_penduduk` (`id_penduduk`);
--
-- Indexes for table `surat_nikah`
--
ALTER TABLE `surat_nikah`
ADD PRIMARY KEY (`id`),
ADD KEY `id_penduduk` (`id_penduduk`);
--
-- Indexes for table `surat_pindah_domisili`
--
ALTER TABLE `surat_pindah_domisili`
ADD PRIMARY KEY (`id`),
ADD KEY `id_penduduk` (`id_penduduk`);
--
-- Indexes for table `surat_sku`
--
ALTER TABLE `surat_sku`
ADD PRIMARY KEY (`id`),
ADD KEY `id_penduduk` (`id_penduduk`);
--
-- Indexes for table `surat_tugas`
--
ALTER TABLE `surat_tugas`
ADD PRIMARY KEY (`id`),
ADD KEY `id_perangkat_desa` (`id_perangkat_desa`);
--
-- Indexes for table `surat_undangan`
--
ALTER TABLE `surat_undangan`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `tb_keluar`
--
ALTER TABLE `tb_keluar`
ADD PRIMARY KEY (`no`);
--
-- Indexes for table `tb_masuk`
--
ALTER TABLE `tb_masuk`
ADD PRIMARY KEY (`no`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `kategori_surat`
--
ALTER TABLE `kategori_surat`
MODIFY `id_kategori` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `penduduk`
--
ALTER TABLE `penduduk`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT for table `perangkat_desa`
--
ALTER TABLE `perangkat_desa`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `surat`
--
ALTER TABLE `surat`
MODIFY `id` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=30;
--
-- AUTO_INCREMENT for table `surat_kematian`
--
ALTER TABLE `surat_kematian`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `surat_nikah`
--
ALTER TABLE `surat_nikah`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `surat_pindah_domisili`
--
ALTER TABLE `surat_pindah_domisili`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `surat_sku`
--
ALTER TABLE `surat_sku`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `surat_tugas`
--
ALTER TABLE `surat_tugas`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `surat_undangan`
--
ALTER TABLE `surat_undangan`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `tb_keluar`
--
ALTER TABLE `tb_keluar`
MODIFY `no` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `tb_masuk`
--
ALTER TABLE `tb_masuk`
MODIFY `no` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `surat_kematian`
--
ALTER TABLE `surat_kematian`
ADD CONSTRAINT `surat_kematian_ibfk_1` FOREIGN KEY (`id_penduduk`) REFERENCES `penduduk` (`id`);
--
-- Constraints for table `surat_nikah`
--
ALTER TABLE `surat_nikah`
ADD CONSTRAINT `surat_nikah_ibfk_1` FOREIGN KEY (`id_penduduk`) REFERENCES `penduduk` (`id`);
--
-- Constraints for table `surat_pindah_domisili`
--
ALTER TABLE `surat_pindah_domisili`
ADD CONSTRAINT `surat_pindah_domisili_ibfk_1` FOREIGN KEY (`id_penduduk`) REFERENCES `penduduk` (`id`);
--
-- Constraints for table `surat_sku`
--
ALTER TABLE `surat_sku`
ADD CONSTRAINT `surat_sku_ibfk_1` FOREIGN KEY (`id_penduduk`) REFERENCES `penduduk` (`id`);
--
-- Constraints for table `surat_tugas`
--
ALTER TABLE `surat_tugas`
ADD CONSTRAINT `surat_tugas_ibfk_1` FOREIGN KEY (`id_perangkat_desa`) REFERENCES `perangkat_desa` (`id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep> <footer class="footer text-faded text-center py-5">
<div class="container">
<p class="m-0 small">Copyright © 2020</p>
</div>
</footer>
<!-- Bootstrap core JavaScript -->
<script src="<?php echo base_url()?>/user penduduk/vendor/jquery/jquery.min.js"></script>
<script src="<?php echo base_url()?>/user penduduk/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<file_sep><!DOCTYPE html>
<!-- Created by pdf2htmlEX (https://github.com/coolwanglu/pdf2htmlex) -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<link href="<?php echo base_url()?>/assets/print_assets/surat_pindah_domisili/base.min.css" rel="stylesheet">
<link href="<?php echo base_url()?>/assets/print_assets/surat_pindah_domisili/fancy.min.css" rel="stylesheet">
<link href="<?php echo base_url()?>/assets/print_assets/surat_pindah_domisili/main.css" rel="stylesheet">
<script src="<?php echo base_url()?>/assets/print_assets/surat_pindah_domisili/compatibility.min.js"></script>
<script src="<?php echo base_url()?>/assets/print_assets/surat_pindah_domisili/theViewer.min.js"></script>
<script>
try{
theViewer.defaultViewer = new theViewer.Viewer({});
}catch(e){}
</script>
<title>Surat Pindah Domisili</title>
</head>
<body>
<div id="sidebar">
<div id="outline"></div>
</div>
<div id="page-container">
<div id="pf1" class="pf w0 h0" data-page-no="1">
<div class="pc pc1 w0 h0">
<img class="bi x0 y0 w0 h0" alt="" src="<?php echo base_url()?>assets/print_assets/surat_pindah_domisili/bg1.png">
<div class="c x1 y1 w1 h1">
<div class="t m0 x2 h2 y2 ff1 fs0 fc0 sc0 ls0 ws0">PEMERINTAH KABUPATEN CILACAP</div>
<div class="t m0 x3 h2 y3 ff1 fs0 fc0 sc0 ls0 ws0">KECAMATAN GANDRUNGMANGU</div>
<div class="t m0 x4 h2 y4 ff1 fs0 fc0 sc0 ls0 ws0">KELURAHAN GANDRUNGMANGU</div>
</div>
<div class="t m0 x5 h3 y5 ff2 fs1 fc0 sc0 ls0 ws0">Alamat: Jalan Infra 14/15 Bumi Dipasena Abadi Kode Pos 34675</div>
<div class="t m0 x6 h3 y6 ff2 fs1 fc0 sc0 ls0 ws0">Website<span class="fc1">: https://semarapurakaja.desa.id/</span> Email: <EMAIL></div>
<div class="t m0 x7 h4 y7 ff1 fs2 fc0 sc0 ls0 ws0">SURAT KETERANGAN PINDAH DOMISILI</div>
<div class="t m0 x8 h5 y8 ff2 fs2 fc0 sc0 ls0 ws0">Nomor<span class="_ _0"> </span>: <?=$data_surat['no_surat']?></div>
<div class="t m0 x9 h5 y9 ff2 fs2 fc0 sc0 ls0 ws0">Yang <span class="_ _1"> </span>bertanda <span class="_ _1"> </span>tangan <span class="_ _1"> </span>di <span class="_ _1"> </span>bawah <span class="_ _1"> </span>ini <span class="_ _1"> </span>Kepala <span class="_ _1"> </span>Desa <span class="_ _1"> </span>Gandrungmangu <span class="_ _1"> </span>Kecamatan </div>
<div class="t m0 x9 h5 ya ff2 fs2 fc0 sc0 ls0 ws0">Gandrungmangu menerangkan dengan sesungguhnya bahwa : </div>
<div class="t m0 xa h5 yb ff2 fs2 fc0 sc0 ls0 ws0">N a m a<span class="_ _2"> </span>: <?=$data_surat['nama']?></div>
<div class="t m0 xa h5 yc ff2 fs2 fc0 sc0 ls0 ws0">Tempat, tanggal lahir<span class="_ _3"> </span>: <?=$data_surat['tempat_tgl_lahir']?></div>
<div class="t m0 xa h5 yd ff2 fs2 fc0 sc0 ls0 ws0">Status perkawinan<span class="_ _4"> </span>: <?=$data_surat['status']?></div>
<div class="t m0 xa h5 ye ff2 fs2 fc0 sc0 ls0 ws0">A g a m a<span class="_ _5"> </span>: <?=$data_surat['agama']?></div>
<div class="t m0 xa h5 yf ff2 fs2 fc0 sc0 ls0 ws0"> </div>
<div class="t m0 xa h5 y10 ff2 fs2 fc0 sc0 ls0 ws0">Jenis kelamin<span class="_ _6"> </span>: <?=$data_surat['jk']?></div>
<div class="t m0 xa h5 y11 ff2 fs2 fc0 sc0 ls0 ws0">Pekerjaan<span class="_ _7"> </span>: <?=$data_surat['pekerjaan']?></div>
<div class="t m0 xa h5 y12 ff2 fs2 fc0 sc0 ls0 ws0">Alamat<span class="_ _8"></span> Asal<span class="_ _9"> </span>: <?=$data_surat['alamat']?></div>
<div class="t m0 xa h5 y13 ff2 fs2 fc0 sc0 ls0 ws0">Pindah ke<span class="_ _a"> </span>: <?=$data_surat['alamat_pindah']?></div>
<div class="t m0 xa h5 y14 ff2 fs2 fc0 sc0 ls0 ws0">Alasan Pindah<span class="_ _b"> </span>: <?=$data_surat['alasan_pindah']?></div>
<div class="t m0 xa h5 y15 ff2 fs2 fc0 sc0 ls0 ws0">Pengikut<span class="_ _c"> </span>: <?=$data_surat['pengikut']?></div>
<div class="t m0 x9 h5 y16 ff2 fs2 fc0 sc0 ls0 ws0">Demikianlah <span class="_ _8"></span>surat <span class="_ _d"></span>keterangan <span class="_ _8"></span>ini <span class="_ _d"></span>dibuat <span class="_ _8"></span>untuk <span class="_ _d"></span>dapat <span class="_ _8"></span>dipergunakan <span class="_ _d"></span>sebagaimana <span class="_ _8"></span>mestinya. </div>
<div class="t m0 x9 h5 y17 ff2 fs2 fc0 sc0 ls0 ws0">Atas kerja samanya diucapkan terima kasih.</div>
<div class="t m0 xb h5 y18 ff2 fs2 fc0 sc0 ls0 ws0"> <span class="_ _e"> </span>Gandrungmangu, <?=$data_surat['tanggal']?></div>
<div class="t m0 x9 h5 y19 ff2 fs2 fc0 sc0 ls0 ws0"> <span class="_ _f"> </span><span class="fs1"> </span></div>
<div class="t m0 xc h5 y1a ff2 fs2 fc0 sc0 ls0 ws0"> <span class="_ _10"> </span> <?=$jabatan_ttd?></div>
<div class="t m0 xd h5 y1b ff2 fs2 fc0 sc0 ls0 ws0"> </div>
<div class="t m0 xd h4 y1c ff1 fs2 fc0 sc0 ls0 ws0"> <span class="_ _11"> </span> <?=$nama_ttd?></div>
</div>
<div class="pi" data-data='{"ctm":[1.000000,0.000000,0.000000,1.000000,0.000000,0.000000]}'></div>
</div>
<div id="pf2" class="pf w0 h0" data-page-no="2">
<div class="pc pc2 w0 h0"><img class="bi x0 y0 w0 h0" alt="" src="bg2.png"/></div>
<div class="pi" data-data='{"ctm":[1.000000,0.000000,0.000000,1.000000,0.000000,0.000000]}'></div>
</div>
</div>
<div class="loading-indicator">
</div>
</body>
</html>
<script>
window.onload = function () {
window.print();
path = location.pathname.split("/")
if (path[2] == 'suratkeluar') {
window.onafterprint = function(){
console.log("Printing completed...");
location.replace("<?= base_url('suratkeluar')?>")
}
}else{
window.onafterprint = function(){
console.log("Printing completed...");
location.replace("<?= base_url('suratPengantar/permintaan')?>")
}
}
};
</script><file_sep><body>
<h1 class="site-heading text-center text-white d-none d-lg-block">
<span class="site-heading-upper text-primary mb-3">Selamat Datang di Website Ajuan Surat Pengantar Online</span>
<span class="site-heading-lower"><NAME></span>
</h1>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark py-lg-4" id="mainNav">
<div class="container">
<a class="navbar-brand text-uppercase text-expanded font-weight-bold d-lg-none" href="#">Start Bootstrap</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav mx-auto">
<li class="nav-item active px-lg-4">
<a class="nav-link text-uppercase text-expanded" href="<?= base_url('DashboardUser') ?>">Home
<span class="sr-only"></span>
</a>
</li>
<!---<li class="nav-item px-lg-4">
<a class="nav-link text-uppercase text-expanded" href="<?= base_url('Prosedur') ?>">Prosedur</a>
</li>!-->
<li class="nav-item px-lg-4">
<div class="dropdown show">
<a class="nav-link text-uppercase text-expanded" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fa fa-list"></i> Layanan Surat Online
</a>
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="<?= base_url('layananSurat/pindahdomisili') ?>">Surat Pindah Daerah</a>
<a class="dropdown-item" href="<?= base_url('layananSurat/nikah') ?>">Surat Nikah</a>
<!--- <a class="dropdown-item" href="#">Surat Cerai</a>!--->
<!-- <a class="dropdown-item" href="<?//= base_url('layananSurat/kelahiran') ?>">Surat Kelahiran</a> -->
<a class="dropdown-item" href="<?= base_url('layananSurat/kematian') ?>">Surat Kematian</a>
<a class="dropdown-item" href="<?= base_url('layananSurat/sku') ?>">Surat Keterangan Usaha</a>
<!--- <a class="dropdown-item" href="#">Surat Kehilangan STNK</a>
<a class="dropdown-item" href="#">Surat Kehilangan KTP</a>!--->
</div>
</div>
</li>
</ul>
</div>
</div>
</nav><file_sep><div class="container-fluid">
<div class="table-responsive">
<div class="card mb-3">
<div class="card-header">
<i class=""></i>
Surat Undangan</div>
<form method ='post' action='#'>
<div class="container-fluid"></br>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>Jenis Surat : </label>
<input type="text" width="50%" name="jenis_surat" class="form-control" value="Surat Undangan" readonly required/ >
<input type="hidden" width="50%" name="tanggal" class="form-control" placeholder="" value="<?php echo date('Y-m-d'); ?>" readonly required/>
<input type="hidden" width="50%" name="kategori" class="form-control" placeholder="" value="Undangan" readonly required/>
<input type="hidden" width="50%" name="jumlah" class="form-control" placeholder="" value="1" readonly required/>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Nomor Surat :</label>
<input type="text" name="no_surat" class="form-control" placeholder="Nomor Surat" value=" " readonly required/>
<input type="hidden" name="nosu" class="form-control" placeholder="Nomor Surat" value="" readonly required/>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Informasi :</label>
<textarea id="informasi" name="informasi" class="form-control" >
Sifat : <br>
Lampiran :
</textarea>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Kepada :</label>
<textarea id="instansi" name="instansi" class="form-control" ></textarea>
</div>
</div>
</div>
</br>
<textarea name="keterangan" id="textarea" class="form-control">Mengharap dengan hormat kehadiran Bapak/ Ibu besuk pada :
<table width="55%">
<tr>
<td width="15%">hari, tanggal</td>
<td width="2%"> : </td>
<td width="40%"></td>
</tr>
<tr>
<td>waktu</td>
<td> : </td>
<td></td>
</tr>
<tr>
<td>tempat</td>
<td> : </td>
<td></td>
</tr>
<tr>
<td>acara</td>
<td> : </td>
<td></td>
</tr>
<tr>
<td>catatan</td>
<td> : </td>
<td></td>
</tr>
<tr></tr>
</table>
<p></p>
Demikian surat undangan ini kami sampaikan, atas partisipasi dan kerjasamanya kami ucapakan terimakasih.
</textarea></br>
<select name="ttd" class="form-control" required >
<option value="">---Pilih TTD---</option>
<option value="<NAME>">Camat</option>
<option value="Suryanto">Sekretaris Camat</option>
</select></br>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
<button type="submit" class="btn btn-primary">Buat</button>
</div>
</form>
</div>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_user extends CI_Model{
public function login($user,$pw)
{
$this->db->where('username', $user);
$this->db->where('password', $pw);
$query = $this->db->get('users');
return $query;
}
public function get($id = null){
$this->db->from('users');
if($id != null){
$this->db->where('id', $id);
}
$query = $this->db->get();
return $query;
}
public function add($post){
$params['name'] = $post['name'];
$params['username'] = $post['username'];
$params['password'] = <PASSWORD>($post['password']);
$params['address'] = $post['address'];
$params['level'] = $post['level'];
$this->db->insert('users', $params);
}
public function edit($post){
$params['name'] = $post['name'];
$params['username'] = $post['username'];
if(!empty($post['password'])){
$params['password'] = <PASSWORD>($post['password']);
}
$params['address'] = $post['address'];
$params['level'] = $post['level'];
$this->db->where('id', $post['id']);
$this->db->update('users', $params);
}
public function del($id){
$this->db->where('id', $id);
$this->db->delete('users');
}
public function deleteData($table,$where){
$this->db->delete($table,$where);
}
}
?><file_sep><?php
class M_masuk extends CI_Model{
private function CustomDataTabel()
{
$sql = "
SELECT * FROM tb_masuk LIMIT ". $_POST['length']." OFFSET ". $_POST['start'] ."
";
if($_POST['search']['value']){
$query = $_POST['search']['value'];
$sql = "
SELECT * FROM tb_masuk WHERE no_surat LIKE'%".$query."%' OR pengirim LIKE'%".$query."%' OR tgl_surat LIKE'%".$query."%' OR perihal LIKE'%".$query."%' OR tgl_terima LIKE'%".$query."%' OR keterangan LIKE'%".$query."%'
";
return $this->db->query($sql)->result();
}
if($_POST['length'] != -1);
return $this->db->query($sql)->result();
}
function get_datatables()
{
$query = $this->CustomDataTabel();
return $query;
}
function count_filtered()
{
$sql = "
SELECT COUNT(no) AS `jumlah_surat` FROM tb_masuk
";
$data = $this->db->query($sql)->row_array();
return $data['jumlah_surat'];
}
public function count_all()
{
$sql = "
SELECT COUNT(no) AS `jumlah_surat` FROM tb_masuk
";
$data = $this->db->query($sql)->row_array();
return $data['jumlah_surat'];
}
public function get($no = null){
$this->db->from('tb_masuk');
if($no != null){
$this->db->where('no', $no);
}
//$this->db->order_by('no_surat', 'asc');
$query = $this->db->get();
return $query;
}
function proses(){
$config['upload_path'] = './assets/upload/';
$config['allowed_types'] = 'gif|jpg|png|pdf|doc';
$config['overwrite'] = true;
$config['max_size'] = 1024; // 1MB
$this->load->library('upload', $config);
if ($this->upload->do_upload('file_surat')) {
return $this->upload->data("file_name");
}else {
return $this->upload->display_errors();
}
}
function add($post){
$params = [
'no_surat' => $post['no_surat'],
'pengirim' => $post['pengirim'],
'tgl_surat' => $post['tgl_surat'],
'tgl_terima' => $post['tgl_terima'],
'keterangan' => empty($post['keterangan']) ? null : $post['keterangan']
];
if ($_FILES['file_surat']['name'] != null) {
$params['file_surat'] = $this->proses();
}
$this->db->insert('tb_masuk', $params);
}
function edit($post){
$params = [
'no_surat' => $post['no_surat'],
'pengirim' => $post['pengirim'],
'tgl_surat' => $post['tgl_surat'],
'tgl_terima' => $post['tgl_terima'],
'keterangan' => empty($post['keterangan']) ? null : $post['keterangan']
];
if ($_FILES['file_surat']['name'] != null) {
$params['file_surat'] = $this->proses();
}
$this->db->where('no', $post['no']);
$this->db->update('tb_masuk', $params);
}
public function deleteData($table,$where)
{
$this->db->delete($table,$where);
}
public function download($no){
$query = $this->db->get_where('tb_masuk',array('no'=>$no));
return $query->row_array();
}
}
?>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Suratmasuk extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('m_masuk');
$this->load->helper(array('url','download'));
check_not_login();
$this->load->library('form_validation');
}
public function index()
{
$data = [
'row' => $this->m_masuk->get(),
'title' => "Surat Masuk",
];
$data['row'] = $this->m_masuk->get();
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('suratmasuk/suratmasuk_data', $data);
$this->load->view('template_admin/footer', $data);
}
public function add(){
$suratmasuk = new stdClass();
$suratmasuk->no = null;
$suratmasuk->no_surat = null;
$suratmasuk->pengirim = null;
$suratmasuk->tgl_surat = null;
$suratmasuk->tgl_terima = null;
$suratmasuk->keterangan = null;
$suratmasuk->file_surat = null;
$data = array(
'page' => 'add',
'row' => $suratmasuk,
'title' => "Surat Masuk"
);
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('suratmasuk/suratmasuk_form', $data);
$this->load->view('template_admin/footer',$data);
}
public function edit($no){
$query = $this->m_masuk->get($no);
if($query->num_rows() > 0){
$suratmasuk = $query->row();
$data = array(
'page' => 'edit',
'row' => $suratmasuk,
'title' => "Surat Masuk"
);
$this->load->view('template_admin/header',$data);
$this->load->view('template_admin/sidebar');
$this->load->view('suratmasuk/suratmasuk_form', $data);
$this->load->view('template_admin/footer',$data);
}else{
echo "<script> alert('Data tidak ditemukan');</script>";
echo "<script>window.location='".site_url('suratmasuk')."';</script>";
}
}
public function proses2(){
$post = $this->input->post(null, TRUE);
if(isset($_POST['add'])){
$config['upload_path'] ='assets/upload/';
$config['allowed_types'] ='pdf|doc|jpg|png';
$config['max_size'] = 2000;
$config['file_name'] = 'laporan-'.date('ymd').'-'.substr(md5(rand()), 0,10);
$this->load->library('upload', $config);
if(@$_POST['lampiran'] ['name'] != null){
if($this->upload->do_upload('lampiran')){
$post['lampiran'] = $this->upload->data('file_name');
$this->m_masuk->add($post);
if($this->db->affected_rows() > 0) {
$this->session->set_flashdata('success', 'Data berhasil di simpan');
}
redirect('suratmasuk');
}else{
$error = $this->upload->display_error();
$this->session->set_flashdata('error', $error);
redirect('suratmasuk/add');
}
}else{
$post['lampiran'] = null;
$this->m_masuk->add($post);
if($this->db->affected_rows() > 0) {
$this->session->set_flashdata('success', 'Data berhasil di simpan');
}
redirect('suratmasuk');
}
}else if (isset($_POST['edit'])) {
$this->m_masuk->edit($post);
}
if($this->db->affected_rows() > 0){
echo "<script> alert('Data berhasil disimpan');</script>";
}
echo "<script>window.location='".site_url('suratmasuk')."';</script>";
}
public function hapusdata()
{
$id = $this->input->post("no");
$where = array('no' => $id);
$this->m_masuk->deleteData('tb_masuk', $where);
if($this->db->affected_rows() > 0){
$this->session->set_flashdata('success', 'Data berhasil dihapus');
}
redirect ('suratmasuk');
}
public function download($no){
$this->load->helper('download');
$fileinfo = $this->m_masuk->download($no);
$masuk = './assets/upload/'.$fileinfo['file_surat'];
force_download($masuk, NULL);
}
public function openfile($file_surat)
{
// Lokasi file
$filename = "./assets/upload/" . $file_surat;
if (file_exists($filename)) {
// check jika ekstensi file (pdf/docx/image) maka
$ext = pathinfo($file_surat, PATHINFO_EXTENSION);
if ($ext == 'pdf') {
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename"' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
@readfile($filename);
} elseif ($ext == 'png' || 'jpg' || 'jpeg') {
header('Content-type: image/png');
echo file_get_contents($filename);
}
} else {
echo 'file tidak ditemukan, <a href="' . base_url('suratmasuk') . '"> kembali </a>';
}
}
}
?><file_sep>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title><NAME></title>
<link rel="icon" type="image/png" href="<?= base_url(); ?>assets/img/Logo.png" height='35' width='40'>
<!-- Bootstrap core CSS -->
<link href="<?php echo base_url()?>/user penduduk/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom fonts for this template -->
<link href="https://fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Lora:400,400i,700,700i" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="<?php echo base_url()?>/user penduduk/css/business-casual.min.css" rel="stylesheet">
<!-- Jquery -->
<script src="<?php echo base_url()?>assets/js/jquery-3.5.1.min.js"></script>
</head><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laporan Surat Keluar</title>
<style>
body{
padding: 0;
margin: 0;
}
.content {
max-width: 793px;
margin: auto;
}
th, td {
padding: 0px;
}
.logo{
width: 70.79px;
height: 95.05px;
display: block;
margin-left: auto;
margin-right: auto;
}
.kop-judul{
font-weight: bold;
font-size: x-large;
text-align: center;
}
.kop-sub{
font-size: x-small;
text-align: center;
}
hr.solid {
border-top: 4px solid rgb(17, 17, 17);
}
.tabel-surat{
border-collapse: collapse;
}
.tabel-surat tr td {
padding: 4px;
}
.tabel-surat tr th {
padding: 6px;
}
</style>
</head>
<body>
<center>
<div class="content">
<table border="0" width="593">
<tr>
<td rowspan="2"><img class="logo" alt="" src="<?=base_url('assets\img\image1.png')?>" title=""></td>
<td class="kop-judul">PEMERINTAH KABUPATEN CILACAP <br>
KECAMATAN CIPARI <br>
</td>
</tr>
<tr>
<td class="kop-sub">Alamat: Kota Gandrungmangu Jl. Mangesti Luhur No. 10, Telp. (0271) 71543 <br>
Website: https://semarapurakaja.desa.id/ Email: <EMAIL></td>
</tr>
<tr>
<td style="padding: -3px;" colspan="2">
<hr class="solid">
</td>
</tr>
<tr>
<td align="center" colspan="2">
<b><u>LAPORAN SURAT MASUK</u></b>
</td>
</tr>
</table>
<table border="0" width="593">
<tr>
<td style="padding-bottom: 20px;" colspan="2">
<table class="tabel-surat" style=" margin-left: auto; margin-right: auto; margin-top: 30px;" border="1" width="95%">
<tr>
<th width="10%">No.</th>
<th width="33%">No. Surat</th>
<th width="33%">Tanggal Surat </th>
<th width="33%">Keterangan</th>
</tr>
<?php $i=1; ?>
<?php foreach ($datafilter as $data) :?>
<tr>
<th scope="row"><?= $i;?></th>
<td><?= $data->no_surat?></td>
<td><?= $data_surat['tanggal'] = tanggal_indo(date('Y-n-d', strtotime($data->tgl_surat))); ?></td>
<td><?= $data->keterangan?></td>
</tr>
<?php $i++; ?>
<?php endforeach; ?>
</table>
</td>
</tr>
<tr>
<td colspan="2">
<table style="margin-left:350px; margin-top: 100px;">
<tr>
<td align="center" style="padding-bottom: 10px;">Cipari, <?= Date('d F Y')?></td>
</tr>
<tr>
<td align="center">Petugas</td>
</tr>
<tr>
<td><center><img width="100" height="100" src="..\<?=$ttd_img?>" alt=""></center></td>
</tr>
<tr>
<td align="center" style="padding-bottom: 10px;" >Parsiman</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</center>
</body>
</html>
<script>
window.onload = function () {
window.print();
path = location.pathname.split("/")
if (path[2] == 'laporanmasuk') {
window.onafterprint = function(){
console.log("Printing completed...");
location.replace("<?= base_url('laporanMasuk')?>")
}
}else{
window.onafterprint = function(){
console.log("Printing completed...");
location.replace("<?= base_url('laporanMasuk')?>")
}
}
};
</script>
<file_sep><?php
function check_already_login(){
$ci =& get_instance();
$user_session = $ci->session->userdata('id');
if ($user_session) {
redirect('dashboard');
}
}
function check_not_login(){
$ci =& get_instance();
$user_session = $ci->session->userdata('id');
if (!$user_session) {
redirect('auth');
}
function count_rows($table)
{
$instance = &get_instance();
$instance->db->from($table);
return $instance->db->get()->num_rows();
}
function check_admin(){
$ci =& get_instance();
$ci->load->library('fungsi');
if($ci->fungsi->user_login()->level != 1){
redirect('dashboard');
}
}
}
?><file_sep><body id="page-top">
<div class="container-fluid">
<div class="row">
<div class="col">
<h1 class="judul h3 text-gray-800">Daftar <?= $title ?></h1>
<div class="card shadow mb-4">
<div class="card-header py-3">
<!-- <a href="<?= base_url('suratkeluar/add'); ?>" class="btn btn-primary mb-3">Tambah Data</a> -->
</div>
<div class="card-body">
<div class="table-responsive">
<table id="datatable-surat-keluar" class = "table table table-bordered table-striped">
<thead>
<tr align="center" class="bg-primary" style = "color: white;">
<th></th>
<th>No</th>
<th>No. Surat</th>
<th>Jenis Surat</th>
<th>Tanggal Surat</th>
<th>NIK</th>
<th>Nama</th>
<th>Action</th>
</tr>
</thead>
<tbody align="center">
</tbody>
</table>
</div>
</div>
<!-- Modal hapus data -->
<div class="modal fade" id="hapusData" tabindex="-1" role="dialog" aria-labelledby="hapusDataLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="hapusData">Hapus data </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="deleteSurat" action="">
<div class="modal-body">
<b>Anda yakin ingin menghapus data ini ?</b><br><br>
<input class="form-control" type="hidden" name="input_idDelete" id="id">
<input class="form-control" type="hidden" name="input_idDelete" id="jenis_surat">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
<button type="submit" class="btn btn-danger" name="btn_delete" id="btn_delete"> Hapus</button>
</div>
</form>
</div>
</div>
</div>
<!-- End modal hapus data -->
<script>
$(document).ready(function() {
var table = $('#datatable-surat-keluar').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
"url": "<?php echo site_url('/suratkeluar/permintaan_surat_datatabel') ?>",
"type": "POST"
},
"columns": [{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{
"data": "no"
},
{
"data": "no_surat"
},
{
"data": "jenis_surat"
},
{
"data": "tanggal"
},
{
"data": "NIK",
"render": function(data){
if (data != null) {
return data
}else{
return '-'
}
}
},
{
"data": "nama",
"render": function(data){
if (data != null) {
return data
}else{
return '-'
}
}
},
{
"data": "aksi",
"render": function(data) {
var jenis_surat = data.jenis_surat.replace(/ /g, "_")
return `<td align="center">
<a class="btn btn-success btn-xs" href="<?= site_url('/suratkeluar/cetak_pdf/') ?>${jenis_surat}/${data.id}" align="text-center"><i class="fa fa-print"></i></a>
<a style="cursor:pointer" class="btn btn-danger btn-xs" onclick="hapusSurat(${data.id},'${data.jenis_surat}')"><i class="fa fa-trash"></i></a>
</td>`
}
},
]
});
$("#deleteSurat").on("submit", function(e) {
e.preventDefault();
var id = $('#id').val();
var jenis_surat = $('#jenis_surat').val()
$.ajax({
type: "POST",
url: "<?php echo site_url('suratkeluar/deleteSurat') ?>",
dataType: "JSON",
data: {
id: id,
jenis_surat: jenis_surat
},
success: function(data) {
$('#hapusData').modal('hide');
$('#datatable-surat-keluar').DataTable().ajax.reload()
//setTimeout(function() {
// alert('data berhasil dihapus')
// }, 1000);
}
});
});
});
</script>
<script>
function hapusSurat(id, jenis_surat) {
$('#id').val(id);
$('#jenis_surat').val(jenis_surat)
$('#hapusData').modal('show');
}
</script><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
check_not_login();
$this->load->model('m_keluar');
$this->load->model('m_masuk');
$this->load->helper('tgl_indo_helper');
}
public function index()
{
$suratmasuk = $this->db->query("SELECT * FROM tb_masuk");
$suratkeluar = $this->M_keluar->count_all();
$data['title'] = "Dashboard";
$data['masuk'] = $suratmasuk->num_rows();
$data['keluar'] = $suratkeluar;
$this->load->view('template_admin/header', $data);
$this->load->view('template_admin/sidebar');
$this->load->view('admin/dashboard', $data);
$this->load->view('template_admin/footer');
}
public function permintaan_surat_datatabel(){
$list = $this->m_keluar->get_datatables();
$data = array();
$no = $_POST['start'];
$type=$this->input->get('type');
$count = $this->m_keluar->count_all();
foreach ($list as $field) {
$no++;
$row = array();
$row['no'] = $no;
$row['id'] = $field->id;
$row['NIK'] = $field->nik;
$row['nama'] = $field->nama;
$row['alamat'] = $field->alamat;
$row['email'] = $field->email;
$row['jenis_surat'] = $field->jenis_surat;
$row['keterangan'] = $field->keterangan;
$row['kk'] = $field->kk;
$row['kode_surat'] = $field->kode_surat;
$row['ktp'] = $field->ktp;
$row['ktp_ortu'] = $field->ktp_ortu;
$row['no_surat'] = $field->no_surat;
$row['surat_keterangan_rs'] = $field->surat_keterangan_rs;
$row['surat_nikah'] = $field->surat_nikah;
$row['surat_rt_rw'] = $field->surat_rt_rw;
$row['tanggal'] = tanggal_indo(date('Y-n-d', strtotime($field->tanggal)));
$row['akta_kelahiran'] = $field->akta_kelahiran;
$row['ijazah'] = $field->ijazah;
$row['aksi'] = array('id' => $field->id, 'jenis_surat' => $field->jenis_surat);
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $count,
"recordsFiltered" => $count,
"data" => $data,
);
echo json_encode($output);
}
public function get_surat_masuk(){
$list = $this->m_masuk->get_datatables();
$data = array();
$no = $_POST['start'];
$type=$this->input->get('type');
$count = $this->m_masuk->count_all();
foreach ($list as $field) {
$no++;
$row = array();
$row['no'] = $no;
$row['id'] = $field->no;
$row['pengirim'] = $field->pengirim;
$row['no_surat'] = $field->no_surat;
$row['tgl_surat'] = $field->tgl_surat;
$row['tgl_terima'] = $field->tgl_terima;
$row['keterangan'] = $field->keterangan;
$row['file_surat'] = $field->file_surat;
$row['aksi'] = array('no' => $field->no);
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $count,
"recordsFiltered" => $count,
"data" => $data,
);
echo json_encode($output);
}
public function detail_surat(){
$id_surat = $this->input->post('id');
$jenis_surat = $this->input->post('jenis_surat');
$data_surat = null;
if ($jenis_surat == 'Surat Keterangan Usaha') {
$data_surat = $this->db->select('*')->from('surat_sku')->join('penduduk', 'penduduk.id=surat_sku.id_penduduk')->where(['surat_sku.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat Kematian') {
$data_surat = $this->db->select('*')->from('surat_kematian')->join('penduduk', 'penduduk.id=surat_kematian.id_penduduk')->where(['surat_kematian.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat Nikah') {
$data_surat = $this->db->select('*')->from('surat_nikah')->join('penduduk', 'penduduk.id=surat_nikah.id_penduduk')->where(['surat_nikah.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat Pindah Daerah') {
$data_surat = $this->db->select('*')->from('surat_pindah_domisili')->join('penduduk', 'penduduk.id=surat_pindah_domisili.id_penduduk')->where(['surat_pindah_domisili.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat Tugas') {
$data_surat = $this->db->select('*')->from('surat_tugas')->join('perangkat_desa', 'surat_tugas.id_perangkat_desa=perangkat_desa.id')->where(['surat_tugas.id' => $id_surat])->get()->row_array();
}elseif ($jenis_surat == 'Surat Undangan') {
$data_surat = $this->db->select('*')->from('surat_undangan')->where(['surat_undangan.id' => $id_surat])->get()->row_array();
}
$data_surat['tanggal'] = tanggal_indo(date('Y-n-d', strtotime($data_surat['tanggal'])));
$output =[
'data_surat' => $data_surat,
];
echo json_encode($output);
}
public function detail_surat_masuk(){
$no_surat = $this->input->post('id');
$data_surat = $this->db->select('*')->from('tb_masuk')->where(['no' => $no_surat])->get()->row_array();
$data_surat['tgl_surat'] = tanggal_indo(date('Y-n-d', strtotime($data_surat['tgl_surat'])));
$data_surat['tgl_terima'] = tanggal_indo(date('Y-n-d', strtotime($data_surat['tgl_terima'])));
$output =[
'data_surat' => $data_surat,
];
echo json_encode($output);
}
}
| c9671d17b9dba5010d61d756c51038628484c9a2 | [
"SQL",
"reStructuredText",
"PHP"
] | 62 | PHP | fflah/administrasisuratcipari | b3337ebada4a685264d5b279600839166663b74c | b7adb8103c7741ceb844ed99197ee6e605296c22 |
refs/heads/master | <file_sep>package DIP;
import java.util.Map;
import DIP.sintomak;
public interface InterfaceAfection {
double calculateSympomsAfection(Map<sintomak, Integer> sintomak);
}
<file_sep>package LSK;
import static org.junit.jupiter.api.Assertions.*;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
class Testak {
@Test
void test() {
Covid19Pacient covid = new Covid19Pacient("ibon",19);
Symptom a = new CurableSymptom("a",1,1);
Symptom b = new CurableSymptom("b",2,2);
Symptom c = new CurableSymptom("c",3,3);
Symptom d = new IncurableSymptom("d",4,4);
covid.addSymptom(a, 1);
covid.addSymptom(b, 2);
covid.addSymptom(c, 3);
covid.addSymptom(d, 4);
covid.showSymptoms();
assertTrue(true);
}
@Test
void test1() {
Covid19Pacient covid = new Covid19Pacient("ibon",19);
Symptom a = new CurableSymptom("a",1,1);
Symptom b = new CurableSymptom("b",2,2);
Symptom c = new CurableSymptom("c",3,3);
Symptom d = new IncurableSymptom("d",4,4);
covid.addSymptom(a, 1);
covid.addSymptom(b, 2);
covid.addSymptom(c, 3);
covid.addSymptom(d, 4);
covid.cure();
assertTrue(true);
}
}
<file_sep>package DIP;
import java.util.HashMap;
import java.util.Map;
public class Afection implements InterfaceAfection{
@Override
public double calculateSympomsAfection(Map<sintomak, Integer> sinto) {
double afection=0;
int elems = 0;
//calculate afection
for (sintomak s:sinto.keySet())
if (s.getCovidImpact()>50) {
afection = afection +s.getSeverityIndex()*sinto.get(s);
elems++;
}
if(elems!=0) {
afection = afection /elems;
}
return afection;
}
}
<file_sep>package DIP;
public interface sintomak {
public double calcCovid19Impact();
public int getSeverityIndex();
public int getaffectedDays();
public int getCovidImpact();
}
<file_sep>package LSK;
public class CurableSymptom extends Symptom implements Cura{
public CurableSymptom(String name, int covidImpact, int severityIndex) {
super(name, covidImpact,severityIndex);
}
public void cure(){
System.out.println("treatment applied to: "+name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCovidImpact() {
return covidImpact;
}
public void setCovidImpact(int covidImpact) {
this.covidImpact = covidImpact;
}
public int getSeverityIndex() {
return severityIndex;
}
public void setSeverityIndex(int severityIndex) {
this.severityIndex = severityIndex;
}
}<file_sep>package DIP;
public class Increment implements InterfaceIncrement{
@Override
public double CalcIncrement(Covid19Pacient pacient, double afection) {
if (pacient.getYears()>65) return afection*0.5;
else if(pacient.getYears()>45) return afection*0.3;
else return 0;
}
}
<file_sep>package DIP;
import java.util.HashMap;
import java.util.Map;
public class Afection1 implements InterfaceAfection{
@Override
public double calculateSympomsAfection(Map<sintomak, Integer> sinto) {
return 0;
}
}
<file_sep>package SRP;
import static org.junit.jupiter.api.Assertions.*;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
class Testa {
@Test
void testCovid() {
sintomak n = new NeuroMuscularSymptom(1,1,1);
sintomak c = new CardioVascularSymptom(2,2,2);
sintomak r = new RespiratorySymptom(3,3,3);
Map<sintomak,Integer> sintomak = new HashMap<sintomak,Integer>();
Covid19Pacient covid = new Covid19Pacient("ibon",19);
covid.addsintomak(n,1);
covid.addsintomak(c,2);
covid.addsintomak(r,3);
double emaitza = covid.calcCovid19Impact();
System.out.println(emaitza);
assertEquals(14,emaitza);
}
@Test
void testEgunak() {
sintomak n = new NeuroMuscularSymptom(1,1,1);
sintomak c = new CardioVascularSymptom(2,2,2);
sintomak r = new RespiratorySymptom(3,3,3);
Map<sintomak,Integer> sintomak = new HashMap<sintomak,Integer>();
Covid19Pacient covid = new Covid19Pacient("ibon",19);
covid.addsintomak(n,1);
covid.addsintomak(c,2);
covid.addsintomak(r,3);
double emaitza = covid.senatedDays();
System.out.println(emaitza);
assertEquals(3,emaitza);
}
}
<file_sep>package LSK;
import java.util.HashMap;
import java.util.Map;
public class Covid19Pacient extends Pacient {
String name;
Map<Symptom,Integer> symptoms=new HashMap<Symptom,Integer>();
public Covid19Pacient(String name, int years) {
super(name, years);
}
public void addSymptom(Symptom p, Integer w){
symptoms.put(p,w);
}
public void showSymptoms(){
for (Symptom s: symptoms.keySet())
s.show();
}
public void cure(){
for (Symptom s: symptoms.keySet())
if(s instanceof Cura) {
((Cura) s).cure();
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<Symptom, Integer> getSymptoms() {
return symptoms;
}
public void setSymptoms(Map<Symptom, Integer> symptoms) {
this.symptoms = symptoms;
}
}<file_sep>package DIP;
import java.util.HashMap;
import java.util.Map;
public class Covid19Pacient extends Pacient {
public Covid19Pacient(String name, int years) {
super(name, years);
// TODO Auto-generated constructor stub
}
Map<sintomak,Integer> sintomak = new HashMap<sintomak,Integer>();
public void addsintomak(sintomak s, Integer w) {
sintomak.put(s,w);
}
double calcCovid19Impact(InterfaceAfection ca, InterfaceIncrement incr) {
double afection=0;
double increment=0;
double impact;
//calculate afection
afection=ca.calculateSympomsAfection(sintomak);
//calculate increment
increment=incr.CalcIncrement (this, afection);
//calculate impact
impact=afection+increment;
return impact;
}
}<file_sep>package DIP;
public interface InterfaceIncrement {
double CalcIncrement(Covid19Pacient pacient, double afection);
}
<file_sep>package DIP;
public class Increment1 implements InterfaceIncrement{
@Override
public double CalcIncrement(Covid19Pacient pacient, double afection) {
return 0;
}
}
| 6a53d281c7b22d8c02542e9ebe59bf63c3dcd379 | [
"Java"
] | 12 | Java | IbonPerez/SOLID | 98aea262d1f6bcbffd2ddf700934a490ceafa660 | b0e1f579793989169c4e0419789e5ead01402bdf |
refs/heads/master | <repo_name>magicksid/cfeclipse<file_sep>/org.cfeclipse.cfml/src/org/cfeclipse/cfml/preferences/BrowserPreferenceConstants.java
package org.cfeclipse.cfml.preferences;
import org.eclipse.jface.preference.IPreferenceStore;
public class BrowserPreferenceConstants {
public static final String P_PRIMARY_BROWSER_PATH = "primaryBrowserPath";
public static final String P_SECONDARY_BROWSER_PATH = "secondaryBrowserPath";
public static final String P_TESTCASE_QUERYSTRING = "testCaseQueryString";
public static void setDefaults(IPreferenceStore store) {
store.setDefault(P_PRIMARY_BROWSER_PATH,"C:\\Program Files\\Mozilla Firefox\\firefox.exe");
store.setDefault(P_SECONDARY_BROWSER_PATH,"C:\\Program Files\\Internet Explorer\\iexplore.exe");
store.setDefault(P_TESTCASE_QUERYSTRING,"?method=RunTestRemote");
}
}
| 108a4506caeb43e32c8f145158f20e601169ef59 | [
"Java"
] | 1 | Java | magicksid/cfeclipse | f9becbeb0340959cd8697f76ee420b7242b07885 | 58ff332cc2748441a6d9c8c250bde066161c1efb |
refs/heads/main | <file_sep>//
// TableViewHeader.swift
// avito_intern
//
// Created by <NAME> on 08.09.2021.
//
import UIKit
class TableViewHeader: UITableViewHeaderFooterView {
@IBOutlet weak var titleLabel: UILabel!
func setup(title: String) {
self.titleLabel.text = title
self.titleLabel.font = UIFont.boldSystemFont(ofSize: 24.0)
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
<file_sep>//
// TableViewCell.swift
// avito_intern
//
// Created by <NAME> on 07.09.2021.
//
import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet weak var employeeNameLabel: UILabel!
@IBOutlet weak var employeePhoneNumberLabel: UILabel!
@IBOutlet weak var collectionView: UICollectionView! {
didSet {
self.collectionView.delegate = self
self.collectionView.dataSource = self
}
}
@IBOutlet weak var collectionViewHeight: NSLayoutConstraint!
var skills: [String] = []
var collectionViewCellIdentifier: String = "CollectionViewCell"
let fontHeight: CGFloat = 22.0
override func awakeFromNib() {
super.awakeFromNib()
let layout = GridLayout()
layout.delegate = self
self.collectionView.collectionViewLayout = layout
self.collectionView.alwaysBounceVertical = false
self.collectionView.register(UINib(nibName: collectionViewCellIdentifier, bundle: nil), forCellWithReuseIdentifier: collectionViewCellIdentifier)
}
func setup(employee: Employee) {
self.collectionView.collectionViewLayout.invalidateLayout()
self.employeeNameLabel.text = "Name: \(employee.name)"
self.employeePhoneNumberLabel.text = "Phone number: \(employee.phone_number)"
self.skills = employee.skills.sorted { $0.lowercased() < $1.lowercased() }
self.collectionView.reloadData()
}
}
extension TableViewCell: UICollectionViewDelegate {
}
extension TableViewCell: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.skills.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellIdentifier, for: indexPath) as? CollectionViewCell else {
print("Return default cell!")
return UICollectionViewCell()
}
cell.setup(title: skills[indexPath.row])
return cell
}
}
extension TableViewCell: GridLayoutDelegate {
func collectionView(_ collectionView: UICollectionView, widthForContentAtIndexPath indexPath: IndexPath) -> CGFloat {
let text = skills[indexPath.item]
let referenceSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: self.fontHeight)
let calculatedSize = (text as NSString).boundingRect(with: referenceSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: self.fontHeight)], context: nil)
return calculatedSize.width
}
}
<file_sep>//
// GridLayout.swift
// iPlanner
//
// Created by <NAME> on 16.07.2021.
//
import UIKit
protocol GridLayoutDelegate: AnyObject {
func collectionView(_ collectionView: UICollectionView, widthForContentAtIndexPath indexPath: IndexPath) -> CGFloat
}
class GridLayout: UICollectionViewLayout {
weak var delegate: GridLayoutDelegate?
private let numberOfColumns = 3
private let cellPadding: CGFloat = 10
private var cache: [UICollectionViewLayoutAttributes] = []
private var contentHeight: CGFloat {
guard let collectionView = collectionView else {
return 0
}
return collectionView.bounds.height - (collectionView.contentInset.top + collectionView.contentInset.bottom)
}
private var contentWidth: CGFloat = 0
override var collectionViewContentSize: CGSize {
return CGSize(width: contentWidth, height: contentHeight)
}
override func prepare() {
super.prepare()
cache.removeAll()
guard let collectionView = collectionView else {
return
}
let columnHeight = contentHeight / CGFloat(numberOfColumns)
var xOffset = Array<CGFloat>(repeating: 0, count: numberOfColumns)
var yOffset = Array<CGFloat>()
for column in 0..<numberOfColumns {
yOffset.append(CGFloat(column) * columnHeight)
}
var column = 0
let numberOfItems = collectionView.numberOfItems(inSection: 0)
for item in 0..<numberOfItems {
let indexPath = IndexPath(item: item, section: 0)
let cellWidth = delegate?.collectionView(collectionView, widthForContentAtIndexPath: indexPath) ?? 180
let width = (cellPadding * 2) + cellWidth
let frame = CGRect(x: xOffset[column], y: yOffset[column], width: width, height: columnHeight)
let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = insetFrame
cache.append(attributes)
contentWidth = max(contentWidth, frame.maxX)
xOffset[column] = xOffset[column] + width
column = (column + 1) % numberOfColumns
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var visibleAttributes: [UICollectionViewLayoutAttributes] = []
for attributes in cache {
if attributes.frame.intersects(rect) {
visibleAttributes.append(attributes)
}
}
return visibleAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache[indexPath.item]
}
}
<file_sep>//
// Model.swift
// avito_intern
//
// Created by <NAME> on 07.09.2021.
//
import Foundation
struct AvitoData: Codable {
var company: Company
}
struct Company: Codable {
var name: String
var employees: [Employee]
}
struct Employee: Codable {
var name: String
var phone_number: String
var skills: [String]
}
<file_sep>//
// ViewController.swift
// avito_intern
//
// Created by <NAME> on 07.09.2021.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
}
}
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var dataArray = Array<AvitoData>()
let cellIdentifier = "TableViewCell"
var session: URLSession!
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundView = activityIndicator
activityIndicator.hidesWhenStopped = true
tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier)
let config = URLSessionConfiguration.default
config.timeoutIntervalForResource = 5
config.timeoutIntervalForRequest = 5
self.session = URLSession(configuration: config)
self.getData()
}
private func showAlert(title: String, message: String) {
DispatchQueue.main.async { [weak self] in
self?.activityIndicator.stopAnimating()
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self?.present(alert, animated: true, completion: nil)
}
}
private func getData() {
self.activityIndicator.startAnimating()
guard let url = URL(string: "https://run.mocky.io/v3/1d1cb4ec-73db-4762-8c4b-0b8aa3cecd4c") else {
print("Wrong url!")
return
}
self.session.dataTask(with: url) { [weak self] (data, response, error) in
guard error == nil, let data = data else {
print("Error detected! Cannot get data! \(error?.localizedDescription ?? "Empty description")")
self?.showAlert(title: "Bad internet", message: "Reconnect every 5 sesonds")
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { [weak self] in
self?.getData()
}
return
}
guard let data = try? JSONDecoder().decode(AvitoData.self, from: data) else {
print("Can't parse companies")
return
}
self?.dataArray.append(data)
self?.dataArray[0].company.employees.sort { $0.name.lowercased() < $1.name.lowercased() }
DispatchQueue.main.async { [weak self] in
self?.tableView.reloadData()
self?.activityIndicator.stopAnimating()
}
}.resume()
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
self.dataArray[section].company.name
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "TableViewHeader") as? TableViewHeader else {
return UITableViewHeaderFooterView()
}
header.setup(title: self.dataArray[section].company.name)
return header
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArray[section].company.employees.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? TableViewCell else {
print("Return default table cell!")
return UITableViewCell()
}
cell.setup(employee: self.dataArray[indexPath.section].company.employees[indexPath.row])
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
self.dataArray.count
}
}
<file_sep>//
// CollectionViewCell.swift
// avito_intern
//
// Created by <NAME> on 10.09.2021.
//
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var titleButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setup(title: String) {
self.titleButton.setTitle(title, for: .normal)
self.titleButton.setLayer()
}
}
extension UIButton {
func setLayer() {
UIGraphicsBeginImageContext(layer.frame.size)
let recPath = UIBezierPath(roundedRect: frame, byRoundingCorners: [.topLeft, .bottomRight, .topRight, .bottomLeft], cornerRadii: CGSize(width: 10, height: 10))
UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.1).setFill()
recPath.fill()
let imageBuffer = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
layer.contents = imageBuffer?.cgImage
titleEdgeInsets = UIEdgeInsets(top: 3.0, left: 3.0, bottom: 3.0, right: 3.0)
}
}
| a0ba1bbf4b3b6a852026c32708154bbcaaf5dedc | [
"Swift"
] | 6 | Swift | seryogasx/avito_intern | 4cf1360aa7801a87e0292e0ed93065f61283cb9e | b4a98edc9b025591254a155af5572a09187a3647 |
refs/heads/master | <file_sep>// 带头结点
void InitList(LinkList &L)
{
L = (LNode*)malloc(sizeof(LNode));
if(!L)
exit(OVERFLOW);
L->next = NULL;
}
void DestroyList(LinkList &L)
{
LinkList p;
while(L)
{
p = L->next;
free(L);
L = p;
}
}
void ClearList(LinkList L)
{
LinkList p = L->next;
L->next = NULL;
DestroyList(p);
}
Status ListEmpty(LinkList L)
{
if(L->next)
return FALSE;
return TRUE;
}
int ListLength(LinkList L)
{
int i = 0;
LinkList p = L->next;
while(p)
{
i++;
p = p->next;
}
return i;
}
Status GetElem(LinkList L, int i, ElemType &e)
{
int j = 1;
LinkList p = L->next;
while(p && j < i)
{
j++;
p = p->next;
}
if(!p || j > i)
return ERROR;
e = p->data;
return OK;
}
int LocateElem(LinkList L, ElemType e, Status(*compare)(ElemType, ElemType))
{
int i = 1;
LinkList p = L->next;
// while(p && !compare(e, p->data));
// {
// p = p->next;
// i++;
// }
// return i;
while(p)
{
i++;
if(compare(p->data, e))
return i;
p = p->next;
}
return 0;
}
Status PriorElem(LinkList L, ElemType cur_e, ElemType &pre_e)
{
// LinkList p = L->next, q;
// while(p->next && p->next->data != cur_e)
// {
// q = P;
// p = p->next;
// }
// pre_e = q->data;
// return OK;
LinkList q, p = L->next;
while(p && p->next)
{
q = p->next;
if(q->data == cur_e)
{
pre_e = p->data;
return OK;
}
p = q;
}
return ERROR;
}
Status NextElem(LinkList L, ElemType cur_e, ElemType &next_e)
{
LinkList p = L->next;
while(p && p->next)
{
if(p->data == cur_e)
{
next_e = p->next->data;
return OK;
}
p = p->next;
}
return ERROR;
}
Status ListInsert(LinkList L, int i, ElemType e)
{
int j = 0; // 因为可以插在表头,所以j可以为0
LinkList s, p = L;
while(p && j < i-1)
{
j++;
p = p->next;
}
if(!p || j > i-1) // i<1或大于表长
return ERROR;
s = (LinkList)malloc(sizeof(LinkList)); // 创建新结点s
s->data = e;
s->next = p->next;
p->next = s;
return OK;
}
Status ListDelete(LinkList L, int i, ElemType &e)
{
int j = 0;
LinkList q, p = L;
while(p->next && j < i-1)
{
j++;
p = p->next;
}
if(!p || j > i-1)
return ERROR;
q = p->next;
e = q->data;
p->next = q->next;
free(q);
return OK;
}
void ListTraverse(LinkList L, void(*visit)(ElemType))
{
LinkList p = L->next;
while(p)
{
visit(p->data);
p = p->next;
}
printf("\n");
}
<file_sep>//// algo8-1.cpp 无序顺序表部分程序
//#include "c1.h"
//#include "func8-1.h"
//#include "c8-1.h"
//#include "c8-2.h"
//#include "bo8-1.h"
//int main()
//{
// SSTable st;
// int i;
// long s;
// char filename[13] = "f8-1.txt";
// Create_SeqFromFile(st, filename);
// for(i = 1; i <= st.length; i++)
// st.elem[i].total = st.elem[i].politics + st.elem[i].Chinese + st.elem[i].math + st.elem[i].English + st.elem[i].physics + st.elem[i].chemistry + st.elem[i].biology;
// printf("准考证号 姓名 政治 语文 数学 英语 物理 化学 生物 总分\n");
// Traverse(st, Visit);
// printf("进行非降序排列:\n");
// Ascend(st);
// Traverse(st, Visit);
// printf("请输入待查找人的考号:");
// InputKey(s);
// i = Search_Bin(st, s);
// if(i)
// Visit(st.elem[i]);
// else
// printf("未找到\n");
// Destroy(st);
// return 0;
//}
// algo8-2.cpp
//#include "c1.h"
//#include "func8-2.h"
//#include "c8-1.h"
//#include "c8-2.h"
//#include "bo8-1.h"
//int main()
//{
// SSTable st;
// int i;
// KeyType s;
// Create_OrdFromFile(st,"f8-2.txt");
// printf("有序表为:");
// Traverse(st, Visit);
// printf("\n");
// printf("请输入待查找数据的关键字:");
// InputKey(s);
// i = Search_Bin(st,s);
// if(i)
// printf("%d是第%d个数据的关键字\n",st.elem[i].key,i);
// else
// printf("未找到\n");
// Destroy(st);
// return 0;
//}
// algo8-3.app 静态查找树的操作
//#include "c1.h"
//#include "func8-3.h"
//#include "c8-1.h"
//#include "c8-2.h"
//#include "bo8-1.h"
//typedef ElemType TElemType;
//#include "c6-1.h"
//#include "bo6-1.h"
//#define N 100
//Status SecondOptimal(BiTree &T, ElemType R[], int sw[], int low, int high)
//{// 由有序表R[low~high]及其累计权值表sw(其中sw[0]==0)递归构造次优查找树T
// int j, i = low; // 有最小deltPi值的序号,初值设为当low==high(有序表仅为一个元素)时的值
// double dw = sw[high] + sw[low - 1];
// double min_ = fabs(sw[high]-sw[low]);
// for(j = low + 1; j <= high; j++)
// if(fabs(dw - sw[j] - sw[j-1]) < min_)
// {
// i = j;
// min_ = fabs(dw - sw[j] - sw[j-1]);
// }
// if(!(T = (BiTree)malloc(sizeof(BiTree)))) // 生成结点失败
// return ERROR;
// T->data = R[i];
// if(i == low)
// T->lchild = NULL;
// else
// SecondOptimal(T->lchild, R, sw, low, i-1);
// if(i == high)
// T->rchild = NULL;
// else
// SecondOptimal(T->rchild, R, sw, i+1, high);
// return OK;
//}
//
//void FindSW(int sw[],SSTable ST)
//{// 按照有序表ST中各数据元素的weight域求累计权值数组sw,CreateSOSTree()调用
// int i;
// sw[0] = 0; // 置边界值
// printf("\nsw = 0");
// for(i = 1; i <= ST.length; i++)
// {
// sw[i] = sw[i - 1] + ST.elem[i].weight;
// printf("%5d",sw[i]);
// }
//}
//
//typedef BiTree SOSTree; // 次优查找树采用二叉链表的存储结构
//void CreateSOSTree(SOSTree &T, SSTable ST)
//{
// int sw[N + 1];
// if(ST.length == 0)
// T = NULL;
// else
// {
// FindSW(sw, ST);
// SecondOptimal(T, ST.elem, sw, 1, ST.length);
// }
//}
//
//Status Search_SOSTree(SOSTree &T, KeyType key)
//{
// while(T)
// if(T->data.key == key)
// return OK;
// else if(T->data.key > key)
// T = T->lchild;
// else
// T = T->rchild;
// return FALSE;
//}
//
//int main()
//{
// SSTable st;
// SOSTree t;
// Status i;
// KeyType s;
// Create_OrdFromFile(st, "f8-3.txt");
// printf(" ");
// Traverse(st, Visit);
// CreateSOSTree(t,st);
// printf("\n请输入待查找的字符:");
// InputKey(s);
// i = Search_SOSTree(t, s);
// if(i)
// printf("%c的权值是%d\n",s,t->data.weight);
// else
// printf("表中不存在此字符\n");
// DestroyBiTree(t);
// return 0;
//}
// algo8-4.cpp
#include "c1.h"
#include "func8-5.h" // 包括数据元素类型的定义及其操作
#include "c8-2.h" // 对两个数值型关键字比较的约定
typedef ElemType TElemType; // 定义二叉树的元素类型为数据元素类型
#include "c6-1.h" // 二叉链表的存储结构
#include "func8-4.h"
#include "bo8-2.h" // 二叉排序树的基本操作
int main()
{
BiTree dt, p;
int i, n;
KeyType j;
ElemType r;
Status k;
FILE *f;
f = fopen("f8-4.txt","r");
fscanf(f,"%d",&n);
InitDSTable(dt); // 构造空二叉排序树dt
for(i = 0; i < n; i++) // 依次在二叉排序树dt中插入n个数据元素
{
InputFromFile(f,r); // 由数据文件输入数据元素的值并赋给r
k = InsertBST(dt, r); // 依次将数据元素r插入二叉排序树dt中
if(!k) // 插入数据元素r失败
printf("二叉排序树dt中已存在关键字为%d的数据,故(%d,%d)无法插入到dt中。\n",r.key,r.key,r.others);
}
fclose(f);
printf("中序遍历二叉排序树dt:\n");
TraverseDSTable(dt, Visit);
printf("先序遍历二叉排序树dt:\n");
PreOrderTraverse(dt, Visit);
printf("\n请输入待查找的关键字的值:");
InputKey(j);
p = SearchBST(dt, j);
if(p)
{
printf("dt中存在关键字为%d的结点。",j);
DeleteBST(dt,j);
printf("删除此结点后,中序遍历二叉树dt:\n");
TraverseDSTable(dt, Visit);
printf("\n先序遍历二叉树dt:\n");
PreOrderTraverse(dt,Visit);
printf("\n");
}
else // 未找到,p为空
printf("dt中不存在关键字为%d的结点。\n",j);
DestroyDSTable(dt); // 销毁二叉树
return 0;
}
<file_sep>// bo2-3.h 不带头结点的单链表基本操作
#define DestroyList ClearList
void InitList(LinkList &L)
{
L = NULL;
}
void ClearList(LinkList &L)
{
LinkList p;
while(L)
{
p = L;
L = L->next;
free(p);
}
}
Status ListEmpty(LinkList L)
{
if(L)
return FALSE;
return TRUE;
}
int ListLength(LinkList L)
{
int i = 0;
LinkList p = L;
while(p)
{
i++;
p = p->next;
}
return i;
}
Status GetElem(LinkList L, int i, ElemType &e)
{
int j = 1;
LinkList p = L;
while(p && j < i)
{
j++;
p = p->next;
}
if(j == i && p)
{
e = p->data;
return OK;
}
return ERROR;
}
int LocateElem(LinkList L, ElemType e, Status(*compare)(ElemType, ElemType))
{
int i = 0;
LinkList p = L;
// while(p && !compare(e,p->data))
// {
// i++;
// p = p->next;
// }
// return i;
while(p)
{
i++;
if(compare(e, p->data))
return i;
p = p->next;
}
return 0;
}
Status ListInsert(LinkList &L, int i, ElemType e)
{// 在第i个元素前插入值
int j = 1;
LinkList s, p = L;
if(i < 0)
return ERROR;
s = (LinkList)malloc(sizeof(LNode));
s->data = e;
if(i == 1) // 插入表头
{
s->next = L;
L = s;
}
else
{
while(p && j < i-1) // 找到第i-1个结点
{
j++;
p = p->next;
}
if(!p) // 超过表长
return ERROR;
s->next = p->next;
p->next = s;
}
return OK;
}
Status ListDelete(LinkList &L, int i, ElemType &e)
{
int j = 1;
LinkList q, p = L;
if(!p)
return ERROR;
else if(i == 1)
{
L = p->next;
e = p->data;
free(p);
}
else
{
while(p && j < i)
{
j++;
p = p->next;
}
if(!p || j > i-1)
return ERROR;
q = p->next;
e = p->data;
p->next = q->next;
free(q);
}
return OK;
}
void ListTraverse(LinkList L, void(*vi)(ElemType))
{
LinkList p = L;
while(p && p->next)
{
vi(p->data);
p = p->next;
}
printf("\n");
}
<file_sep>// bo5-1.h 顺序存储数组的基本操作(5个)
Status InitArray(Array &A, int dim, ...)
{// 若维数dim和各维长度合法,则构造数组A,返回OK
int elemtotal = 1, i; // 数组元素总数
va_list ap; // 边长参数类型,在stdarg.h中
if(dim < 1 || dim > MAX_ARRAY_DIM)
return ERROR;
A.dim = dim;
A.bounds = (int*)malloc(dim*sizeof(int)); // 动态分配维界基址
if(!A.bounds)
exit(OVERFLOW);
va_start(ap,dim);
for(i = 0; i < dim ;i++)
{
A.bounds[i] = va_arg(ap, int); // 逐一将变长参数赋给A.bounds[i]
if(A.bounds[i] < 0)
return UNDERFLOW;
elemtotal *= A.bounds[i];
}
va_end(ap); // 结束提取变长参数
A.base = (ElemType*)malloc(elemtotal * sizeof(ElemType));
if(!A.base)
exit(OVERFLOW);
A.constants = (int*)malloc(dim*sizeof(int)); // 动态分配数组偏移量基址
if(!A.constants)
exit(OVERFLOW);
A.constants[dim - 1] = 1; // 最后一维的偏移量为1
for(i = dim - 2; i >= 0; i--)
A.constants[i] = A.bounds[i + 1] * A.constants[i + 1]; // 每一维的偏移量
return OK;
}
void DestroyArray(Array &A)
{
if(A.base)
free(A.base);
if(A.bounds)
free(A.bounds);
if(A.constants)
free(A.constants);
A.base = A.bounds = A.constants = NULL;
A.dim = 0;
}
Status Locate(Array A, va_list ap, int &off)
{
int i, ind;
off = 0;
for(i = 0; i < A.dim; i++)
{
ind = va_arg(ap, int);
if(ind < 0 || ind >= A.bounds[i])
return OVERFLOW;
off += A.constants[i]*ind;
}
return OK;
}
Status Value(ElemType &e, Array A, ...)
{
va_list ap;
int off;
va_start(ap, A);
if(Locate(A, ap, off) == OVERFLOW)
return ERROR;
e = *(A.base + off);
return OK;
}
Status Assign(Array A, ElemType e, ...)
{
va_list ap;
int off;
va_start(ap,e);
if(Locate(A, ap, off) == OVERFLOW)
return ERROR;
*(A.base + off) = e;
return OK;
}
<file_sep>// c6-3.h 哈夫曼树和哈夫曼编码的存储结构
typedef struct
{
unsigned int weight; // 结点权值
unsigned int parent, lchild, rchild;
}HTNode, *HuffmanTree; // 动态分配数组存储哈弗曼树
typedef char* *HuffmanCode; // 动态分配数组存储哈夫曼编码表
<file_sep>// c8-1.h 静态查找表的顺序存储结构
struct SSTable // 静态查找表
{
ElemType *elem; // 表空间基址,0号单元不存数据
int length; // 表长
};
<file_sep>// main5-1.h 检验bo5-1.h
//#include "c1.h"
//typedef int ElemType;
//#include "c5-1.h"
//#include "bo5-1.h"
//
//int main()
//{
// Array A;
// int i, j, k, dim = 3;
// int bound1 = 3, bound2 = 4, bound3 = 2; // 维数
// ElemType e;
// InitArray(A, dim, bound1, bound2, bound3); // 构造3×4×2的三维数组
// printf("A.bounds = ");
// for(i = 0; i < dim; i++)
// printf("%d", *(A.bounds + i));
// printf("\nA.constants = ");
// for(i = 0; i < dim; i++)
// printf("%d", *(A.constants + i));
// printf("\n%d页%d行%d列矩阵元素如下:\n",bound1,bound2,bound3);
// for(i = 0; i < bound1; i++)
// {
// for(j = 0; j < bound2; j++)
// {
// for(k = 0; k < bound3; k++)
// {
// Assign(A, i*100 + j*10 + k,i,j,k);
// Value(e,A,i,j,k);
// printf("A[%d][%d][%d] = %2d ", i,j,k,e);
// }
// printf("\n");
// }
// printf("\n");
// }
// printf("A.base = \n");
// for(i = 0; i < bound1*bound2*bound3; i++)
// {
// printf("%4d", *(A.base+i));
// if(i%(bound2*bound3)==bound2*bound3-1)
// printf("\n");
// }
// printf("A.dim = %d\n",A.dim);
// DestroyArray(A);
//
// return 0;
//}
// algo5-1.cpp 变长参数表(函数的实参个数可变)
//#include "c1.h"
//typedef int ElemType;
//ElemType Max(int num,...)
//{// 求num个数中最大值
// va_list ap;
// int i;
// ElemType m, n;
// if(num < 1)
// exit(OVERFLOW);
// va_start(ap, num);
// m = va_arg(ap, ElemType);
// for(i = 1; i < num; i++)
// {
// n = va_arg(ap, ElemType);
// if (m < n)
// m = n;
// }
// va_end(ap);
// return m;
//}
//int main()
//{
// printf("最大值为%d\n",Max(4,7,9,5,8));
// printf("最大值为%d\n",Max(3,17,36,25));
// return 0;
//}
// main5-2.cpp 检验bo5-2.h和bo5-3.h的主程序
//#include"c1.h"
//typedef int ElemType;
//#include"c5-2.h"
//#include"func5-1.h"
//#include"bo5-2.h"
//#include"bo5-3.h"
//#include"func5-2.h"
// algo.cpp 实现算法5.2的程序
#include "c1.h"
typedef int ElemType;
#include "c5-2.h"
#include "func5-1.h"
#include "bo5-2.h"
#include "bo5-3.h"
void FastTransposeSMatrix(TSMatrix M, TSMatrix &T)
{// 快速求稀疏矩阵M的转置矩阵T
int p, q, col, *num, *cpot;
num = (int*)malloc((M.nu+1)*sizeof(int)); // 存M每列非零元个数
cpot = (int*)malloc((M.nu+1)*sizeof(int)); // 存T每行下一个非零元素的位置
T.mu = M.mu;
T.nu = M.nu;
T.tu = M.tu;
if(T.tu)
{
for(col = 1; col <= M.nu; col++) // 从M的第一列到最后一列
num[col] = 0; // 计数器初值清零
for(p = 1; p <= M.tu; p++) // M的非零元素
++num[M.data[p].j]; // 根据所在列进行统计
cpot[1] = 1; // T的第一行的第一个非零元在T.data中的序号为1
for(col = 2; col <= M.nu; col++) // 从M的第二列到最后一列
cpot[col] = cpot[col - 1] + num[col - 1];
for(p = 1; p <= M.tu; p++)
{
col = M.data[p].j; // 将其在M中的列数赋给col
q = cpot[col]; // q指示M当前的元素在T中的序号
T.data[q].i = M.data[p].j;
T.data[q].j = M.data[p].i;
T.data[q].e = M.data[p].e;
cpot[col]++;
}
}
free(num);
free(cpot);
}
int main()
{
TSMatrix A, B;
printf("创建矩阵A: ");
CreateSMatrix(A);
PrintSMatrix(A);
FastTransposeSMatrix(A, B);
printf("矩阵B(A的快速转置:)\n");
PrintSMatrix(B);
return 0;
}
<file_sep>// bo3-2.h链队列的基本操作(9个)
void InitQueue(LinkQueue &Q)
{
Q.front1 = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if(!Q.front1)
exit(OVERFLOW);
Q.front1->next = NULL;
}
void DestroyQueue(LinkQueue &Q)
{
while(Q.front1)
{
Q.rear = Q.front1->next;
free(Q.front1);
Q.front1 = Q.rear;
}
}
void ClearQueue(LinkQueue &Q)
{
DestroyQueue(Q);
InitQueue(Q);
}
Status QueueEmpty(LinkQueue Q)
{
if(Q.front1 == Q.rear)
return TRUE;
return FALSE;
}
int QueueLength(LinkQueue Q)
{
int len = 0;
QueuePtr p = Q.front1;
while(Q.rear != p)
{
len++;
p = p->next;
}
return len;
}
Status GetHead(LinkQueue Q, QElemType &e)
{
if(Q.front1 == Q.rear)
return ERROR;
QueuePtr p = Q.front1->next;
e = p->data;
return OK;
}
void EnQueue(LinkQueue &Q, QElemType e)
{// 入队
QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
if(!p)
exit(OVERFLOW);
p->data = e;
p->next = NULL;
Q.rear->next = p; // 追加到队尾
Q.rear = p;
}
Status DeQueue(LinkQueue &Q, QElemType &e)
{
if(Q.front1 == Q.rear)
return ERROR;
QueuePtr p = Q.front1->next;
e = p->data;
Q.front1->next = p->next; // 队头后移
if(Q.rear == p)
Q.rear = Q.front1;
free(p);
return OK;
}
void QueueTraverse(LinkQueue Q, void(*visit)(QElemType))
{
QueuePtr p = Q.front1->next;
while(p)
{
visit(p->data);
p = p->next;
}
printf("\n");
}
<file_sep>// bo7-1.h 图的邻接矩阵存储的基本操作(17个)
int LocateVex(MGraph G, VertexType u)
{// 定位图G中顶点u的位置,若无返回-1
int i;
for(i = 0; i < G.vexnum; i++) // 依次查找
{
if(strcmp(u.name, G.vexs[i].name) == 0)
return i; // 返回顶点序号
}
return -1;
}
void CreateDG(MGraph &G)
{// 采用数组(邻接矩阵)表示法,构造有向图G
int i, j, k, IncInfo; // IncInfo若为0,则弧不含相关信息
VertexType v1, v2; // 顶点类型
printf("请输入有向图G的顶点数,弧数,弧是否含相关信息(是:1 否:0):");
scanf("%d,%d,%d",&G.vexnum,&G.arcnum,&IncInfo);
printf("请输入%d个顶点的值(名称<%d个字符):\n",G.vexnum,MAX_NAME);
for(i = 0; i < G.vexnum; i++)
{
Input(G.vexs[i]); // 输入顶点信息,在func7-1.h中
}
for(i = 0; i < G.vexnum; i++)
{// 初始化二维邻接矩阵(弧信息)
for(j = 0; j < G.vexnum; j++)
{
G.arcs[i][j].adj = 0; // 图,不相邻
G.arcs[i][j].info = NULL; // 无相关信息
}
}
printf("请输入%d条弧的弧尾 弧头:\n",G.arcnum);
for(k = 0; k < G.arcnum; k++)
{
scanf("%s%s%*c",v1.name, v2.name); // %*c吃掉回车符
i = LocateVex(G, v1); // 弧尾序号
j = LocateVex(G, v2); // 弧头序号
G.arcs[i][j].adj = 1; // 有向图
if(IncInfo) // 有相关信息
InputArc(G.arcs[i][j].info); // 动态生成弧的相关信息
}
G.kind = DG;
}
void CreateDN(MGraph &G)
{// 采用数组(邻接矩阵)表示法,构造有向网G
int i, j, k, IncInfo; // IncInfo若为0,则弧不含相关信息
VRType w; // 顶点关系类型
VertexType v1, v2; // 顶点类型
printf("请输入有向网G的顶点数,弧数,弧是否含相关信息(是:1 否:0):");
scanf("%d,%d,%d",&G.vexnum, &G.arcnum, &IncInfo);
printf("请输入%d个顶点的值(名称<%d个字符):\n",G.vexnum, MAX_NAME);
for(i = 0; i < G.vexnum; i++) // 构造顶点向量
Input(G.vexs[i]); // 根据顶点信息类型,输入顶点信息,在func7-1.h中
for(i = 0; i < G.vexnum; i++) // 初始化二维邻接矩阵
for(j = 0; j < G.vexnum; j++)
{
G.arcs[i][j].adj = INFINITY; // 网,不相邻
G.arcs[i][j].info = NULL; // 无相关信息
}
printf("请输入%d条弧的弧尾 弧头 权值:\n",G.arcnum);
for(k = 0; k < G.arcnum; k++)
{
scanf("%s,%s,%d%*c", v1.name, v2.name, &w);
i = LocateVex(G, v1); // 弧尾的序号
j = LocateVex(G, v2); // 弧头的序号
G.arcs[i][j].adj = w; // 有向网
if(IncInfo)
{
InputArc(G.arcs[i][j].info); // 动态生成存储空间,输入相关弧的信息
}
}
G.kind = DN;
}
void CreateUDG(MGraph &G)
{// 采用数组(邻接矩阵)表示法,构造无向图G
int i, j, k, IncInfo;
VertexType v1, v2;
printf("请输入无向图G的顶点数,边数,边是否含相关信息(是:1 否:0):");
scanf("%d,%d,%d",&G.vexnum, &G.arcnum, IncInfo);
printf("请输入%d个顶点的值(名称<%d个字符):\n",G.vexnum,MAX_NAME);
for(i = 0; i < G.vexnum; i++)
{
Input(G.vexs[i]);
}
for(i = 0; i < G.vexnum; i++) // 初始化二维邻接矩阵
for(j = 0; j < G.vexnum; j++)
{
G.arcs[i][j].adj = 0; // 图,不相邻
G.arcs[i][j].info = NULL; // 不含相关信息
}
printf("请输入%d条边的顶点1 顶点2:\n",G.arcnum);
for(k = 0; k < G.arcnum; k++)
{
scanf("%s%s%*c",v1.name, v2.name);
i = LocateVex(G, v1);
j = LocateVex(G, v2);
G.arcs[i][j].adj = 1; // 图
if(IncInfo) // 有相关信息
{
InputArc(G.arcs[i][j].info);
}
G.arcs[j][i] = G.arcs[i][j]; // 无向,对称矩阵
}
G.kind = UDG;
}
void CreateUDN(MGraph &G)
{// 无向网
int i, j, k, IncInfo;
VRType w; // 顶点关系类型
VertexType v1, v2; // 顶点类型
printf("请输入无向网G的顶点数,边数,边是否含相关信息:");
scanf("%d,%d,%d",&G.vexnum, &G.arcnum, IncInfo);
printf("请输入%d个顶点的值(名称<%d个字符):\n",G.vexnum, MAX_NAME);
for(i = 0; i < G.vexnum; i++)
{// 初始化顶点向量
Input(G.vexs[i]);
}
for(i = 0; i < G.vexnum; i++)
for(j = 0; j <G.vexnum; j++)
{
G.arcs[i][j].adj = INFINITY; // 网,不相邻
G.arcs[i][j].info = NULL;
}
printf("请输入%d条边的顶点1 顶点2权值:\n",G.arcnum);
for(k = 0; k < G.arcnum; k++)
{
scanf("%s%s%d%*c",v1.name, v2.name, &w);
i = LocateVex(G, v1);
j = LocateVex(G, v2);
G.arcs[i][j].adj = w; // 网
if(IncInfo)
{
InputArc(G.arcs[i][j].info);
}
G.arcs[j][i] = G.arcs[i][j];
}
G.kind = UDN;
}
void CreateGraph(MGraph &G)
{// 采用数组(邻接矩阵)表示法,构造图G
printf("请输入图G的类型(有向图:0 有向网:1 无向图:2 无向网:3)");
scanf("%d",&G.kind);
switch(G.kind)
{
case DG: CreateDG(G); break;
case DN: CreateDN(G); break;
case UDG: CreateUDG(G); break;
case UDN: CreateUDN(G); break;
}
}
VertexType GetVex(MGraph G, int v)
{// 返回顶点序号为v的值
if(v >= G.vexnum || v < 0)
exit(OVERFLOW);
return G.vexs[v];
}
Status PutVex(MGraph &G, VertexType v, VertexType value)
{// 对v赋新值
int k = LocateVex(G, v);
if(k < 0)
return ERROR;
G.vexs[k] = value;
return OK;
}
int FirstAdjVex(MGraph G, int v)
{// 返回v的第一个邻接顶点的序号,若无邻接顶点,返回-1
int i;
VRType j = 0; // 顶点关系类型,图
if(G.kind % 2) // 网
{
j = INFINITY;
}
for(i = 0; i < G.vexnum; i++) // 从第一个顶点开始找
if(G.arcs[v][i].adj != j) // 是第一个邻接顶点
return i;
return -1;
}
int NextAdjVex(MGraph G, int v, int w)
{// 返回v的下一个邻接顶点的序号,若w是v的最后一个邻接顶点,则返回-1
int i;
VRType j = 0; // 顶点关系类型,图
if(G.kind % 2) // 网
{
j = INFINITY;
}
for(i = w+1; i < G.vexnum; i++) // 从第w+1个顶点开始找
if(G.arcs[v][i].adj != j)
return i;
return -1;
}
void InsertVex(MGraph &G, VertexType v)
{// 向图G中新增顶点
int i;
VRType j = 0; // 顶点关系类型,图
if(G.kind % 2) // 网
{
j = INFINITY;
}
G.vexs[G.vexnum] = v; // 将v值赋给新顶点
for(i = 0; i <= G.vexnum; i++) // 初始化新增
{
G.arcs[G.vexnum][i].adj = G.arcs[G.vexnum][i].adj = j;
G.arcs[G.vexnum][i].info = G.arcs[i][G.vexnum].info = NULL;
}
G.vexnum++;
}
Status InsertArc(MGraph &G, VertexType v, VertexType w)
{// 向图G中新增弧<v,w>若G为无向,则还新增弧<w,v>
int i, v1, w1;
v1 = LocateVex(G, v); // 弧尾顶点v的序号
w1 = LocateVex(G, w); // 弧头顶点w的序号
if(v1 < 0 || w1 <0) // 不存在顶点v或w
return ERROR;
G.arcnum++; // 弧数+1
if(G.kind % 2) // 网
{
printf("请输入此弧的权值:");
scanf("%d",G.arcs[v1][w1].adj);
}
else // 图
G.arcs[v1][w1].adj = 1;
printf("是否有该弧的相关信息(0:无 1:有):");
scanf("%d%*c",&i);
if(i) // 有相关信息
InputArc(G.arcs[v1][w1].info);
if(G.kind > 1) // 无向
G.arcs[w1][v1] = G.arcs[v1][w1];
return OK;
}
Status DeleteArc(MGraph &G, VertexType v, VertexType w)
{// 删除弧<v,w>,若G无向,删除对称弧<w,v>
int v1, w1;
VRType j = 0; // 顶点关系类型,图
if(G.kind % 2) // 网
{
j = INFINITY;
}
v1 = LocateVex(G, v);
w1 = LocateVex(G, w);
if(v1 < 0 || w1 < 0)
return ERROR;
if(G.arcs[v1][w1].adj != j) // 有弧<v,w>
{
G.arcs[v1][w1].adj = j; // 删除弧<v,w>
if(G.arcs[v1][w1].info) // 有相关信息
{
free(G.arcs[v1][w1].info); // 释放空间
G.arcs[v1][w1].info = NULL; // 指针置空
}
if(G.kind >= 2) // 无向
G.arcs[w1][v1] = G.arcs[v1][w1]; // 删除对称弧<w,v>
G.arcnum--;
}
return OK;
}
Status DeleteVex(MGraph &G, VertexType v)
{// 删除顶点v及其相关弧
int i, j, k;
k = LocateVex(G, v); // k为待删顶点序号
if(k < 0)
return ERROR;
for(i = 0; i < G.vexnum; i++)
DeleteArc(G, v, G.vexs[i]); // 删除由顶点v发出的所有弧
if(G.kind < 2) // 有向
for(i = 0; i < G.vexnum; i++)
DeleteArc(G, G.vexs[i], v); // 删除发向顶点v的所有弧
for(j = k + 1; j < G.vexnum; j++)
G.vexs[j-1] = G.vexs[j]; // 序号k后面的顶点向量依次前移
for(i = 0; i < G.vexnum; i++)
for(j = k + 1; j < G.vexnum; j++)
{
G.arcs[i][j - 1] = G.arcs[i][j]; // 移动待删除顶点之右的矩阵元素
}
for(i= 0; i< G.vexnum; i++)
for(j = k + 1; j < G.vexnum; j++)
G.arcs[j - 1][i] = G.arcs[j][i]; // 移动待删除顶点之下的矩阵元素
G.vexnum--;
return OK;
}
void DestroyGraph(MGraph &G)
{// 销毁图G
int i;
for(i = G.vexnum - 1; i >= 0; i--) // 从大到小逐一删除顶点及其相关弧
DeleteVex(G, G.vexs[i]);
}
void Display(MGraph G)
{// 输出邻接矩阵存储结构的图G
int i, j;
char s[7] = "无向图", s1[3] = "边";
switch(G.kind)
{
case DG:strcpy(s, "有向图");
strcpy(s1, "弧");
break;
case DN:strcpy(s, "有向网");
strcpy(s1, "弧");
break;
case UDG:strcpy(s, "无向图");
break;
case UDN: ;
}
printf("%d个顶点%d条%s的%s。顶点依次是:",G.vexnum, G.arcnum, s1, s);
for(i = 0; i < G.vexnum; i++)
Visit(GetVex(G, i)); // 根据顶点信息的类型,访问第i个顶点,在func7-1.h中
printf("\nG.arcs.adj:\n");
for(i = 0; i < G.vexnum; i++) // 输出二维数组G.arcs.adj
{
for(j = 0; j < G.vexnum; j++)
if(G.arcs[i][j].adj == INFINITY)
printf("∞");
else
printf("%4d",G.arcs[i][j].adj);
printf("\n");
}
printf("G.arcs.info:\n"); // 输出G.arcs.info
if(G.kind < 2) // 有向
printf("弧尾 弧头 该%s的信息:\n",s1);
else // 无向
printf("顶点1顶点2该%s的信息:\n",s1);
for(i= 0; i< G.vexnum; i++)
if(G.kind < 2) // 有向
{
for(j = 0; j < G.vexnum; j++)
if(G.arcs[i][j].info)
{
printf("%5s %5s",G.vexs[i].name, G.vexs[j].name);
OutputArc(G.arcs[i][j].info); // 输出弧的相关信息,在func7-1.h
}
}
else // 无向,输出上三角
{
for(j = i + 1; j < G.vexnum; j++)
if(G.arcs[i][j].info)
{
printf("%5s %5s",G.vexs[i].name, G.vexs[j].name);
OutputArc(G.arcs[i][j].info);
}
}
}
void CreateFromFile(MGraph &G, char* filename, int IncInfo)
{// 由文件构造图或网G.IncInfo 表示弧有无相关信息1:有 0:无
int i, j, k;
VRType w = 0; // 顶点关系类型,图
VertexType v1, v2; // 顶点类型
FILE *f; // 文件指针
f = fopen(filename,"r");
fscanf(f,"%d",&G.kind); // 由文件输入G的类型
if(G.kind % 2) // 网
w = INFINITY;
fscanf(f, "%d", &G.vexnum); // 由文件输入顶点数
for(i = 0; i < G.vexnum; i++)
InputFromFile(f,G.vexs[i]); // 由文件输入顶点信息,在func7-1.h中
fscanf(f, "%d", &G.arcnum); // 由文件输入弧数
for(i = 0; i < G.vexnum; i++)
for(j = 0; j < G.vexnum; j++)
{
G.arcs[i][j].adj = w; // 不相邻
G.arcs[i][j].info = NULL; // 无相关信息
}
if(!(G.kind % 2)) // 图
w = 1;
for(k = 0; k < G.arcnum; k++) // 对所有弧
{
fscanf(f,"%s%s",v1.name, v2.name);
if(G.kind % 2) // 网
fscanf(f,"%d",&w); // 权值
i = LocateVex(G, v1); // 弧尾序号
j = LocateVex(G, v2); // 弧头序号
G.arcs[i][j].adj = w; // 权值
if(IncInfo) // 有相关信息
InputArcFromFile(f,G.arcs[i][j].info);
if(G.kind >1) // 无向
G.arcs[j][i] = G.arcs[i][j];
}
fclose(f);
}
<file_sep>// c6-2.h 树的二叉链表存储结构(孩子-兄弟)
typedef struct CSNode
{
TElemType data;
CSNode *firstchild, *nextsibling;
}CSNode, *CSTree;
<file_sep>void Create_SeqFromFile(SSTable &ST, char *filename)
{// 由数据文件构造静态顺序查找表ST
int i;
FILE *f;
f = fopen(filename,"r");
fscanf(f,"%d",&ST.length); // 输入数据元素个数
ST.elem = (ElemType*)calloc(ST.length+1,sizeof(ElemType)); // calloc动态分配内存后并清零
if(!ST.elem) // 分配空间失败
exit(OVERFLOW);
for(i = 1; i <= ST.length; i++)
InputFromFile(f, ST.elem[i]); // 从文件依次输入ST的元素
fclose(f);
}
void Ascend(SSTable &ST)
{// 重建静态查找表为按关键字非降序排序
int i, j, k;
for(i = 1; i < ST.length; i++)
{
k = i; // k存当前关键字最小值的序号
ST.elem[0] = ST.elem[i]; // 待比较值存[0]单元
for(j = i + 1; j <= ST.length; j++)
if LT(ST.elem[j].key, ST.elem[0].key) // 当前元素的关键字小于待比较元素的关键字
{
k = j; // 将当前元素序号存到k中
ST.elem[0] = ST.elem[j]; // 将当前元素的值存[0]中
}
if(k != i) // 有比[i]更小的值则交换
{
ST.elem[k] = ST.elem[i];
ST.elem[i] = ST.elem[0];
}
}
}
void Create_OrdFromFile(SSTable &ST, char *filename)
{// 由含n个数据元素的数组r构造按关键字非降序查找表ST
Create_SeqFromFile(ST,filename);
Ascend(ST); // 按关键字非降序重构
}
Status Destroy(SSTable &ST)
{// 销毁静态查找表ST
free(ST.elem);
ST.elem = NULL;
ST.length = 0;
return OK;
}
int Search_Seq(SSTable ST, KeyType key)
{// 查找关键字为key的数据元素,返回其在表中位置,若不存在,返回0
int i;
ST.elem[0].key = key; // 哨兵,关键字存[0]单元
for(i = ST.length; !EQ(ST.elem[i].key, key); --i); // 从后往前找
return i;
}
int Search_Bin(SSTable ST, KeyType key)
{// 在有序表ST中折半查找其关键字为key的数据元素,返回其在表中的位置,若不存在,返回0
int mid, low = 1, high = ST.length;
while(low <= high)
{
mid = (low + high)/2;
if(EQ(key, ST.elem[mid].key))
return mid; // 找到
else if(LT(key, ST.elem[mid].key)) // 往前查找
high = mid - 1;
else // 往后查找
low = mid + 1;
}
return 0; // 未找到
}
void Traverse(SSTable ST, void(*Visit)(ElemType))
{// 按顺序对ST的每个元素调用Visit()一次
int i;
ElemType *p = ++ST.elem; // p指向第一个元素
for(i = 1; i <= ST.length; i++)
Visit(* p++); // 调用Visit(),p指向下一个元素
}
<file_sep>// func8-1.h 包括数据元素的类型定义和对它的操作
typedef long KeyType; // 定义关键字域为长整型
#define key number // 定义关键字为准考证号
struct ElemType
{
long number; // 准考证号,与关键字类型相同
char name[9]; // 姓名(4个汉字加一个串结束标记符)
int politics; // 政治
int Chinese; // 语文
int English; // 英语
int math; // 数学
int physics; // 物理
int chemistry; // 化学
int biology; // 生物
int total; // 总分
};
void Visit(ElemType c)
{
printf("%-8ld%-8s%5d%5d%5d%5d%5d%5d%5d%5d\n",c.number,c.name,c.politics,c.Chinese,c.English,c.math,c.physics,c.chemistry,c.biology,c.total);
}
void InputFromFile(FILE *f, ElemType &c)
{// 从文件输入数据元素
fscanf(f,"%ld%s%d%d%d%d%d%d%d",&c.number,c.name,&c.politics,&c.Chinese,&c.English,&c.math,&c.physics,&c.chemistry,&c.biology,&c.total);
}
void InputKey(KeyType &k)
{
scanf("%ld",&k);
}
<file_sep>// 线性表的单链表存储结构 带头结点
struct LNode
{
LNode *next;
int data;
};
typedef LNode *LinkList;
<file_sep>// OrderList.h 有序链表的基本操作
<file_sep>// bo6-1.h 二叉链表的4个基本操作,包括算法6.1,func8-4.h等调用
#define ClearBiTree DestroyBiTree
void InitBiTree(BiTree &T)
{// 构造空二叉树
T = NULL;
}
void DestroyBiTree(BiTree &T)
{// 销毁二叉树
if(T)
{
DestroyBiTree(T->lchild);
DestroyBiTree(T->rchild);
free(T);
T = NULL;
}
}
void PreOrderTraverse(BiTree T, void(*Visit)(TElemType))
{// 先序遍历
if(T)
{
Visit(T->data);
PreOrderTraverse(T->lchild, Visit);
PreOrderTraverse(T->rchild, Visit);
}
}
void InOrderTraverse(BiTree T, void(*Visit)(TElemType))
{// 中序遍历
if(T)
{
InOrderTraverse(T->lchild,Visit);
Visit(T->data);
InOrderTraverse(T->rchild,Visit);
}
}
<file_sep>// func6-4.h 求哈夫曼编码的主函数
int main()
{
HuffmanTree HT; // 哈夫曼树
HuffmanCode HC; // 哈夫曼编码
int *w, n, i; // w存放权值,n权值个数
printf("请输入权值的个数(>1):");
scanf("%d",&n);
w = (int*)malloc(n * sizeof(int));
printf("请依次输入%d个权值(整型):\n",n);
for(i = 0; i <= n-1; i++)
scanf("%d",w+i);
HuffmanCoding(HT,HC,w,n); // 根据w所存的n个权值构造哈夫曼树HT,n个哈夫曼编码存于HC
for(i = 1; i <= n; i++)
puts(HC[i]); // 依次输出哈夫曼编码
return 0;
}
<file_sep>// bo6-2.h 二叉链表(存储结构由c6-1.h定义)的基本操作(18个),包括算法6.2~6.4
Status BiTreeEmpty(BiTree T)
{// 判断二叉树是否为空
if(T)
return FALSE;
return TRUE;
}
int BiTreeDepth(BiTree T)
{// 求树深度
int i, j;
if(!T)
return 0;
i = BiTreeDepth(T->lchild);
j = BiTreeDepth(T->rchild);
return i > j ? i + 1 : j + 1;
}
TElemType Root(BiTree T)
{// 返回树的根的值
if(BiTreeEmpty(T))
return Nil;
return T->data;
}
TElemType Value(BiTree p)
{// 返回p所指结点的值
return p->data;
}
void Assign(BiTree p, TElemType value)
{// 给p所指结点赋值
p->data = value;
}
typedef BiTree QElemType; // 二叉树指针类型
#include"c3-2.h"
#include"bo3-2.h"
BiTree Point(BiTree T, TElemType s)
{// 返回二叉树T中指向元素值为s的结点的指针
LinkQueue q; // 队列
QElemType a; // 二叉树指针类型
if(T)
{
InitQueue(q);
EnQueue(q,T);
while(!QueueEmpty)
{
DeQueue(q, a);
if(a->data == s)
{
DestroyQueue(q);
return a;
}
if(a->lchild)
EnQueue(q, a->lchild);
if(a->rchild)
EnQueue(q, a->rchild);
}
DestroyQueue(q);
}
return NULL;
}
TElemType LeftChild(BiTree T, TElemType e)
{// 二叉树存在,e为树中某个结点
// 返回e的左孩子,若无返回空
BiTree a;
if(T)
{
a = Point(T,e); // 先定位元素的位置
if(a && a->lchild)
return a->lchild->data;
}
return Nil;
}
TElemType RightChild(BiTree T, TElemType e)
{// 二叉树存在,e为树中某个结点
// 返回e的左孩子,若无返回空
BiTree a;
if(T)
{
a = Point(T,e);
if(a &&a->rchild)
return a->rchild->data;
}
return Nil;
}
Status DeleteChild(BiTree p, int LR)
{// 二叉树存在,p指向T中某个结点,LR为0或1
// 根据LR为0或1,删除T中指向p所指结点的左子树或右子树
if(p)
{
if(LR == 0)
ClearBiTree(p->lchild);
else if(LR == 1)
ClearBiTree(p->rchild);
return OK;
}
return ERROR;
}
void PostOrderTraverse(BiTree T, void(*Visit)(TElemType))
{// 二叉树存在,Visit是对结点操作的应用函数
// 后序递归遍历,对每个结点只调用一次Visit
if(T)
{
PostOrderTraverse(T->lchild, Visit);
PostOrderTraverse(T->rchild, Visit);
Visit(T->data);
}
}
void LevelOrderTraverse(BiTree T, void(*Visit)(TElemType))
{// 二叉树存在,Visit是对结点操作的应用函数
// 层序递归遍历T(利用队列)
LinkQueue q;
QElemType a;
if(T)
{
InitQueue(q);
EnQueue(q, T);
while(!QueueEmpty(q))
{
DeQueue(q,a);
Visit(a->data);
if(a->lchild)
EnQueue(q,a->lchild);
if(a->rchild)
EnQueue(q,a->rchild);
}
printf("\n");
DestroyQueue(q);
}
}
void CreateBiTree(BiTree &T)
{// 按先序次序输入二叉树中结点的值
// 构造二叉链表表示的二叉树,Nil表示空树
TElemType ch;
scanf(form, &ch); // 输入结点的值
if(ch == Nil)
T = NULL;
else
{
T = (BiTree)malloc(sizeof(BiTNode));
if(!T)
exit(OVERFLOW);
T->data = ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
TElemType Parent(BiTree T, TElemType e)
{// 二叉树存在,e为T中某个结点
// 若e为T的非根节点,则返回其双亲,否则返回空
LinkQueue q;
QElemType a;
if(T)
{
InitQueue(q);
EnQueue(q,T);
while(!QueueEmpty(q))
{
DeQueue(q,a);
if(a->lchild && a->lchild->data == e || a->rchild && a->rchild->data == e)
return a->data;
else
{
if(a->lchild)
EnQueue(q,a->lchild);
if(a->rchild)
EnQueue(q,a->rchild);
}
}
}
return Nil;
}
TElemType LeftSibling(BiTree T, TElemType e)
{// 二叉树存在,e为T中某个结点
// 返回e的左兄弟,若e无左孩子,返回空
TElemType a;
BiTree p;
if(T)
{
a = Parent(T,e);
if(a != Nil)
{
p = Point(T,a);
if(p->lchild && p->rchild && p->rchild->data == e)
return p->lchild->data;
}
}
return Nil;
}
TElemType RightSibling(BiTree T, TElemType e)
{
TElemType a;
BiTree p;
if(T)
{
a = Parent(T,e);
if(a != Nil)
{
p = Point(T,a);
if(p->lchild && p->rchild && p->lchild->data == e)
return p->rchild->data;
}
}
return Nil;
}
Status InsertChild(BiTree p, int LR, BiTree c)
{// 二叉树存在,p指向T中某个结点,LR为0或1, 非空二叉树c与T不相交且右子树为空
// 根据LR为0或1,插入c为p所指结点的左子树或右子树,p所指结点的原左子树或右子树成为c的左子树或右子树
if(p)
{
if(LR == 0)
{
c->rchild = p->lchild;
p->lchild = c;
}
if(LR == 1)
{
c->rchild = p->rchild;
p->rchild = c;
}
return OK;
}
return ERROR;
}
typedef BiTree SElemType;
#include"c3-1.h"
#include"bo3-1.h"
void InOrderTraverse1(BiTree T, void(*Visit)(TElemType))
{// 采用二叉链表存储结构,Visit是对每个元素进行操作的函数
// 中序遍历二叉树T的非递归算法(利用栈)
SqStack S;
InitStack(S);
while(T || !StackEmpty(S))
{
if(T)
{// 根指针进栈,遍历左子树
Push(S, T);
T = T->lchild;
}
else
{
Pop(S, T);
Visit(T->data);
T = T->rchild;
}
}
printf("\n");
DestroyStack(S);
}
void InOrderTraverse2(BiTree T, void(*Visit)(TElemType))
{
SqStack S;
BiTree p;
InitStack(S);
Push(S, T);
while(!StackEmpty(S))
{
while(GetTop(S, p) && p)
Push(S, p->lchild);
Pop(S, p);
if(!StackEmpty(S))
{
Pop(S, p);
Visit(p->data);
Push(S, p->rchild);
}
}
printf("\n");
DestroyStack(S);
}
void PreOrderTraverse1(BiTree T, void(*Visit)(TElemType))
{// 非递归先序遍历算法(利用栈)
SqStack S;
InitStack(S);
BiTree p = T;
while(p || !StackEmpty(S))
{
while(p)
{
Visit(p->data);
Push(S,p);
p = p->lchild;
}
if(!StackEmpty(S))
{
Pop(S,p);
p = p->rchild;
}
}
printf("\n");
DestroyStack(S);
}
void InOrderTraverse3(BiTree T, void(*Visit)(TElemType))
{// 非递归中序遍历算法(利用栈)
SqStack S;
InitStack(S);
BiTree p = T;
while(p || !StackEmpty(S))
{
while(p)
{
Push(S,p);
p = p->lchild;
}
// 遍历到左下角尽头再出栈访问
Pop(S,p);
Visit(p->data);
p = p->rchild;
}
printf("\n");
DestroyStack(S);
}
void PostOrderTraverse1(BiTree T, void(*Visit)(TElemType))
{// 非递归后续遍历算法(利用栈)
SqStack S;
InitStack(S);
BiTree p = T, r = NULL; // r为辅助指针
while(p || !StackEmpty(S))
{
if(p)
{
Push(S, p);
p = p->lchild;
}
else
{
GetTop(S, p); // 取栈顶,不是出栈,不是出栈,不是出栈
// 右子树不空,且右子树未访问
if(p->rchild && p->rchild != r)
p = p->rchild;
// 右子树为空,或者右子树访问完,出栈访问结点
else
{
Pop(S,p);
Visit(p->data);
r = p; // 指向访问过的右子树的根节点
p == NULL; // p置空,为了继续访问栈顶
}
}
}
}
<file_sep>// func6-2.h 程序algo6-1.cpp 和algo6-2.cpp要调用的两个函数
#define Order
int minum(HuffmanTree t,int i)
{// 返回哈夫曼树t的前i个结点权值最小的树的根节点序号,函数select()调用
int j, m;
unsigned int k = UINT_MAX; // k存最小权值,初值取无符号整型最大值
for(j = 1; j <= i; j++)
{
if(t[j].weight < k && t[j].parent == 0) // t[j]的权值小于k,又是树的根结点
{
k = t[j].weight; // t[j]的权值赋给k
m = j; // 序号赋给m
}
}
t[m].parent = 1; // 选中的根结点的双亲赋非零值,避免第二次查找该结点
return m; // 返回权值最小的根结点序号
}
void select(HuffmanTree t, int i, int &s1, int &s2)
{// 在哈夫曼树t的前i个结点中选择两个权值最小的树的根节点序号,s1为其中序号(权值)较小的
#ifdef Order // 如果定义了Order,则以下语句起作用
int j;
#endif // Order
s1 = minum(t,i); // 权值最小的根结点序号
s2 = minum(t,i); // 权值第二小的根结点序号
#ifdef Order
if(s1 > s2) // s1的序号大于s2的序号
{
j = s1;
s1 = s2;
s2 = j;
}
#endif // Order
}
<file_sep>//// main6-1.cpp 检验二叉链表基本操作的主程序
//#define CHAR 1
////#define CHAR 0 // 整型(二者选一)。第3行
//#include"func6-1.h"
//#include"c6-1.h"
//#include"bo6-1.h"
//#include"bo6-2.h"
//int main()
//{
// int i;
// BiTree T, p, c;
// TElemType e1, e2;
// InitBiTree(T);
// printf("构造空二叉树后,树空否?%d(1:是 0:否)。树的深度=%d。\n",
// BiTreeEmpty(T), BiTreeDepth(T));
// e1=Root(T);
// if(e1!=Nil)
// printf("二叉树的根为"form"。\n", e1);
// else
// printf("树空,无根。\n");
// #if CHAR
// printf("请按先序输入二叉树(如:ab###表示a为根结点,b为左子树的二叉树):\n");
// #else
// printf("请按先序输入二叉树(如:1 2 0 0 0表示1为根结点,2为左子树的二叉树):\n");
// #endif
// CreateBiTree(T);
// printf("建立二叉树后,树空否?%d(1:是 0:否)。树的深度=%d。\n", BiTreeEmpty(T),
// BiTreeDepth(T));
// e1=Root(T);
// if(e1!=Nil)
// printf("二叉树的根为"form"。\n", e1);
// else
// printf("树空,无根。\n");
// printf("中序递归遍历二叉树:\n");
// InOrderTraverse(T, Visit);
// printf("\n后序递归遍历二叉树:\n");
// PostOrderTraverse(T, Visit);
// printf("\n请输入一个结点的值:");
// scanf("%*c"form, &e1);
// p=Point(T, e1);
// printf("结点的值为"form"。\n", Value(p));
// printf("欲改变此结点的值,请输入新值:");
// scanf("%*c"form"%*c", &e2);
// Assign(p, e2);
// printf("层序遍历二叉树:\n");
// LevelOrderTraverse(T, Visit);
// e1=Parent(T, e2);
// if(e1!=Nil)
// printf(form"的双亲是"form",", e2, e1);
// else
// printf(form"没有双亲,", e2);
// e1=LeftChild(T, e2);
// if(e1!=Nil)
// printf("左孩子是"form",", e1);
// else
// printf("没有左孩子,");
// e1=RightChild(T, e2);
// if(e1!=Nil)
// printf("右孩子是"form",", e1);
// else
// printf("没有右孩子,");
// e1=LeftSibling(T, e2);
// if(e1!=Nil)
// printf("左兄弟是"form",", e1);
// else
// printf("没有左兄弟,");
// e1=RightSibling(T, e2);
// if(e1!=Nil)
// printf("右兄弟是"form"。\n", e1);
// else
// printf("没有右兄弟。\n");
// InitBiTree(c);
// printf("请构造一个右子树为空的二叉树c:\n");
// #if CHAR
// printf("请按先序输入二叉树(如:ab###表示a为根结点,b为左子树的二叉树):\n");
// #else
// printf("请按先序输入二叉树(如:1 2 0 0 0表示1为根结点,2为左子树的二叉树):\n");
// #endif
// CreateBiTree(c);
// printf("中序递归遍历二叉树c:\n");
// InOrderTraverse(c, Visit);
// printf("\n树c插到树T中,请输入树T中树c的双亲结点 c为左(0)或右(1)子树:");
// scanf("%*c"form"%d", &e1, &i);
// p=Point(T, e1);
// InsertChild(p, i, c);
//
// printf("先序递归遍历二叉树:\n");
// PreOrderTraverse(T, Visit);
// printf("\n删除子树,请输入待删除子树的双亲结点 左(0)或右(1)子树:");
// scanf("%*c"form"%d", &e1, &i);
// p=Point(T, e1);
// DeleteChild(p, i);
// printf("先序递归遍历二叉树:\n");
// PreOrderTraverse(T, Visit);
// printf("\n中序非递归遍历二叉树:\n");
// InOrderTraverse1(T, Visit);
// printf("中序非递归遍历二叉树(另一种方法):\n");
// InOrderTraverse2(T, Visit);
// DestroyBiTree(T);
// return 0;
//}
// main6-2.cpp 检验bo6-3.h和bo6-4.h的程序
//#define CHAR 10
//#include"func6-1.h"
//#include"c6-2.h"
//#include"bo6-3.h"
//#include"bo6-4.h"
//int main()
//{
// int i;
// CSTree T, p, q;
// TElemType e, e1;
// InitTree(T);
// printf("构造空树后,树空否?%d(1:是 0:否)。树根为%c,树的深度为%d。\n",TreeEmpty(T), Root(T), TreeDepth(T));
// CreateTree(T);
// printf("构造树T后,树空否?%d(1:是 0:否)。树根为%c,树的深度为%d。\n",TreeEmpty(T), Root(T), TreeDepth(T));
// printf("层序遍历树T:\n");
// LevelOrderTraverse(T, Visit);
// printf("请输入待修改的结点的值 新值:");
// scanf("%c%*c%c%*c", &e, &e1);
// Assign(T, e, e1);
// printf("层序遍历修改后的树T:\n");
// LevelOrderTraverse(T, Visit);
// printf("%c的双亲是%c,长子是%c,下一个兄弟是%c。\n", e1, Parent(T, e1),
// LeftChild(T, e1), RightSibling(T, e1));
// printf("建立树p:\n");
// CreateTree(p);
// printf("层序遍历树p:\n");
// LevelOrderTraverse(p, Visit);
// printf("将树p插到树T中,请输入T中p的双亲结点 子树序号:");
// scanf("%c%d%*c", &e, &i);
// q=Point(T, e);
// InsertChild(T, q, i, p);
// printf("层序遍历修改后的树T:\n");
// LevelOrderTraverse(T, Visit);
// printf("先根遍历树T:\n");
// PreOrderTraverse(T, Visit);
// printf("\n后根遍历树T:\n");
// PostOrderTraverse(T, Visit);
// printf("\n删除树T中结点e的第i棵子树,请输入e i:");
// scanf("%c%d", &e, &i);
// q=Point(T, e);
// DeleteChild(T, q, i);
// printf("层序遍历修改后的树T:\n");
// LevelOrderTraverse(T, Visit);
// DestroyTree(T);
// return 0;
//}
// algo6-1.cpp 求哈夫曼编码
//#include "c1.h"
//#include "c6-3.h"
//#include "func6-2.h"
//void HuffmanCoding(HuffmanTree &HT, HuffmanCode &HC, int *w, int n)
//{// w存放n个字符的权值(均>0)构造哈夫曼树HT并求出n个字符的哈夫曼编码HC
// int start;
// unsigned f;
//#include "func6-3.h"
// HC = (HuffmanCode)malloc((n+1) * sizeof(char*)); // 分配n个字符编码的头指针向量([0]不用)
// cd = (char*)malloc(n * sizeof(char)); // 分配求编码的工作空间
// cd[n-1] = '\0'; // 编码结束符
// for(i= 1; i <= n; i++)
// {// 逐个求哈夫曼编码
// start = n-1; // 编码结束符位置
// for(c = i, f = HT[i].parent; f != 0; c = f, f = HT[f].parent)
// {
// if(HT[f].lchild == c) // c是其双亲左孩子
// cd[--start] = '0'; // 由叶子结点向根赋值'0'
// else // c是其双亲右孩子
// cd[--start] = '1'; // 由叶子结点向根赋值'1'
// }
// HC[i] = (char*)malloc((n-start) * sizeof(char));
// strcpy(HC[i], &cd[start]);
// }
// free(cd);
//}
//#include "func6-4.h" // 求哈夫曼编码主函数
// algo6-2.cpp
#include"c1.h"
#include"c6-3.h"
#include"func6-2.h"
void HuffmanCoding(HuffmanTree &HT, HuffmanCode &HC, int *w, int n)
{
unsigned cdlen;
#include"func6-3.h"
HC = (HuffmanCode)malloc((n+1)*sizeof(char*));
cd = (char*)malloc(n*sizeof(char));
c = m; // m = 2*n-1
cdlen = 0; // 码长初值为0
for(i = 1; i <= m; i++)
{
HT[i].weight = 0; // 求编码不需要权值域,改作结点状态标志,0表示左右孩子都没有访问过
}
while(c)
{
if(HT[c].weight == 0)
{
HT[c].weight = 1; // 左孩子被访问过,右孩子未访问
if(HT[c].lchild != 0) // 有左孩子(不是叶子结点)
{
c = HT[c].lchild; // 将c置为其左孩子的序号(向叶子结点方向走一步)
cd[cdlen++] = '0'; // 左分支编码为0
}
else if(HT[c].rchild == 0) // 序号为c的叶子结点
{// 登记叶子结点的字符编码
HC[c] = (char*)malloc((cdlen+1) * sizeof(char)); // 生成编码空间
cd[cdlen] = '\0'; // 最后一个位置赋值串尾结束符
strcpy(HC[c],cd); // 复制编码
}
}
else if(HT[c].weight == 1) // 左孩子被访问过
{
HT[c].weight = 2;
if(HT[c].rchild != 0)
{
c = HT[c].rchild;
cd[cdlen++] = '1';
}
}
else
{
c = HT[c].parent;
--cdlen;
}
}
free(cd);
}
#include "func6-4.h"
<file_sep>#define INFINITY INT_MAX // 用整型最大值代替无穷大
typedef int VRType; //
#define MAX_VERTEX_NUM 26 //
enum GrapgKind{DG, DN, UDG, UDN}; // {有向图,有向网,无向图,无向网}
typedef struct // 弧信息
{
VRType adj; // 顶点关系类型,对于无权图,1:相邻,0:不相邻;对于有权图,则为权值
InfoType * info; // 该弧相关信息的指针(可无)
}ArcCell, AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; //二维数组
struct MGraph
{// 图的结构
VertexType vexs[MAX_VERTEX_NUM]; // 顶点向量
AdjMatrix arcs; // 邻接矩阵
int vexnum, arcnum; // 顶点数,弧数
GrapgKind kind; // 图的种类标志(枚举类型)
#ifndef C7-1_H_INCLUDED
#define C7-1_H_INCLUDED
#define INFINITY INT_MAX // 鐢ㄦ暣鍨嬫渶澶у€间唬鏇挎棤绌峰ぇ
typedef int VRType; // 瀹氫箟椤剁偣鍏崇郴绫诲瀷涓烘暣鍨?涓嶪NFINITY绫诲瀷涓€鑷?
#define MAX_VERTEX_NUM 26 // 鏈€澶ч《鐐逛釜鏁?
enum GrapgKind{DG, DN, UDG, UDN}; // {鏈夊悜鍥?鏈夊悜缃?鏃犲悜鍥?鏃犲悜缃憓
typedef struct // 寮т俊鎭?
{
VRType adj; // 椤剁偣鍏崇郴绫诲瀷
InfoType *info; // 璇ュ姬鐩稿叧淇℃伅鐨勬寚閽?鍙棤)
}ArcCell, AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; //浜岀淮鏁扮粍
struct MGraph // 鍥剧殑缁撴瀯
{
VertexType vexs[MAX_VERTEX_NUM]; // 椤剁偣鍚戦噺
AdjMatrix arcs; // 閭绘帴鐭╅樀
int vexnum, arcnum; // 椤剁偣鏁?寮ф暟
GrapgKind kind; // 鍥剧殑绉嶇被鏍囧織(鏋氫妇绫诲瀷)
};
<file_sep>// func8-2.h 包括数据元素类型定义及对它的操作
typedef int KeyType; // 关键字类型为int
struct ElemType
{
KeyType key;
};
void Visit(ElemType c)
{
printf("%d ",c.key);
}
void InputFromFile(FILE *f, ElemType &c)
{
fscanf(f,"%d",&c.key);;
}
void InputKey(KeyType &k)
{
scanf("%d",&k);
}
<file_sep>// c6-1.h 二叉树的二叉链表存储结构
typedef struct BiTNode
{
TElemType data;
BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
<file_sep># DataStruct
DataStruct
本仓库是严蔚敏版《数据结构》教中的代码实现。后续会持续不定时更新。
<file_sep>// bo3-3.h 用单链表的基本操作实现链队列基本操作(9个)
typedef QElemType ElemType;
#define LinkList QueuePtr
#define LNode QNode
#include "bo2-2.h" // 链表的基本操作
void InitQueue(LinkQueue &Q)
{
InitList(Q.front1);
Q.rear = Q.front1;
}
void DestroyQueue(LinkQueue &Q)
{
DestroyList(Q.front1);
Q.rear = Q.front1;
}
void ClearQueue(LinkQueue &Q)
{
ClearList(Q.front1);
Q.rear = Q.front1;
}
Status QueueEmpty(LinkQueue Q)
{
return ListEmpty(Q.front1);
}
int QueueLength(LinkQueue Q)
{
return ListLength(Q.front1);
}
Status GetHead(LinkQueue Q, QElemType &e)
{
return GetElem(Q.front1, 1, e);
}
void EnQueue(LinkQueue &Q, QElemType e)
{
ListInsert(Q.front1, ListLength(Q.front1)+1, e);
}
Status DeQueue(LinkQueue &Q, QElemType &e)
{
if(Q.front1->next == Q.rear)
Q.rear = Q.front1;
return ListDelete(Q.front1, 1, e);
}
void QueueTraverse(LinkQueue Q, void(*visit)(QElemType))
{
ListTraverse(Q.front1, visit);
}
<file_sep>// 栈的顺序存储结构
#define STACK_INIT_SIZE 10
#define STACK_INCREMENT 2
struct SqStack
{
SElemType *top;
SElemType *base;
int stacksize;
};
<file_sep>// c4-1.h 串的定长顺序存储结构
#define MAX_STR_LEN 40
typedef unsigned char SString[MAX_STR_LEN + 1];
<file_sep>// bo4-2.h 串的堆存储结构基本操作(12个)
#define DestroyString ClearString
void InitString(HString &S)
{
S.length = 0;
S.ch = NULL;
}
void ClearString(HString &S)
{
free(S.ch);
InitString(S);
}
void StrAssign(HString &T, char* chars)
{// 生成一个其值等于串常量chars的串T
int i,j;
if(T.ch)
free(T.ch);
i = strlen(chars);
if(!i)
InitString(T);
else
{
T.ch = (char*)malloc(i*sizeof(char));
if(!T.ch)
exit(OVERFLOW);
for(j = 0; j < i; j++)
T.ch[j] = chars[j];
T.length = i;
}
}
void StrCopy(HString &T, HString S)
{// S的串赋值给T
int i;
if(T.ch)
free(T.ch);
T.ch = (char*)malloc(S.length*sizeof(char));
if(!T.ch)
exit(OVERFLOW);
for(i = 0; i < S.length; i++)
T.ch[i] = S.ch[i];
T.length = S.length;
}
Status StrEmpty(HString S)
{
if(S.length == 0 && S.ch == NULL)
return TRUE;
return FALSE;
}
int StrCompare(HString S, HString T)
{// 若S>T, 则返回值>0 ;若S=T,返回0
int i;
for(i = 0; i < S.length && i < T.length; i++)
if(S.ch[i] != T.ch[i])
return S.ch[i]-T.ch[i];
return S.length-T.length;
}
int StrLength(HString S)
{
return S.length;
}
void Concat(HString &T, HString S1, HString S2)
{// 用T返回S1和S2拼接的新串
int i;
if(T.ch)
free(T.ch);
T.length = S1.length + S2.length;
T.ch = (char*)malloc(T.length * sizeof(char));
for(i = 0; i < S1.length; i++)
T.ch[i] = S1.ch[i];
for(i = 0; i < S2.length; i++)
T.ch[i + S1.length] = S2.ch[i];
}
Status SubString(HString &Sub, HString S, int pos, int len)
{// 返回第pos个位置起,len个长的子串
int i;
if(pos < 1 || pos + len > S.length+1 || len < 0)
return ERROR;
if(Sub.ch)
free(Sub.ch);
if(!len)
InitString(Sub);
else
{
Sub.ch = (char*)malloc(len * sizeof(char));
if(!Sub.ch)
exit(OVERFLOW);
for(i = 0; i < len - 1; i++)
Sub.ch[i] = S.ch[i + pos - 1];
Sub.length = len;
}
return OK;
}
Status StrInsert(HString &S, int pos, HString T)
{// 在S的第pos个位置插入T
int i;
if(pos < 1 || pos > S.length + 1)
return ERROR;
if(T.length)
{
S.ch = (char*) realloc(S.ch,(S.length + T.length)*sizeof(char));
if(!S.ch)
exit(OVERFLOW);
// 此时S.length为多少
for(i = S.length - 1; i >= pos - 1; i--)
S.ch[i + T.length] = S.ch[i];
for(i = 0; i < T.length; i++)
S.ch[i + pos - 1] = T.ch[i];
S.length += T.length;
}
return OK;
}
Status StrDelete(HString &S, int pos, int len)
{// 删除S的第pos个位置后.len个长度的子串
int i;
if(pos < 1 || pos + len > S.length +1)
return ERROR;
for(i = pos - 1; i <= S.length - len; i++)
S.ch[i] = S.ch[i + len];
S.length -=len;
S.ch = (char*)realloc(S.ch,S.length * sizeof(char));
return OK;
}
void StrPrint(HString S)
{
int i;
for(i = 0; i< S.length; i++)
printf("%c", S.ch[i]);
printf("\n");
}
<file_sep>// main1-1.cpp 检验基本操作bo1-1.h的主函数
#include"c1.h"
// 以下两行可根据需要选其一(且只能选其一),而无须改变基本操作bo1-1.h
typedef int ElemType;
//typedef double ElemType; // 定义抽象数据类型ElemType在本程序中为双精度型。第5行
#include"c1-1.h"
#include"bo1-1.h"
#include"func1-1.h"
int main()
{
Triplet T;
ElemType m;
Status i;
i=InitTriplet(T, 5, 7, 9);
//i=InitTriplet(T, 5.0, 7.1, 9.3); // 当ElemType为双精度型时,可取代上句。第15行
printf("调用初始化函数后,i=%d(1:成功)。T的3个值为",i);
PrintT(T);
i=Get(T, 2, m);
if(i==OK)
{
printf("T的第2个值为");
PrintE(m);
}
i=Put(T, 2, 6);
if(i==OK)
{
printf("将T的第2个值改为6后,T的3个值为");
PrintT(T);
}
i=IsAscending(T);
printf("调用测试升序的函数后,i=%d(0:否 1:是)\n", i);
i=IsDescending(T);
printf("调用测试降序的函数后,i=%d(0:否 1:是)\n", i);
if((i=Max(T, m))==OK)
{
printf("T中的最大值为");
PrintE(m);
}
if((i=Min(T, m))==OK)
{
printf("T中的最小值为");
PrintE(m);
}
DestroyTriplet(T);
printf("销毁T后,T=%u\n", T);
return 0;
}
//// algo1-1.cpp 变量的引用类型和非引用类型的区别
//#include"c1.h"
//void fa(int a)
//{
// a++;
// printf("在函数fa中:a=%d\n", a);
//}
//void fb(int &a)
//{
// a++;
// printf("在函数fb中:a=%d\n", a);
//}
//int main()
//{
// int n=1;
// printf("在主程中,调用函数fa之前:n=%d\n", n);
// fa(n);
// printf("在主程中,调用函数fa之后,调用函数fb之前:n=%d\n", n);
// fb(n);
// printf("在主程中,调用函数fb之后:n=%d\n", n);
// return 0;
//}
//// algo1-2.cpp 计算1-1/x+1/(x*x)…
//#include"c1.h"
//int main()
//{
// timeb t1, t2;
// long t;
// double x, sum=1, sum1;
// int i, j, n;
// printf("请输入x n:");
// scanf("%lf%d", &x, &n);
// ftime(&t1);
// for(i=1; i<=n; i++)
// {
// sum1=1;
// for(j=1; j<=i; j++)
// sum1=sum1*(-1.0/x);
// sum+=sum1;
// }
// ftime(&t2);
// t=(t2.time-t1.time)*1000+(t2.millitm-t1.millitm);
// printf("sum=%lf,用时%ld毫秒\n", sum, t);
//
// return 0;
//}
//// algo1-3.cpp 计算1-1/x+1/(x*x)…的更快捷的算法
//#include"c1.h"
//int main()
//{
// timeb t1, t2;
// long t;
// double x, sum1=1, sum=1;
// int i, n;
// printf("请输入x n:");
// scanf("%lf%d", &x, &n);
// ftime(&t1);
// for(i=1; i<=n; i++)
// {
// sum1*=-1.0/x;
// sum+=sum1;
// }
// ftime(&t2);
// t=(t2.time-t1.time)*1000+(t2.millitm-t1.millitm);
// printf("sum=%lf,用时%ld毫秒\n", sum, t);
// return 0;
//}
<file_sep>// c8-3.h 平衡二叉树的存储结构
typedef struct BSTNode
{
ElemType data; // 结点值
int bf; // 结点的平衡因子,比二叉树结构多此项
BSTNode *lchild, *rchild; // 左、右孩子指针
}BSTNode, *BSTree;
<file_sep>#include "c1.h"
#include "func7-2.h"
#include "func7-1.h"
#include "c7-1.h"
#include "bo7-1.h"
typedef MGraph Graph;
#include "func7-3.h"
<file_sep>// bo2-1.h 顺序存储的线性表
void InitList(SqList &L)
{
L.elem = (ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem)
exit(OVERFLOW);
L.length = 0;
L.listsize = LIST_INIT_SIZE;
}
void DestroyList(SqList &L)
{
free(L.elem);
L.elem = NULL;
L.length = 0;
L.listsize = 0;
}
void ClearList(SqList &L)
{
L.length = 0;
}
Status ListEmpty(SqList L)
{
if(L.length == 0)
return TRUE;
return FALSE;
}
int ListLength(SqList L)
{
return L.length;
}
Status GetElem(SqList L, int i, ElemType &e)
{
if(i < 1 || i > L.length)
return ERROR;
e = *(L.elem+i-1);
return OK;
}
int LocateElem(SqList L, ElemType e, Status(*compare)(ElemType, ElemType))
{
int i = 1;
ElemType *p = L.elem;
while(i <= L.length && !compare(*p++, e));
i++;
// if(i>L.length)
// return 0;
// return i;
if(i <= L.length)
return i;
return 0;
}
Status PriorElem(SqList L, ElemType cur_e, ElemType &pre_e)
{
int i = 2;
ElemType *p = L.elem+1;
while(i <= L.length && *p != cur_e)
{
i++;
p++;
}
if(i > L.length)
return ERROR;
pre_e = *--p;
return OK;
}
Status NextElem(SqList L, ElemType cur_e, ElemType &next_e)
{
int i = 1;
ElemType *p = L.elem;
while(i < L.length && *p != cur_e)
{
i++;
p++;
}
if(i == L.length)
return ERROR;
next_e = *++p;
return OK;
}
Status ListInsert(SqList &L, int i, ElemType e)
{
ElemType *p, *q, *newbase;
if(i < 1 || i > L.length+1) // 插入位置可以是第L.length位,所以i不能大于L.length+1
return ERROR;
if(L.length == L.listsize) // 线性表满,追加内存
{
newbase = (ElemType*)realloc(L.elem,(L.listsize+LIST_INCREMENT)*sizeof(ElemType));
if(!newbase)
exit(OVERFLOW);
L.elem = newbase;
L.listsize += LIST_INCREMENT;
}
q = L.elem+i-1;
for(p = L.elem+L.length-1; p >= q; --p)
*(p+1) = *p;
*q = e;
L.length++;
return OK;
}
Status ListDelete(SqList &L, int i, ElemType &e)
{
ElemType *p, *q;
if(i < 1 || i > L.length)
return ERROR;
p = L.elem+i-1;
e = *p;
// for(j = 0; j < L.length; j++)
// {
// *p = *(p+1);
// p++;
// }
q = L.elem+L.length-1;
for(p++; p <= q; p++)
*(p-1) = *p;
L.length--;
return OK;
}
void ListTraverse(SqList L, void(*visit)(ElemType&))
{
ElemType *p = L.elem;
for(int i = 1; i <= L.length; i++)
visit(*p++);
printf("\n");
}
<file_sep>// func5-1.h
int comp(int c1, int c2)
{
if(c1 < c2)
return -1;
if(c1 == c2)
return 0;
return 1;
}
<file_sep>// bo2-4.h 不带头结点的单链表基本操作
Status PriorElem(LinkList L, ElemType cur_e, ElemType &pre_e)
{
LinkList q, p = L;
if(!p)
return ERROR;
while(p->next)
{
q = p->next;
if(q->data == cur_e)
{
pre_e = p->data;
return OK;
}
p = q;
}
return ERROR;
}
Status NextElem(LinkList L, ElemType cur_e, ElemType &next_e)
{
LinkList p = L;
if(!p)
return ERROR;
while(p->next)
{
if(p->data == cur_e)
{
next_e = p->next->data;
return OK;
}
p = p->next;
}
return ERROR;
}
<file_sep>// 线性表的动态分配顺序存储结构
#define LIST_INIT_SIZE 10
#define LIST_INCREMENT 2
struct SqList
{
ElemType *elem;
int length;
int listsize;
};
<file_sep>int main()
{
int i, j, k, n;
char s[3] = "边";
Graph g;
VertexType v1, v2;
printf("请依次选择有向图,有向网,无向图,无向网:\n");
for(i = 0; i < 4; i++) // 验证4种情况
{
CreateGraph(g); // 构造图g
Display(g);
printf("插入新顶点,请输入新顶点的值:");
Input(v1);
InsertVex(g, v1);
if(g.kind < 2) // 有向
strcpy(s,"弧");
printf("插入与新顶点有关的%s,请插入%s数:",s,s);
scanf("%d",&n);
for(k = 0; k < n; k++)
{
printf("请输入另一顶点的名称:");
scanf("%s",v2.name);
if(g.kind < 2) // 有向
{
printf("请输入另一顶点的方向(0:弧头 1:弧尾):");
scanf("%d",&j);
if(j) // v2为弧尾
InsertArc(g, v2, v1);
else // v2为弧头
InsertArc(g, v1, v2);
}
else // 无向
InsertArc(g, v1, v2);
}
Display(g);
printf("删除顶点及相关的%s,请输入待删顶点名称:",s);
scanf("%s",&v1.name);
DeleteVex(g, v1);
Display(g);
if(i == 3)
{
printf("修改顶点的值,请输入待修改顶点的名称 新值:");
scanf("%s",v1.name); // 输入待修改顶点名称
Input(v2); // 输入顶点新值
PutVex(g, v1, v2); // 将图g中顶点v1的值改为v2
if(g.kind < 2) // 有向
printf("删除一条%s,请输入待删除%s的弧尾 弧头:",s,s);
else // 无向
printf("删除一条%s,请输入待删除%s的顶点1 顶点2:",s,s);
scanf("%s%s",v1.name, v2.name); // 输入待删除弧的两个顶点名称
DeleteArc(g,v1,v2);
Display(g);
}
DestroyGraph(g);
}
return 0;
}
<file_sep>// bo4-1.h 串采用定长顺序存储结构的基本操作(12个)
#define DestroyString ClearString
#define InitString ClearString
Status StrAssign(SString T, char *chars)
{// 生成一个其值等于chars的串T
int i;
if(strlen(chars) > MAX_STR_LEN)
return ERROR;
else
{
T[0] = strlen(chars);
for(i = 1; i <= T[0]; i++)
T[i] = *(chars + i - 1);
return OK;
}
}
void StrCopy(SString T, SString S)
{// T <- S 赋值
int i;
for(i = 0; i <= S[0]; i++)
T[i] = S[i];
}
Status StrEmpty(SString S)
{
if(S[0] == 0)
return TRUE;
return FALSE;
}
int StrCompare(SString S, SString T)
{
int i;
for(i = 1; i <= S[0] && i <= T[0]; i++)
if(S[i] != T[i])
return S[i] - T[i];
return S[0] - T[0];
}
int StrLength(SString S)
{
return S[0];
}
void ClearString(SString S)
{
S[0] = 0;
}
Status Concat(SString T, SString S1, SString S2)
{// 用T返回S1和S2连接成的新串,若未截断,返回TRUE
int i;
if(S1[0] + S2[0] <= MAX_STR_LEN)
{
for(i = 1; i <= S1[0]; i++)
T[i] = S1[i];
for(i = 1; i <= S2[0]; i++)
T[S1[0]+i] = S2[i];
T[0] = S1[0] + S2[0];
return TRUE;
}
else
{
for(i = 1; i < S1[0]; i++)
T[i] = S1[i];
for(i = 1; i <= MAX_STR_LEN - S1[0]; i++)
T[S1[0]+i] = S2[i];
T[0] = MAX_STR_LEN;
return FALSE;
}
}
Status SubString(SString Sub, SString S, int pos, int len)
{// 用Sub返回S的第pos个字符起长度为len的子串
int i;
if(pos < 1 || pos > S[0] || pos + len > S[0]+1 || len < 0 )
return ERROR;
for(i = 1; i <= len; i++)
Sub[i] = S[pos + i - 1];
Sub[0] = len;
return OK;
}
int Index1(SString S, SString T, int pos)
{// 返回T在S中第pos个字符之后的位置,若不存在,返回0
// T非空, 1 <= pos <= StrLength(S)
int i, j;
if(1 <= pos && pos <= S[0])
{
i = pos;
j = 1;
while(i <= S[0] && j <= T[0])
if(S[i] == T[j])
{
i++;
j++;
}
else
{
i = i - j + 2;
j = 1;
}
if(j > T[0])
return i - T[0];
else
return 0;
}
else
return 0;
}
Status StrInsert(SString S, int pos, SString T)
{// S和T存在, 1 <= pos <= StrLength(S) + 1
// 在S的第pos个字符之前插入T,完全插入返回TRUE
int i;
if(pos < 1 || pos > S[0]+1)
return ERROR;
if(S[0] + T[0] <= MAX_STR_LEN)
{
for(i = S[0]; i >= pos; i--) // S的pos后面部分后移T[0]个位置
S[i+T[0]] = S[i];
for(i = pos; i < pos + T[0]; i++) // 错过 i--
S[i] = T[i - pos + 1];
S[0] += T[0];
return TRUE;
}
else
{
for(i = MAX_STR_LEN; i >= pos +T[0]; i--)
S[i] = S[i-T[0]];
for(i = pos; i < pos + T[0] && i <= MAX_STR_LEN; i++)
S[i] = T[i - pos + 1];
S[0] = MAX_STR_LEN;
return FALSE;
}
}
Status StrDelete(SString S, int pos, int len)
{// S存在.1 <= pos <= StrLength(S) - len + 1
// 从S中删除第pos个字符起长度为len的子串
int i;
if(pos < 1 || pos > S[0] - len + 1 || len < 0)
return ERROR;
for(i = pos + len; i <= S[0]; i++) // 错过没有考虑剩余字符
S[i - len] = S[i];
S[0] -= len;
return OK;
}
void StrPrint(SString S)
{
int i;
for(i = 1; i <= S[0]; i++)
printf("%c",S[i]);
printf("\n");
}
<file_sep>typedef ElemType *Triplet;
// Triplet类型是ElemType类型的指针,存放ElemType类型的地址
<file_sep>// main3-1.h 检验bo3-1.h的主程序
//#include"c1.h"
//typedef int SElemType;
//#include"c3-1.h"
//#include"bo3-1.h"
//#define ElemType SElemType
//#include"func2-2.h"
//int main()
//{
// int j;
// SqStack s;
// SElemType e;
// InitStack(s);
// for(j=1; j<=12; j++)
// Push(s, j);
// printf("栈中元素依次为");
// StackTraverse(s, print);
// Pop(s, e);
// printf("弹出的栈顶元素e=%d\n", e);
// printf("栈空否?%d(1:空 0:否),", StackEmpty(s));
// GetTop(s, e);
// printf("栈顶元素e=%d,栈的长度为%d\n", e, StackLength(s));
// ClearStack(s);
// printf("清空栈后,栈空否?%d(1:空 0:否)\n", StackEmpty(s));
// DestroyStack(s);
// printf("销毁栈后,s.top=%u,s.base=%u,s.stacksize=%d\n", s.top, s.base, s.stacksize);
// return 0;
//}
// algo3-1.cpp 需调用算法3.1
// 十进制转2进制、8进制或16进制
//#define N 16
//typedef int SElemType;
//#include "c1.h"
//#include "c3-1.h" // 顺序栈
//#include "bo3-1.h"
//
//void conversion()
//{// 对于输入的任意一个非负十进制整数,打印输出与其对应的N进制数
// SqStack s;
// unsigned x;
// SElemType e;
// InitStack(s);
// if(N == 16)
// Push(s, 'H');
// printf("请输入一个非负十进制整数: ");
// scanf("%u",&x);
// while(x)
// {
// Push(s, x%N);
// x = x / N;
// }
// if(N == 8)
// printf("0");
// while(!StackEmpty(s))
// {
// Pop(s,e);
// if(e <= 9)
// printf("%d", e);
// else
// printf("%c", e + 55);
// }
// if(N == 2)
// printf("B");
// if(N == 16)
// printf("H");
// printf("\n");
//}
//
//int main()
//{
// conversion();
// return 0;
//}
// algo3-3.cpp 行编辑程序 实现算法3.2
//typedef char SElemType;
//#include "c1.h"
//#include "c3-1.h"
//#include "bo3-1.h"
//FILE *fp;
//void copy1(SElemType c)
//{
// fputc(c, fp);
//}
//
//void LineEdit()
//{
// SqStack s;
// char ch;
// InitStack(s);
// printf("请输入一个文本文件,^Z结束输入:\n");
// ch = getchar();
// while(ch != EOF)
// {
// while(ch != '\n')
// {
// switch(ch)
// {
// case '#': if(!StackEmpty(s))
// Pop(s,ch); break;
// case '@': ClearStack(s); break;
// default: Push(s,ch);
// }
// ch = getchar();
// }
// StackTraverse(s,copy1);
// fputc('\n',fp);
// ClearStack(s);
// if(ch != EOF)
// ch = getchar();
// }
// DestroyStack(s);
//}
//int main()
//{
// fp = fopen("ed.txt","w");
// if(fp)
// {
// LineEdit();
// fclose(fp);
// }
// else
// printf("建立文件失败!\n");
// return 0;
//}
// main3-2.cpp
//#include"c1.h"
//typedef int QElemType;
//#include"c3-2.h"
//#include"bo3-2.h"
//#define ElemType QElemType
//#include"func2-2.h"
//#include"func3-2.h"
// main3-3.cpp
//#include"c1.h"
//typedef int QElemType;
//#include"c3-2.h"
//#include"bo3-3.h"
//#include"func2-2.h"
//#include"func3-2.h"
// main3-4.cpp 循环队列 检验bo3-4.h的主程序
//#include"c1.h"
//typedef int QElemType;
//#include"c3-3.h"
//#include"bo3-4.h"
//#define ElemType QElemType
//#include"func2-2.h"
//int main()
//{
// Status j;
// int i=0, m;
// QElemType d;
// SqQueue Q;
// InitQueue(Q);
// printf("初始化队列后,队列空否?%u(1:空 0:否)\n", QueueEmpty(Q));
// printf("请输入整型队列元素(不超过%d个),-1为提前结束符:", MAX_QSIZE-1);
// do
// {
// scanf("%d", &d);
// if(d==-1)
// break;
// i++;
// EnQueue(Q, d);
// }while(i<MAX_QSIZE-1);
// printf("队列长度为%d,", QueueLength(Q));
// printf("现在队列空否?%u(1:空 0:否)\n", QueueEmpty(Q));
// printf("连续%d次由队头删除元素,队尾插入元素:\n", MAX_QSIZE);
// for(m=1; m<=MAX_QSIZE; m++)
// {
// DeQueue(Q, d);
// printf("删除的元素是%d,请输入待插入的元素:", d);
// scanf("%d", &d);
// EnQueue(Q, d);
// }
// m=QueueLength(Q);
// printf("现在队列中的元素为");
// QueueTraverse(Q, print);
// printf("共向队尾插入了%d个元素。", i+MAX_QSIZE);
// if(m-2>0)
// printf("现在由队头删除%d个元素,", m-2);
// while(QueueLength(Q)>2)
// {
// DeQueue(Q, d);
// printf("删除的元素值为%d,", d);
// }
// j=GetHead(Q, d);
// if(j)
// printf("现在队头元素为%d\n", d);
// ClearQueue(Q);
// printf("清空队列后,队列空否?%u(1:空 0:否)\n", QueueEmpty(Q));
// DestroyQueue(Q);
// return 0;
//}
// algo3-5.cpp 表达式求值(输入的值在0~9之间,中间结果和输出的值在-128~127之间),
// 算法3.4
//typedef char SElemType;
//#include"c1.h"
//#include"c3-1.h"
//#include"bo3-1.h"
//#include"func3-1.h"
//SElemType EvaluateExpression()
//{
// SqStack OPTR, OPND;
// SElemType a, b, c, x;
// InitStack(OPTR);
// InitStack(OPND);
// Push(OPTR, '\n');
// c=getchar();
// GetTop(OPTR, x);
// while(c!='\n' || x!='\n')
// {
// if(In(c))
// switch(Precede(x, c))
// {
// case'<': Push(OPTR, c);
// c=getchar();
// break;
// case'=': Pop(OPTR, x);
// c=getchar();
// break;
// case'>': Pop(OPTR,x);
// Pop(OPND, b);
// Pop(OPND, a);
// Push(OPND, Operate(a, x, b));
// }
// else if(c>='0' && c<='9')
// {
// Push(OPND, c-48);
// c=getchar();
// }
// else
// {
// printf("出现非法字符\n");
// exit(OVERFLOW);
// }
// GetTop(OPTR, x);
// }
// Pop(OPND, x);
// if(!StackEmpty(OPND))
// {
// printf("表达式不正确\n");
// exit(OVERFLOW);
// }
// return x;
//}
//int main()
//{
// printf("请输入算术表达式(输入的值要在0~9之间、");
// printf("中间运算值和输出结果在-128~127之间)\n");
// printf("%d\n", EvaluateExpression());
// return 0;
//}
// algo3-6.cpp 表达式求值(范围为int类型,输入负数要用(0-正数)表示)
//typedef int SElemType;
//#include"c1.h"
//#include"c3-1.h"
//#include"bo3-1.h"
//#include"func3-1.h"
//SElemType EvaluateExpression()
//{
// SqStack OPTR, OPND;
// SElemType a, b, d, x;
// char c;
// c=getchar();
// InitStack(OPTR);
// InitStack(OPND);
// Push(OPTR, '\n');
// GetTop(OPTR, x);
// while(c!='\n' || x!='\n')
// {
// if(In(c))
// switch(Precede(x, c))
// {
// case'<': Push(OPTR, c);
// c=getchar();
// break;
// case'=': Pop(OPTR, x);
// c=getchar();
// break;
// case'>': Pop(OPTR, x);
// Pop(OPND, b);
// Pop(OPND, a);
// Push(OPND, Operate(a, x, b));
// }
// else if(c>='0' && c<='9')
// {
// d=0;
// while(c>='0' && c<='9')
// {
// d=d*10+c-'0';
// c=getchar();
// }
// Push(OPND, d);
// }
// else
// {
// printf("出现非法字符\n");
// DestroyStack(OPTR);
// DestroyStack(OPND);
// exit(OVERFLOW);
// }
// GetTop(OPTR, x);
// }
// Pop(OPND, x);
// if(!StackEmpty(OPND))
// {
// printf("表达式不正确\n");
// DestroyStack(OPTR);
// DestroyStack(OPND);
// exit(OVERFLOW);
// }
// DestroyStack(OPTR);
// DestroyStack(OPND);
// return x;
//}
//int main()
//{
// printf("请输入算术表达式,负数要用(0-正数)表示\n");
// printf("%d\n", EvaluateExpression());
// return 0;
//}
// algo3-7.cpp 用递归调用求Ackerman(m, n)的值
//#include"c1.h"
//int ack(int m, int n)
//{
// int z;
// if(m==0)
// z=n+1;
// else if(n==0)
// z=ack(m-1, 1);
// else
// z=ack(m-1, ack(m, n-1));
// return z;
//}
//int main()
//{
// int m, n;
// printf("请输入m,n:");
// scanf("%d,%d", &m, &n);
// printf("Ack(%d, %d)=%d\n", m, n, ack(m, n));
// return 0;
//}
<file_sep>// bo2-6.h 设立尾指针的单循环链表
void InitList(LinkList &L)
{
L = (LinkList)malloc(sizeof(LNode));
if(!L)
exit(OVERFLOW);
L->next = L;
}
void ClearList(LinkList &L)
{
LinkList p, q;
L = L->next; // L指向头结点
p = L->next; // p指向第一个结点
while(p != L)
{
q = p->next;
free(p);
p = q;
}
L->next = L;
}
void DestroyList(LinkList &L)
{
ClearList(L);
free(L);
L = NULL;
}
Status ListEmpty(LinkList L)
{
if(L->next == L)
return TRUE;
return FALSE;
}
int ListLength(LinkList L)
{
int i = 0;
LinkList p = L->next; // 尾指针
while(p != L)
{
i++;
p = p->next;
}
return i;
}
Status GetElem(LinkList L, int i, ElemType &e)
{
if(i < 1 || i > ListLength(L))
return ERROR;
int j = 0;
LinkList p = L->next;
for(j; j < i; j++)
p = p->next;
e = p->data;
return OK;
}
int LocateElem(LinkList L, ElemType e, Status(*compare)(ElemType,ElemType))
{
int i = 0;
LinkList p = L->next->next; // p指向第一个结点
while(p != L->next)
{
i++;
if(compare(e, p->data))
return i;
p = p->next;
}
return 0;
}
Status PriorElem(LinkList L, ElemType cur_e, ElemType &pre_e)
{
// LinkList p = L->next;
// while(p != L)
// {
// if(p->next->data == cur_e)
// {
// pre_e = p->data;
// return OK;
// }
// p = p->next;
// }
// return ERROR;
LinkList q, p=L->next->next;
q=p->next;
while(q!=L->next)
{
if(q->data==cur_e)
{
pre_e=p->data;
return OK;
}
p=q;
q=q->next;
}
return ERROR;
}
Status NextElem(LinkList L, ElemType cur_e, ElemType &next_e)
{
LinkList p = L->next->next;
while(p != L)
{
if(p->data == cur_e)
{
next_e = p->next->data;
return OK;
}
p = p->next;
}
return ERROR;
}
Status ListInsert(LinkList &L, int i, ElemType e)
{
LinkList s, p = L->next;
int j = 0;
if(i < 1 || i > ListLength(L)+1)
return ERROR;
while(j < i-1)
{
j++;
p = p->next;
}
s = (LinkList)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
if(p == L)
L = s;
return OK;
}
Status ListDelete(LinkList &L, int i, ElemType &e)
{
LinkList q, p = L->next;
int j = 0;
while(j < i-1)
{
j++;
p = p->next;
}
e = p->next->data;
q = p->next;
p->next = q->next;
if(q == L)
L = p;
free(q);
return OK;
}
void ListTraverse(LinkList L, void(*vi)(ElemType))
{
LinkList p = L->next->next;
while(p != L->next)
{
vi(p->data);
p = p->next;
}
printf("\n");
}
<file_sep>int main()
{
TSMatrix A, B, C;
printf("创建矩阵A:");
CreateSMatrix(A);
PrintSMatrix(A);
CopySMatrix(A, B);
printf("由矩阵A复制矩阵B:\n");
PrintSMatrix(B);
DestroySMatrix(B);
printf("销毁矩阵B后:\n");
PrintSMatrix(B);
printf("创建矩阵B2:(与矩阵A的行、列数相同,行、列分别为%d,%d)\n", A.mu, A.nu);
CreateSMatrix(B);
PrintSMatrix(B);
AddSMatrix(A, B, C);
printf("矩阵C1(A+B):\n");
PrintSMatrix(C);
SubtSMatrix(A, B, C);
printf("矩阵C2(A-B):\n");
PrintSMatrix(C);
TransposeSMatrix(A, C);
printf("矩阵C3(A的转置):\n");
PrintSMatrix(C);
printf("创建矩阵A2:");
CreateSMatrix(A);
PrintSMatrix(A);
printf("创建矩阵B3:(行数应与矩阵A2的列数相同=%d)\n", A.nu);
CreateSMatrix(B);
PrintSMatrix(B);
#ifndef FLAG
MultSMatrix(A, B, C);
#else
MultSMatrix1(A, B, C);
#endif
printf("矩阵C5(A×B):\n");
PrintSMatrix(C);
return 0;
}
<file_sep>// bo2-7.h 带头结点的双向循环列表基本操作(14个)
void InitList(DuLinkList &L)
{
L = (DuLinkList)malloc(sizeof(DuLNode));
if(!L)
exit(OVERFLOW);
L->next = L;
L->prior = L;
}
void ClearList(DuLinkList L)
{
DuLinkList p = L->next;
while(p != L)
{
p = p->next;
free(p->prior);
}
L->next = L->prior = L;
}
void DestroyList(DuLinkList &L)
{
ClearList(L);
free(L);
L->next = L->prior = NULL;
}
Status ListEmpty(DuLinkList L)
{
if(L->next == L && L->prior == L)
return TRUE;
return FALSE;
}
int ListLength(DuLinkList L)
{
int i = 0;
DuLinkList p = L->next;
while(p != L)
{
i++;
p = p->next;
}
return i;
}
Status GetElem(DuLinkList L, int i, ElemType &e)
{
if(i < 1 || i > ListLength(L))
return ERROR;
int j = 0;
DuLinkList p = L->next;
while(j < i && p != L)
{
j++;
p = p->next;
}
if(p == L || j >i)
return ERROR;
e = p->data;
return OK;
}
int LocateElem(DuLinkList L, ElemType e, Status(*compare)(ElemType, ElemType))
{
int i = 0;
DuLinkList p = L->next;
while(p != L)
{
i++;
if(compare(e, p->data))
return i;
p = p->next;
}
return 0;
}
Status PriorElem(DuLinkList L, ElemType cur_e, ElemType &pre_e)
{
DuLinkList p = L->next->next; // 指向第二个元素
while(p != L)
{
if(cur_e = p->data)
{
pre_e = p->prior->data;
return OK;
}
p = p->next;
}
return ERROR;
}
Status NextElem(DuLinkList L, ElemType cur_e, ElemType &next_e)
{
DuLinkList p = L->next->next;
while(p != L)
{
if(cur_e = p->data)
{
next_e = p->next->data;
return OK;
}
p = p->next;
}
return ERROR;
}
DuLinkList GetElemP(DuLinkList L, int i)
{
int j;
DuLinkList p = L;
if(i < 1 || i > ListLength(L))
return NULL;
for(j = 0; j < i; j++)
p = p->next;
return p;
}
Status ListInsert(DuLinkList L, int i, ElemType e)
{
DuLinkList s, p;
if(i < 1 || i > ListLength(L)+1) // i
return ERROR;
p = GetElemP(L, i-1);
if(!p)
return ERROR;
s = (DuLinkList)malloc(sizeof(DuLNode));
if(!s)
return ERROR;
s->data = e;
s->prior = p;
s->next = p->next;
p->next->prior = s;
p->next = s;
return OK;
}
Status ListDelete(DuLinkList L, int i, ElemType &e)
{
DuLinkList p;
if(i < 1 ) // i
return ERROR;
p = GetElemP(L, i);
if(!p)
return ERROR;
e = p->data;
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
return OK;
}
void ListTraverse(DuLinkList L, void(*visit)(ElemType))
{
DuLinkList p = L->next;
while(p != L)
{
visit(p->data);
p = p->next;
}
printf("\n");
}
void ListTraverseBack(DuLinkList L, void(*visit)(ElemType))
{
DuLinkList p = L->prior;
while(p != L)
{
visit(p->data);
p = p->prior;
}
printf("\n");
}
<file_sep>// func6-3.h 构造哈夫曼树
int m, i, s1, s2;
unsigned c;
HuffmanTree p;
char *cd;
if(n <= 1) // 叶子结点数不大于1
return;
m = 2*n-1; // n个叶子结点的哈夫曼树共有m个结点
HT = (HuffmanTree)malloc((m+1)*sizeof(HTNode)); // 0号单元未用
for(p = HT+1,i = 1; i <= n; i++, p++, w++) // 从1号单元开始到n号单元,给叶子结点赋值
{// 给叶子结点赋值
(*p).weight = *w; // 赋权值
(*p).parent = 0; // 双亲域为空(叶子结点的根结点)
(*p).lchild = 0; // 左右孩子为空(叶子结点)
(*p).rchild = 0;
}
for(; i <= m; i++, p++) // i从n+1到m
{
(*p).parent = 0; // 其余结点的双亲域初值为0
}
for(i = n+1; i <= m; i++) // 建哈夫曼树
{
select(HT,i-1,s1,s2);
HT[s1].parent = HT[s2].parent = i; // i号单元为s1和s2的双亲
HT[i].lchild = s1; // i号单元的左右孩子分别为s1和s2
HT[i].rchild = s2;
HT[i].weight = HT[s1].weight + HT[s2].weight; // i号单元的权值是s1和s2权值和
}
<file_sep>// c5-1.h 数组的顺序存储结构
#define MAX_ARRAY_DIM 8
struct Array
{
ElemType *base; // 数组基址
int dim; // 数组维数
int *bounds; // 数组维界基址
int *constants; // 数组映像函数常量基址
};
<file_sep>// bo8-2.h 二叉排序树的基本操作(4个)
Status SearchBST(BiTree &T, KeyType key, BiTree f, BiTree &p)
{// S在根指针T所指二叉排序树中递归查找其关键字等于Key的数据元素
// 若查找成功,p指向该元素结点,并返回TRUE
// 若不成功,p指向查找路径上访问的最后一个结点,并返回FALSE
// f指向T的双亲,初始值为NULL
if(!T) // 查找不成功
{
p = f;
return FALSE;
}
else if EQ(key, T->data.key) // 查找成功
{
p = T; // p指向该元素结点
return TRUE;
}
else if LT(key, T->data.key)
return SearchBST(T->lchild, key, T, p);
else
return SearchBST(T->rchild, key, T, p);
}
Status InsertBST(BiTree &T, ElemType e)
{// 若二叉排序树T中没有关键字等于e.key的元素,插入e并返回TRUE,否则返回FALSE
BiTree p, s;
if(!SearchBST(T, e.key, NULL, p)) // 没有找到等于e.key的元素
{
s = (BiTree)malloc(sizeof(BiTNode)); // 生成新结点
s->data = e; // 新结点赋值
s->lchild = s->rchild = NULL;
if(!p) // 树T空
T = s;
else if LT(e.key, p->data.key) // s的关键字<p的关键字
p->lchild = s; // s置为p的左孩子
else
p->rchild = s;
return TRUE;
}
else
return FALSE;
}
void Delete(BiTree &p)
{// 从二叉排序树删除p所指结点,重连其左右子树
BiTree s, q = p; // q指向待删除结点
// 待删结点只有半边子树
if(!p->rchild) // 若右子树为空,则只需要重连其左子树
{
p = p->lchild;
free(q);
}
else if(!p->lchild)
{
p = p->rchild;
free(q);
}
// 待删结点有左右子树
else // p左右子树均不空
{
s = p->lchild; // s指向待删结点左孩子
while(s->rchild) // s有右孩子
{
q = s; // q指向s
s = s->rchild; // s指向右孩子
}
p->data = s->data; // 将待删结点前驱的值取代待删结点的值
// 待删除结点的左孩子有右子树
if(q != p)
q->rchild = s->lchild;
// 待删除结点的左孩子没有右子树
else
q->lchild = s->lchild;
free(s); // 释放s所指结点
}
}
Status DeleteBST(BiTree &T, KeyType key)
{// 存在关键字为key的数据元素,删除并返回TRUE,否则返回FALSE
if(!T)
return FALSE;
else
{
if EQ(key, T->data.key)
{
Delete(T);
return TRUE;
}
else if LT(key, T->data.key)
return DeleteBST(T->lchild, key);
else
return DeleteBST(T->rchild, key);
}
}
<file_sep>// c5-2.h 稀疏矩阵的三元组顺序表存储结构
#define MAX_SIZE 100
struct Triple
{
int i,j; // 行, 列下标
ElemType e; // 非零元素值
};
struct TSMatrix
{
Triple data[MAX_SIZE + 1]; // 非零元三元组表,data[0]未使用
int mu, nu, tu; // 行数,列数,非零元个数
};
<file_sep>// bo3-1.h 顺序栈的基本操作(9个)
void InitStack(SqStack &S)
{
S.base = (SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S.base)
exit(OVERFLOW);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
void DestroyStack(SqStack &S)
{
free(S.base);
S.top = S.base = NULL;
S.stacksize = 0;
}
void ClearStack(SqStack &S)
{
S.top = S.base;
}
Status StackEmpty(SqStack S)
{
if(S.base == S.top)
return TRUE;
return FALSE;
}
int StackLength(SqStack S)
{
return (S.top - S.base);
}
Status GetTop(SqStack S, SElemType &e)
{
if(S.top > S.base)
{
e = *(S.top - 1);
return OK;
}
return ERROR;
}
void Push(SqStack &S, SElemType e)
{// 先判断是否栈满
if((S.top - S.base) == S.stacksize)
{
S.base = (SElemType*)realloc(S.base,(STACK_INIT_SIZE + STACK_INCREMENT)*sizeof(SElemType));
if(!S.base)
exit(OVERFLOW);
S.top = S.base + S.stacksize;
S.stacksize += STACK_INCREMENT;
}
*(S.top)++ = e;
}
Status Pop(SqStack &S, SElemType &e)
{
if(S.top == S.base)
return ERROR;
e = *--S.top;
return OK;
}
void StackTraverse(SqStack S, void(*visit)(SElemType))
{
SElemType *p = S.base;
while(S.top > p)
visit(*p++);
printf("\n");
}
<file_sep>// func6-1.h 利用条件编译,在主程序中选择结点的类型,访问树结点的函数
#include "c1.h"
#if CHAR
typedef char TElemType;
TElemType Nil = '#';
#define form "%c"
#else
typedef int TElemType;
TElemType Nil = 0;
#define form "%d"
#endif // CHAR
void Visit(TElemType e)
{
printf(form" ",e);
}
<file_sep>#ifndef FUNC7-2_H_INCLUDED
#define FUNC7-2_H_INCLUDED
#define MAX_INFO 20 // 弧的相关信息字符串的最大长度+1
typedef char InfoType; // 弧的相关信息类型
void InputArc(InfoType * &arc)
{// 输入弧的相关信息
char s[MAX_INFO]; // 临时存储空间
int m;
printf("请输入该弧的相关信息(<%d个字符):",MAX_INFO);
gets(s); // 输入字符串(可包括空格)
m = strlen(s); // 字符串长度
if(m)
{
arc = (char*)malloc((m+1)*sizeof(char)); // 动态生成相关信息存储空间
strcpy(arc,s); // 将s复制到arc
}
}
void InputArcFromFile(FILE* f, InfoType* &arc)
{// 由文件输入弧的相关信息的函数
char s[MAX_INFO];
fgets(s, MAX_INFO, f); // 由文件输入字符串
arc = (char*)malloc((strlen(s)+1)*sizeof(char)); // 动态生成相关信息存储空间
strcpy(arc,s);
}
void OutputArc(InfoType *arc)
{// 输出弧的信息
printf("%s\n",arc);
}
#endif // FUNC7-2_H_INCLUDED
<file_sep>// c3-3.h 队列的顺序存储结构(循环队列)
#define MAX_QSIZE 5
struct SqQueue
{
QElemType *base;
int front1;
int rear;
};
<file_sep>//#include "c1.h"
//typedef int ElemType;
//#include "c2-1.h"
//#include "bo2-1.h"
//#include "func2-2.h"
//
//Status sq(ElemType c1, ElemType c2)
//{
// if(c1 == c2*c2)
// return TRUE;
// return FALSE;
//}
//
//void dbl(ElemType &c)
//{
// c *= 2;
//}
//
//
//int main()
//{
// SqList L;
// ElemType e, e0;
// Status i;
// int j, k;
// InitList(L);
// printf("初始化L后,L.length=%d,L.listsize=%d,L.elem=%u\n",
// L.length, L.listsize, L.elem);
// for(j=1; j<=5; j++)
// i=ListInsert(L, 1, j);
// printf("在L的表头依次插入1~5后,*L.elem=");
// for(j=1; j<=5; j++)
// printf("%d ", *(L.elem+j-1));
// printf("\n调用ListTraverse()函数,依次输出表L中的元素:");
// ListTraverse(L, print1);
// i=ListEmpty(L);
// printf("L.length=%d,L.listsize=%d(不变),", L.length, L.listsize);
// printf("L.elem=%u(不变),L是否空?i=%d\n", L.elem, i);
// ClearList(L);
// i=ListEmpty(L);
// printf("清空L后,L.length=%d,L.listsize=%d,", L.length, L.listsize);
// printf("L.elem=%u,L是否空?i=%d(1:是 0:否)\n", L.elem, i);
// for(j=1; j<=10; j++)
// ListInsert(L, j, j);
// printf("在L的表尾依次插入1~10后,L=");
// ListTraverse(L, print1);
// printf("L.length=%d,L.listsize=%d,L.elem=%u\n",L.length,L.listsize,L.elem);
// ListInsert(L, 1, 0);
// printf("在L的表头插入0后,L.length=%d,L.listsize=%d(改变),"
// "L.elem=%u(可能改变)\n", L.length, L.listsize, L.elem);
// GetElem(L, 5, e);
// printf("第5个元素的值为%d\n", e);
// for(j=10; j<=11; j++)
// {
// k=LocateElem(L, j, equal);
// if(k)
// printf("第%d个元素的值为%d,", k, j);
// else
// printf("没有值为%d的元素\n", j);
// }
// for(j=3; j<=4; j++)
// {
// k=LocateElem(L, j, sq);
// if(k)
// printf("第%d个元素的值为%d的平方,", k, j);
// else
// printf("没有值为%d的平方的元素\n", j);
// }
// for(j=1; j<=2; j++)
// {
// GetElem(L, j, e0);
// i=PriorElem(L, e0, e);
// if(i==ERROR)
// printf("元素%d无前驱,", e0);
// else
// printf("元素%d的前驱为%d\n", e0, e);
// }
// for(j=ListLength(L)-1; j<=ListLength(L); j++)
// {
// GetElem(L, j, e0);
// i=NextElem(L, e0, e);
// if(i==ERROR)
// printf("元素%d无后继\n", e0);
// else
// printf("元素%d的后继为%d,", e0, e);
// }
// k=ListLength(L);
// for(j=k+1; j>=k; j--)
// {
// i=ListDelete(L, j, e);
// if(i==ERROR)
// printf("删除第%d个元素失败。", j);
// else
// printf("删除第%d个元素成功,其值为%d", j, e);
// }
// ListTraverse(L, dbl);
// printf("L的元素值加倍后,L=");
// ListTraverse(L, print1);
// DestroyList(L);
// printf("销毁L后,L.length=%d,L.listsize=%d,L.elem=%u\n",
// L.length, L.listsize, L.elem);
// return 0;
//}
//// algo2-1.cpp 实现算法2.7的程序
//#include"c1.h"
//typedef int ElemType;
//#include"c2-1.h"
//#include"bo2-1.h"
//#include"func2-2.h"
//void MergeList(SqList La, SqList Lb, SqList &Lc)
//{
//
// ElemType *pa, *pa_last, *pb, *pb_last, *pc;
// pa=La.elem;
// pb=Lb.elem;
// Lc.listsize=Lc.length=La.length+Lb.length;
// pc=Lc.elem=(ElemType*)malloc(Lc.listsize*sizeof(ElemType));
// if(!Lc.elem)
// exit(OVERFLOW);
// pa_last=La.elem+La.length-1;
// pb_last=Lb.elem+Lb.length-1;
// while(pa<=pa_last && pb<=pb_last)
// {
// if(*pa<=*pb)
// *pc++=*pa++;
// else
// *pc++=*pb++;
// }
// while(pa<=pa_last)
// *pc++=*pa++;
// while(pb<=pb_last)
// *pc++=*pb++;
//}
//int main()
//{
// SqList La, Lb, Lc;
// int j;
// InitList(La);
// for(j=1; j<=5; j++)
// ListInsert(La, j, j);
// printf("La= ");
// ListTraverse(La, print1);
// InitList(Lb);
// for(j=1; j<=5; j++)
// ListInsert(Lb, j, 2*j);
// printf("Lb= ");
// ListTraverse(Lb, print1);
// MergeList(La, Lb, Lc);
// printf("Lc= ");
// ListTraverse(Lc, print1);
// return 0;
//}
//// main2-2.cpp 检验bo2-2.h的主程序
//#include"c1.h"
//typedef int ElemType;
//#include"c2-2.h"
//#include"bo2-2.h"
//#include"func2-2.h"
//#include"func2-3.h"
// algo2-2.cpp 用SqList类型和LinkList类型分别实现算法2.1和2.2的程序
//#include"c1.h"
//typedef int ElemType;
//#define Sq
//#ifdef Sq
// #include"c2-1.h"
// #include"bo2-1.h"
// typedef SqList List;
// #define printer print1
//#else
// #include"c2-2.h"
// #include"bo2-2.h"
// typedef LinkList List;
// #define printer print
//#endif
//#include"func2-2.h"
//#include"func2-1.h"
//int main()
//{
// List La, Lb, Lc;
// int j, b[7]={2, 6, 8, 9, 11, 15, 20};
//
// InitList(La);
// for(j=1; j<=5; j++)
// ListInsert(La, j, j);
// printf("La= ");
// ListTraverse(La, printer);
//
// InitList(Lb);
// for(j=1; j<=5; j++)
// ListInsert(Lb, j, 2*j);
// printf("Lb= ");
// ListTraverse(Lb, printer);
//
// Union(La, Lb);
// printf("new La= ");
// ListTraverse(La, printer);
//
// ClearList(Lb);
// for(j=1; j<=7; j++)
// ListInsert(Lb, j, b[j-1]);
// printf("Lb= ");
// ListTraverse(Lb, printer);
//
// MergeList(La, Lb, Lc);
// printf("Lc= "); /// ??? 为什么不输出Lc
// ListTraverse(Lc, printer);
//
// return 0;
//}
// algo2-3.cpp 实现算法2.11和算法2.12
//#include "c1.h"
//typedef int ElemType;
//#include "c2-2.h"
//#include "bo2-2.h"
//#include "func2-2.h"
//
//void CreateList(LinkList &L, int n)
//{// 逆位序,结点插在表头,输入n个元素的值,简历带头结点的链表
// LinkList p;
// int i;
// L = (LinkList)malloc(sizeof(LNode)); // 创建头结点
// L->next = NULL;
// printf("请输入%d个数据\n",n);
// for(i = n; i > 0; i--)
// {
// p = (LinkList)malloc(sizeof(LNode));
// scanf("%d",&p->data);
// p->next = L->next;
// L->next = p;
// }
//
//}
//
//void CreateList1(LinkList &L, int n)
//{// 正位序
// int i;
// LinkList p, q;
// L = (LinkList)malloc(sizeof(LNode));
// L->next = NULL;
// q = L;
// printf("请输入%d个数据\n",n);
// for(i = 1; i <= n; i++)
// {
// p = (LinkList)malloc(sizeof(LNode));
// scanf("%d",&p->data);
// q->next = p;
// q = q->next;
// }
// p->next = NULL;
//}
//
//void MergeList(LinkList &La, LinkList &Lb, LinkList &Lc)
//{// La与Lb按非递减合并
// LinkList pa = La->next, pb = Lb->next, pc;
// Lc = pc = La;
// while(pa && pb)
// if(pa->data <= pb->data)
// {
// pc->next = pa;
// pc = pa;
// pa = pa->next;
// }
// else
// {
// pc->next = pb;
// pc = pb;
// pb = pb->next;
// }
// pc->next = pa ? pa : pb;
// free(Lb);
// Lb = NULL;
//}
//
//int main()
//{
// int n = 5;
// LinkList La, Lb, Lc;
//
// CreateList1(La, n);
// printf("La = ");
// ListTraverse(La, print);
//
// CreateList(Lb, n);
// printf("Lb = ");
// ListTraverse(Lb, print);
//
// MergeList(La, Lb, Lc);
// printf("Lc = ");
// ListTraverse(Lc, print);
//
// return 0;
//}
// main2-3.cpp 检验bo2-3.h 和bo2-4.h
//#include"c1.h"
//typedef int ElemType;
//#include"c2-2.h"
//#include"bo2-3.h"
//#include"bo2-4.h"
//#include"func2-2.h"
//#include"func2-3.h"
// algo2-4.cpp 静态链表示例
//#include "c1.h"
//#define N 6
//typedef char ElemType[N];
//#include "c2-3.h"
//
//int main()
//{
// SLinkList s = {{"",1}, {"ZHAO",2}, {"QIAN",3}, {"SUN",4}, {"LI",5}, {"ZHOU",6}, {"WU",7}, {"ZHEN",8}, {"WANG", 0} };
// int i = s[0].cur;
// while(i)
// {
// printf("%s ",s[i].data);
// i = s[i].cur;
// }
// printf("\n");
// s[4].cur = 9;
// s[9].cur = 5;
// strcpy(s[9].data, "SHI");
// s[6].cur = 8;
// i = s[0].cur;
// while(i)
// {
// printf("%s ",s[i].data);
// i = s[i].cur;
// }
// printf("\n");
// return 0;
//}
// main2-4.cpp 检验bo2-5.h
//#include"c1.h"
//typedef int ElemType;
//#include"c2-3.h"
//#include"bo2-5.h"
//#include"func2-2.h"
//typedef SLinkList LinkList;
//#define SLL
//#include"func2-3.h"
// main2-5.cpp 检验bo2-6.h
//#include"c1.h"
//typedef int ElemType;
//#include"c2-2.h"
//#include"bo2-6.h"
//#include"func2-2.h"
//#include"func2-3.h"
// main2-6.cpp 检验bo2-7.h的主程序
#include"c1.h"
typedef int ElemType;
#include"c2-4.h"
#include"bo2-7.h"
#include"func2-2.h"
int main()
{
DuLinkList L;
int i, n=4;
Status j;
ElemType e;
InitList(L);
for(i=1; i<=5; i++)
ListInsert(L, i, i);
printf("逆序输出链表:");
ListTraverseBack(L, print);
j=GetElem(L, 2, e);
if(j)
printf("链表的第2个元素值为%d\n", e);
else
printf("不存在第2个元素\n");
i=LocateElem(L, n, equal1);
if(i)
printf("等于%d的元素是第%d个\n", n, i);
else
printf("没有等于%d的元素\n", n);
j=PriorElem(L, n, e);
if(j)
printf("%d的前驱是%d,", n, e);
else
printf("不存在%d的前驱\n", n);
j=NextElem(L, n, e);
if(j)
printf("%d的后继是%d\n", n, e);
else
printf("不存在%d的后继\n", n);
ListDelete(L, 2, e);
printf("删除第2个结点,值为%d,其余结点为 ", e);
ListTraverse(L, print);
printf("链表的元素个数为%d,", ListLength(L));
printf("链表是否空?%d(1:是 0:否)\n", ListEmpty(L));
ClearList(L);
printf("清空后,链表是否空?%d(1:是 0:否)\n", ListEmpty(L));
DestroyList(L);
return 0;
}
<file_sep>#define EQ(a,b) ((a) == (b)) // equal
#define LT(a,b) ((a) < (b)) // less than
#define LQ(a,b) ((a) <= (b)) // less and equal
#define GT(a,b) ((a) > (b)) // greater than
<file_sep>// c2-3.h 线性表的静态单链表存储结构
#define MAX_SIZE 100
typedef struct
{
ElemType data;
int cur;
}component, SLinkList[MAX_SIZE];
<file_sep>// func8-4.h
#include "bo6-1.h"
#define InitDSTable InitBiTree // 构造二叉排序树和平衡二叉树与初始化二叉树的操作相同
#define DestroyDSTable DestroyBiTree // 销毁
#define TraverseDSTable InOrderTraverse // 按关键字遍历二叉排序树
BiTree SearchBST(BiTree T, KeyType key)
{// 递归查找关键字为key的数据元素,若查找成功,返回该元素指针,不存在返回空指针
if(!T || EQ(key, T->data.key))
return T;
else if LT(key, T->data.key)
return SearchBST(T->lchild,key);
else
return SearchBST(T->rchild,key);
}
<file_sep>// func 3-1.h algo3-5.cpp 和 algo3-6.cpp 需要调用的函数
char Precede(SElemType t1, SElemType t2)
{
char f;
switch(t2)
{
case '+':
case '-': if(t1 == '(' || t1 == '\n')
f = '<';
else
f = '>';
break;
case '*':
case '/': if(t1 == '*' || t1 == '/' || t1 == ')')
f = '>';
else
f = '<';
break;
case '(': if(t1 == ')')
{
printf("括号不匹配\n");
exit(OVERFLOW);
}
else
f = '<';
break;
case ')': switch(t1)
{
case '(': f = '='; break;
case '\n': printf("缺少左括号\n"); exit(OVERFLOW);
default: f = '>';
}
break;
case '\n':switch(t1)
{
case '\n': f = '='; break;
case '(': printf("缺少右括号\n"); exit(OVERFLOW);
default: f = '>';
}
}
return f;
}
Status In(SElemType c)
{
switch(c)
{
case '+':
case '-':
case '*':
case '/':
case '(':
case ')':
case '\n': return TRUE;
default: return FALSE;
}
}
SElemType Operate(SElemType a, SElemType theta, SElemType b)
{
switch(theta)
{
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': if(b == 0)
{
printf("分母不能为0\n");
return FALSE;
}
else
return a / b;
default: return FALSE;
}
}
<file_sep>// bo6-3.h 数的二叉链表存储结构基本操作(16个)
#define CLearTree DestroyTree
void InitTree(CSTree &T)
{// 构造空树
T = NULL;
}
void DestroyTree(CSTree &T)
{// 销毁树T
if(T)
{
DestroyTree(T->firstchild);
DestroyTree(T->nextsibling);
free(T);
T = NULL;
}
}
typedef CSTree QElemType; // 定义队列元素类型为二叉链表的指针类型
#include "c3-2.h"
#include "bo3-2.h"
void CreateTree(CSTree &T)
{// 构造树
char c[20]; // 临时存放孩子结点的值(设不超过20个)
CSTree p, p1;
LinkQueue q;
int i,m;
InitQueue(q);
printf("请输入根结点(字符型,#为空):");
scanf("%c%*c",&c[0]); // 输入根结点的值
if(c[0] != Nil)
{
T = (CSTree)malloc(sizeof(CSNode)); // 建立根结点
T->data = c[0];
T->nextsibling = NULL; // 根结点无兄弟结点
EnQueue(q,T); // 根结点入队
while(!QueueEmpty(q))
{
DeQueue(q,p); // 出队一个结点的指针
printf("请按长幼顺序输入结点 %c 的所有孩子:", p->data);
gets(c); // 将结点的所有孩子作为字符串输入
m = strlen(c);
if(m > 0)
{
p1 = p->firstchild = (CSTree)malloc(sizeof(CSNode)); // 建立第一个孩子结点
p1->data = c[0]; // 给长子结点赋值
EnQueue(q, p1); // 入队p1结点的指针
for(i = 1; i < m; i++)
{
p1->nextsibling = (CSTree)malloc(sizeof(CSNode)); // 建立下一个兄弟结点
p1 = p1->nextsibling; // p1指向下一个兄弟结点
p1->data = c[i];
EnQueue(q, p1);
}
p1->nextsibling = NULL; // 最后一个结点没有下一个兄弟
}
else
p->firstchild = NULL; // 长子为空
}
}
else
T = NULL; // 空树
}
Status TreeEmpty(CSTree T)
{// 树T存在,判空
if(T)
return FALSE;
return TRUE;
}
int TreeDepth(CSTree T)
{// 树空,则树的深度为0,树不空,返回树的深度(递归)
CSTree p;
int depth, max_depth = 0;
if(!T)
return 0;
for(p = T->firstchild; p; p = p->nextsibling)
{
depth = TreeDepth(p);
if(depth > max_depth)
max_depth = depth;
}
return max_depth+1;
}
TElemType Value(CSTree p)
{// 返回p所指结点的值
return p->data;
}
TElemType Root(CSTree T)
{// 返回T的根
if(T)
return Value(T);
else
return Nil;
}
CSTree Point(CSTree T, TElemType s)
{// 返回二叉链表树T中指向元素值为s的结点指针
LinkQueue q;
QElemType a;
if(T)
{
InitQueue(q);
EnQueue(q, T);
while(!QueueEmpty(q))
{
DeQueue(q, a);
if(a->data == s)
return a;
if(a->firstchild)
EnQueue(q, a->firstchild);
if(a->nextsibling)
EnQueue(q, a->nextsibling);
}
}
return NULL;
}
Status Assign(CSTree &T, TElemType cur_e,TElemType value)
{// 树T存在,cur_e是树T中结点的值,将cur_e该为value
CSTree p;
if(T)
{
p = Point(T,cur_e);
if(p)
{
p->data = value;
return OK;
}
}
return ERROR;
}
TElemType Parent(CSTree T, TElemType cur_e)
{// 树T存在,cur_e为T中某结点的值,若cur_e非根节点,返回其双亲结点,否则返回空
CSTree p,t;
LinkQueue q;
InitQueue(q);
if(T)
{
if(Value(T) == cur_e)
return Nil;
EnQueue(q, T);
while(!QueueEmpty(q))
{
DeQueue(q, p);
if(p->firstchild) // p有长子
{
if(p->firstchild->data == cur_e)
return Value(p);
t = p;
p = p->firstchild;
EnQueue(q, p); // 长子入队
while(p->nextsibling)
{
p = p->nextsibling;
if(Value(p) == cur_e)
return Value(t);
EnQueue(q, p); // 入队下一个兄弟
}
}
}
}
return Nil;
}
TElemType LeftChild(CSTree T, TElemType cur_e)
{// 若cur_e为非叶子结点,则返回其左孩子,否则返回空
CSTree f;
f = Point(T, cur_e); // f指向cur_e
if(f->firstchild && f)
return f->firstchild->data;
else
return Nil;
}
TElemType RightSibling(CSTree T, TElemType cur_e)
{// 若cur_e有右兄弟,则返回其右兄弟,否则返回空
CSTree f;
f = Point(T,cur_e);
if(f && f->nextsibling)
return f->nextsibling->data;
else
return Nil;
}
Status InsertChild(CSTree &T, CSTree p, int i, CSTree c)
{// p指向T中某个结点,1<= i <=p所指结点的度+1,非空树T与c不相交
// 插入c为T中p结点的第i棵子树(因为p所指结点地址不变,所以p不需要引用)
int j;
CSTree q;
if(T) // T不空
{
if(i == 1) // 插入c作为p的长子
{
c->nextsibling = p->firstchild; // p的原长子是现在c的兄弟
p->firstchild = c; // c成为p的长子
}
else // c不是p的长子
{
q = p->firstchild; // q指向p的长子
j = 2;
while(q && j < i) // 找c的插入点
{
q = q->nextsibling; // q指向下一个兄弟结点
j++;
}
if(j == i)
{
c->nextsibling = q->nextsibling; // c的下一个兄弟指向p的原第i个孩子
q->nextsibling = c; // p中插入c作为p的第i个孩子
}
else // 原有孩子数小于i-1
return ERROR;
}
return OK;
}
else // T空
return ERROR;
}
Status DeleteChild(CSTree &T, CSTree p, int i)
{// 删除T中p所指结点的第i棵子树
CSTree b,q;
int j;
if(T)
{
if(i == 1) // 删除长子
{
b = p->firstchild; // b指向p的长子
p->firstchild = b->nextsibling; // p的第二个孩子成为长子
b->nextsibling = NULL; // p的长子结点成为待删除子树的根节点,其下一个兄弟指针为空
DestroyTree(b);
}
else // 删除非长子
{
q = p->firstchild; // q指向p的长子
j = 2;
while(q && j < i) // 找第i棵子树
{
q = q->nextsibling; // q指向下一个兄弟结点
j++;
}
if(j == i)
{
b = q->nextsibling; // b指向待删子树
q->nextsibling = b->nextsibling; // 从树p中删除该子树
b->nextsibling = NULL; // 待删子树的下一个兄弟指针为空
DestroyTree(b);
}
else // p原有孩子数小于i
return ERROR;
}
return OK;
}
else
return ERROR;
}
void PostOrderTraverse(CSTree T, void(*Visit)(TElemType))
{// 后序遍历
CSTree p;
if(T)
{
if(T->firstchild) // 长子存在
{
PostOrderTraverse(T->firstchild,Visit); // 后根遍历长子子树
p = T->firstchild->nextsibling; // p指向长子的下一个兄弟
while(p) // 还有下一个兄弟
{
PostOrderTraverse(p, Visit); // 后根遍历下一个兄弟子树
p = p->nextsibling; // p指向下一个兄弟
}
}
Visit(Value(T)); // 最后访问根节点
}
}
void LevelOrderTraverse(CSTree T, void(*Visit)(TElemType))
{// 层序遍历
CSTree p;
LinkQueue q;
InitQueue(q);
if(T) // 树非空
{
Visit(Value(T)); // 先访问根节点
EnQueue(q,T); // 根指针入队
while(!QueueEmpty(q))
{
DeQueue(q,p); // 指针出队
if(p->firstchild) // 长子存在
{
p = p->firstchild;
Visit(Value(p)); // 访问长子结点
EnQueue(q,p); // 入队长子结点
while(p->nextsibling) // 有下一个兄弟
{
p = p->nextsibling;
Visit(Value(p)); // 访问下一个兄弟
EnQueue(q,p); // 入队兄弟结点
}
}
}
}
printf("\n");
}
<file_sep>void PreOrderTraverse(CSTree T, void(*Visit)(TElemType))
{
if(T)
{
Visit(Value(T));
PreOrderTraverse(T->firstchild,Visit);
PreOrderTraverse(T->nextsibling,Visit);
}
}
<file_sep>// 线性表的双向链表结构
typedef struct DuLNode
{
ElemType data;
DuLNode *prior, *next;
}DuLNode, *DuLinkList;
<file_sep>// func8-3.h 包括数据元素类型的定义及对它的操作
typedef char KeyType;
struct ElemType
{
KeyType key; // 关键字
int weight; // 权值
};
void Visit(ElemType c)
{
printf("(%c,%d)",c.key,c.weight);
}
void InputFromFile(FILE *f, ElemType &c)
{
fscanf(f,"%*c%c%d",&c.key,&c.weight);
}
void InputKey(KeyType &k)
{
scanf("%c", &k);
}
<file_sep>// main4-1.cpp 检验bo4-1.h的主程序
//#include"c1.h"
//#include"c4-1.h"
//#include"bo4-1.h"
//typedef SString String;
//#include"func4-1.h"
//int main()
//{
// int i, j;
// Status k;
// char s, c[MAX_STR_LEN+1];
// String t, s1, s2;
// printf("请输入串s1:");
// gets(c);
// k=StrAssign(s1, c);
// if(!k)
// {
// printf("串长超过MAX_STR_LEN(=%d)\n", MAX_STR_LEN);
// exit(OVERFLOW);
// }
// printf("串长为%d,串空否?%d(1:是 0:否)\n", StrLength(s1), StrEmpty(s1));
// StrCopy(s2, s1);
// printf("复制s1生成的串为");
// StrPrint(s2);
// printf("请输入串s2:");
// gets(c);
// StrAssign(s2, c);
// i=StrCompare(s1, s2);
// if(i<0)
// s = '<';
// else if(i==0)
// s = '=';
// else
// s = '>';
// printf("串s1%c串s2\n", s);
// k=Concat(t, s1, s2);
// printf("串s1连接串s2得到的串t为");
// StrPrint(t);
// if(k==FALSE)
// printf("串t有截断\n");
// ClearString(s1);
// printf("清为空串后,串s1为");
// StrPrint(s1);
// printf("串长为%d,串空否?%d(1:是 0:否)\n", StrLength(s1), StrEmpty(s1));
// printf("求串t的子串,请输入子串的起始位置,子串长度:");
// scanf("%d,%d", &i, &j);
// k=SubString(s2, t, i, j);
// if(k)
// {
// printf("子串s2为");
// StrPrint(s2);
// }
// printf("从串t的第pos个字符起,删除len个字符,请输入pos,len:");
// scanf("%d,%d", &i, &j);
// StrDelete(t, i, j);
// printf("删除后的串t为");
// StrPrint(t);
// i=StrLength(s2)/2;
//
// StrInsert(s2, i, t);
//
// printf("在串s2的第%d个字符之前插入串t后,串s2为", i);
// StrPrint(s2);
// i=Index1(s2, t, 1);
// printf("s2的第%d个字符起和t第一次匹配\n", i);
// i=Index(s2, t, 1);
// printf("s2的第%d个字符起和t第一次匹配\n", i);
// SubString(t, s2, 1, 1);
// printf("串t为");
// StrPrint(t);
// Concat(s1, t, t);
// printf("串s1为");
// StrPrint(s1);
// k=Replace(s2, t, s1);
// if(k)
// {
// printf("用串s1取代串s2中和串t相同的不重叠的串后,串s2为");
// StrPrint(s2);
// }
// DestroyString(s2);
// return 0;
//}
// main4-2.cpp 检验bo4-2.h的主程序
//#include"c1.h"
//#include"c4-2.h"
//#include"bo4-2.h"
//typedef HString String;
//#include"func4-1.h"
//int main()
//{
// int i;
// char c, *p="God bye!", *q="God luck!";
// HString t, s, r;
// InitString(t);
// InitString(s);
// InitString(r);
// StrAssign(t, p);
// printf("串t为");
// StrPrint(t);
// printf("串长为%d,串空否?%d(1:空 0:否)\n", StrLength(t), StrEmpty(t));
// StrAssign(s, q);
// printf("串s为");
// StrPrint(s);
// i=StrCompare(s, t);
// if(i<0)
// c = '<';
// else if(i==0)
// c = '=';
// else
// c = '>';
// printf("串s%c串t\n", c);
// Concat(r, t, s);
// printf("串t连接串s产生的串r为");
// StrPrint(r);
// StrAssign(s, "oo");
// printf("串s为");
// StrPrint(s);
// StrAssign(t, "o");
// printf("串t为");
// StrPrint(t);
// Replace(r, t, s);
// printf("把串r中和串t相同的子串用串s代替后,串r为");
// StrPrint(r);
// ClearString(s);
// printf("串s清空后,串长为%d,空否?%d(1:空 0:否)\n", StrLength(s), StrEmpty(s));
// SubString(s, r, 6, 4);
// printf("串s为从串r的第6个字符起的4个字符,长度为%d,串s为", s.length);
// StrPrint(s);
// StrCopy(t, r);
// printf("由串r复制得串t,串t为");
// StrPrint(t);
// StrInsert(t, 6, s);
// printf("在串t的第6个字符前插入串s后,串t为");
// StrPrint(t);
// StrDelete(t, 1, 5);
// printf("从串t的第1个字符起删除5个字符后,串t为");
// StrPrint(t);
// printf("%d是从串t的第1个字符起,和串s相同的第1个子串的位置\n", Index(t, s, 1));
// printf("%d是从串t的第2个字符起,和串s相同的第1个子串的位置\n", Index(t, s, 2));
// DestroyString(t);
// return 0;
//}
// algo4-1.cpp KMP算法
#include"c1.h"
#include"c4-1.h"
#include"bo4-1.h"
void get_next(SString T, int next[])
{// 求T的next函数值并存入next数组
int i = 1, j = 0;
next[1] = 0; // T的第i个字符与主串不匹配时,主串的下一个字符与T的第1个字符比较
while(i < T[0])
if(j == 0 || T[i] == T[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
void get_nextval(SString T, int nextval[])
{// 求T的next函数修正值并存入nextval数组
int i = 1, j = 0;
nextval[1] = 0;
while(i < T[0])
if(j == 0 || T[i] == T[j])
{
i++;
j++;
if(T[i] != T[j])
nextval[i] = j;
else
nextval[i] = nextval[j];
}
else
j = nextval[j];
}
int Index_KMP(SString S, SString T, int pos, int next[])
{
int i = pos, j = 1;
while(i <= S[0] && j <= T[0])
if(j == 0 || S[i] == T[j])
{
i++;
j++;
}
else
j = next[j];
if(j > T[0])
return i - T[0];
else
return 0;
}
int main()
{
int i, *p;
SString s1, s2;
StrAssign(s1, "aaabaaaab");
printf("主串为");
StrPrint(s1);
StrAssign(s2, "aaaab");
printf("子串为");
StrPrint(s2);
p=(int*)malloc((StrLength(s2)+1)*sizeof(int));
get_next(s2, p);
printf("子串的next数组为");
for(i=1; i<=StrLength(s2); i++)
printf("%d ", *(p+i));
printf("\n");
i=Index_KMP(s1, s2, 1, p);
if(i)
printf("主串和子串在第%d个字符处首次匹配\n", i);
else
printf("主串和子串匹配不成功\n");
get_nextval(s2, p);
printf("子串的nextval数组为");
for(i=1; i<=StrLength(s2); i++)
printf("%d ", *(p+i));
printf("\n");
printf("主串和子串在第%d个字符处首次匹配\n", Index_KMP(s1, s2, 1, p));
}
<file_sep>// bo2-5.h 静态链表的基本操作
#define DestroyList ClearList
int Malloc(SLinkList space)
{// 若备用链表space非空,则返回分配的结点下标
// 调用后会少一个结点
int i = space[0].cur;
if(i)
space[0].cur = space[i].cur;
return i;
}
void Free(SLinkList space, int k)
{// 将下标为k的空闲结点回收到备用链表的头结点
space[k].cur = space[0].cur;
space[0].cur = k;
}
void InitList(SLinkList L)
{// 构造一个空的链表L,表头为L的最后一个单元L[MAX_SIZE-1],其余
// 单元链成一个备用链表,表头为L[0]
int i; // 相当于指针
L[MAX_SIZE-1].cur = 0; // 表头
for(i = 0; i < MAX_SIZE-2; i++)
L[i].cur = i+1;
L[MAX_SIZE-2].cur = 0;
}
void ClearList(SLinkList L)
{
int j, i = L[0].cur; // 相当于指针
while(i)
{
j = i;
i = L[i].cur;
}
L[j].cur = L[MAX_SIZE-1].cur; // 指向表头
L[MAX_SIZE-1].cur = 0; // 链表空
}
Status ListEmpty(SLinkList L)
{
if(L[MAX_SIZE-1].cur == 0)
return TRUE;
return FALSE;
}
int ListLength(SLinkList L)
{
int j = 0, i = L[0].cur;
while(i)
{
j++;
i = L[i].cur;
}
return j;
}
Status GetElem(SLinkList L, int i, ElemType &e)
{
int m, k = MAX_SIZE-1; // 指向头结点
if(i < 1 || i > ListLength(L))
return ERROR;
for(m = 1; m <= i; m++)
k = L[k].cur;
e = L[k].data;
return OK;
}
int LocateElem(SLinkList L, ElemType e)
{
int i = L[MAX_SIZE-1].cur;
while(i && L[i].data != e)
i = L[i].cur;
return i;
}
Status PriorElem(SLinkList L, ElemType cur_e, ElemType &pre_e)
{
int j, i = L[MAX_SIZE-1].cur;
do
{
j = i;
i = L[i].cur;
}while(i && L[i].data != cur_e);
if(i)
{
pre_e = L[i].data;
return OK;
}
return ERROR;
}
Status NextElem(SLinkList L, ElemType cur_e, ElemType &next_e)
{
// int i = L[MAX_SIZE-1].cur;
// while(i && L[i].data != cur_e)
// {
// i = L[i].cur;
// }
// i = L[i].cur;
// next_e = L[i].data;
// return OK;
int j, i = LocateElem(L, cur_e);
if(i)
{
j = L[i].cur;
if(j)
{
next_e = L[j].data;
return OK;
}
}
return ERROR;
}
Status ListInsert(SLinkList L, int i, ElemType e)
{
int m, j, k = MAX_SIZE-1;
if(i < 1 || i > ListLength(L)+1)
return ERROR;
j = Malloc(L); // 申请新单元
if(j)
{
L[j].data = e;
for(m = 1; m < i; m++)
k = L[k].cur;
L[j].cur = L[k].cur;
L[k].cur = j;
return OK;
}
return ERROR;
}
Status ListDelete(SLinkList L, int i, ElemType &e)
{
int j, k = MAX_SIZE-1;
if(i < 1 || i > ListLength(L))
return ERROR;
for(j = 1; j < i; j++)
k = L[k].cur;
j = L[k].cur;
L[k].cur = L[j].cur;
e = L[j].data;
Free(L,j);
return OK;
}
void ListTraverse(SLinkList L, void(*visit)(ElemType))
{
int i = L[MAX_SIZE-1].cur;
while(i)
{
visit(L[i].data);
i = L[i].cur;
}
printf("\n");
}
<file_sep>// bo5-2.h 三元组稀疏矩阵的基本操作(4个)
Status CreateSMatrix(TSMatrix &M)
{
int i;
Triple T;
Status k;
printf("请输入矩阵行数,列数,非零元素个数: ");
scanf("%d,%d,%d",&M.mu,&M.nu,&M.tu);
if(M.tu > MAX_SIZE)
return ERROR;
M.data[0].i = 0;
for(i = 1; i <= M.tu; i++)
{
do
{
printf("请按顺序输入第%d个非零元素所在的行(1~%d),列(1~%d),元素值: ",i,M.mu,M.nu);
scanf("%d,%d,%d",&T.i,&T.j,&T.e);
k = 0;
if(T.i < 1 || T.i > M.mu || T.j < 1 || T.j > M.nu)
k = 1;
if(T.i < M.data[i-1].i || T.i == M.data[i-1].i && T.j <= M.data[i-1].j)
k = 1; // 行或列的顺序有错
}while(k);
M.data[i] = T;
}
return OK;
}
Status AddSMatrix(TSMatrix M, TSMatrix N, TSMatrix &Q)
{
int m = 1, n = 1, q = 0;
if(M.mu != N.mu || M.nu != N.nu)
return ERROR;
Q.mu = M.mu;
Q.nu = M.nu;
while(m <= M.tu && n <= N.tu)
switch(comp(M.data[m].i,N.data[n].i))
{
case -1: Q.data[++q] = M.data[m++]; break;
case 0: switch(comp(M.data[m].j,N.data[n].j))
{
case -1: Q.data[++q] = M.data[m++];
case 0: Q.data[++q] = M.data[m++];
Q.data[q].e += N.data[n++].e;
if(Q.data[q].e == 0)
q--;
break;
case 1: Q.data[++q] = N.data[n++];
}
break;
case 1: Q.data[++q] = N.data[n++];
}
while(m <= M.tu)
Q.data[++q] = M.data[m++];
while(n <= N.tu)
Q.data[++q] = N.data[n++];
if(q > MAX_SIZE)
return ERROR;
Q.tu = q;
return OK;
}
void TransposeSMatrix(TSMatrix M, TSMatrix &T)
{// 转置
int p, col, q = 1;
T.mu = M.nu;
T.nu = M.mu;
T.tu = M.tu;
if(T.tu)
for(col = 1; col <= M.nu; col++)
for(p = 1; p <= M.mu; p++)
if(M.data[p].j == col)
{
T.data[q].i = M.data[p].i;
T.data[q].j = M.data[p].j;
T.data[q++].e = M.data[p].e;
}
}
Status MultSMatrix(TSMatrix M, TSMatrix N,TSMatrix &Q)
{
int i, j, q, p;
ElemType Qs;
TSMatrix T;
if(M.nu != N.mu)
return ERROR;
Q.mu = M.mu;
Q.nu = M.nu;
Q.tu = 0;
TransposeSMatrix(N, T);
for(i = 1; i <= Q.mu; i++)
{
q = 1;
for(j = 1; j <= T.mu; j++)
{
Qs = 0;
p = 1;
while(M.data[p].i < i)
p++;
while(T.data[q].i < j)
q++;
while(p <= M.tu && q <= T.tu && M.data[p].i == i && T.data[q].i == j)
switch(comp(M.data[p].j,T.data[q].j))
{
case -1: p++; break;
case 0: Qs += M.data[p++].e * T.data[q++].e; break;
case 1: q++;
}
if(Qs)
{
if(++Q.tu > MAX_SIZE)
return ERROR;
Q.data[Q.tu].i = i;
Q.data[Q.tu].j = j;
Q.data[Q.tu].e = Qs;
}
}
}
return OK;
}
<file_sep>#define MAX_NAME 9 // 顶点名称字符串最大长度+1
struct VertexType // 最简单的顶点信息类型(只有顶点名称)
{
char name[MAX_NAME]; // 顶点名
};
void Visit(VertexType ver)
{// 输出顶点信息
printf("%s",ver.name);
}
void Input(VertexType &ver)
{// 输入顶点信息
scanf("%s",ver.name);
}
void InputFromFile(FILE *f, VertexType &ver)
{// 从文件输入顶点信息
fscanf(f,"%s",ver.name);
}
<file_sep>// bo5-3.h 三元稀疏矩阵的基本操作(4个)
void DestroySMatrix(TSMatrix &M)
{
M.mu = M.nu = M.tu = 0;
}
void PrintSMatrix(TSMatrix M)
{
int i, j, k = 1;
Triple *p = M.data + 1;
for(i = 1; i <= M.mu; i++)
{
for(j = 1; j <= M.nu; j++)
{
if(k <= M.tu && p->i == i &&p->j == j)
{
printf("%3d",(p++)->e);
k++;
}
else
printf("%3d",0);
}
printf("\n");
}
}
void CopySMatrix(TSMatrix M, TSMatrix &T)
{
T = M;
}
Status SubtSMatrix(TSMatrix M, TSMatrix N, TSMatrix &Q)
{
int i;
if(M.mu != N.mu || M.nu != N.nu)
return ERROR;
for(i = 1; i <= N.tu; i++)
N.data[i].e *= -1;
AddSMatrix(M, N, Q);
return OK;
}
<file_sep>// bo8-3.h 平衡二叉树的基本操作
void R_Rotate(BSTree &p)
{// 以*p为根的二叉排序树作右旋处理,使二叉排序树的重心右移,但不改变平衡因子
// 处理之后p指向新的树根节点,即旋转处理之前的左子树的根结点
BSTree lc;
lc = p->lchild; // lc指向p的左孩子,lc的左子树不变
p->lchild = lc->rchild; // lc的右子树挂接为p的左子树
lc->rchild = p; // 原根结点成为lc的右孩子
p = lc; // p指向原左孩子结点
}
void L_Rotate(BSTree &p)
{// 左旋
BSTree rc;
rc = p->rchild;
p->rchild = lc->lchild;
rc->lchild = p;
p = rc;
}
void LR_Rotate(BSTree &p)
{// 对以*p为根的平衡二叉树的LR型失衡,直接进行平衡旋转处理,不修改平衡因子
BSTree lc = p->lchild; // lc指向小值结点
p->lchild = lc->rchild->rchild; // 中值结点的右子树成为大值结点的左子树
lc->rchild->rchild = p; // 大值结点成为中值结点的右子树
p = lc->rchild; // p指向中值结点
lc->rchild = p->lchild; // 中值结点左子树成为小值结点的右子树
p->lchild = lc; // 小值结点成为中值结点左子树
}
void RL_Rotate(BSTree &p)
{
BSTree rc = p->rchild;
p->rchild = rc->lchild->lchild;
rc->lchild->lchild = p;
p = rc->lchild;
rc->lchild = p->rchild;
p->rchild = rc;
}
#define LH +1 // 左高
#define EH 0 // 等高
#define RH -1 // 右高
void LeftBalance(BSTree &T)
{// 初始条件:原平衡二叉排序树T的左子树比右子树高(T->bf=1)
// 操作:在左子树中插入结点,导致树T不平衡,对不平衡的树T进行左旋处理使其平衡
BSTree lc, rd;
lc = T->lchild;
switch(T->bf)
{
case LH: T->bf = lc->bf = EH;
R_Rotate(T);
break;
case RH: rd = lc->rchild;
switch(rd->bf)
{
case LH: T->bf = RH;
lc->bf = EH;
break;
case EH: T->bf = lc->bf = EH;
break;
case RH: T->bf = EH;
lc->bf = LH;
}
rd->bf = EH;
#ifndef FLAG // 未定义FLAG使用两个函数实现双旋处理
L_Rotate(T->lchild);
R_Rotate(T);
#else
LR_Rotate(T);
#endif // FLAG
}
}
<file_sep>// 队列的链式存储结构
typedef struct QNode
{
QElemType data;
QNode *next;
} *QueuePtr;
struct LinkQueue
{
QueuePtr front1, rear; // 队头, 队尾
};
| 17532e63277f4adb19b85a7f72a9af18d843946c | [
"Markdown",
"C",
"C++"
] | 65 | C | HDY20171130/DataStruct | baeb0b39934ff78f5f837d14c758857036887b10 | 67c03cc462e73dd6c68304edd456f83194becb51 |
refs/heads/master | <file_sep>import React,{Component} from 'react';
import {Text,ScrollView} from 'react-native';
import axios from 'axios';
import AlbumDetails from './AlbumDetails';
// Make a component
class AlbumList extends Component{
state = { albums: []};
componentWillMount(){
fetch('https://rallycoding.herokuapp.com/api/music_albums')
.then((response)=>response.json())
//.then((responseData)=>{
// console.log(responseData);});
.then((responseData) => this.setState({ albums: responseData }));
}
renderAlbums(){
return this.state.albums.map(album=>
<AlbumDetails key={album.title} album={album}/>
);
}
render(){
console.log(this.state);
return (
<ScrollView>
{this.renderAlbums()}
</ScrollView>
);
};
}
export default AlbumList;
| 50d194aa046793905cf209b05cbb7511cca93254 | [
"JavaScript"
] | 1 | JavaScript | shailendra93/react-native | 19dc0d00a11345d0fe98db0bf150a10261914d71 | 90dfb629b9b9f5164a03265d9d42341fd53c7ec8 |
refs/heads/main | <file_sep># SpringSecurityDemoBike
Spring Securit yDemo Bike
<file_sep>package com.educacionit.bike.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.educacionit.bike.models.Usuario;
public interface UsuarioRepository extends JpaRepository<Usuario, Integer>{
//modificamos la consulta y buscamos por una columna (nombre) para que luego podamos buscar un registro por nombre al momento que se haga un login
//findBy${nombreDeLaColumna} el findBy es una palabra reservada de spring donde le indicamos por que columan queremos hacer el where
Usuario findByNombre(String nombre); //esto es como si hicieramos un : select * from usuario where nobre = "${algo}";
}
| 505c9f8c7aab15010fd33a9869c33a37ce656a31 | [
"Markdown",
"Java"
] | 2 | Markdown | alexdeassis7/SpringSecurityDemoBike | 28a5e441b8c4643c1fe16245752b9f3ab336663d | a2f007ee572d2126aae73a78194af312d372ce02 |
refs/heads/master | <file_sep>package br.com.rd.ecom.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import javax.persistence.criteria.CriteriaBuilder;
import java.math.BigDecimal;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "tb_pedido_item")
public class ItemPedido {
@Id
@Column(name = "cd_pedido_item")
private Integer codPed;
@Column(name = "vl_produto")
private BigDecimal vlProduto;
@Column(name = "vl_frete")
private BigDecimal vlFrete;
@Column(name = "quantidade")
private Integer quantidade;
@Column(name = "cd_produto")
private Integer codProduto;
@ManyToOne
@JoinColumn(name = "cod_pedido")
private Pedido pedido;
}
<file_sep>package br.com.rd.ecom.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.math.BigDecimal;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "tb_produtos")
public class Products {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long codProduto;
@Column(name = "ds_produto",nullable = false)
private String descProduto;
@ManyToOne
@JoinColumn(name = "cd_categoria")
private Categoria codCategoria;
@Column(name = "vl_produto")
private BigDecimal vlProduto;
}
<file_sep>package br.com.rd.ecom.user;
import br.com.rd.ecom.user.model.Clients;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserRepository extends JpaRepository<Clients, Long> {
List<Clients> findByName(String name);
List<Clients> findByCpf(String cpf);
List<Clients> findByEmail(String email);
List<Clients> findByContact(Integer contact);
}<file_sep>package br.com.rd.ecom.repository;
import br.com.rd.ecom.model.Categoria;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CategoriaRepository extends JpaRepository<Categoria, Long> {
List<Categoria> findByCodCategoria(String ds_categoria);
}
<file_sep>package br.com.rd.ecom.repository;
import br.com.rd.ecom.model.Products;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ProductsRepository extends JpaRepository<Products, Long> {
public List<Products> findByDescProduto(String descProduto);
public List<Products> findByCodProdutoAndDescProduto(Long codProduto, String descProduto);
}
<file_sep>package br.com.rd.ecommerce.models.entities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Table;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "tb_client")
public class Client {
private Integer id;
private String name;
private String CPF;
private String email;
private Long phoneNumber;
private String password;
}
<file_sep>package br.com.rd.ecom.controller;
import br.com.rd.ecom.model.Clients;
import br.com.rd.ecom.repository.ClientsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class ClientsController {
@Autowired
private ClientsRepository clientsRepository;
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/create-user")
public Clients save (@RequestBody Clients clients) {
return clientsRepository.save(clients);
}
@GetMapping("/find-user/list")
public List<Clients> find() {return clientsRepository.findAll(); }
}<file_sep>package br.com.rd.ecom.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "tb_pedido")
public class Pedido {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_pedido")
private Integer codPedido;
@Column(name = "dt_pedido")
@Temporal(TemporalType.TIMESTAMP)
private Date dtPedido;
@ManyToOne
@JoinColumn(name = "id_clients")
private Clients clients;
@Column(name = "vl_pedido")
private BigDecimal vlPedido;
@Column(name = "vl_frete")
private BigDecimal vlFrete;
@Column(name = "ds_forma_pagamento")
private String dsFormaPagto;
@OneToMany(mappedBy = "pedido")
private List<ItemPedido> itensPedido;
}
<file_sep>package br.com.rd.ecom.user;
import br.com.rd.ecom.user.model.Clients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/create-user")
public Clients save (@RequestBody Clients clients) {
return userRepository.save(clients);
}
@GetMapping("/find-user/list")
public List<Clients> find() {return userRepository.findAll(); }
}<file_sep>package br.com.rd.ecom;
import br.com.rd.ecom.model.Clients;
public class Teste {
public static void main(String[] args) {
Clients clients = new Clients(1L,"Lucas","133133","shuayisga",131331,"1231");
}
}
| e01c714ad268c2acc63618cc69b1ab3aeddaebf0 | [
"Java"
] | 10 | Java | PrietoLucas/JavaSpringAPI | c6bb6219a3a6d02f556eb8e7da08eca0c92afda4 | 4a9bb6e10965a7a5c3f2bbd6f98072cc941d5071 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProyectoNuevoRegistro.Entidades;
using ProyectoNuevoRegistro.DAL;
using System.Linq.Expressions;
namespace ProyectoNuevoRegistro.BLL
{
public class RolesBLL
{
public static bool Guardar(Roles roles)
{
if (!Existe(roles.RolId))
return Insertar(roles);
else
return false;
}
private static bool Insertar(Roles roles)
{
bool paso = false;
Contexto contexto = new Contexto();
try
{
contexto.Roles.Add(roles);
paso = contexto.SaveChanges() > 0;
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return paso;
}
public static bool Modificar(Roles roles)
{
bool paso = false;
Contexto contexto = new Contexto();
try
{
contexto.Entry(roles).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
paso = contexto.SaveChanges() > 0;
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return paso;
}
public static bool Eliminar(int id)
{
bool paso = false;
Contexto contexto = new Contexto();
try
{
var usuario = contexto.Usuarios.Find(id);
if (usuario != null)
{
contexto.Usuarios.Remove(usuario);
paso = contexto.SaveChanges() > 0;
}
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return paso;
}
public static Roles Buscar(int id)
{
Contexto contexto = new Contexto();
Roles roles;
try
{
roles = contexto.Roles.Find(id);
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return roles;
}
public static bool Existe(int id)
{
Contexto contexto = new Contexto();
bool encontrado = false;
try
{
encontrado = contexto.Roles.Any(e => e.RolId == id);
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return encontrado;
}
public static List<Usuarios> GetList(Expression<Func<Usuarios, bool>> criterio)
{
List<Usuarios> lista = new List<Usuarios>();
Contexto contexto = new Contexto();
try
{
lista = contexto.Usuarios.Where(criterio).ToList();
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return lista;
}
}
}
<file_sep>using ProyectoNuevoRegistro.DAL;
using ProyectoNuevoRegistro.BLL;
using ProyectoNuevoRegistro.Entidades;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProyectoNuevoRegistro
{
public partial class rUsuarios : Form
{
public rUsuarios()
{
InitializeComponent();
}
private void Limpiar()
{
IDNumericUpDown1.Value = 0;
NombresTextBox.Clear();
AliasTextBox.Clear();
ClaveConfirmTextBox.Clear();
EmailTextBox.Clear();
errorProvider1.Clear();
FechaDateTimePicker.CustomFormat = " ";
ClaveTextBox.Clear();
ActivoCheckBox.Checked = false;
RolComboBox.Text = " ";
}
private void LlenaCampo(Usuarios usuarios)
{
IDNumericUpDown1.Value = usuarios.UsuarioId;
NombresTextBox.Text = usuarios.Nombres;
EmailTextBox.Text = usuarios.Email;
AliasTextBox.Text = usuarios.Alias;
RolComboBox.Text = usuarios.DescripcionRol;
ClaveTextBox.Text = usuarios.Clave;
FechaDateTimePicker.Value = usuarios.FechaIngreso;
ActivoCheckBox.Checked = usuarios.Activo;
ClaveConfirmTextBox.Text = usuarios.Clave;
}
private Usuarios LlenaClase()
{
Usuarios usuarios = new Usuarios();
usuarios.UsuarioId = (int)IDNumericUpDown1.Value;
usuarios.Clave = ClaveTextBox.Text;
usuarios.Email = EmailTextBox.Text;
usuarios.Nombres = NombresTextBox.Text;
usuarios.FechaIngreso = FechaDateTimePicker.Value;
usuarios.Alias = AliasTextBox.Text;
usuarios.DescripcionRol = RolComboBox.Text;
usuarios.Activo = ActivoCheckBox.Checked;
return usuarios;
}
private bool ExisteEnLaBaseDeDatos()
{
Usuarios usuarios = UsuariosBLL.Buscar((int)IDNumericUpDown1.Value);
return (usuarios != null);
}
private void Nuevo_Click(object sender, EventArgs e)
{
Limpiar();
}
private void Guardar_Click(object sender, EventArgs e)
{
Usuarios usuarios;
bool paso = false;
if (!Validar())
return;
usuarios = LlenaClase();
if (!(UsuariosBLL.Existe((int)IDNumericUpDown1.Value)))
{
if (!ExisteEnLaBaseDeDatos())
paso = UsuariosBLL.Guardar(usuarios);
else
{
paso = UsuariosBLL.Modificar(usuarios);
}
}
if (paso)
{
Limpiar();
MessageBox.Show("Guardado!", "Exito", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("No se pudo guardar!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private bool Validar()
{
bool paso = true;
if (NombresTextBox.Text == string.Empty)
{
errorProvider1.SetError(NombresTextBox, "El campo nombre no puede estar vacio");
NombresTextBox.Focus();
paso = false;
}
if (string.IsNullOrWhiteSpace(EmailTextBox.Text))
{
errorProvider1.SetError(EmailTextBox, "El Email no puede estar vacio");
EmailTextBox.Focus();
paso = false;
}
if (string.IsNullOrWhiteSpace(AliasTextBox.Text))
{
errorProvider1.SetError(AliasTextBox, "El campo Alias no puede estar vacio");
AliasTextBox.Focus();
paso = false;
}
if (string.IsNullOrWhiteSpace(RolComboBox.Text))
{
errorProvider1.SetError(RolComboBox, "Debe agregar un rol especifico");
RolComboBox.Focus();
paso = false;
}
if (string.IsNullOrWhiteSpace(ClaveTextBox.Text))
{
errorProvider1.SetError(ClaveTextBox, "Debe asignar una clave a su usuario");
ClaveTextBox.Focus();
paso = false;
}
if (string.IsNullOrWhiteSpace(ClaveConfirmTextBox.Text))
{
errorProvider1.SetError(ClaveConfirmTextBox, "Debe confirmar la clave");
ClaveConfirmTextBox.Focus();
paso = false;
}
if (string.IsNullOrWhiteSpace(FechaDateTimePicker.Text))
{
errorProvider1.SetError(FechaDateTimePicker, "Debe agregar una fecha de registro");
FechaDateTimePicker.Focus();
paso = false;
}
if(ClaveTextBox.Text != ClaveConfirmTextBox.Text)
{
errorProvider1.SetError(ClaveConfirmTextBox, "Las contrseñas deben ser iguales.");
ClaveConfirmTextBox.Focus();
errorProvider1.SetError(ClaveTextBox, "Las contraseñas deben ser iguales.");
ClaveTextBox.Focus();
paso = false;
}
if (UsuariosBLL.ExisteAlias(AliasTextBox.Text))
{
errorProvider1.SetError(AliasTextBox, "Los Alias no pueden repetirse!");
AliasTextBox.Focus();
paso = false;
}
return paso;
}
private void Eliminar_Click(object sender, EventArgs e)
{
errorProvider1.Clear();
int id;
int.TryParse(IDNumericUpDown1.Text, out id);
Limpiar();
if (UsuariosBLL.Eliminar(id))
MessageBox.Show("Eliminado!", "Exito", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
errorProvider1.SetError(IDNumericUpDown1, "No se puede eliminar una persona que no existe");
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
FechaDateTimePicker.CustomFormat = "dd / MM / yyyy";
}
private void Buscar_Click(object sender, EventArgs e)
{
int id;
Usuarios usuario = new Usuarios();
int.TryParse(IDNumericUpDown1.Text, out id);
Limpiar();
usuario = UsuariosBLL.Buscar(id);
if (usuario != null)
{
MessageBox.Show("Persona Encotrada","Exito",MessageBoxButtons.OK, MessageBoxIcon.Information);
LlenaCampo(usuario);
}
else
{
MessageBox.Show("Persona no Encontrada","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
}
<file_sep>using ProyectoNuevoRegistro.Entidades;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
namespace ProyectoNuevoRegistro.DAL
{
class Contexto : DbContext
{
public DbSet<Usuarios> Usuarios { get; set; }
public DbSet<Roles> Roles { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source = GestionUsuarios.Db");
}
}
}
| 64981381b9168f4fac3ec954ad858596bbf71d51 | [
"C#"
] | 3 | C# | Anneury/RegistroNuevo | 65c5ed02d1c0a75378ca9b81686f6511e7148af3 | 0572a515520d4871761c5ee92dab564b2bcc7f1d |
refs/heads/master | <file_sep># EVENT SOURCING
```
Given
[Events in ARRAY]
When
Single-Command
Then
[Resulting Event(s) ARRAY]
```
## 1
```
Given
[ GameCreated ]
When
Place(0,0,X)
Then
[ MovePlaced ]
```
## 2
```
Given
[ GameCreated, Placed(0,0,X) ]
When
Place(0,0,Y)
Then
[ IllegalMove ]
```
## 3
```
Given
[ GameCreated, Placed(0,0,X) ]
When
Place(0,0,X)
Then
[ NotYourMove ]
```
## 4
```
Given
[ GameCreated, Placed(0,0,X), Placed(0,1,X) ]
When
Place(0,2,X)
Then
[ X Won ]
```
## 5
```
Given
[ Placed(0,0,X) ]
When
Place(0,0,Y)
Then
[ NotAllowed ]
```
## 6
```
Given
[ GameCreated, GameStarted ]
When
GameJoin
Then
[ FullGameJoinAttempted ]
```
## 7
```
Given
[ GameCreated ]
When
GameJoin
Then
[ GameJoined ]
```
## 8
```
Given
[ X Won ]
When
Place(0,0,Y)
Then
[ NotAllowed ]
```
## 9
```
Given
[ Placed(0,0,X), Placed(1,1,X) ]
When
Place(2,2,X)
Then
[ GameWon X]
```
## 10
```
Given
[ Placed(0,0,Y), Placed(1,1,Y) ]
When
Place(2,2,Y)
Then
[ GameWon Y]
```
## 11
```
Given
[ GameCreated ]
When
Place(3,0,X)
Then
[ NotAllowed ]
```
## 12
```
Given
[ GameCreated, Placed(0,2,X), Placed(1,2,X) ]
When
Place(2,2,X)
Then
[ GameWon ]
```
## 13
```
Given
[ GameCreated,
Placed(0,0,X), Placed(0,1,Y), Placed(0,2,X),
Placed(1,1,Y), Placed(1,0,X), Placed(1,2,Y),
Placed(2,1,X), Placed(2,0,Y)
When
Place(2,2,X)
Then
[ Tie, GameEnded ]
```
## 14
```
Given
[ GameCreated,
Placed(0,0,X), Placed(0,1,Y), Placed(0,2,X),
Placed(1,0,Y), Placed(1,1,X), Placed(1,2,Y),
Placed(2,1,X), Placed(2,0,Y)
When
Place(2,2,X)
Then
[ GameWon ]
```
## 15
```
Given
[]
When
CreateGame
Then
[ GameCreated ]
```
## Store events - not state
- Atburðir sem gerast í kerfinu
- Event Concepts
- hlutir sem gerast í þátíð
- t.d. PlayerPlacedMove, GameCreated, GameJoined
- Triggeruð af Commands
- Commands => hlutir sem ég vil að gerist
- þ.e. PlaceMove, CreateGame, JoinGame
- oftast eitt command á móti hverjum event
- Aggregate (samansafn)
- einn tictactoe leikur
- Command handler (sem tekur við command)
- kann að túlka command, hlaða upp aggregate og setja saman, láta aggregate fá command
- Event Store
- Geymir eventa sem hafa orðið til í kerfinu
- gagnagrunnar (postgres)
- tvær töflur (commands store, event store)
- app context
- uppúr "domain driven design"
- hluturinn sem "límir" allt saman
- Projections
- ef event fjöldinn hefur efri mörk þarf ekki
- til að gera event hröð
<file_sep># Week 2
## Links
* __[Jenkins](http://ec2-35-177-96-250.eu-west-2.compute.amazonaws.com:8080)__
* __[TicTacToe](http://ec2-54-76-136-201.eu-west-1.compute.amazonaws.com:8080)__
### Scripts
#### Start by provisioning an ec2 instance.
Run [Provision ec2](provision_aws.sh) which creates a new ec2 instance in region eu-west-2 (london)
It creates a security group that opens for:
- GitHub addresses for hooks: (172.16.17.32/22, 172.16.58.3/22, 2620:112:3000::/44)
- my home address: 22 and 8080
- schools address (the address where I was located at time of running the script): 22 and 8080
After ec2 instance is up'n running [bootstrap-jenkins](bootstrap-jenkins.sh) script is called:
It connects to the new ec2 instance and runs [EC2 Bootstrap](ec2-bootstrap-jenkins.sh).
EC2-Bootstrap installs:
- Jenkins
- java 1.8
- docker
- docker-compose
- Git
- nodejs
- npm
- nvm
- yarn
### Manual work
__Inside Jenkins__
- Create a project (hgop) that pulls tictactoe code from GitHub
- A hook is configured on github to notify jenkins which then pulls from repo.
- Generated public/private keys on Jenkins and public key added to github to allow jenkins to connect to repo
- enable security (/var/lib/jenkins/config.xml)
- Add Plugins:
- GitHub Authentication
- GitHub Integration
- Gravatar
- NodeJS
- Pipeline
### Jenkinsfile
The file that binds all the steps in the pipeline.
[Jenkinsfile]()
The stages are:
- __Build__ - (install needed packages with yarn (or npm))
- __Test__ - (run unit test on the tictactoe app)
- __Project Build__ -(package the tictactoe app for deploy)
- __Docker build__ - (create a docker image with new version of tictactoe)
- __Deploy To AWS__ - (deploy tictactoe to ec2 instance )
Prior to running those stages, we run: "_checkout scm_" which checks out newest version of the code, using pipeline plugin in jenkins.
Some stages could maybe be joined, but that would not make this any clearer.
### Jenkins credentials for external services (dockerhub / aws)
This needs to be done manually, which can be done by connecting to Jenkins ec2 instance with ssh (use script: aws.sh)
- run bash as jenkins: sudo su -s /bin/bash jenkins
- run: docker login
- this creates credentials file under /var/lib/jenkins/.docker/config.json
- run: "aws configure"
## More
[Version info](http://ec2-54-76-136-201.eu-west-1.compute.amazonaws.com:8080/version.html)
- [dockerbuild.sh]()
- builds docker image after application is built and pushes it to dockerhub
- [docker-compose.yml](provisioning/docker-compose.yml)
- add postgres port 5432:5432
- [server/database.json](database.json)
- change from localhost -> postgres
# Author
[<NAME>](mailto:<EMAIL>)
<EMAIL>
<file_sep>#!/bin/bash
# test the setup of jenkins server
# <NAME> - 2017
# <EMAIL> / <EMAIL>
echo "http://$(cat ec2_instance-jenkins/instance-public-name.txt):8080"
curl http://$(cat ec2_instance-jenkins/instance-public-name.txt):8080
echo $?
<file_sep># Automated acceptance testing
## Costs less than frequent manual regression testing
- when properly done
- þarft að vita hvað þú ert að gera
--
## Costs less than releasing poor-quality software
- viljum grípa villur helst áður en við gefum út
- geta sagst ætla að laga eitthvað áður en við gefum út, t.d. fresta útgáfu.
-
## Manual testing phases
- add a lot to the cycle time
- oft gerð undir mikilli pressu
- lagfæringar á hlutum leiða til regression
## Catch error classes that other tests do not
- einingapróf ættu að covera 100% en prófari ætti að vinna í exploratory (manual) testing
### are unit and component test enough?
- do not test user scenarios
- do not go through series of states
- unit test oft ekki í þráðum
- fáum ekki environment/configuration villur
- acceptance test are goot to catch:
-- thread problems
-- event-driven applications
-- architectural mistakes
-- configuration problems
## Acceptance test protect your application when
- making large-scale changes to it
- shortens the feedback loop, bugs are found sooner
## dangerous?
- hard to do properly
- UI tests introduce a lot of rigidity
-- getur haldið aftur af þróun
-- drivers/adapteres need to be maintained
-- ui will evolve slower as a result
## conclusion
- Use a handful of automated acceptance test through UI
-- < 5, one may be enough
- bulk of acceptance test should be through services
-- through the UI
- have the bulk in unit levelk
## how to create maintainable acceptance test suites
- careful attention to the analysis process
-- horfa á ferlið, millifæra, úttekt, staða á reikning eftir
- hafa þetta sem conclusion sögum (invest)
## Roles
- analyst
- tester
## summary
- viðbót, ekki meira/minna mikilvægt
- eykur traust á því að kerfið skili því sem það á að skila
- hjálpar til við stórar breytingar, validation
- losar fólk til að vinna frekar í explatory, user experience
- reduces cycle time
<file_sep>#!/bin/bash
# provision new ec2 instance for jenkins
# should accept argument for group name ( purpose ) ,like: ./create_ec2_stuff.sh jenkins
# <NAME> - 2017
# <EMAIL> / <EMAIL>
# make it more general
if [ $# -eq 0 ]; then
echo "No arguments provided"
MY_ROLE=jenkins
else
MY_ROLE=$1
fi
# SETTINGS
#GitHub addresses for hooks
GIT1=192.168.127.12/22
GIT2=192.168.127.12/22
GIT3=2620:112:3000::/44
# my home address
HOME_IP=192.168.127.12/32
## the name of the security group
SECURITY_GROUP_NAME=jenkins${USERNAME}
## the name of the ec2 image we use:
AMI_ID=ami-e7d6c983
#AMI_ID=ami-1a962263
## in what region are we running
REGION=eu-west-2
# open http for public internet?
PUBLIC_WEB_ACCESS=false
# sleep time to create delay as we are unable to connect straight away to install docker
SLEEP=5
# create instance if directory doesn't exist
INSTANCE_DIR="ec2_instance-$MY_ROLE"
if [ -d "${INSTANCE_DIR}" ]; then
exit
fi
[ -d "${INSTANCE_DIR}" ] || mkdir ${INSTANCE_DIR}
echo "create key pair"
# create public/private key pair without password
aws ec2 create-key-pair --key-name ${SECURITY_GROUP_NAME} --query 'KeyMaterial' --output text > ${INSTANCE_DIR}/${SECURITY_GROUP_NAME}.pem
echo "set permission on key pair"
# set correct permission on the private key
chmod 400 ${INSTANCE_DIR}/${SECURITY_GROUP_NAME}.pem
echo "fetch group id"
# fetch the group id of newly created group
SECURITY_GROUP_ID=$(aws ec2 create-security-group --group-name ${SECURITY_GROUP_NAME} --description "security group for $MY_ROLE in EC2" --query "GroupId" --output=text)
echo "group id to file"
# echo the security id to a file
echo ${SECURITY_GROUP_ID} > ${INSTANCE_DIR}/security-group-id.txt
# echo the name of the security_gropu to a file
echo "security group name to a file"
echo ${SECURITY_GROUP_NAME} > ${INSTANCE_DIR}/security-group-name.txt
echo "what is my address"
# get the address of my computer
MY_PUBLIC_IP=$(curl http://checkip.amazonaws.com)
echo "what is my cidr"
# add 32 bit mask to my address, making it a legal CIDR address
MY_CIDR=${MY_PUBLIC_IP}/32
echo "security group modify"
# allow incoming traffic on port 80, add rule to security group, I also want to be able to connect to port 22
if [ $PUBLIC_WEB_ACCESS ]
then
echo "open for public web access"
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 80 --cidr 0.0.0.0/0
else
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 8080 --cidr ${GIT1}
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 8080 --cidr ${GIT2}
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 8080 --cidr ${GIT3}
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 8080 --cidr ${MY_CIDR}
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 80 --cidr ${MY_CIDR}
fi
# open for ssh
echo "open for ssh"
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 22 --cidr ${MY_CIDR}
# open for icmp from my address
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol icmp --port -1 --cidr ${MY_CIDR}
# open for ssh from home
if [ ${MY_CIDR} != ${HOME_IP} ]
then
echo "my home address is not my current CIDR, always open for home"
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 8080 --cidr ${HOME_IP}
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 80 --cidr ${HOME_IP}
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 22 --cidr ${HOME_IP}
fi
echo "start instance ami-e7d6c983"
# start instance and get the instance ID
INSTANCE_ID=$(aws ec2 run-instances --user-data file://bootstrap-jenkins.sh --image-id $AMI_ID --security-group-ids ${SECURITY_GROUP_ID} --count 1 --instance-type t2.micro --key-name ${SECURITY_GROUP_NAME} --query 'Instances[0].InstanceId' --output=text)
echo "name of instance"
# duh, echo the instance ID
echo ${INSTANCE_ID} > ${INSTANCE_DIR}/instance-id.txt
echo "wait for instance startup..."
aws ec2 wait --region $REGION instance-running --instance-ids ${INSTANCE_ID}
echo "get public name"
# get public name, reachable from public internet to a variable
export INSTANCE_PUBLIC_NAME=$(aws ec2 describe-instances --instance-ids ${INSTANCE_ID} --query "Reservations[*].Instances[*].PublicDnsName" --output=text)
# put the public address in a file
echo "add public address to a file"
echo ${INSTANCE_PUBLIC_NAME} > ${INSTANCE_DIR}/instance-public-name.txt
# sleep for few seconds as we are not able to connect to instance straight away...
echo "wait $SLEEP seconds"
sleep $SLEEP
# check if instance is answering, ping until it responses (max 60)
PING_COUNT="0"
ping -c 1 ${INSTANCE_PUBLIC_NAME} > /dev/null
while [ $? != 0 ] && [ $PING_COUNT -lt 60 ]
do
PING_COUNT=$[$PING_COUNT+1]
sleep 1
echo .
ping -c 1 ${INSTANCE_PUBLIC_NAME} > /dev/null
done
aws ec2 associate-iam-instance-profile --instance-id $(cat ./ec2_instance-jenkins/instance-id.txt) --iam-instance-profile Name=CICDServer-Instance-Profile
# call jenkins install script
./bootstrap-jenkins.sh
echo "running: bootstrap-jenkins.sh"
<file_sep>#!/usr/bin/env bash
# used to install needed tools on jenkins server
# <NAME> - 2017
# <EMAIL> / <EMAIL>
sudo exec > >(tee /var/log/user-data.log | logger -t user-data -s 2>/dev/console) 2>&1
sudo yum update
sudo wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins.io/redhat/jenkins.repo
sudo rpm --import https://pkg.jenkins.io/redhat/jenkins.io.key
sudo yum -y remove java-1.7.0-openjdk
sudo yum -y install java-1.8.0
# install docker and docker-compose
sudo yum -y install docker
sudo yum -y install docker-compose
# start docker and add ec2-user to docker group
sudo service docker start
sudo usermod -a -G docker ec2-user
# install jenkins and add jenkins user to docker group, then start service
sudo yum install jenkins -y
sudo usermod -a -G docker jenkins
sudo service jenkins start
# install git client
sudo yum install git
# install nodejs and jpm
sudo yum install nodejs npm --enablerepo=epel
# install nvm
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash
# install correct version of nodejs
nvm install 6.9.1
# install yarn
sudo wget https://dl.yarnpkg.com/rpm/yarn.repo -O /etc/yum.repos.d/yarn.repo
curl --silent --location https://rpm.nodesource.com/setup_6.x | sudo bash -
sudo yum install yarn
touch ec2-init-done.markerfile
<file_sep>#!/bin/bash
# setup key for github
ssh -i "./ec2_instance-jenkins/jenkins.pem" ec2-user@${INSTANCE_PUBLIC_NAME}
sudo su -s /bin/bash jenkins
cd /var/lib/jenkins/
ssh-keygen
cat .ssh/id_rsa.pub
<file_sep>#!/bin/bash
# update security settings on jenkins
# should accept argument for group name ( purpose ) ,like: ./create_ec2_stuff.sh jenkins
# <EMAIL> / <EMAIL>
# <NAME> - 2017
# SETTINGS
# my home address
HOME_IP=172.16.31.10/32
## the name of the security group
SECURITY_GROUP_NAME=jenkins${USERNAME}
## the name of the ec2 image we use:
AMI_ID=ami-e7d6c983
#AMI_ID=ami-1a962263
## in what region are we running
REGION=eu-west-2
# open http for public internet?
PUBLIC_WEB_ACCESS=false
# sleep time to create delay as we are unable to connect straight away to install docker
SLEEP=5
# create instance if directory doesn't exist
INSTANCE_DIR="ec2_instance-$MY_ROLE"
echo "create key pair"
# create public/private key pair without password
aws ec2 create-key-pair --key-name ${SECURITY_GROUP_NAME} --query 'KeyMaterial' --output text > ${INSTANCE_DIR}/${SECURITY_GROUP_NAME}.pem
echo "set permission on key pair"
# set correct permission on the private key
chmod 400 ${INSTANCE_DIR}/${SECURITY_GROUP_NAME}.pem
echo "fetch group id"
# fetch the group id of newly created group
SECURITY_GROUP_ID=$(aws ec2 create-security-group --group-name ${SECURITY_GROUP_NAME} --description "security group for $MY_ROLE in EC2" --query "GroupId" --output=text)
echo "group id to file"
# echo the security id to a file
echo ${SECURITY_GROUP_ID} > ${INSTANCE_DIR}/security-group-id.txt
# echo the name of the security_gropu to a file
echo "security group name to a file"
echo ${SECURITY_GROUP_NAME} > ${INSTANCE_DIR}/security-group-name.txt
echo "what is my address"
# get the address of my computer
MY_PUBLIC_IP=$(curl http://checkip.amazonaws.com)
echo "what is my cidr"
# add 32 bit mask to my address, making it a legal CIDR address
MY_CIDR=${MY_PUBLIC_IP}/32
echo "security group modify"
# allow incoming traffic on port 80, add rule to security group, I also want to be able to connect to port 22
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 8080 --cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 8080 --cidr ${MY_CIDR}
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 80 --cidr ${MY_CIDR}
# open for ssh
echo "open for ssh"
aws ec2 authorize-security-group-ingress --group-name ${SECURITY_GROUP_NAME} --protocol tcp --port 22 --cidr ${MY_CIDR}
<file_sep>#!/bin/bash
# runs docker host, starts both postgres database and application
# <NAME> - 2017
# <EMAIL> / <EMAIL>
set -e
sleep 10
npm run migratedb
node run.js
exit 0
| 1cc3a5834920b6081250bcf564224c0917ecdf56 | [
"Markdown",
"Shell"
] | 9 | Markdown | elmaratlason/week2 | 507c2909c234324fe8578704028d24c6dc769a8e | 58812ede0c095df74a7dfb776cae6bf08bd8c591 |
refs/heads/master | <file_sep>arthurius
=========
Silly game with shuriken shooting goblins, a shuriken shooting old comic, and a prince with a quest.
<file_sep>package gameframework.base;
public interface MoveStrategy {
SpeedVector getSpeedVector(Movable m);
}
<file_sep>package gameframework.game;
import java.awt.Graphics;
import java.awt.Point;
/**
* Manage sprite libraries by displaying the right sprite based on a set of
* types and an increment for the animation.
*/
public interface SpriteManager {
/**
* Set the different types that the entity being displayed can have. The
* types order must be the same as the one in the picture. For example, if
* in the picture the first row represents the entity going to the left and
* the second row represents the entity going to the right, you would call:
* <code>setTypes("left","right")</code>
*/
void setTypes(String... types);
/**
* Set the current type the entity has. Throws an
* {@link IllegalArgumentException} if the type is not in the types list as
* set using {@link #setTypes(String...)}.
*
* @param type
*/
void setType(String type);
/**
* Draw the sprite at the given position. Uses the current type and
* increment to choose the right sprite to display.
*
* @see #increment()
* @see #setType(String)
*/
void draw(Graphics g, Point position);
/**
* Go to the next sprite in the animation without changing the type.
*/
void increment();
/**
* Sets the increment to 0.
*/
void reset();
/**
* Manually set the increment. You won't need that most of the time and will
* only require {@link #increment()}.
*
* @see #increment()
*/
void setIncrement(int increment);
/**
* Cancel the next drawing of the sprite, if the sprite has not already blinked.
*/
void blink();
}
<file_sep>package gameplay;
import characters.Goblin;
import gameframework.game.IllegalMoveException;
import gameframework.game.MoveBlockerRulesApplierDefaultImpl;
public class MoveBlockers extends MoveBlockerRulesApplierDefaultImpl {
public void moveBlockerRule(Goblin g, Wall w) throws IllegalMoveException {
if (g.isActive()) {
throw new IllegalMoveException();
}
}
public void moveBlockerRule(Projectile p, Wall w) throws IllegalMoveException {
p.stop();
}
}
<file_sep>package levels;
import gameframework.base.MoveStrategyKeyboard;
import gameframework.base.MoveStrategyStraightLine;
import gameframework.game.CanvasDefaultImpl;
import gameframework.game.Game;
import gameframework.game.GameLevelDefaultImpl;
import gameframework.game.GameMovableDriverDefaultImpl;
import gameframework.game.GameUniverseDefaultImpl;
import gameframework.game.GameUniverseViewPortDefaultImpl;
import gameframework.game.MoveBlockerChecker;
import gameframework.game.MoveBlockerCheckerDefaultImpl;
import gameframework.game.OverlapProcessor;
import gameframework.game.OverlapProcessorDefaultImpl;
import gameplay.Boots;
import gameplay.Door;
import gameplay.MoveBlockers;
import gameplay.Mud;
import gameplay.OverlapRules;
import gameplay.Projectile;
import gameplay.Shooter;
import gameplay.SuperCandy;
import gameplay.Sword;
import gameplay.TeleportPairOfPoints;
import gameplay.Wall;
import gameplay.Water;
import java.awt.Canvas;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import characters.Arthurius;
import characters.Wizard;
import characters.Goblin;
import utils.Observer;
public class GameLevelThree extends GameLevelDefaultImpl implements Observer<Shooter> {
Canvas canvas;
// 0 : Botte; 1 : Walls; 2 : SuperPacgums; 3 : Doors; 4 : Jail; 5 : empty
// 6: Mud 7:Water 8:Door 10: sword
// Note: teleportation points are not indicated since they are defined by
// directed pairs of positions.
static int[][] tab = {
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, 1, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,10, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
public static final int SPRITE_SIZE = 16;
public static int NUMBER_OF_GOBLINS = 8;
protected Vector<Goblin> vG = new Vector<Goblin>();
protected Arthurius _Arthurius;
protected static MoveBlockerChecker moveBlockerChecker = new MoveBlockerCheckerDefaultImpl();
private OverlapRules r;
@Override
protected void init() {
OverlapProcessor overlapProcessor = new OverlapProcessorDefaultImpl();
moveBlockerChecker.setMoveBlockerRules(new MoveBlockers());
OverlapRules overlapRules = new OverlapRules(new Point(14 * SPRITE_SIZE, 17 * SPRITE_SIZE),
new Point(14 * SPRITE_SIZE, 15 * SPRITE_SIZE), life[0], score[0],stuff, levelCompleted, gameOver);
overlapProcessor.setOverlapRules(overlapRules);
universe = new GameUniverseDefaultImpl(moveBlockerChecker, overlapProcessor);
overlapRules.setUniverse(universe);
gameBoard = new GameUniverseViewPortDefaultImpl(canvas, universe);
((CanvasDefaultImpl) canvas).setDrawingGameBoard(gameBoard);
r = overlapRules;
int totalNbGums = 0;
// Filling up the universe with basic non movable entities and inclusion in the universe
for (int i = 0; i < 31; ++i) {
for (int j = 0; j < 28; ++j) {
if (tab[i][j] == 0) {
universe.addGameEntity(new Boots(canvas, new Point(j * SPRITE_SIZE, i * SPRITE_SIZE)));
totalNbGums++;
}
if (tab[i][j] == 1) {
universe.addGameEntity(new Wall(canvas, j * SPRITE_SIZE, i * SPRITE_SIZE));
}
if (tab[i][j] == 2) {
universe.addGameEntity(new SuperCandy(canvas, new Point(j * SPRITE_SIZE, i * SPRITE_SIZE)));
totalNbGums++;
}
if (tab[i][j] == 10) {
universe.addGameEntity(new Sword(canvas, new Point(j * SPRITE_SIZE, i * SPRITE_SIZE)));
}
if (tab[i][j] == 6) {
universe.addGameEntity(new Mud(canvas, new Point(j * SPRITE_SIZE, i * SPRITE_SIZE)));
totalNbGums++;
}
if (tab[i][j] == 7) {
universe.addGameEntity(new Water(canvas, j * SPRITE_SIZE, i * SPRITE_SIZE));
}
if (tab[i][j] == 8) {
universe.addGameEntity(new Door(canvas, new Point(j * SPRITE_SIZE, i * SPRITE_SIZE)));
totalNbGums++;
}
}
}
overlapRules.setTotalNbGums(totalNbGums);
// Two teleport points definition and inclusion in the universe
// (west side to east side)
universe.addGameEntity(new TeleportPairOfPoints(new Point(0 * SPRITE_SIZE, 14 * SPRITE_SIZE), new Point(
25 * SPRITE_SIZE, 14 * SPRITE_SIZE)));
// (east side to west side)
universe.addGameEntity(new TeleportPairOfPoints(new Point(27 * SPRITE_SIZE, 14 * SPRITE_SIZE), new Point(
2 * SPRITE_SIZE, 14 * SPRITE_SIZE)));
_Arthurius = Arthurius.getInstance(canvas);
GameMovableDriverDefaultImpl arthDriver = new GameMovableDriverDefaultImpl();
MoveStrategyKeyboard keyStr = new MoveStrategyKeyboard();
arthDriver.setStrategy(keyStr);
arthDriver.setmoveBlockerChecker(moveBlockerChecker);
canvas.addKeyListener(keyStr);
_Arthurius.setDriver(arthDriver);
_Arthurius.setPosition(new Point(1 * SPRITE_SIZE, 1 * SPRITE_SIZE));
universe.addGameEntity(_Arthurius);
//Wizard time
Wizard greatWizard;
greatWizard = new Wizard(canvas);
greatWizard.setPosition( new Point(10 * SPRITE_SIZE,10 * SPRITE_SIZE));
greatWizard.setFireDirection( new Point( 9 * SPRITE_SIZE, 9 * SPRITE_SIZE));
greatWizard.register(this);
universe.addGameEntity(greatWizard);
overlapRules.addBoss(greatWizard);
//...and his goblin buddies
List<Point> goblinsPos = new ArrayList<Point>();
goblinsPos.add(new Point( 5 * SPRITE_SIZE, 6 * SPRITE_SIZE));
goblinsPos.add(new Point( 6 * SPRITE_SIZE, 5 * SPRITE_SIZE));
goblinsPos.add(new Point( 5 * SPRITE_SIZE,19 * SPRITE_SIZE));
goblinsPos.add(new Point( 6 * SPRITE_SIZE,20 * SPRITE_SIZE));
goblinsPos.add(new Point(19 * SPRITE_SIZE, 5 * SPRITE_SIZE));
goblinsPos.add(new Point(20 * SPRITE_SIZE, 6 * SPRITE_SIZE));
goblinsPos.add(new Point(19 * SPRITE_SIZE,20 * SPRITE_SIZE));
goblinsPos.add(new Point(20 * SPRITE_SIZE,19 * SPRITE_SIZE));
List<Point>goblinsFire = new ArrayList<Point>();
int[][] fireDirs = new int[][] {
{ 0, 1}, //down
{ 1, 0}, //right
{ 0,-1}, //up
{ 1, 0}, //right
{-1, 0}, //left
{ 0, 1}, //down
{-1, 0}, //left
{ 0,-1} //up
};
int index = 0;
for(Point pos : goblinsPos){
goblinsFire.add((Point) pos.clone());
goblinsFire.get(goblinsFire.size()-1)
.translate(fireDirs[index][0], fireDirs[index][1]);
index++;
}
// Goblin myGoblin;
// for (int t = 0; t < NUMBER_OF_GOBLINS; ++t) {
// myGoblin = new Goblin(canvas);
// myGoblin.setPosition(goblinsPos.get(t));
// myGoblin.setFireDirection(goblinsFire.get(t));
// myGoblin.register(this);
// universe.addGameEntity(myGoblin);
// (overlapRules).addGoblin(myGoblin);
// }
}
public GameLevelThree(Game g) {
super(g);
canvas = g.getCanvas();
}
//Créer un projectile quand un Shooter tire
@Override
public void update(Shooter shooter) {
if(shooter instanceof Goblin){
System.out.println("Goblin shooting");
GameMovableDriverDefaultImpl pDriv = new GameMovableDriverDefaultImpl();
MoveStrategyStraightLine strat = new MoveStrategyStraightLine(shooter.getPosition(), shooter.getFireDirection());
moveBlockerChecker.setMoveBlockerRules(new MoveBlockers());
pDriv.setStrategy(strat);
pDriv.setmoveBlockerChecker(moveBlockerChecker);
Projectile p = new Projectile(canvas, shooter);
p.setDriver(pDriv);
p.setPosition(shooter.getPosition());
universe.addGameEntity(p);
}
else if(shooter instanceof Wizard){
GameMovableDriverDefaultImpl projectileDriver = new GameMovableDriverDefaultImpl();
MoveStrategyStraightLine strat = new MoveStrategyStraightLine(shooter.getPosition(), _Arthurius.getPosition());
moveBlockerChecker.setMoveBlockerRules(new MoveBlockers());
projectileDriver.setStrategy(strat);
projectileDriver.setmoveBlockerChecker(moveBlockerChecker);
Projectile projectile = new Projectile(canvas, shooter);
projectile.setDriver(projectileDriver);
projectile.setPosition(shooter.getPosition());
universe.addGameEntity(projectile);
// System.out.println("Wizard shooting at: " +shooter.getFireDirection().getX()+";"+shooter.getFireDirection().getY());
}
}
}
<file_sep>package gameplay;
import gameframework.base.Drawable;
import gameframework.base.DrawableImage;
import gameframework.base.Overlappable;
import gameframework.game.GameEntity;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
public class Sword implements Drawable, GameEntity, Overlappable {
protected static DrawableImage image = null;
protected Point position;
public static final int RENDERING_SIZE = 50;
public Sword(Canvas defaultCanvas, Point pos) {
image = new DrawableImage("images/sword.png", defaultCanvas);
position = pos;
}
public Point getPosition() {
return position;
}
public void draw(Graphics g) {
g.drawImage(image.getImage(), (int) getPosition().getX(),
(int) getPosition().getY(), RENDERING_SIZE, RENDERING_SIZE,
null);
}
public Rectangle getBoundingBox() {
return (new Rectangle((int) position.getX(), (int) position.getY(),
RENDERING_SIZE, RENDERING_SIZE));
}
}
<file_sep>package levels;
import gameframework.base.MoveStrategyKeyboard;
import gameframework.base.MoveStrategyStraightLine;
import gameframework.game.CanvasDefaultImpl;
import gameframework.game.Game;
import gameframework.game.GameLevelDefaultImpl;
import gameframework.game.GameMovableDriverDefaultImpl;
import gameframework.game.GameUniverseDefaultImpl;
import gameframework.game.GameUniverseViewPortDefaultImpl;
import gameframework.game.MoveBlockerChecker;
import gameframework.game.MoveBlockerCheckerDefaultImpl;
import gameframework.game.OverlapProcessor;
import gameframework.game.OverlapProcessorDefaultImpl;
import gameplay.Boots;
import gameplay.Door;
import gameplay.Jail;
import gameplay.MoveBlockers;
import gameplay.Mud;
import gameplay.OverlapRules;
import gameplay.Projectile;
import gameplay.Shooter;
import gameplay.SuperCandy;
import gameplay.Wall;
import gameplay.Water;
import java.awt.Canvas;
import java.awt.Point;
import java.util.ArrayList;
import characters.Arthurius;
import characters.Goblin;
import utils.Observer;
public class GameLevelTwo extends GameLevelDefaultImpl implements Observer<Shooter> {
Canvas canvas;
// 0 : Botte; 1 : Walls; 2 : SuperPacgums; 3 : Doors; 4 : Jail; 5 : empty 6: Mud 7:Water 8:Door
// Note: teleportation points are not indicated since they are defined by
// directed pairs of positions.
static int[][] tab = {
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 8, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 1, 5, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 },
{ 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 2, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
public static final int SPRITE_SIZE = 16;
public static final int NUMBER_OF_GOBLINS = 5;
protected Arthurius _Arthurius;
protected static MoveBlockerChecker moveBlockerChecker = new MoveBlockerCheckerDefaultImpl();
@Override
protected void init() {
OverlapProcessor overlapProcessor = new OverlapProcessorDefaultImpl();
moveBlockerChecker.setMoveBlockerRules(new MoveBlockers());
OverlapRules overlapRules = new OverlapRules(new Point(14 * SPRITE_SIZE, 17 * SPRITE_SIZE),
new Point(14 * SPRITE_SIZE, 15 * SPRITE_SIZE), life[0], score[0],stuff, levelCompleted, gameOver);
overlapProcessor.setOverlapRules(overlapRules);
universe = new GameUniverseDefaultImpl(moveBlockerChecker, overlapProcessor);
overlapRules.setUniverse(universe);
gameBoard = new GameUniverseViewPortDefaultImpl(canvas, universe);
((CanvasDefaultImpl) canvas).setDrawingGameBoard(gameBoard);
int totalNbGums = 0;
// Filling up the universe with basic non movable entities and inclusion in the universe
for (int i = 0; i < 31; ++i) {
for (int j = 0; j < 28; ++j) {
if (tab[i][j] == 0) {
universe.addGameEntity(new Boots(canvas, new Point(j * SPRITE_SIZE, i * SPRITE_SIZE)));
totalNbGums++;
}
if (tab[i][j] == 1) {
universe.addGameEntity(new Wall(canvas, j * SPRITE_SIZE, i * SPRITE_SIZE));
}
if (tab[i][j] == 2) {
universe.addGameEntity(new SuperCandy(canvas, new Point(j * SPRITE_SIZE, i * SPRITE_SIZE)));
totalNbGums++;
}
if (tab[i][j] == 4) {
universe.addGameEntity(new Jail(new Point(j * SPRITE_SIZE, i * SPRITE_SIZE)));
}
if (tab[i][j] == 6) {
universe.addGameEntity(new Mud(canvas, new Point(j * SPRITE_SIZE, i * SPRITE_SIZE)));
totalNbGums++;
}
if (tab[i][j] == 7) {
universe.addGameEntity(new Water(canvas, j * SPRITE_SIZE, i * SPRITE_SIZE));
}
if (tab[i][j] == 8) {
universe.addGameEntity(new Door(canvas, new Point(j * SPRITE_SIZE, i * SPRITE_SIZE)));
totalNbGums++;
}
}
}
overlapRules.setTotalNbGums(totalNbGums);
// Two teleport points definition and inclusion in the universe
// (west side to east side)
//universe.addGameEntity(new TeleportPairOfPoints(new Point(0 * SPRITE_SIZE, 14 * SPRITE_SIZE), new Point(
// 25 * SPRITE_SIZE, 14 * SPRITE_SIZE)));
// (east side to west side)
//universe.addGameEntity(new TeleportPairOfPoints(new Point(27 * SPRITE_SIZE, 14 * SPRITE_SIZE), new Point(
// 2 * SPRITE_SIZE, 14 * SPRITE_SIZE)));
// Pacman definition and inclusion in the universe
_Arthurius = Arthurius.getInstance(canvas);
GameMovableDriverDefaultImpl arthDriver = new GameMovableDriverDefaultImpl();
MoveStrategyKeyboard keyStr = new MoveStrategyKeyboard();
arthDriver.setStrategy(keyStr);
arthDriver.setmoveBlockerChecker(moveBlockerChecker);
canvas.addKeyListener(keyStr);
_Arthurius.setDriver(arthDriver);
_Arthurius.setPosition(new Point(1 * SPRITE_SIZE, 1 * SPRITE_SIZE));
universe.addGameEntity(_Arthurius);
//Goblins time !
ArrayList<Point> goblinsPos = new ArrayList<Point>();
goblinsPos.add(new Point(25 * SPRITE_SIZE, 5 * SPRITE_SIZE));
goblinsPos.add(new Point(25 * SPRITE_SIZE,10 * SPRITE_SIZE));
goblinsPos.add(new Point(25 * SPRITE_SIZE,15 * SPRITE_SIZE));
goblinsPos.add(new Point(25 * SPRITE_SIZE,20 * SPRITE_SIZE));
goblinsPos.add(new Point(25 * SPRITE_SIZE,25 * SPRITE_SIZE));
ArrayList<Point>goblinsFire = new ArrayList<Point>();
goblinsFire.add(new Point(24 * SPRITE_SIZE, 5 * SPRITE_SIZE));
goblinsFire.add(new Point(24 * SPRITE_SIZE,10 * SPRITE_SIZE));
goblinsFire.add(new Point(24 * SPRITE_SIZE,15 * SPRITE_SIZE));
goblinsFire.add(new Point(24 * SPRITE_SIZE,20 * SPRITE_SIZE));
goblinsFire.add(new Point(24 * SPRITE_SIZE,25 * SPRITE_SIZE));
Goblin myGoblin;
for (int t = 0; t < NUMBER_OF_GOBLINS; ++t) {
myGoblin = new Goblin(canvas);
myGoblin.setPosition(goblinsPos.get(t));
myGoblin.setFireDirection(goblinsFire.get(t));
myGoblin.register(this);
universe.addGameEntity(myGoblin);
(overlapRules).addGoblin(myGoblin);
}
}
public GameLevelTwo(Game g) {
super(g);
canvas = g.getCanvas();
}
//Créer un projectile quand un Shooter tire
@Override
public void update(Shooter s) {
GameMovableDriverDefaultImpl pDriv = new GameMovableDriverDefaultImpl();
MoveStrategyStraightLine strat = new MoveStrategyStraightLine(s.getPosition(), s.getFireDirection());
moveBlockerChecker.setMoveBlockerRules(new MoveBlockers());
pDriv.setStrategy(strat);
pDriv.setmoveBlockerChecker(moveBlockerChecker);
Projectile p = new Projectile(canvas, s);
p.setDriver(pDriv);
p.setPosition(s.getPosition());
universe.addGameEntity(p);
}
}
<file_sep>package gameplay;
import gameframework.base.Overlappable;
import gameframework.game.GameEntity;
import java.awt.Point;
import java.awt.Rectangle;
public class TeleportPairOfPoints implements GameEntity, Overlappable {
public static final int RENDERING_SIZE = 16;
protected Point position;
protected Point destination;
public TeleportPairOfPoints(Point pos, Point destination) {
position = pos;
this.destination = destination;
}
public Point getDestination() {
return destination;
}
public Point getPosition() {
return position;
}
public Rectangle getBoundingBox() {
return (new Rectangle((int) position.getX(), (int) position.getY(),
RENDERING_SIZE, RENDERING_SIZE));
}
}<file_sep>package gameplay;
import java.awt.Point;
import characters.Arthurius;
import utils.Observer;
import gameframework.base.Movable;
import gameframework.base.SpeedVector;
import gameframework.base.SpeedVectorDefaultImpl;
import gameframework.game.GameMovableDriverDefaultImpl;
public class GoblinMovableDriver extends GameMovableDriverDefaultImpl implements Observer<Arthurius> {
private static Point target;
private static boolean arthuriusFound = false;
@Override
public SpeedVector getSpeedVector(Movable m) {
//SpeedVector currentSpeedVector;
//currentSpeedVector = m.getSpeedVector();
if(arthuriusFound){
//Double distance = m.getPosition().distance(target);
SpeedVector escapeSVector = new SpeedVectorDefaultImpl(target, 1);
return escapeSVector;
}
return m.getSpeedVector();
}
@Override
public void update(Arthurius s) {
target = s.getPosition();
arthuriusFound = true;
}
}<file_sep>package gameframework.game;
import gameframework.base.ObservableValue;
import java.util.Date;
/**
* To be implemented with respect to a specific game. Expected to initialize the
* universe and the gameBoard
*/
public abstract class GameLevelDefaultImpl extends Thread implements GameLevel {
private static final int MINIMUM_DELAY_BETWEEN_GAME_CYCLES = 75;
protected GameUniverse universe;
protected GameUniverseViewPort gameBoard;
protected ObservableValue<Integer> score[];
protected ObservableValue<Integer> life[];
protected ObservableValue<String> stuff[];
protected ObservableValue<Boolean> levelCompleted;
protected ObservableValue<Boolean> gameOver;
boolean pauseGameLoop;
protected final Game g;
private Thread levelThread;
protected abstract void init();
public GameLevelDefaultImpl(Game g) {
this.g = g;
this.score = g.score();
this.life = g.life();
this.stuff=g.stuff();
}
@Override
public void start() {
levelCompleted = g.levelCompleted();
gameOver = g.gameOver();
levelCompleted.setValue(false);
gameOver.setValue(false);
init();
levelThread = new Thread(this);
levelThread.start();
try {
levelThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void reset() {
init();
}
@Override
public void run() {
Thread thisThread = Thread.currentThread();
pauseGameLoop = false;
// main game loop :
long start;
while (thisThread == levelThread && !this.isInterrupted()) {
start = new Date().getTime();
if(!pauseGameLoop){
gameBoard.paint();
universe.allOneStepMoves();
universe.processAllOverlaps();
}
try {
long sleepTime = MINIMUM_DELAY_BETWEEN_GAME_CYCLES
- (new Date().getTime() - start);
if (sleepTime > 0) {
Thread.sleep(sleepTime);
}
} catch (Exception e) {
}
}
}
public void end() {
levelThread = null;
}
public void pause() {
pauseGameLoop = true;
gameBoard.display("PAUSE", 25, 50);
}
public void unpause() {
pauseGameLoop = false;
}
protected void overlap_handler() {
}
}
<file_sep>package gameframework.game;
import gameframework.base.ObservableValue;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Frame;
import java.awt.GridBagLayout;
import java.awt.Label;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
/**
* Create a basic game application with menus and displays of lives and score
*/
public class GameDefaultImpl implements Game, Observer {
protected static final int NB_ROWS = 31;
protected static final int NB_COLUMNS = 28;
protected static final int SPRITE_SIZE = 16;
public static final int MAX_NUMBER_OF_PLAYER = 4;
public static final int NUMBER_OF_LIVES = 5;
protected CanvasDefaultImpl defaultCanvas = null;
protected ObservableValue<Integer> score[] = new ObservableValue[MAX_NUMBER_OF_PLAYER];
protected ObservableValue<Integer> life[] = new ObservableValue[MAX_NUMBER_OF_PLAYER];
protected ObservableValue<String> stuff[] = new ObservableValue[4];
// initialized before each level
protected ObservableValue<Boolean> levelCompleted = null;
protected ObservableValue<Boolean> gameOver = null;
private Frame f;
private GameLevelDefaultImpl currentPlayedLevel = null;
protected int levelNumber;
protected ArrayList<GameLevel> gameLevels;
protected Label stuffText;
protected Label epeeT;
protected Label lifeText, scoreText;
protected Label information;
protected Label informationValue;
protected Label lifeValue, scoreValue;
protected Label currentLevel;
protected Label currentLevelValue;
public GameDefaultImpl() {
for (int i = 0; i < MAX_NUMBER_OF_PLAYER; ++i) {
score[i] = new ObservableValue<Integer>(0);
life[i] = new ObservableValue<Integer>(0);
}
for (int i = 0; i < 4; ++i) {
stuff[i]= new ObservableValue<String>("Vide");
}
lifeText = new Label("Lives:");
scoreText = new Label("Score:");
information = new Label("State:");
informationValue = new Label("Loading");
currentLevel = new Label("Level:");
createGUI();
}
public void createGUI() {
f = new Frame("La quête d'Arthurius");
f.dispose();
f.setBackground(Color.BLACK);
createMenuBar();
Container c = createStatusBar();
Container s= createStuffBorder();
defaultCanvas = new CanvasDefaultImpl();
defaultCanvas.setSize(SPRITE_SIZE * NB_COLUMNS, SPRITE_SIZE * NB_ROWS);
f.add(defaultCanvas);
f.add(c, BorderLayout.NORTH);
f.add(s, BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private void createMenuBar() {
MenuBar menuBar = new MenuBar();
Menu file = new Menu("file");
MenuItem start = new MenuItem("new game");
MenuItem restartlevel = new MenuItem("restart level");
MenuItem save = new MenuItem("save");
MenuItem restore = new MenuItem("load");
MenuItem quit = new MenuItem("quit");
Menu game = new Menu("game");
MenuItem pause = new MenuItem("pause");
MenuItem resume = new MenuItem("resume");
menuBar.add(file);
menuBar.add(game);
f.setMenuBar(menuBar);
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start();
}
});
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
save();
}
});
restartlevel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
restartLevel();
}
});
restore.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
restore();
}
});
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pause.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pause();
}
});
resume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resume();
}
});
file.add(start);
file.add(restartlevel);
file.add(save);
file.add(restore);
file.add(quit);
game.add(pause);
game.add(resume);
}
private Container createStuffBorder() {
JPanel Stuff = new JPanel();
Stuff.setBackground(Color.WHITE);
BoxLayout layout = new BoxLayout(Stuff,0);
Stuff.setLayout(layout);
Label titre=new Label("Equipement:");
Stuff.add(titre);
stuffText = new Label(stuff[0].getValue());
Stuff.add(stuffText);
epeeT = new Label (stuff[1].getValue());
Stuff.add(epeeT);
for(int i=2;i<MAX_NUMBER_OF_PLAYER;i++){
Label st = new Label(stuff[i].getValue());
Stuff.add(st);
}
return Stuff;
}
private Container createStatusBar() {
JPanel c = new JPanel();
c.setBackground(Color.WHITE);
GridBagLayout layout = new GridBagLayout();
c.setLayout(layout);
lifeValue = new Label(Integer.toString(life[0].getValue()));
scoreValue = new Label(Integer.toString(score[0].getValue()));
currentLevelValue = new Label(Integer.toString(levelNumber));
c.add(lifeText);
c.add(lifeValue);
c.add(scoreText);
c.add(scoreValue);
c.add(currentLevel);
c.add(currentLevelValue);
c.add(information);
c.add(informationValue);
return c;
}
public Canvas getCanvas() {
return defaultCanvas;
}
public void start() {
for (int i = 0; i < MAX_NUMBER_OF_PLAYER; ++i) {
score[i].addObserver(this);
life[i].addObserver(this);
life[i].setValue(NUMBER_OF_LIVES);
score[i].setValue(0);
}
for (int i = 0; i < 4; ++i) {
stuff[i].addObserver(this);
stuff[i].setValue("Vide");
}
levelNumber = 0;
levelCompleted = new ObservableValue<Boolean>(false);
levelCompleted.addObserver(this);
gameOver = new ObservableValue<Boolean>(false);
gameOver.addObserver(this);
while(true){
try {
if (currentPlayedLevel != null && currentPlayedLevel.isAlive()) {
currentPlayedLevel.interrupt();
currentPlayedLevel = null;
}
currentPlayedLevel = (GameLevelDefaultImpl) gameLevels.get(levelNumber);
levelNumber++;
informationValue.setText("Playing");
currentLevelValue.setText(Integer.toString(levelNumber));
currentPlayedLevel.start();
currentPlayedLevel.join();
} catch (Exception e) {
System.out.println("Exception in main game loop !");
e.printStackTrace();
return;
}
}
}
public void restore() {
System.out.println("restore(): Unimplemented operation");
}
public void restartLevel(){
currentPlayedLevel.init();
}
public void save() {
System.out.println("save(): Unimplemented operation");
}
public void pause() {
currentPlayedLevel.pause();
}
public void resume() {
currentPlayedLevel.unpause();
}
public ObservableValue<Integer>[] score() {
return score;
}
public ObservableValue<Integer>[] life() {
return life;
}
public ObservableValue<Boolean> levelCompleted() {
return levelCompleted;
}
public ObservableValue<Boolean> gameOver() {
return gameOver;
}
public void setLevels(ArrayList<GameLevel> levels) {
gameLevels = levels;
}
public void update(Observable o, Object arg) {
if (o == levelCompleted) {
if (levelCompleted.getValue()) {
informationValue.setText(":D");
try {
//TODO: replace by a more explicit countdown
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentPlayedLevel.interrupt();
currentPlayedLevel.end();
}
} else if (o == gameOver) {
if (gameOver.getValue()) {
informationValue.setText("Nooo :'(");
try {
//TODO: replace by a more explicit countdown
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(gameOver.getValue()){
for(ObservableValue<Integer> lifeCharacter : life)
lifeCharacter.setValue(NUMBER_OF_LIVES);
levelNumber = 0;
}
currentPlayedLevel.interrupt();
currentPlayedLevel.end();
}
else
informationValue.setText("Playing");
} else {
for (ObservableValue<Integer> lifeObservable : life) {
if (o == lifeObservable) {
int lives = ((ObservableValue<Integer>) o).getValue();
lifeValue.setText(Integer.toString(lives));
if (lives == 0) {
gameOver.setValue(true);
}
}
}
for (ObservableValue<Integer> scoreObservable : score) {
if (o == scoreObservable) {
scoreValue
.setText(Integer
.toString(((ObservableValue<Integer>) o)
.getValue()));
}
}
for (ObservableValue<String> stuffObservable : stuff) {
if (o == stuffObservable) {
String t = (((ObservableValue<String>) o).getValue());
if(t == "Bottes")
stuffText.setText(t);
if(t=="Epee")
epeeT.setText(t);
}
}
}
}
@Override
public ObservableValue<String>[] stuff() {
return stuff;
}
}
<file_sep>package characters;
import gameframework.base.Drawable;
import gameframework.base.DrawableImage;
import gameframework.base.Overlappable;
import gameframework.game.GameEntity;
import gameframework.game.SpriteManagerDefaultImpl;
import gameplay.Shooter;
import gameplay.GameMovableUnique;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import utils.Observer;
public class Goblin extends GameMovableUnique implements Drawable, GameEntity,
Overlappable, Shooter {
protected static DrawableImage image = null;
protected boolean movable = true;
protected int afraidTimer = 0;
protected int maxAfraidTimer = 0;
public int shootTimer = 0;
protected boolean active = true;
private final SpriteManagerDefaultImpl spriteManager;
public static final int RENDERING_SIZE = 32;
public static int SHOOT_INTERVAL = 15;
protected Point fireDirection = null;
private Observer<Shooter> levelObserver;
public Goblin(Canvas defaultCanvas) {
spriteManager = new SpriteManagerDefaultImpl("images/goblin.gif",
defaultCanvas, RENDERING_SIZE, 6);
spriteManager.setTypes(
//
"left",
"right",
"up",
"down",//
"beginAfraid-left",
"beginAfraid-right",
"beginAfraid-up",
"beginAfraid-down", //
"endAfraid-left", "endAfraid-right",
"endAfraid-up",
"endAfraid-down", //
"inactive-left", "inactive-right", "inactive-up",
"inactive-down", //
"unused");
}
public boolean isAfraid() {
return afraidTimer > 0;
}
public void setAfraid(int timer) {
maxAfraidTimer = afraidTimer = timer;
}
public boolean isActive() {
return active;
}
public void setAlive(boolean aliveState) {
active = aliveState;
}
public void draw(Graphics g) {
String spriteType = "";
Point pos = getPosition();
Point target = getFireDirection();
movable = true;
if (!isActive()) {
spriteType = "inactive-";
} else if (afraidTimer > maxAfraidTimer / 2) {
spriteType = "beginAfraid-";
} else if (isAfraid()) {
spriteType = "endAfraid-";
}
if (target.getX() < pos.getX()) {
spriteType += "left";
} else if (target.getX() > pos.getX()) {
spriteType += "right";
} else if (target.getY() < pos.getY()) {
spriteType += "up";
} else {
spriteType += "down";
}
spriteManager.setType(spriteType);
spriteManager.draw(g, getPosition());
}
@Override
public void oneStepMoveAddedBehavior() {
if(isAfraid()) afraidTimer--;
else shoot();
spriteManager.increment();
}
public Rectangle getBoundingBox() {
return (new Rectangle(0, 0, RENDERING_SIZE, RENDERING_SIZE));
}
public void shoot() {
if(shootTimer > 0) shootTimer--;
else {
notify(this);
shootTimer = SHOOT_INTERVAL;
}
}
@Override
public Point getFireDirection() {
return fireDirection;
}
@Override
public void setFireDirection(Point p) {
fireDirection = p;
}
public void register(Observer<Shooter> ob) {
levelObserver = ob;
}
@Override
public void unregister(Observer<Shooter> ob) {
levelObserver = ob;
}
@Override
public void notify(Shooter s) {
levelObserver.update(this);
}
}
<file_sep>
import gameframework.game.GameLevel;
import gameplay.ArthuriusTheGame;
import java.util.ArrayList;
import levels.*;
public class Main {
public static void main(String[] args) {
ArthuriusTheGame g = new ArthuriusTheGame();
ArrayList<GameLevel> levels = new ArrayList<GameLevel>();
levels.add(new GameLevelOne(g));
levels.add(new GameLevelTwo(g));
levels.add(new GameLevelThree(g));
g.setLevels(levels);
g.createIntro();
g.start();
}
}
<file_sep>package gameplay;
import gameframework.base.ObservableValue;
import gameframework.base.MoveStrategyRandom;
import gameframework.base.Overlap;
import gameframework.base.Overlappable;
import gameframework.game.GameEntity;
import gameframework.game.GameMovableDriverDefaultImpl;
import gameframework.game.GameUniverse;
import gameframework.game.OverlapRulesApplierDefaultImpl;
import java.awt.Point;
import java.util.Vector;
import characters.Arthurius;
import characters.Wizard;
import characters.Goblin;
public class OverlapRules extends OverlapRulesApplierDefaultImpl {
protected GameUniverse universe;
protected Vector<Goblin> vGoblins = new Vector<Goblin>();
protected GameEntity boss;
// Time duration during which pacman is invulnerable and during which ghosts
// can be eaten (in number of cycles)
static final int INVULNERABLE_DURATION = 10;
static final int BERZERK_DURATION = 20;
static final int REPULSION_SHIFT_MUD = 5;
static final int REPULSION_SHIFT_ENEMY = 20;
protected Point pacManStartPos;
protected Point ghostStartPos;
protected boolean manageHeroDeath;
private final ObservableValue<Integer> score;
private final ObservableValue<Integer> life;
private final ObservableValue<Boolean> levelCompleted;
private final ObservableValue<Boolean> gameOver;
private int totalNbGums = 0;
private int nbEatenGums = 0;
private ObservableValue<String>[] stuff;
public OverlapRules(Point pacPos, Point gPos,
ObservableValue<Integer> life, ObservableValue<Integer> score,
ObservableValue<String>[] stuff, ObservableValue<Boolean> endOfGame,
ObservableValue<Boolean> gameOver) {
pacManStartPos = (Point) pacPos.clone();
ghostStartPos = (Point) gPos.clone();
this.life = life;
this.score = score;
this.levelCompleted = endOfGame;
this.gameOver = gameOver;
this.stuff = stuff;
}
public void setUniverse(GameUniverse universe) {
this.universe = universe;
}
public void setTotalNbGums(int totalNbGums) {
this.totalNbGums = totalNbGums;
}
public void addGoblin(Goblin g) {
vGoblins.addElement(g);
}
public void addBoss(Wizard w) {
boss = w;
}
public void applyOverlapRules(Vector<Overlap> overlappables) {
manageHeroDeath = true;
super.applyOverlapRules(overlappables);
}
public void overlapRule(Arthurius arthurius, Goblin g) {
repulseHeroHandler(arthurius, g, REPULSION_SHIFT_ENEMY);
if (arthurius.isVulnerable()) {
heroHurtHandler(arthurius);
}
}
public void overlapRule(Arthurius arthurius, Projectile g) {
if (!arthurius.isVulnerable()) {
universe.removeGameEntity(g);
} else {
heroHurtHandler(arthurius);
}
}
public void overlapRule(Goblin g, SuperCandy spg) {
}
public void overlapRule(Goblin g, Boots spg) {
}
public void overlapRule(Goblin g, TeleportPairOfPoints teleport) {
g.setPosition(teleport.getDestination());
}
public void overlapRule(Arthurius a, TeleportPairOfPoints teleport) {
a.setPosition(teleport.getDestination());
}
public void overlapRule(Goblin g, Jail jail) {
if (!g.isActive()) {
g.setAlive(true);
MoveStrategyRandom strat = new MoveStrategyRandom();
GameMovableDriverDefaultImpl ghostDriv = (GameMovableDriverDefaultImpl) g
.getDriver();
ghostDriv.setStrategy(strat);
g.setPosition(ghostStartPos);
}
}
public void overlapRule(Goblin g, Projectile p) {
if(!g.equals(p.getShooter()))
universe.removeGameEntity(p);
}
public void overlapRule(Arthurius arthurius, SuperCandy spg) {
score.setValue(score.getValue() + 5);
universe.removeGameEntity(spg);
pacgumEatenHandler();
arthurius.setInvulnerable(BERZERK_DURATION);
for (Goblin goblin : vGoblins) {
goblin.setAfraid(BERZERK_DURATION);
}
}
public void overlapRule(Arthurius arthurius, Mud m) {
if(stuff[0].getValue()=="Vide"){
repulseHeroHandler(arthurius, m, REPULSION_SHIFT_MUD);
}
}
public void overlapRule(Arthurius a, Door d) {
levelCompleted.setValue(true);
}
public void overlapRule(Arthurius a, Sword s) {
a.addEquipment("Epee");
stuff[1].setValue("Epee");
universe.removeGameEntity(s);
}
public void overlapRule(Arthurius a, Wizard wizard) {
if(stuff[1].getValue() == "Epee"){
universe.removeGameEntity(wizard);
levelCompleted.setValue(true);
}
}
public void overlapRule(Arthurius a, Boots b) {
a.addEquipment("Bottes");
stuff[0].setValue("Bottes");
universe.removeGameEntity(b);
}
private void pacgumEatenHandler() {
nbEatenGums++;
if (nbEatenGums >= totalNbGums) {
levelCompleted.setValue(true);
}
}
private void heroHurtHandler(Arthurius arthurius){
if (manageHeroDeath) {
life.setValue(life.getValue() - 1);
if(life.getValue() == 0)
gameOver.setValue(true);
else
arthurius.setInvulnerable(INVULNERABLE_DURATION);
manageHeroDeath = false;
}
}
private void repulseHeroHandler(Arthurius arthurius, Overlappable obstacle, int distance){
Point newPosition = new Point(arthurius.getPosition());
Point obstaclePos = obstacle.getPosition();
Point direction = arthurius.getSpeedVector().getDirection();
if(direction.getX() != 0 && direction.getX() != 0)
newPosition.translate((int) direction.getX() * -1, (int) direction.getY() * -1);
else if(direction.getX() != 0)
newPosition.translate((int) direction.getX() * -1, 0);
arthurius.setPosition(newPosition);
}
}
<file_sep>package gameframework.game;
public interface GameLevel extends Runnable{
public void start();
public void reset();
}
<file_sep>package gameplay;
import java.awt.Point;
import utils.Observable;
public interface Shooter extends Observable<Shooter> {
public void shoot();
public Point getPosition();
public Point getFireDirection();
void setFireDirection(Point p);
}
<file_sep>package characters;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import gameframework.base.Drawable;
import gameframework.base.Overlappable;
import gameframework.game.GameEntity;
import gameframework.game.GameMovable;
import gameframework.game.SpriteManager;
import gameframework.game.SpriteManagerDefaultImpl;
import utils.Observable;
import utils.Observer;
import utils.army.AgeFactory;
import utils.army.ArmedUnit;
import utils.army.InfantryMan;
import utils.army.Soldier;
import utils.army.VisitorClassicForArmedUnit;
import utils.army.VisitorFunForArmedUnit;
public class Arthurius extends GameMovable implements Drawable, GameEntity, Overlappable, ArmedUnit, Observable<Arthurius>
{
private static Arthurius _singleton=null;
protected Soldier soldier;
protected List<String> equipments = new ArrayList<String>();
protected final SpriteManager spriteManager;
public static final int RENDERING_SIZE = 32;
protected boolean movable = true;
protected int vulnerableTimer = 0;
private ArrayList<Observer<Arthurius>> observers = new ArrayList<Observer<Arthurius>>();
private Arthurius(String name,Canvas defaultCanvas) {
soldier=new InfantryMan("Arthurius");
spriteManager = new SpriteManagerDefaultImpl("images/pac1.gif",
defaultCanvas, RENDERING_SIZE, 6);
spriteManager.setTypes(
"right",
"left",
"up",
"down",
"static");
}
public static synchronized Arthurius getInstance(Canvas defaultCanvas){
if (_singleton==null)
return new Arthurius("Arthurius",defaultCanvas);
else
return _singleton;
}
public static synchronized Arthurius getInstance() throws Exception{
if (_singleton==null)
throw new Exception("Singleton not yet instantiated");
else
return _singleton;
}
public void setInvulnerable(int timer) {
vulnerableTimer = timer;
}
public boolean isVulnerable() {
return (vulnerableTimer <= 0);
}
public void draw(Graphics g) {
String spriteType = "";
Point tmp = getSpeedVector().getDirection();
movable = true;
// if (!isVulnerable()) {
// spriteType += "invulnerable-";
// }
if (tmp.getX() == 1) {
spriteType += "right";
} else if (tmp.getX() == -1) {
spriteType += "left";
} else if (tmp.getY() == 1) {
spriteType += "down";
} else if (tmp.getY() == -1) {
spriteType += "up";
} else {
spriteType = "static";
spriteManager.reset();
movable = false;
}
spriteManager.setType(spriteType);
spriteManager.draw(g, getPosition());
}
@Override
public void oneStepMoveAddedBehavior() {
if (!isVulnerable()) {
vulnerableTimer--;
spriteManager.blink();
}
if (movable) {
spriteManager.increment();
if(getSpeedVector().getSpeed() > 0)
notify(this);
}
}
public Rectangle getBoundingBox() {
return (new Rectangle(0, 0, RENDERING_SIZE, RENDERING_SIZE));
}
public void addEquipment(String equipmentType) {
if (alive()) { // XXX "else" not treated
if (equipments.contains(equipmentType)) {
return; // decoration not applied
} else {
try {
equipments.add(equipmentType);
} catch (Exception e) {
throw new RuntimeException("Unknown equipment type "
+ e.toString());
}
}
}
}
public String getName() {
return soldier.getName();
}
public float getHealthPoints() {
return soldier.getHealthPoints();
}
public AgeFactory getAge() {
return null;
}
public boolean alive() {
return soldier.alive();
}
public void heal() {
soldier.heal();
}
public float strike() {
return soldier.strike();
}
public boolean parry(float force) {
return soldier.parry(force);
}
public void accept(VisitorClassicForArmedUnit v) {
v.visit(this);
}
public <T> T accept(VisitorFunForArmedUnit<T> v) {
return v.visit(this);
}
//Observable by goblins
@Override
public void register(Observer<Arthurius> ob) {
observers.add(ob);
}
@Override
public void unregister(Observer<Arthurius> ob) {
observers.remove(ob);
}
@Override
public void notify(Arthurius s) {
for(Observer<Arthurius> obs : observers)
obs.update(this);
}
}
| 804da854390b85a34296ea759969ac44082e788a | [
"Markdown",
"Java"
] | 17 | Markdown | grdscrc/arthurius | 4f21e12c7427c1a1e3b30133ab3223e2f277c5c5 | c1b6118cb72401af246e13169216aaaf7c69610e |
refs/heads/master | <file_sep>from models.ptt_user import PttUserModel
import os
import setting
class PttUser():
def __init__(self, id):
self.id = id
self.acc = os.getenv("ptt_acc")
self.pswd = os.getenv("ptt_pswd")
def get(self):
user = PttUserModel(self.id, self.acc, self.pswd).get_user()
if not user:
return {
'errcode': 1,
'message': 'username not exist!'
}, 403
return {
'errcode': 0,
'message':
{
'id': user.getID(),
'money': str(user.getMoney()),
'loginTime': str(user.getLoginTime()),
'legalPost': str(user.getLegalPost()),
'illegalPost': str(user.getIllegalPost()),
'state': user.getState(),
'mail': user.getMail(),
'lastLogin': user.getLastLogin(),
'lastIP': user.getLastIP(),
'fiveChess': user.getFiveChess(),
'chess': user.getChess(),
'signatureFile': user.getSignatureFile(),
}}
def get_posts(self, crawlHandler):
PttUserModel(
self.id, self.acc, self.pswd).get_posts(crawlHandler)
<file_sep># -*- coding: utf-8 -*
import sys
from PTTLibrary import PTT
def login(pttBot, id, password):
try:
pttBot.login(
id,
password,
KickOtherLogin=False)
except PTT.Exceptions.LoginError:
pttBot.log('登入失敗')
sys.exit()
except PTT.Exceptions.WrongIDorPassword:
pttBot.log('帳號密碼錯誤')
sys.exit()
except PTT.Exceptions.LoginTooOften:
pttBot.log('請稍等一下再登入')
sys.exit()
pttBot.log('登入成功')
def logout(pttBot):
pttBot.logout()
def get_user(pttBot, id):
user = pttBot.getUser(id)
# pttBot.log('使用者ID: ' + user.getID())
# pttBot.log('使用者經濟狀況: ' + str(user.getMoney()))
# pttBot.log('登入次數: ' + str(user.getLoginTime()))
# pttBot.log('有效文章數: ' + str(user.getLegalPost()))
# pttBot.log('退文文章數: ' + str(user.getIllegalPost()))
# pttBot.log('目前動態: ' + user.getState())
# pttBot.log('信箱狀態: ' + user.getMail())
# pttBot.log('最後登入時間: ' + user.getLastLogin())
# pttBot.log('上次故鄉: ' + user.getLastIP())
# pttBot.log('五子棋戰績: ' + user.getFiveChess())
# pttBot.log('象棋戰績:' + user.getChess())
# pttBot.log('簽名檔:' + user.getSignatureFile())
return user
def show_condition(Board, SearchType, Condition):
if SearchType == PTT.PostSearchType.Keyword:
Type = '關鍵字'
if SearchType == PTT.PostSearchType.Author:
Type = '作者'
if SearchType == PTT.PostSearchType.Push:
Type = '推文數'
if SearchType == PTT.PostSearchType.Mark:
Type = '標記'
if SearchType == PTT.PostSearchType.Money:
Type = '稿酬'
print(f'{Board} 使用 {Type} 搜尋 {Condition}')
def get_posts(pttBot, id, size, crawlHandler):
postList = [
('ALLPOST', PTT.PostSearchType.Author, id),
# ('Gossiping', PTT.PostSearchType.Keyword, '[公告]'),
# ('Gossiping', PTT.PostSearchType.Author, 'ReDmango'),
# ('Gossiping', PTT.PostSearchType.Push, '10'),
# ('Gossiping', PTT.PostSearchType.Mark, 'm'),
# ('Gossiping', PTT.PostSearchType.Money, '5'),
# ('Gossiping', PTT.PostSearchType.Push, '-100'),
# ('Gossiping', PTT.PostSearchType.Push, '150'),
]
for (Board, SearchType, Condition) in postList:
show_condition(Board, SearchType, Condition)
NewestIndex = pttBot.getNewestIndex(
PTT.IndexType.BBS,
Board,
SearchType=SearchType,
SearchCondition=Condition,
)
if(NewestIndex > 1000):
continue
if(NewestIndex < size):
StartIndex = 1
else:
StartIndex = NewestIndex - size + 1
print(f'{Board} StartIndex {StartIndex}')
print(f'{Board} 最新文章編號 {NewestIndex}')
ErrorPostList, DelPostList = pttBot.crawlBoard(
crawlHandler,
PTT.CrawlType.BBS,
Board,
StartIndex=StartIndex,
EndIndex=NewestIndex,
SearchType=SearchType,
SearchCondition=Condition,
Query=True, # Optional
)
def createPost(post):
if post.getDeleteStatus() != PTT.PostDeleteStatus.NotDeleted:
if post.getDeleteStatus() == PTT.PostDeleteStatus.ByModerator:
print(f'[板主刪除][{post.getAuthor()}]')
elif post.getDeleteStatus() == PTT.PostDeleteStatus.ByAuthor:
print(f'[作者刪除][{post.getAuthor()}]')
elif post.getDeleteStatus() == PTT.PostDeleteStatus.ByUnknow:
print(f'[不明刪除]')
return {}
return {
'aid': post.getAID(),
'title': post.getTitle(),
'author': post.getAuthor(),
'url': post.getWebUrl(),
'date': post.getDate(),
'money': str(post.getMoney()),
'ip': post.getIP(),
'date': post.getDate(),
'board': post.getBoard(),
'list_date': post.getListDate(),
'location': post.getLocation(),
'push': post.getPushNumber(),
}
<file_sep>import flask
import common.ptt_data as ptt
from flask import jsonify
from flask_caching import Cache
from resources.ptt_user import PttUser
app = flask.Flask(__name__)
app.config.update(
DEBUG=True,
JSON_AS_ASCII=False
)
cache = Cache(app, config={'CACHE_TYPE': 'simple',
"CACHE_DEFAULT_TIMEOUT": 300})
@app.route('/', methods=['GET'])
def home():
return "<h1>PttData Works!</h1>"
@cache.cached(timeout=120)
@app.route('/user/<string:id>', methods=['GET'])
def getUser(id=None):
if id is not None:
user = cache.get(id)
if user is None:
user = PttUser(id).get()
cache.set(id, user)
return jsonify(user)
@cache.cached(timeout=120)
@app.route('/post/<string:id>', methods=['GET'])
def getUserPosts(id=None):
if id is not None:
posts = cache.get(id+"post")
if posts is None:
posts = []
PttUser(id).get_posts(
lambda post: posts.append(ptt.createPost(post)))
cache.set(id+"post", posts)
return jsonify(posts)
if __name__ == '__main__':
app.run()
<file_sep>Flask==1.1.1
Flask-Caching==1.7.2
flask-marshmallow==0.10.1
Flask-RESTful==0.3.7
gunicorn==20.0.4
marshmallow==3.2.2
PTTLibrary==0.8.27
python-dotenv==0.10.3
<file_sep># PttData
Get ptt user's info and post
change .env.example to .env and enter
```
ptt_acc={ptt acount}
ptt_pswd={ptt password}
```
then
```
pip install -r requirements.txt
python app.py
```
## Api
### get user info
http://127.0.0.1:5000/user/{ptt_id}
### get user 5 post within 7 days
http://127.0.0.1:5000/post/{ptt_id}
## Example
https://pttdata.herokuapp.com/user/ptt
https://pttdata.herokuapp.com/post/ptt
<file_sep>import common.ptt_data as ptt
from PTTLibrary import PTT
class PttUserModel:
def __init__(self, id, acc, pswd):
self.id = id
self.bot = PTT.Library()
self.acc = acc
self.pswd = pswd
def get_user(self):
try:
ptt.login(self.bot, self.acc, self.pswd)
user = ptt.get_user(self.bot, self.id)
ptt.logout(self.bot)
except PTT.Exceptions.NoSuchUser:
return None
return user
def get_posts(self, crawlHandler, range=5):
try:
ptt.login(self.bot, self.acc, self.pswd)
ptt.get_posts(self.bot, self.id, range, crawlHandler)
ptt.logout(self.bot)
except PTT.Exceptions.NoSuchUser:
return None
| 7e7a2186b027adde4ab7e0111e1e2fa01eb6b945 | [
"Markdown",
"Python",
"Text"
] | 6 | Python | ewanhohou/PttData | f7b7cc8828899cbb7ac790488e00533319669055 | 8269c96b1cf519d2317fe2ca3b1ae6486e4e658c |
refs/heads/master | <file_sep>import os
import sqlite3
import datetime
import logging
from selenium import webdriver
###########
# Globals #
###########
YEAR = '2014'
TYPE = 'Individual HSA'
CREATE_DATABASE = True
COUNTIES = ['Carson City', 'Elko', 'Nye', 'Washoe']
DATABASE = 'data_{0}_{1}.sqlite'.format(YEAR, TYPE.replace(' ', ''))
STARTING_URL = 'http://healthrates.doi.nv.gov/Wizard.aspx?type=Small%20Group'
BAD_LINKS = [
'http://exchange.nv.gov/',
'http://healthrates.doi.nv.gov/Default.aspx#',
'http://www.nevadahealthlink.com/'
]
logging.basicConfig(filename="error.log", level=logging.INFO)
log = logging.getLogger("ex")
########
# Code #
########
def create_database_and_tables():
print("Creating database...")
con = sqlite3.connect(DATABASE)
with con:
cur = con.cursor()
try:
cur.execute(
"""
CREATE TABLE links(
id INTEGER PRIMARY KEY, url TEXT, county_name TEXT)
"""
)
except sqlite3.OperationalError:
log.exception("Error!")
try:
cur.execute(
"""
CREATE TABLE data(
id INTEGER PRIMARY KEY,
plan_name TEXT,
carrier TEXT,
metal TEXT,
exchange TEXT,
county TEXT,
cost TEXT,
status TEXT,
plan_year TEXT,
market_sement TEXT,
january TEXT,
april TEXT,
july TEXT,
october TEXT,
url TEXT,
benefit_schedule TEXT
)
"""
)
except sqlite3.OperationalError:
log.exception("Error!")
def get_all_data():
"""
This function navigates to the results page, from the starting URL, and
grabs all the URLs.
"""
print("Grabbing links...")
# driver = webdriver.Firefox()
driver = webdriver.PhantomJS()
for county in COUNTIES:
counter = 1
# navigate to results page
driver.get(STARTING_URL)
driver.find_element_by_class_name('rates_review_button_submit').click()
driver.find_element_by_tag_name('form').submit()
# perform search
driver.find_element_by_xpath(
"//select[@name='type']/option[text()='"+TYPE+"']").click()
driver.find_element_by_xpath(
"//select[@name='planyear']/option[text()='"+YEAR+"']").click()
driver.find_element_by_xpath(
"//select[@name='county']/option[text()='"+county+"']").click()
driver.find_element_by_tag_name('form').submit()
# find all links and add each to the DB
first_element = driver.find_element_by_xpath(
'//*[@id="resultsBox"]/div[5]')
all_links = first_element.find_elements_by_xpath('.//*[@href]')
cleaned_links = cleanup_links(all_links)
all_links_length = len(all_links)
for link in cleaned_links:
add_link_to_database(link, county)
print('Added link # {0} of {1} in {2} county to DB'.format(
counter, all_links_length, county))
counter += 1
driver.quit()
def cleanup_links(all_links_list_of_objects):
clean_links = []
for link in all_links_list_of_objects:
if str(link.get_attribute('href')) != BAD_LINKS[0] and \
str(link.get_attribute('href')) != BAD_LINKS[1] and \
str(link.get_attribute('href')) != BAD_LINKS[2]:
clean_links.append(link.get_attribute('href'))
return clean_links
def add_link_to_database(single_link, county):
"""
Given a url, update the database.
"""
con = sqlite3.connect(DATABASE)
with con:
cur = con.cursor()
cur.execute(
"""
INSERT INTO links(url, county_name) VALUES(?, ?)
""", (single_link, county)
)
def cleanup_database():
print("Removing bad links...")
con = sqlite3.connect(DATABASE)
with con:
cur = con.cursor()
for link in BAD_LINKS:
cur.execute('DELETE FROM links WHERE url=?', (link,))
def grab_links_from_database():
"""
Grab all data from the links table.
"""
print("Scraping data...")
counter = 1
con = sqlite3.connect(DATABASE)
with con:
cur = con.cursor()
cur.execute('SELECT * FROM links')
all_database_rows = len(cur.fetchall())
for row_id in range(1, all_database_rows+1):
cur.execute('SELECT * FROM links WHERE id=?', (row_id,))
link = cur.fetchone()
if link:
data_object = get_relevant_data(link[1])
if data_object:
print('Added scraped link # {0} of {1} to the DB.'.format(
counter, all_database_rows))
add_relevant_data_to_database(data_object)
counter += 1
def get_relevant_data(link):
"""
Given a link from the links table in the database, scrape relevant data -
Plan Name
Carrier
Metal
Exchange
County
Proposed Cost
Status
Plan Year
Market Segment
January
April
July
October
URL
Schedule of Benefits
- returning a dict
"""
all_data = {}
# driver = webdriver.Firefox()
driver = webdriver.PhantomJS()
driver.get(link)
# grab plan name and carrier, add to dict
try:
plan_name = driver.find_element_by_tag_name('h2').text
carrier = (driver.find_element_by_xpath(
'//*[@id="secondary-wrapper"]/section/div/h3[1]').text)
all_data['Plan Name'] = str(plan_name)
all_data['Carrier'] = str(carrier.encode('utf-8'))
# grab remaining data, add to dict
plan_data = driver.find_elements_by_class_name('planData')
all_data[str(plan_data[0].text)] = str(plan_data[1].text) # year
all_data[str(plan_data[2].text)] = str(plan_data[3].text) # market
all_data[str(plan_data[5].text)] = str(plan_data[6].text) # metal
all_data[str(plan_data[7].text)] = str(plan_data[8].text) # exchange
all_data[str(plan_data[10].text)] = str(plan_data[11].text) # status
all_data[str(plan_data[12].text)] = str(plan_data[13].text) # county
all_data[str(plan_data[14].text)] = str(plan_data[15].text) # cost
all_data[str(plan_data[16].text)] = str(plan_data[17].text) # avg age
all_data[str(plan_data[20].text)] = str(plan_data[21].text) # january
all_data[str(plan_data[22].text)] = str(plan_data[23].text) # july
all_data[str(plan_data[24].text)] = str(plan_data[25].text) # april
all_data[str(plan_data[26].text)] = str(plan_data[27].text) # october
# add pdf link to dict
pdf_link = driver.find_element_by_xpath(
'//*[@id="secondary-wrapper"]/section/div/a[1]')
all_data["Schedule of Benefits"] = str(pdf_link.get_attribute('href'))
# add url to dict
all_data["URL"] = str(link)
driver.quit()
return all_data
except Exception as e:
print(e)
log.exception("Error!")
driver.quit()
def add_relevant_data_to_database(all_data_object):
"""
Given the 'all_data' object, this function adds the data to the database.
"""
con = sqlite3.connect(DATABASE)
con.text_factory = str
with con:
cur = con.cursor()
cur.execute(
"""
INSERT INTO data(
plan_name,
carrier,
metal,
exchange,
county,
cost,
status,
plan_year,
market_sement,
january,
april,
july,
october,
url,
benefit_schedule
)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
all_data_object['Plan Name'],
all_data_object['Carrier'],
all_data_object['Metal Tier:'],
all_data_object['Exchange:'],
all_data_object['County:'],
all_data_object['Proposed:'],
all_data_object['Rate Status:'],
all_data_object['Plan Year:'],
all_data_object['Market Segment:'],
all_data_object['January:'],
all_data_object['April:'],
all_data_object['July:'],
all_data_object['October:'],
all_data_object['URL'],
all_data_object['Schedule of Benefits'],
)
)
def timestamp_database():
database_without_extension = os.path.splitext(DATABASE)[0]
now = datetime.datetime.now()
new_database_name = database_without_extension + '{0}.sqlite'.format(
now.strftime("%Y-%m-%d_%H:%M"))
os.rename(DATABASE, new_database_name)
print("Done!")
def main():
if CREATE_DATABASE:
# create database
create_database_and_tables()
# grab links, add to database
get_all_data()
# get links from database, grab relevant data, and then add to database
grab_links_from_database()
# add timestamp once complete
timestamp_database()
if __name__ == '__main__':
main()
<file_sep>## Welcome!
### Instructions
1. Install pip requirements
1. Install phantomjs via brew - `brew install phantomjs`
1. Update `YEAR`, `TYPE`, and `CREATE_DATABASE` in *bot.py*
1. Then run `python bot.py`<file_sep>selenium==2.44.0
wsgiref==0.1.2
| 7fce3f20d6227c2a8c634da8cf6a158cbe61c9ec | [
"Markdown",
"Python",
"Text"
] | 3 | Python | mjhea0/healthrates-scraper | b301aec82566299240789915cc57c72edd31dfbd | f799bf55d189c0db994daabf3d90b75ed46b7c9c |
refs/heads/master | <file_sep>def valid_move? (board, index)
return true if index.between?(0, 8) && position_taken?(board, index) == false
end
def position_taken? (board, index)
return false if board[index] == " " || board[index] == "" || board[index] == nil
true
end | 6c21975ba53016582e7e86961e25f3fcec8149d0 | [
"Ruby"
] | 1 | Ruby | Astrodynamo/ttt-7-valid-move-online-web-sp-000 | 3518d34290a24edda1178bdf3a0e3dccd14cd7d6 | 1013b1427fe22bd0c3d508f9c7d34294f6f01822 |
refs/heads/master | <repo_name>ionut-banu/JavaCodeWars<file_sep>/MoleculeToAtoms/README.md
# Molecule to atoms
For a given chemical formula represented by a string, count the number of atoms of each element contained in the molecule and return an object (associative array in PHP, Dictionary<string, int> in C#, Map<String,Integer> in Java).
For example:
String water = "H2O";
parseMolecule.getAtoms(water); // return [H: 2, O: 1]
String magnesiumHydroxide = "Mg(OH)2";
parseMolecule.getAtoms(magnesiumHydroxide); // return ["Mg": 1, "O": 2, "H": 2]
String fremySalt = "K4[ON(SO3)2]2";
parseMolecule.getAtoms(fremySalt); // return ["K": 4, "O": 14, "N": 2, "S": 4]
parseMolecule.getAtoms("pie"); // throw an IllegalArgumentException
As you can see, some formulas have brackets in them. The index outside the brackets tells you that you have to multiply count of each atom inside the bracket on this index. For example, in Fe(NO3)2 you have one iron atom, two nitrogen atoms and six oxygen atoms.
Note that brackets may be round, square or curly and can also be nested. Index after the braces is optional.
<file_sep>/README.md
# JavaCodeWars
<file_sep>/MatrixDeterminant/src/Main.java
public class Main {
public static void main(String[] args) {
int[][] matrix1 = {{4}};
int[][] matrix2 = {{1, 2}, {3, 4}};
int[][] matrix3 = {{2,5,3}, {1,-2,-1}, {1, 3, 4}};
System.out.println(Matrix.determinant(matrix3));
}
}
<file_sep>/HumanReadableDuration/src/TimeFormatter.java
/**
* Created by Ionut on Dec, 2019
*/
public class TimeFormatter {
public static String formatDuration(int seconds) {
System.out.println(seconds);
if (seconds == 0)
return "now";
String out = "";
int sec = seconds % 60;
if (sec != 0) out += sec + " second" + (sec > 1 ? "s" : "");
seconds /= 60;
int min = seconds % 60;
if (min != 0) out = addUnit(min, "minute", out);
seconds /= 60;
int hours = seconds % 24;
if (hours != 0) out = addUnit(hours, "hour", out);
seconds /= 24;
int days = seconds % 365;
if (days != 0) out = addUnit(days, "day", out);
seconds /= 365;
if (seconds != 0) out = addUnit(seconds, "year", out);
return out;
}
public static String addUnit(int amount, String unit, String out) {
if (out.length() > 0)
if (!out.contains("and")) out = " and " + out;
else out = ", " + out;
return amount + " " + unit + (amount > 1 ? "s" : "") + out;
}
}
<file_sep>/MoleculeToAtoms/src/Main.java
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
static Pattern pAa = Pattern.compile("[A-Z][a-z]");
static Pattern pA = Pattern.compile("[A-Z]");
static Pattern pAad = Pattern.compile("[A-Z][a-z][1-9]");
static Pattern pAd = Pattern.compile("[A-Z][1-9]");
static Pattern pAadd = Pattern.compile("[A-Z][a-z][1-9][0-9]");
static Pattern pAdd = Pattern.compile("[A-Z][1-9][0-9]");
static Pattern p1 = Pattern.compile("\\((.*?)\\)");
static Pattern p2 = Pattern.compile("\\[(.*?)\\]");
static Pattern p3 = Pattern.compile("\\{(.*?)\\}");
public static void main(String[] args) {
String formula = "K4[ON(SO3)2]2";
if(!isValid(formula)){
throw new IllegalArgumentException();
}
HashMap hm = new HashMap<String, Integer>();
int multiply = 1;
Matcher m3 = p3.matcher(formula);
while (m3.find()) {
String s3 = m3.group(0);
int c3 = getMultiply(s3, formula);
int multiply3 = multiply * c3;
s3 = match2(multiply3, formula, s3, hm);
s3 = match1(multiply3, formula, s3, hm);
processAtoms(hm, s3, multiply3);
formula = formula.replace(m3.group(0) + (c3 != 1 ? c3 : ""), "");
}
formula = match2(multiply, formula, formula, hm);
formula = match1(multiply, formula, formula, hm);
processAtoms(hm, formula, 1);
}
static void processAtoms(HashMap hm, String s, int m) {
s = findAtoms(hm, s, pAadd, 2, 2, m);
s = findAtoms(hm, s, pAad, 1, 2, m);
s = findAtoms(hm, s, pAdd, 2, 1, m);
s = findAtoms(hm, s, pAd, 1, 1, m);
s = findAtoms(hm, s, pAa, 0, 0, m);
s = findAtoms(hm, s, pA, 0, 0, m);
}
static String findAtoms(HashMap hm, String s, Pattern p, int digits, int l, int mult) {
Matcher m = p.matcher(s);
while (m.find()) {
String inside = m.group(0);
int n = mult;
if (digits != 0) {
n *= Integer.parseInt(inside.substring(l));
inside = inside.substring(0, inside.length() - digits);
}
addToMap(hm, inside, n);
s = s.replace(m.group(0), "");
}
return s;
}
static void addToMap(HashMap hm, String key, int n) {
int s = n;
if (hm.containsKey(key)) {
s += (int) hm.get(key);
}
hm.put(key, s);
}
static int getMultiply(String s, String parent) {
int end = parent.indexOf(s) + s.length() + 2;
String insideM = parent.substring(parent.indexOf(s) + s.length(), end < parent.length() ? end : parent.length());
int begin = insideM.length() - 2 >= 0 ? insideM.length() - 2 : 0;
try {
return Integer.parseInt(insideM.substring(begin), insideM.length());
} catch (NumberFormatException e1) {
try {
int e = insideM.length() > 1 ? insideM.length() - 1 : insideM.length();
return Integer.parseInt(insideM.substring(begin, e));
} catch (NumberFormatException e2) {
return 1;
}
}
}
static String match1(int prevM, String formula, String s, HashMap hm) {
Matcher m = p1.matcher(s);
while (m.find()) {
String s1 = m.group(0);
int c1 = getMultiply(s1, formula);
int multiply1 = prevM * c1;
processAtoms(hm, s1, multiply1);
s = s.replace(m.group(0) + (c1 != 1 ? c1 : ""), "");
}
return s;
}
static String match2(int prevM, String formula, String s, HashMap hm) {
Matcher m2 = p2.matcher(s);
while (m2.find()) {
String s2 = m2.group();
int c2 = getMultiply(s2, formula);
int multiply2 = prevM * c2;
s2 = match1(multiply2, formula, s2, hm);
processAtoms(hm, s2, multiply2);
s = s.replace(m2.group(0) + (c2 != 1 ? c2 : ""), "");
}
return s;
}
static boolean isValid(String s) {
if(s.matches(".*[\\(].*[\\[].*[\\)].*")) return false;
return s.matches(".*[A-Z].*") && getCount(s,'(') == getCount(s,')') && getCount(s,'[') == getCount(s,']') && getCount(s,'{') == getCount(s,'}');
}
static int getCount(String s, char c) {
return (int) s.chars().filter(ch -> ch == c).count();
}
}
<file_sep>/GrowthOfAPopulation/src/com/ionut/Arge.java
package com.ionut;
/**
* Created by Ionut on Feb, 2020
*/
class Arge {
public static int nbYear(int p0, double percent, int aug, int p) {
int p1 = p0;
int c = 0;
while(p1 < p){
p1 = (int) (p1 + (p1*(percent/100)) + aug);
c++;
}
return c;
}
}
<file_sep>/BreadcrumbGenerator/src/Main.java
public class Main {
public static void main(String[] args) {
System.out.println(Solution.generate_bc("http://www.codewars.com/users/of-uber-the-a-surfer/test.php?sortBy=year" , " / "));
}
}
<file_sep>/BreadcrumbGenerator/src/Solution.java
/**
* Created by Ionut on Dec, 2019
*/
public class Solution {
public static String generate_bc(String url, String separator) {
System.out.println(url);
String out = "<a href=\"/\">HOME</a>" + separator;
if (url.contains("https://")) {
url = url.substring(url.indexOf("https://") + 8);
url = url.substring(url.indexOf('/') + 1);
} else if (url.contains("http://")) {
url = url.substring(url.indexOf("http://") + 7);
url = url.substring(url.indexOf('/') + 1);
} else url = url.substring(url.indexOf('/') + 1);
if (url.lastIndexOf("/") > -1) {
String last = url.substring(url.lastIndexOf("/"));
if (last.contains("index.htm")) url = url.substring(0, url.indexOf(last));
if (last.contains("/#")) url = url.substring(0, url.indexOf("/#"));
if (last.contains("/?")) url = url.substring(0, url.indexOf("/?"));
}
if (url.length() > 0) {
if (url.charAt(url.length() - 1) == '/')
url = url.substring(0, url.length() - 1);
if (!url.contains("/") && url.contains(".")) return "<span class=\"active\">HOME</span>";
} else {
return "<span class=\"active\">HOME</span>";
}
/*String urlRegex = "(http|ftp|https)://([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?";
Pattern urlPattern = Pattern.compile(urlRegex);
Matcher m = urlPattern.matcher(url);
while (m.find()) {
String s = m.group(1);
System.out.println(s);
}*/
while (!url.isEmpty()) {
if (url.contains("/")) {
String path = url.substring(0, url.indexOf('/'));
String s = "";
if (path.length() < 31) {
s = path.replace("-" , " ").toUpperCase();
} else {
s = getAcronym(path);
}
out += "<a href=\"" + "/" + path + "/\">" + s + "</a>" + separator;
url = url.substring(url.indexOf('/') + 1);
} else {
String path;
if (url.contains(".")) path = url.substring(0, url.indexOf("."));
else if (url.contains("?")) path = url.substring(0, url.indexOf("?"));
else if (url.contains("#")) path = url.substring(0, url.indexOf("#"));
else path = url;
String s = "";
if (path.length() < 31) {
s = path.replace("-" , " ").toUpperCase();
} else {
s = getAcronym(path);
}
out += "<span class=\"active\">" + s + "</span>";
url = "";
}
}
return out;
}
static String getAcronym(String in) {
String out = "";
while (!in.isEmpty()) {
if (in.contains("-")) {
String t = in.substring(0, in.indexOf('-'));
if (t.length() > 2 && !t.equals("and") && !t.equals("for") && !t.equals("the")
&& !t.equals("from") && !t.equals("with")) {
out += in.substring(0, 1).toUpperCase();
}
in = in.substring(in.indexOf('-') + 1);
} else {
String t = in;
if (t.length() > 2 && !t.equals("and") && !t.equals("for") && !t.equals("the")
&& !t.equals("from") && !t.equals("with")) {
out += in.substring(0, 1).toUpperCase();
}
in = "";
}
}
return out;
}
}
<file_sep>/MatrixDeterminant/src/Matrix.java
/**
* Created by Ionut on Dec, 2019
*/
public class Matrix {
public static int determinant(int[][] matrix) {
int det = 0;
if (matrix.length == 1) {
return matrix[0][0];
} else if (matrix.length == 2) {
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
} else if (matrix.length > 2) {
for (int i = 0; i < matrix.length; i++) {
int s = i % 2 == 0 ? 1 : -1;
det += s * matrix[i][0] * determinant(getMinor(i, 0, matrix));
}
}
return det;
}
public static int[][] getMinor(int row, int col, int[][] matrix) {
int[][] minor = new int[matrix.length - 1][matrix.length - 1];
int p = 0;
for (int i = 0; i < matrix.length; i++) {
if (i == row)
continue;
int q = 0;
for (int j = 0; j < matrix.length; j++) {
if (j == col)
continue;
minor[p][q] = matrix[i][j];
q++;
}
p++;
}
return minor;
}
}
<file_sep>/StringMerger/src/com/ionut/Main.java
package com.ionut;
public class Main {
public static void main(String[] args) {
String s = "FF8\\62cH%0JtJfknW^?J\\f`h";
String part1 = "F\\c%0JJfkW^\\f`";
String part2 = "F862Htn?Jh";
while (!s.isEmpty()) {
String s1 = test(s, part1, part2);
String s2 = test(s, part2, part1);
if(s1.equals("") && s2.equals("")){
System.out.println(false);
return;
}else if (s1.length() >= s2.length()) {
part1 = part1.substring(s1.length());
s = s.substring(s1.length());
} else if (s1.length() < s2.length()) {
part2 = part2.substring(s2.length());
s = s.substring(s2.length());
}
}
System.out.println(true);
return;
}
static String test(String s1, String s2, String s3) {
String out = "";
for (int i = 0; i < s1.length(); i++) {
if (i < s2.length() && s1.charAt(i) == s2.charAt(i)) {
out += s1.charAt(i);
} else {
while(out.length() > 1 && !s3.isEmpty()){
if(out.charAt(out.length()-1) == s3.charAt(0)){
out = out.substring(0,out.length()-1);
s3 = s3.substring(1);
} else {
return out;
}
}
return out;
}
}
return out;
}
}
<file_sep>/WriteNumberInExpandedForm/src/com/ionut/Main.java
package com.ionut;
public class Main {
public static void main(String[] args) {
Kata.expandedForm(70304);
}
}
<file_sep>/Primes/src/Main.java
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
int n = 53132221;
TreeMap<Integer, Integer> map = new TreeMap<>();
String out = "";
for (int i = 2; i <= Math.sqrt(n); i++) {
if (isPrime(i) && !isPrime(n)) {
while (n % i == 0) {
n = n / i;
addToMap(map, i);
}
}
}
if (isPrime(n)) {
addToMap(map,n);
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
Integer key = entry.getKey();
Integer value = entry.getValue();
out += "(" + key + (value > 1 ? "**" + value : "") + ")";
}
System.out.println(out);
}
static boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt((double) n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
static void addToMap(Map map, int key) {
int val = 1;
if (map.containsKey(key)) {
val += (int) map.get(key);
}
map.put(key, val);
}
}
<file_sep>/NumberOfProperFractions/src/com/ionut/Main.java
package com.ionut;
public class Main {
public static void main(String[] args) {
System.out.println(ProperFractions.properFractions(15));
}
}
<file_sep>/RectangleRotation/src/Solution.java
/**
* Created by Ionut on Dec, 2019
*/
class Solution {
static int rectangleRotation(final int a, final int b) {
return 0;
}
}
<file_sep>/SumOfDivided/README.md
# Sum by Factors
Given an array of positive or negative integers
I= [i1,..,in]
you have to produce a sorted array P of the form
[ [p, sum of all ij of I for which p is a prime factor (p positive) of ij] ...]
P will be sorted by increasing order of the prime numbers. The final result has to be given as a string in Java, C#, C, C++ and as an array of arrays in other languages.
Example:
I = {12, 15}; // result = "(2 12)(3 27)(5 15)"
[2, 3, 5] is the list of all prime factors of the elements of I, hence the result.
<file_sep>/BuildAPileOfCubes/src/com/ionut/ASum.java
package com.ionut;
import java.math.BigInteger;
/**
* Created by Ionut on Feb, 2020
*/
public class ASum {
public static long findNb(long m) {
BigInteger s = BigInteger.valueOf(0);
int i = 1;
while(s.compareTo(BigInteger.valueOf(m)) < 0){
s = s.add(BigInteger.valueOf((long) Math.pow(i, 3)));
if(s.equals(BigInteger.valueOf(m))){
return i;
}
i++;
}
return -1;
}
}
| 55a2d9782f07f24fc16efc66a73de13b097875b0 | [
"Markdown",
"Java"
] | 16 | Markdown | ionut-banu/JavaCodeWars | 6b9e8e7ea4da11af7849d6836fedbbed3b06cd50 | 71f08dd1dba98bdf66d4a45dfc870864fee3abd9 |
refs/heads/master | <file_sep>class Lib {
constructor() {}
method() {
return true
}
}
export default Lib
<file_sep>[](https://badge.fury.io/js/project-name)
ProjectName
===========
## Dev
Dev mode
```sh
npm run dev
```
Build
```sh
npm run build
```
Lint
```sh
npm run lint
```
Fix lint errors
```sh
npm run lint:fix
```
Tests
```sh
npm run test
```
```sh
npm run test:watch
```
```sh
npm run test:browser
```
Bump version and publish to NPM
```sh
npm run release
```
```sh
npm run release:patch
```
```sh
npm run release:minor
```
```sh
npm run release:major
```
<file_sep>/* eslint-env mocha */
export default function test(expect, Lib) {
describe('Some tests', function () {
describe('Init', function () {
it('should works', function () {
expect(new Lib().method()).to.be.equal(true)
})
})
})
}
<file_sep>/* eslint-disable camelcase */
import { terser } from 'rollup-plugin-terser'
import nodeResolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import filesize from 'rollup-plugin-filesize'
import Case from 'case'
import pkg from './package.json'
const NAME = Case.pascal(pkg.name)
const FILENAME = Case.kebab(pkg.name)
const SRC = './src'
const DIST = './build'
const EXPORT = 'default'
const FORMATS = [
'iife',
'esm',
'cjs',
'umd'
]
const configs = []
const now = new Date().toISOString()
const watched = process.env.ROLLUP_WATCH
const mutedWarnings = [ 'CIRCULAR_DEPENDENCY' ]
const bannerMinify = `/*! ${NAME} v${pkg.version} */`
const bannerBeautify = `
/**!
* ${NAME}
* https://github.com/jaysalvat/${FILENAME}
* @version ${pkg.version} built ${now}
* @license ${pkg.license}
* @author <NAME> http://jaysalvat.com
*/`
const config = {
filesize: {
showMinifiedSize: false
},
terser: {
minified: {
mangle: {
toplevel: true
},
compress: {
toplevel: true,
reduce_funcs: true,
keep_infinity: true,
pure_getters: true,
passes: 3
}
},
pretty: {
mangle: false,
compress: false,
output: {
beautify: true,
indent_level: 2,
braces: true
}
}
}
}
FORMATS.forEach((format) => {
const filename = FILENAME + '.' + format
const extension = format === 'cjs' ? '.cjs' : '.js'
configs.push({
input: SRC + '/index.js',
output: [
{
format: format,
file: DIST + '/' + filename + extension,
name: NAME,
exports: EXPORT,
banner: !watched && bannerBeautify,
plugins: [
terser(config.terser.pretty),
filesize(config.filesize)
]
},
{
format: format,
file: DIST + '/' + filename + '.min' + extension,
name: NAME,
exports: EXPORT,
banner: !watched && bannerMinify,
plugins: [
terser(config.terser.minified),
filesize(config.filesize)
]
}
],
plugins: [
commonjs(),
nodeResolve()
],
onwarn: (warning, warn) => {
if (mutedWarnings.includes(warning.code)) {
return
}
warn(warning)
}
})
})
export default configs
| d5e2c7c0cff6947272a5bd9d2e3b2225cebce081 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | jaysalvat/boilerplate-js-lib | d039869c07b11c6e27889b9bd47a0a1e45554bad | 9e232ca2ab589d6be5d984b8925331280ce9b43b |
refs/heads/master | <repo_name>romische/asm-exos-lea<file_sep>/main_aout_2015_Q3.cpp
#include <iostream>
extern "C" int val(int[],unsigned, unsigned=0);
int main() {
int v[4] = {1,5,2,4};
unsigned n = 4;
std::cout << val(v,n) << std::endl;
return 0;
}
| e529986129079d9bebc3904081deafc630561b64 | [
"C++"
] | 1 | C++ | romische/asm-exos-lea | bf0445716218f552db21480f0bf03433080916c6 | d03a65a0c9a8f9eff3af7604d250440d50f1f2f1 |
refs/heads/master | <file_sep># bash-pptp-auto-reconnect
Auto start/reconnect for vpn pptp
## Install client
```sh
apt-get install pptp-linux
mcedit /etc/ppp/chap-secrets
```
## Add VPN user
```sh
# Secrets for authentication using CHAP
# client server secret IP addresses
vpnconn PPTP pass *
```
```sh
touch /etc/ppp/peers/vpnconn
mcedit /etc/ppp/peers/vpnconn
```
## Add VPN connection
```sh
pty "pptp x.x.x.x --nolaunchpppd"
name vpnconn
remotename PPTP
require-mppe-128
defaultroute
replacedefaultroute
file /etc/ppp/options.pptp
ipparam vpnconn
```
## Script location
```sh
Location: /usr/local/bin/vpn
```
## Usage
```sh
Usage: vpn "ppp0" "10.0.0.1" "vpnconn"
```
## Crontab
```sh
* * * * * root /usr/local/bin/vpn "ppp0" "10.0.0.1" "vpnconn" >/dev/null
```
## Quick install
```sh
wget -O /usr/local/bin/vpn https://github.com/vladimirok5959/bash-pptp-auto-reconnect/releases/download/latest/vpn; chmod +x /usr/local/bin/vpn
```
<file_sep>#!/bin/bash
# Location: /usr/local/bin/vpn
# Usage: vpn "ppp0" "10.0.0.1" "connection name"
# /etc/crontab
# * * * * * root /usr/local/bin/vpn "ppp0" "10.0.0.1" "vpnconn" >/dev/null
if ! /sbin/ifconfig $1 | grep -q "$2"
then
/usr/bin/poff $3
/usr/bin/pon $3
fi
| 08f0fc50b5d70a629c7ec506472d77691914e850 | [
"Markdown",
"Shell"
] | 2 | Markdown | vladimirok5959/bash-pptp-auto-reconnect | ad58e4d6bef59df34825e3b0c6eb978a68612595 | 7118cd665ad4ede8ea1e1b0d4ccf54440ad30b10 |
refs/heads/master | <repo_name>MladenPetrov88/Rage-expenses<file_sep>/RageExpenses.java
import java.util.Scanner;
public class RageExpenses {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int lostGames = scanner.nextInt();
double headsetPrice = scanner.nextDouble();
double mousePrice = scanner.nextDouble();
double keybordPrice = scanner.nextDouble();
double displayPrice = scanner.nextDouble();
double totalPrice = (lostGames / 2) * headsetPrice + (lostGames / 3) * mousePrice + (lostGames / 6) * keybordPrice + (lostGames / 12) * displayPrice;
System.out.printf("Rage expenses: %.2f lv.", totalPrice);
}
}
| 330e982ea5160fae8c04ca4371c9d24e03dedd47 | [
"Java"
] | 1 | Java | MladenPetrov88/Rage-expenses | e64d1476b7ad76d4610411c582a1a09d9764f5da | 72df3c73cba69ac0c4e0f60011f721875d961c3d |
refs/heads/master | <file_sep>'use strict';
var studentApp = angular.module("studentApp", ['ngRoute']);
studentApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'list.html',
controller: `indexCtrl`
})
.when('/create', {
templateUrl: 'create.html',
})
.when('/:id', {
templateUrl: 'edit.html',
controller: 'editCtrl'
})
});
studentApp.controller('indexCtrl', ['$scope', '$http', function($scope, $http){
$http({
method: 'GET',
url: 'http://yii.student/students'
}).then(function (response){
$scope.students = response.data;
},function (error){
console.log(error);
});
}]);
studentApp.controller('storeCtrl', ['$scope', '$http', function($scope, $http){
$scope.store = function(user) {
let data = JSON.stringify(user)
let message = ''
$http({
method: 'POST',
data: data,
url: 'http://yii.student/students',
}).then(function (response) {
message = "Stored successfully"
$scope.response = response
$scope.message = message
}, function (error) {
$scope.response = error
$scope.message = error.data[0].message
});
}
}]);
studentApp.controller('editCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){
var id = $routeParams.id
$http({
method: 'GET',
url: 'http://yii.student/students/' + id
}).then(function (response){
$scope.student = response.data;
},function (error){
console.log(error);
});
}]);
studentApp.controller('updateCtrl', function ($scope, $http){
$scope.update = function(user) {
let data = JSON.stringify(user)
let message = ''
$http({
method: 'POST',
data: data,
url: 'http://yii.student/students/:id',
}).then(function (response) {
message = "Updated successfully"
$scope.response = response
$scope.message = message
}, function (error) {
$scope.response = error
$scope.message = error.data[0].message
});
}
}); | b2ac8ce9aa04b545c853e04da32f014fe246b856 | [
"JavaScript"
] | 1 | JavaScript | hoangvu5393/yii_system | 83feedcb5651dd9a5c9a2096a3956c535b3f1a70 | 5b142b32a875f1a99e82c124849d4a4f98e51fe7 |
refs/heads/master | <file_sep>import React from 'react';
import './App.css';
import Amplify from '@aws-amplify/core';
import { AuthState, onAuthUIStateChange } from '@aws-amplify/ui-components';
import awsconfig from './aws-exports';
// import { withAuthenticator } from 'aws-amplify-react';
import telemedicineLogo from './images/telemedicineLogo2.png';
import userIcon from './images/userIcon1.png'
import reportsIcon from './images/Reports.png'
import appointmentIcon from './images/appointmentIcon.png'
import meetingIcon from './images/meetingIcon.png'
import chatIcon from './images/chatIcon.png'
import addUserIcon from './images/addUserIcon.png'
import removeUserIcon from './images/removeUserIcon.png'
import editUserIcon from './images/editUserIcon.png'
import { withAuthenticator, AmplifyForgotPassword, AmplifySignIn, AmplifySignOut, AmplifyAuthenticator, AmplifySignUp } from '@aws-amplify/ui-react';
import {
BrowserRouter as Router,
Switch,
Route,
Link,
} from "react-router-dom";
Amplify.configure(awsconfig);
const App = () => {
const [authState, setAuthState] = React.useState();
const [user, setUser] = React.useState();
React.useEffect(() => {
return onAuthUIStateChange((nextAuthState, authData) => {
setAuthState(nextAuthState);
setUser(authData)
});
}, []);
function Home() {
if (user['signInUserSession']['accessToken']['payload']['cognito:groups'] == undefined) {
return (
<div class="position-absolute top-0 start-50 translate-middle-x square-unauthorized h1-unauthorized">
<h1>Unauthorized User</h1>
<br/>
<AmplifySignOut/>
</div>
)
}
else if (user['signInUserSession']['accessToken']['payload']['cognito:groups'][0] == 'patients') {
return (
<div className="App">
<nav className="navbar navbar-light bg-light">
<div className="container-fluid">
<a className="navbar-brand brand-text" href="#">
<img src={telemedicineLogo} alt="" width="25" height="25" className="d-inline-block align-text-top"/>
Telemedicine
</a>
<div className="btn-group">
<button type="button" className="btn btn-light"><img className="d-inline-block align-text-top" src={userIcon} alt="" width="20" height="20"/>{" " + user.attributes.name}</button>
<button type="button" className="btn btn-light dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false">
<span className="visually-hidden">Toggle Dropdown</span>
</button>
<ul className="dropdown-menu">
<li><a className="dropdown-item" href="#">Profile</a></li>
<li><a className="dropdown-item" href="#">Another action</a></li>
<li><a className="dropdown-item" href="#">Something else here</a></li>
<li><hr className="dropdown-divider"></hr></li>
<li><a className="dropdown-item" href="#"><AmplifySignOut /></a></li>
</ul>
</div>
</div>
</nav>
<div className="d-flex justify-content-evenly navbar primary-color">
<button type="button" className="btn btn-secondary btn-sm">Reports</button>
<button type="button" className="btn btn-secondary btn-sm">Messages</button>
<button type="button" className="btn btn-secondary btn-sm">Appointments</button>
<button type="button" className="btn btn-secondary btn-sm">Recordings</button>
<span className="navbar-brand mb-0 h1"></span>
</div>
<div className="d-flex justify-content-evenly flex-column primary-color welcome-box">
<div className="welcome-textbox">
<h1>Welcome, {user.attributes.name}</h1>
</div>
<div className="beside">
<div className="dot"><img id="center-icons1" src={reportsIcon} alt="" width="130" height="100"/>
</div>
<div className="textbox">
<a href="#"><h3>View your reports</h3></a>
</div>
</div>
</div>
<div className="d-flex justify-content-evenly flex-column primary-color info-box">
<div className="beside">
<div className="dot"><img id="center-icons2" src={appointmentIcon} alt="" width="105" height="100"/>
</div>
<div className="textbox">
<a href="#"><h3>Schedule an Appointment</h3></a>
</div>
</div>
</div>
<div className="d-flex justify-content-evenly flex-column primary-color info-box">
<div className="beside">
<div className="dot"><img id="center-icons2" src={meetingIcon} alt="" width="110" height="100" className="d-inline-block align-text-top"/>
</div>
<div className="textbox">
<a href="#"><h3>Join a Meeting</h3></a>
</div>
</div>
</div>
<div className="d-flex justify-content-evenly flex-column primary-color info-box">
<div className="beside">
<div className="dot"><img id="center-icons2" src={chatIcon} alt="" width="110" height="100" className="d-inline-block align-text-top"/>
</div>
<div className="textbox">
<a href="#"><h3>Chat with a Doctor</h3></a>
</div>
</div>
</div>
</div>
);
} else if (user['signInUserSession']['accessToken']['payload']['cognito:groups'][0] == 'doctors'){
return (
<div className="App">
<nav className="navbar navbar-light bg-light">
<div className="container-fluid">
<a className="navbar-brand brand-text" href="#">
<img src={telemedicineLogo} alt="" width="25" height="25" className="d-inline-block align-text-top"/>
Telemedicine
</a>
<div className="btn-group">
<button type="button" className="btn btn-light"><img className="d-inline-block align-text-top" src={userIcon} alt="" width="20" height="20"/>{" Dr. " + user.attributes.name}</button>
<button type="button" className="btn btn-light dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false">
<span className="visually-hidden">Toggle Dropdown</span>
</button>
<ul className="dropdown-menu">
<li><a className="dropdown-item" href="#">Profile</a></li>
<li><a className="dropdown-item" href="#">Another action</a></li>
<li><a className="dropdown-item" href="#">Something else here</a></li>
<li><hr className="dropdown-divider"></hr></li>
<li><a className="dropdown-item" href="#"><AmplifySignOut /></a></li>
</ul>
</div>
</div>
</nav>
<div className="d-flex justify-content-evenly navbar primary-color">
<button type="button" className="btn btn-secondary btn-sm">Reports</button>
<button type="button" className="btn btn-secondary btn-sm">Messages</button>
<button type="button" className="btn btn-secondary btn-sm">Appointments</button>
<button type="button" className="btn btn-secondary btn-sm">Recordings</button>
<span className="navbar-brand mb-0 h1"></span>
</div>
<div className="d-flex justify-content-evenly flex-column primary-color welcome-box">
<div className="welcome-textbox">
<h1>Welcome, {"Dr. " + user.attributes.name}</h1>
</div>
<div className="beside">
<div className="dot"><img id="center-icons1" src={reportsIcon} alt="" width="130" height="100"/>
</div>
<div className="textbox">
<a href="#"><h3>View your reports</h3></a>
</div>
</div>
</div>
<div className="d-flex justify-content-evenly flex-column primary-color info-box">
<div className="beside">
<div className="dot"><img id="center-icons2" src={appointmentIcon} alt="" width="105" height="100"/>
</div>
<div className="textbox">
<a href="#"><h3>View Appointments</h3></a>
</div>
</div>
</div>
<div className="d-flex justify-content-evenly flex-column primary-color info-box">
<div className="beside">
<div className="dot"><img id="center-icons2" src={meetingIcon} alt="" width="110" height="100" className="d-inline-block align-text-top"/>
</div>
<div className="textbox">
<a href="#"><h3>Start a Meeting</h3></a>
</div>
</div>
</div>
<div className="d-flex justify-content-evenly flex-column primary-color info-box">
<div className="beside">
<div className="dot"><img id="center-icons2" src={chatIcon} alt="" width="110" height="100" className="d-inline-block align-text-top"/>
</div>
<div className="textbox">
<a href="#"><h3>Chat with Patient</h3></a>
</div>
</div>
</div>
<div className="lower-buttons-container">
<button type="button" className="btn btn-secondary lower-buttons">View Patients</button>
<button type="button" className="btn btn-secondary lower-buttons">View Staff</button>
</div>
</div>
)
}
else if (user['signInUserSession']['accessToken']['payload']['cognito:groups'][0] == 'admin'){
return (
<div className="App">
<nav class="navbar navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand brand-text" href="#">
<img src={telemedicineLogo} alt="" width="25" height="25" className="d-inline-block align-text-top"/>
Telemedicine
</a>
<div class="btn-group">
<button type="button" class="btn btn-light"><img class="d-inline-block align-text-top" src={userIcon} alt="" width="20" height="20"/>{" " + user.attributes.name}</button>
<button type="button" class="btn btn-light dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false">
<span class="visually-hidden">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Profile</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
<li><hr class="dropdown-divider"></hr></li>
<li><a class="dropdown-item" href="#"><AmplifySignOut /></a></li>
</ul>
</div>
</div>
</nav>
<div class="d-flex justify-content-evenly navbar primary-color">
<button type="button" class="btn btn-secondary btn-sm">Reports</button>
<button type="button" class="btn btn-secondary btn-sm">Messages</button>
<button type="button" class="btn btn-secondary btn-sm">Appointments</button>
<button type="button" class="btn btn-secondary btn-sm">Recordings</button>
<span class="navbar-brand mb-0 h1"></span>
</div>
<div class="d-flex justify-content-evenly flex-column primary-color welcome-box">
<div class="welcome-textbox">
<h1>Welcome, {" " + user.attributes.name}</h1>
</div>
<div class="beside">
<div class="dot"><img id="center-icons2" src={addUserIcon} alt="" width="105" height="100"/>
</div>
<div class="textbox">
<a href="#"><h3>Add User</h3></a>
</div>
</div>
</div>
<div class="d-flex justify-content-evenly flex-column primary-color info-box">
<div class="beside">
<div class="dot"><img id="center-icons2" src={removeUserIcon} alt="" width="105" height="100"/>
</div>
<div class="textbox">
<a href="#"><h3>Delete User</h3></a>
</div>
</div>
</div>
<div class="d-flex justify-content-evenly flex-column primary-color info-box">
<div class="beside">
<div class="dot"><img id="center-icons2" src={editUserIcon} alt="" width="110" height="100" class="d-inline-block align-text-top"/>
</div>
<div class="textbox">
<a href="#"><h3>Edit User</h3></a>
</div>
</div>
</div>
<div class="lower-buttons-container">
<button type="button" class="btn btn-secondary lower-buttons">View Patients</button>
<button type="button" class="btn btn-secondary lower-buttons">View Staff</button>
</div>
</div>
)
}
}
console.log('USER', user)
var userGroup = '';
//userGroup = user['signInUserSession']['accessToken']['payload']['cognito:groups'][0]
return authState === AuthState.SignedIn && user ? (
// if (authState === AuthState.SignedIn && user ) {
<Router>
<div>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
{/* <Route path="/dashboard">
<Dashboard />
</Route> */}
</Switch>
{/* <ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/dashboard">Dashboard</Link>
</li>
<AmplifySignOut />
</ul>
<hr /> */}
{/*
A <Switch> looks through all its children <Route>
elements and renders the first one whose path
matches the current URL. Use a <Switch> any time
you have multiple routes, but you want only one
of them to render at a time
*/}
</div>
</Router>
):(
//<AmplifyAuthenticator/>
<AmplifyAuthenticator>
<AmplifyForgotPassword
headerText="Forgot Password?"
slot="forgot-password"
usernameAlias="email"
></AmplifyForgotPassword>
<AmplifySignUp headerText="To create an account, fill out all of the slots on this page." slot="sign-up"
usernameAlias="email"
formFields={[
{
type: "email",
label: "Enter Email Address: ",
placeholder: "Type your email...",
inputProps: { required: true, autocomplete: "username" },
},
{
type: "password",
label: "Enter Password: ",
placeholder: "Type password...",
inputProps: { required: true, autocomplete: "new-password" },
},
{
type: "name",
label: "Enter your Name: ",
placeholder: "Name...",
inputProps: { required: true }
},
{
type: "phone_number",
label: "Enter Phone Number: ",
},
{
type: "birthdate",
label: "Enter your birthdate: ",
placeholder: "MM/DD/YYYY",
},
]} />
<AmplifySignIn headerText="Welcome to Telemedicine!" slot="sign-in" usernameAlias="username" />
<div className= "jodi">
My App
<AmplifySignOut buttonText="LOGOUT"/>
</div>
</AmplifyAuthenticator>
)
}
function About() {
return (
<div>
<h2>About</h2>
</div>
);
}
// function Dashboard() {
// export default withAuthenticator(App, {
// signUpConfig: {
// hiddenDefaults: ["phone_number"],
// signUpFields: [
// { label: "Name", key: "name", required: true, type: "string" },
// ]
// }
// });
export default App; | f9e98b14e874207914ac3383759b8036646d9a87 | [
"JavaScript"
] | 1 | JavaScript | jodipatt/amplifyapp | 42963ee67557198a26dc8a2f003521244402c949 | 1102500d39f259314d99b83062a412096360b4e0 |
refs/heads/master | <repo_name>wuRDmemory/Cpp_Util<file_sep>/include/util.h
//
// Created by ubuntu on 18-4-29.
//
#ifndef UTIL_UTIL_H
#define UTIL_UTIL_H
#include <vector>
#include <string>
#include <boost/filesystem.hpp>
#include <iostream>
namespace u_util {
std::vector<std::string> list_dir(const std::string& path, const std::string& pattern="");
std::vector<std::string> split(const std::string& path, char* characters);
}
#endif //UTIL_UTIL_H
<file_sep>/main.cpp
#include "util.h"
using namespace std;
int main() {
const string path("/home/ubuntu/APR/zhang_test/");
vector<string> file_list = u_util::list_dir(path, string(".py"));
for (auto iter = file_list.begin(); iter!=file_list.end();iter++) {
cout << *iter << endl;
}
cout << path << endl;
char* split_cs = "/";
vector<string> splits = u_util::split(path, split_cs);
cout << splits.size()<<endl;
for (auto iter = splits.begin(); iter!=splits.end();iter++) {
cout << *iter << endl;
}
return 0;
}<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.9)
project(Util)
set(CMAKE_CXX_STANDARD 11)
set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)
find_package(Boost REQUIRED COMPONENTS serialization filesystem)
include_directories(${PROJECT_SOURCE_DIR}/include)
link_directories(${PROJECT_SOURCE_DIR}/lib/)
add_subdirectory(${PROJECT_SOURCE_DIR}/source)
add_executable(TEST main.cpp)
target_link_libraries(TEST ${Boost_LIBRARIES} Util)
<file_sep>/source/util.cpp
//
// Created by ubuntu on 18-4-29.
//
#include "util.h"
using namespace std;
namespace fs = boost::filesystem;
namespace u_util{
vector<string> list_dir(const string& path, const string& pattern) {
vector<string> ret;
const fs::path root_path(path);
if (fs::exists(root_path)==false) {
cout << "Your path is not exist!" << endl;
return ret;
}
fs::directory_iterator dir_iter(root_path), iter_end;
for (; dir_iter != iter_end; ++dir_iter) {
if (pattern == ""){
ret.push_back(dir_iter->path().string());
} else {
string file_name = dir_iter->path().filename().string();
if (file_name.find(pattern)!=std::string::npos) {
ret.push_back(file_name);
}
}
}
return ret;
}
vector<string> split(const std::string& path, char* characters) {
vector<string> ret;
if (path.length() == 0) {
printf("Your path is empty! Please check it!");
return ret;
}
const char* c_path = path.c_str();
char* __s = strdup(c_path);
for(char* p = strsep(&__s, characters); p!=NULL; p=strsep(&__s, characters)) {
if (strlen(p) != 0)
ret.push_back(string(p));
}
return ret;
}
}
<file_sep>/README.md
# Some useful function of cpp
## CMakeLists.txt
1.在CMakeLists.txt中添加Boost的依赖,首先要确保系统中加入了Boost库的相关文件
2.在文件中添加find_package(Boost REQUIRED COMPONENTS serialization filesystem),注意不要省事儿少些后面的COMPONENTS
<file_sep>/source/CMakeLists.txt
cmake_minimum_required(VERSION 3.9)
set(CMAKE_CXX_STANDARD 11)
include_directories(${PROJECT_SOURCE_DIR}/include)
aux_source_directory(${PROJECT_SOURCE_DIR}/source SOURCE)
add_library(Util SHARED ${SOURCE})
target_link_libraries(Util ${Boost_LIBRARIES})
| ea9ffaed945b2d65455d3c9f2be1c729eb617be4 | [
"Markdown",
"CMake",
"C++"
] | 6 | C++ | wuRDmemory/Cpp_Util | 717c837aa97ced32e18de1c450e2c114d9033996 | 831dc003c7a3783b9d315e6e855f6a1372b9fffb |
refs/heads/main | <repo_name>lana0911/server<file_sep>/s1.py
from os import truncate
import numpy as np
import cv2
import socket
import threading
import time
from threading import Timer
# from socket import *
import jpysocket
import base64
import time
#client連進來後會在這
def classfly(client_executor, addr):
print("welcome to classfy")
print('Accept new connection from %s:%s...' % addr)
BUFSIZ = 1024*20
who = client_executor.recv(1024)
who = jpysocket.jpydecode(who)
print("first=",who,"first=","face")
if who == "face":
print("else")
while True:
data = client_executor.recv(BUFSIZ)
if not data or len(data) == 0:
break
else:
rec_d = rec_d + data
path = 'D:/task/d.txt'
f = open(path, 'w')
f.write(str(rec_d))
f.close()
with open("D:/task/d.txt","r") as f:
img = base64.b64decode(f.read()[1:])
print(type(f.read()))
fh = open("D:/task/pic_2_sucess22.jpg","wb")
fh.write(img)
fh.close()
time.sleep(1)
fa = open("D:/task/rec.txt","r")
rec_send = fa.readline()
print(rec_send)
client_executor.close()
client_executor, addr = client_executor.accept()
client_executor.send(jpysocket.jpyencode(rec_send))
print('send complete')
client_executor.close()
# #不斷輸入文字傳給unity
# while True:
# str = input("input:")
# client_executor.send(str.encode('utf-8'))
#主函式
if __name__ == '__main__':
# IP , Port......設定
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.bind(('192.168.50.21', 5050))
listener.listen(5)
print('Waiting for connect...')
while True:
client_executor, addr = listener.accept()
t = threading.Thread(target=classfly, args=(client_executor, addr))
t.start()
| 424c02f943af4dad163d597227197281e599a567 | [
"Python"
] | 1 | Python | lana0911/server | a0d45d9d0b17763a0421514b673d47d2a4a0c4af | fe01a108dac655b6c1509db6d925d51db7c3296a |
refs/heads/master | <repo_name>PCreations/SocialConnect<file_sep>/Controller/SocialConnectController.php
<?php
App::uses('SocialConnectAppController', 'SocialConnect.Controller');
App::uses('Router', 'Cake/Routing');
class SocialConnectController extends SocialConnectAppController {
const GOOGLE_CONNECT_URL = 'https://www.google.com/accounts/o8/id';
public $components = array(
'SocialConnect.SocialConnect',
'Session'
);
public function google_connect() {
$this->SocialConnect->setProvider('google');
debug($this->SocialConnect->isAuth());
if(!$this->SocialConnect->isAuth()) {
if(isset($_GET['login'])) {
//set required params to retrieve
$this->SocialConnect->setRequiredAttributes(array(
'email',
'country',
'gender',
));
$this->SocialConnect->setOptionalAttributes(array(
'firstname',
'lastname'
));
$this->SocialConnect->auth();
}
}
elseif($this->SocialConnect->isValidate()) {
$this->redirect($this->SocialConnect->registerCallbackUrl());
}
else {
echo 'User has not logged in.';
}
}
public function facebook_connect() {
$this->SocialConnect->setProvider('facebook');
debug($this->SocialConnect->isAuth());
if(!$this->SocialConnect->isAuth()) {
if(isset($_GET['login'])) {
$this->SocialConnect->setRequiredAttributes(array(
'user_activities',
'user_birthday',
'user_checkins',
'user_education_history',
'user_events',
'user_groups',
'user_hometown',
'user_interests',
'user_likes',
'user_location',
'user_notes',
'user_photos',
'user_questions',
'user_relationships',
'user_relationship_details',
'user_religion_politics',
'user_status',
'user_subscriptions',
'user_videos',
'user_website',
'user_work_history',
'email',
'user_about_me',
));
$this->SocialConnect->auth();
}
}
elseif($this->SocialConnect->isValidate()) {
$this->redirect($this->SocialConnect->registerCallbackUrl());
}
else {
echo 'User has not logged in.';
}
//$this->SocialConnect->logout();
}
}
?><file_sep>/View/Helper/SocialConnectHelper.php
<?php
class SocialConnectHelper extends AppHelper {
public $helpers = array('Html', 'Form');
public function googleConnect() {
$callbackURL = $this->url(Configure::read('SocialConnect.Google.OpenidCallback'), true);
return $this->Html->image(
'SocialConnect.google/mini_btn_google.png',
array(
'alt' => 'Connect with google account',
'url' => $callbackURL
)
);
}
}
?><file_sep>/View/SocialConnect/google_connect.ctp
<form action="?login" method="post">
<button>Login with Google</button>
</form><file_sep>/Controller/Component/SocialConnectComponent.php
<?php
App::uses('GoogleProvider', 'SocialConnect.Lib');
App::uses('FacebookProvider', 'SocialConnect.Lib');
class SocialConnectComponent extends Component {
private $provider;
public $controller;
public function initialize(Controller $controller) {
$this->controller = $controller;
}
public function setProvider($provider) {
switch($provider) {
case 'google':
$this->provider = new GoogleProvider(FULL_BASE_URL);
break;
case 'facebook':
$this->provider = new FacebookProvider(Configure::read('SocialConnect.Facebook.Credentials'));
break;
}
}
public function isAuth() {
return $this->provider->isAuth();
}
public function isAuthCanceled() {
return $this->provider->isAuthCanceled();
}
public function auth() {
$this->provider->auth();
}
public function isValidate() {
return $this->provider->isValidate();
}
public function getProvider() {
return $this->provider->getProvider();
}
public function getUserId() {
return $this->provider->getId();
}
public function setRequiredAttributes($attributes) {
$this->provider->setRequiredAttributes($attributes);
}
public function setOptionalAttributes($attributes) {
$this->provider->setOptionalAttributes($attributes);
}
public function logout() {
$this->provider->logout();
}
public function getUserInfo($name) {
return $this->provider->getAttribute($name);
}
public function registerCallbackUrl() {
$provider = $this->getProvider();
$attributes = $this->provider->getRetrievedAttributes();
$params = array(
'?' => array_merge(
array(
'provider' => $provider,
),
$attributes
)
);
return Hash::merge(Configure::read('SocialConnect.'.ucfirst($provider).'.RegisterCallback'), $params);
}
public function prefillRegisterForm() {
debug($this->controller->request->query);
if(isset($this->controller->request->query['provider'])) {
unset($this->controller->request->query['provider']);
$fields = Configure::read('SocialConnect.Fields');
$userModel = Configure::read('SocialConnect.UserModel');
foreach($this->controller->request->query as $name => $value) {
//if(!in_array($name, $this->getAllowedAttributes) continue;
$fieldName = isset($fields[$name]) ? $fields[$name] : $name;
$this->controller->request->data[$userModel][$fieldName] = $value;
}
}
}
private function getAllAttributesFromProvider() {
return array_merge($this->provider->getRequiredAttributes(), $this->provider->getOptionalAttributes());
}
}
?><file_sep>/Config/bootstrap.php
<?php
define('Auth_OpenID_RAND_SOURCE', null);
Configure::write('SocialConnect.Google.OpenidCallback', array(
'plugin' => 'social_connect',
'controller' => 'social_connect',
'action' => 'google_connect',
));
Configure::write('SocialConnect.Google.RegisterCallback', array(
'plugin' => null,
'controller' => '/',
'action' => 'register',
));
Configure::write('SocialConnect.Facebook.RegisterCallback', array(
'plugin' => null,
'controller' => '/',
'action' => 'register',
));
Configure::write('SocialConnect.Facebook.Credentials', array(
'appId' => '317368205014155',
'secret' => '617a666e8842cecacddf7083e923ddb6',
'cookie' => false
));
Configure::write('SocialConnect.Fields', array(
'email' => 'email',
'country' => 'country'
));
Configure::write('SocialConnect.UserModel', 'AppUser');
?><file_sep>/View/SocialConnect/facebook_connect.ctp
<form action="?login" method="post">
<button>Login with Facebook</button>
</form><file_sep>/Lib/GoogleProvider.php
<?php
App::uses('Provider', 'SocialConnect.Lib');
App::uses('LightOpenID', 'SocialConnect.Lib');
class GoogleProvider extends LightOpenID implements Provider {
const GOOGLE_CONNECT_URL = 'https://www.google.com/accounts/o8/id';
static protected $ax_to_sreg = array(
'contact/email' => 'email',
'namePerson/first' => 'firstname',
'namePerson/last' => 'lastname',
'birthDate' => 'dob',
'person/gender' => 'gender',
'contact/postalCode/home' => 'postcode',
'contact/country/home' => 'country',
'pref/language' => 'language',
'pref/timezone' => 'timezone',
);
function __construct($host) {
parent::__construct($host);
$this->identity = self::GOOGLE_CONNECT_URL;
}
//protected $id;
/*protected function request($url, $method='GET', $params=array(), $update_claimed_id=false) {
parent::request($url, $method, $params, $update_claimed_id);
switch($method) {
case 'GET':
$this->setId($_GET['id']);
break;
case 'POST':
default:
$this->setId($_POST['id']);
}
}*/
/*public function setId($id) {
$this->id = $id;
}*/
public function getProvider() {
return 'google';
}
public function getId() {
return $this->identity;
}
public function isAuth() {
return $this->mode !== null;
}
public function auth() {
header('Location: ' . $this->authUrl());
exit();
}
public function isAuthCanceled() {
return $this->mode == 'cancel';
}
public function isValidate() {
return $this->validate();
}
public function setRequiredAttributes($attributes) {
$sregToAx = array_flip(self::$ax_to_sreg);
foreach($attributes as $attribute) {
$this->required[] = $sregToAx[$attribute];
}
}
public function setOptionalAttributes($attributes) {
$sregToAx = array_flip(self::$ax_to_sreg);
foreach($attributes as $attribute) {
$this->optional[] = $sregToAx[$attribute];
}
}
public function getAllowedAttributes() {
return array_flip($this->$ax_to_sreg);
}
public function getRequiredAttributes() {
$required = array();
foreach($this->required as $attribute) {
$required[] = self::$ax_to_sreg[$attribute];
}
return $required;
}
public function getOptionalAttributes() {
$optional = array();
foreach($this->optional as $attribute) {
$optional[] = self::$ax_to_sreg[$attribute];
}
return $optional;
return $this->optional;
}
protected function axParams()
{
$params = array();
if ($this->required || $this->optional) {
$params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0';
$params['openid.ax.mode'] = 'fetch_request';
$this->aliases = array();
$counts = array();
$required = array();
$optional = array();
foreach (array('required','optional') as $type) {
foreach ($this->$type as $alias => $field) {
if (is_int($alias)) $alias = self::$ax_to_sreg[$field];
$this->aliases[$alias] = 'http://axschema.org/' . $field;
if (empty($counts[$alias])) $counts[$alias] = 0;
$counts[$alias] += 1;
${$type}[] = $alias;
}
}
foreach ($this->aliases as $alias => $ns) {
$params['openid.ax.type.' . $alias] = $ns;
}
foreach ($counts as $alias => $count) {
if ($count == 1) continue;
$params['openid.ax.count.' . $alias] = $count;
}
# Don't send empty ax.requied and ax.if_available.
# Google and possibly other providers refuse to support ax when one of these is empty.
if($required) {
$params['openid.ax.required'] = implode(',', $required);
}
if($optional) {
$params['openid.ax.if_available'] = implode(',', $optional);
}
}
return $params;
}
public function getAttribute($name) {
$sregToAx = array_flip(self::$ax_to_sreg);
$attributes = $this->getAttributes();
return isset($attributes[$sregToAx[$name]]) ? $attributes[$sregToAx[$name]] : '';
}
public function getRetrievedAttributes() {
$attributes = array();
foreach($this->getAttributes() as $name => $value) {
$attributes[self::$ax_to_sreg[$name]] = $value;
}
return $attributes;
}
}
?><file_sep>/Lib/Provider.php
<?php
interface Provider {
public function getProvider();
public function getId();
public function getAttribute($name);
public function isAuth();
public function auth();
public function isAuthCanceled();
public function isValidate();
public function setRequiredAttributes($attributes);
public function setOptionalAttributes($attributes);
public function getAllowedAttributes();
public function getRequiredAttributes();
public function getOptionalAttributes();
public function getRetrievedAttributes();
}
?><file_sep>/Lib/FacebookProvider.php
<?php
App::uses('Provider', 'SocialConnect.Lib');
App::uses('LightOpenID', 'SocialConnect.Lib');
App::uses('Facebook', 'SocialConnect.Lib');
class FacebookProvider extends Facebook implements Provider {
//protected $id;
protected $userInfos = null;
protected $required = array();
protected $permissions = array(
'user_about_me'
'user_activities',
'user_birthday',
'user_checkins',
'user_education_history',
'user_events',
'user_groups',
'user_hometown',
'user_interests',
'user_likes',
'user_location',
'user_notes',
'user_photos',
'user_questions',
'user_relationships',
'user_relationship_details',
'user_religion_politics',
'user_status',
'user_subscriptions',
'user_videos',
'user_website',
'user_work_history',
'email'
);
/*protected function request($url, $method='GET', $params=array(), $update_claimed_id=false) {
parent::request($url, $method, $params, $update_claimed_id);
switch($method) {
case 'GET':
$this->setId($_GET['id']);
break;
case 'POST':
default:
$this->setId($_POST['id']);
}
}*/
/*public function setId($id) {
$this->id = $id;
}*/
public function getProvider() {
return 'facebook';
}
public function getId() {
return $this->getUser();
}
public function getPicture() {
return ($this->getId() !== null) ? 'https://graph.facebook.com/'.$this->getId().'/picture' : null;
}
public function isAuth() {
return $this->getUser() !== 0;
}
public function auth() {
header('Location: ' . $this->getLoginUrl($this->getScope()));
exit();
}
public function isAuthCanceled() {
return $this->mode == 'cancel';
}
public function isValidate() {
try {
$this->userInfos = $this->api('/me', 'GET');
return true;
}
catch(FacebookApiException $e) {
return false;
}
}
public function logout() {
header('Location: ' . $this->getLogoutUrl($params));
exit();
}
public function getAttribute($name) {
if($name == 'picture') {
return $this->getPicture();
}
if($this->userInfos == null) {
try {
$this->userInfos = $this->api('/me');
}catch(FacebookApiException $e) {
debug($e);
}
}
debug($this->userInfos);
return isset($this->userInfos[$name]) ? $this->userInfos[$name] : '';
}
public function getScope() {
foreach($this->required as $key => $attribute) {
if(in_array($attribute, $this->permissions)) continue;
unset($this->required[$key]);
}
return array('scope' => $this->required);
}
public function setRequiredAttributes($attributes) {
$this->required = $attributes;
}
public function setOptionalAttributes($attributes) {
$this->required = array_merge($this->required, $attributes);
}
public function getAllowedAttributes() {
}
public function getRequiredAttributes() {
return $this->required;
}
public function getOptionalAttributes() {
return $this->required;
}
public function getRetrievedAttributes() {
return $this->getUserInfos();
}
public function getUserInfos() {
if($this->userInfos == null) {
$this->userInfos = $this->api('/me', 'GET');
}
return $this->userInfos;
}
}
?><file_sep>/Model/SocialConnectAppModel.php
<?php
class SocialConnectAppModel extends AppModel {
}
<file_sep>/Controller/SocialConnectAppController.php
<?php
class SocialConnectAppController extends AppController {
}
| 8fb3a6a472e56d8b6557bc11c93aefc7aed0d5d7 | [
"PHP"
] | 11 | PHP | PCreations/SocialConnect | 49c2f4615c04fd85c4bd6a652e1fcab0a18d6d62 | 55db606a6bccb9fc3a9fe31c1ac11ed52b1db588 |
refs/heads/master | <repo_name>Zentryn/Ball-Game<file_sep>/Ball Game/MainGame.cpp
#include "MainGame.h"
// Some helpful constants.
const float DESIRED_FPS = 144.0f; // FPS the game is designed to run at
const int MAX_PHYSICS_STEPS = 6; // Max number of physics steps per frame
const float MS_PER_SECOND = 1000; // Number of milliseconds in a second
const float DESIRED_FRAMETIME = MS_PER_SECOND / DESIRED_FPS; // The desired frame time per frame
const float MAX_DELTA_TIME = 1.0f; // Maximum size of deltaTime
MainGame::~MainGame()
{
for (size_t i = 0; i < m_ballRenderers.size(); i++) {
delete m_ballRenderers[i];
}
}
void MainGame::run()
{
initSystems();
gameLoop();
}
void MainGame::initSystems()
{
Bengine::init();
m_window.create("Ball Game", m_screenWidth, m_screenHeight, 0, false);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
m_camera.init(m_screenWidth, m_screenHeight);
// Point camera to the center of the screen
m_camera.setPosition(glm::vec2(m_screenWidth / 2.0f, m_screenHeight / 2.0f));
m_spriteBatch.init();
// Initialize sprite font
m_spriteFont = std::make_unique<Bengine::SpriteFont>("Fonts/04B_30__.TTF", 40);
// Compile texture shader
initShaders();
m_fpsLimiter.setMaxFPS(144.0f);
initBalls();
initRenderers();
resetKeys();
}
void MainGame::initShaders()
{
m_textureProgram.compileShaders("Shaders/textureShading.vert", "Shaders/textureShading.frag");
m_textureProgram.addAttribute("vertexPosition");
m_textureProgram.addAttribute("vertexColor");
m_textureProgram.addAttribute("vertexUV");
m_textureProgram.linkShaders();
}
void MainGame::initRenderers()
{
m_ballRenderers.emplace_back(new BallRenderer);
m_ballRenderers.emplace_back(new MomentumRenderer);
m_ballRenderers.emplace_back(new VelocityRenderer(m_screenWidth, m_screenHeight));
}
struct BallSpawn {
BallSpawn(Bengine::ColorRGBA8 Color,
float Mass,
float Radius,
float Probability
) :
color(Color),
mass(Mass),
radius(Radius),
probability(Probability)
{}
Bengine::ColorRGBA8 color;
float mass;
float radius;
float probability;
};
void MainGame::initBalls()
{
// Initialize grid
m_grid = std::make_unique<Grid>(m_screenWidth, m_screenHeight, CELL_SIZE);
#define ADD_BALL(p, ...) \
totalProbability += p; \
possibleBalls.emplace_back(__VA_ARGS__);
// Amount of balls in the game
const int NUM_BALLS = 10000;
// All ball's to spawn
std::vector<BallSpawn> possibleBalls;
float totalProbability = 0.0f;
// Get random engine and random values
std::mt19937 randomEngine((unsigned int)time(nullptr));
std::uniform_int_distribution<int> rcolor(0, 255);
std::uniform_real_distribution<float> rm(3.0f, 6.0f);
std::uniform_real_distribution<float> randDir(-1.0f, 1.0f);
std::uniform_real_distribution<float> randX(0.0f, (float)m_screenWidth);
std::uniform_real_distribution<float> randY(0.0f, (float)m_screenHeight);
for (size_t i = 0; i < NUM_BALLS; i++) {
float size_mass = rm(randomEngine);
ADD_BALL(1.0f, Bengine::ColorRGBA8(rcolor(randomEngine), rcolor(randomEngine), rcolor(randomEngine), 255),
size_mass, size_mass, totalProbability);
}
std::uniform_real_distribution<float> spawnChance(0.0f, totalProbability);
// Reserve space for the balls, prevents extra ball allocation
m_balls.reserve(NUM_BALLS);
BallSpawn* ballToSpawn = &possibleBalls[0];
for (size_t i = 0; i < NUM_BALLS; i++) {
float spawnVal = spawnChance(randomEngine);
for (size_t j = 0; j < possibleBalls.size(); j++) {
if (spawnVal <= possibleBalls[j].probability) {
ballToSpawn = &possibleBalls[j];
break;
}
}
glm::vec2 direction(randDir(randomEngine), randDir(randomEngine));
direction = glm::normalize(direction);
// Get random spawn position
glm::vec2 pos(randX(randomEngine), randY(randomEngine));
static const unsigned int texture = Bengine::ResourceManager::getTexture("Textures/circle.png").id;
// Add the ball. Don't add balls after this function or the grid will fuck up.
m_balls.emplace_back(
ballToSpawn->mass,
ballToSpawn->radius, pos,
direction,
texture,
ballToSpawn->color
);
// Add the latest ball to the grid
m_grid->addBall(&m_balls.back());
}
}
void MainGame::resetKeys()
{
m_inputManager.releaseKey(SDLK_LEFT);
m_inputManager.releaseKey(SDLK_RIGHT);
m_inputManager.releaseKey(SDLK_UP);
m_inputManager.releaseKey(SDLK_DOWN);
m_inputManager.releaseKey(SDLK_SPACE);
m_inputManager.releaseKey(SDLK_LCTRL);
m_inputManager.releaseKey(SDLK_1);
}
void MainGame::gameLoop()
{
Uint32 previousTicks = SDL_GetTicks();
while (m_gameState == GameState::RUNNING) {
m_fpsLimiter.begin();
processInput();
// Calculate the frameTime in milliseconds
Uint32 newTicks = SDL_GetTicks();
Uint32 frameTime = newTicks - previousTicks;
previousTicks = newTicks; // Store newTicks in previousTicks so we can use it next frame
// Get the total delta time
float totalDeltaTime = (float)frameTime / DESIRED_FRAMETIME;
// This counter makes sure we don't spiral to death!
int i = 0;
// Loop while we still have steps to process.
while (totalDeltaTime > 0.0f && i < MAX_PHYSICS_STEPS) {
// The deltaTime should be the the smaller of the totalDeltaTime and MAX_DELTA_TIME
float deltaTime = std::min(totalDeltaTime, MAX_DELTA_TIME);
// Update all physics here and pass in deltaTime
update(deltaTime);
// Since we just took a step that is length deltaTime, subtract from totalDeltaTime
totalDeltaTime -= deltaTime;
// Increment our frame counter so we can limit steps to MAX_PHYSICS_STEPS
i++;
}
m_camera.update();
drawGame();
m_fps = m_fpsLimiter.end();
}
}
void MainGame::update(float deltaTime)
{
m_ballController.updateBalls(m_balls, m_grid.get(), deltaTime, m_screenWidth, m_screenHeight);
}
void MainGame::processInput()
{
m_inputManager.update();
SDL_Event evnt;
while (SDL_PollEvent(&evnt)) {
switch (evnt.type) {
case SDL_QUIT:
m_gameState = GameState::EXIT;
break;
case SDL_KEYDOWN:
m_inputManager.pressKey(evnt.key.keysym.sym);
break;
case SDL_KEYUP:
m_inputManager.releaseKey(evnt.key.keysym.sym);
break;
case SDL_MOUSEBUTTONDOWN:
m_ballController.onMouseDown(glm::vec2((float)evnt.button.x, (float)m_screenHeight - (float)evnt.button.y), m_balls);
break;
case SDL_MOUSEBUTTONUP:
m_ballController.onMouseUp(glm::vec2((float)evnt.button.x, (float)evnt.button.y), m_balls);
break;
case SDL_MOUSEMOTION:
m_ballController.onMouseMove(glm::vec2((float)evnt.motion.x, (float)m_screenHeight - (float)evnt.motion.y), m_balls);
break;
}
}
// Set gravity direction
if (m_inputManager.isKeyPressed(SDLK_LEFT)) {
m_ballController.setGravityDirection(GravityDirection::LEFT);
}
else if (m_inputManager.isKeyPressed(SDLK_RIGHT)) {
m_ballController.setGravityDirection(GravityDirection::RIGHT);
}
else if (m_inputManager.isKeyPressed(SDLK_UP)) {
m_ballController.setGravityDirection(GravityDirection::UP);
}
else if (m_inputManager.isKeyPressed(SDLK_DOWN)) {
m_ballController.setGravityDirection(GravityDirection::DOWN);
}
else if (m_inputManager.isKeyPressed(SDLK_SPACE)) {
m_ballController.setGravityDirection(GravityDirection::NONE);
}
if (m_inputManager.isKeyPressed(SDLK_1)) {
m_currentRenderer++;
if (m_currentRenderer >= (int)m_ballRenderers.size()) {
m_currentRenderer = 0;
}
}
}
void MainGame::drawGame()
{
// Set the base depth to 1.0
glClearDepth(1.0);
// Clear the color and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
// Grab the camera matrix
glm::mat4 projectionMatrix = m_camera.getCameraMatrix();
m_ballRenderers[m_currentRenderer]->renderBalls(m_spriteBatch, m_balls, projectionMatrix);
m_textureProgram.use();
// Make sure the shader uses texture 0
GLint textureUniform = m_textureProgram.getUniformLocation("mySampler");
glUniform1i(textureUniform, 0);
GLint pUniform = m_textureProgram.getUniformLocation("P");
glUniformMatrix4fv(pUniform, 1, GL_FALSE, &projectionMatrix[0][0]);
drawHud();
m_textureProgram.unuse();
m_window.swapBuffer();
}
void MainGame::drawHud()
{
const Bengine::ColorRGBA8 fontColor(255, 0, 0, 255);
char buffer[64];
sprintf_s(buffer, "%.1f", m_fps);
m_spriteBatch.begin();
m_spriteFont->draw(m_spriteBatch, buffer, glm::vec2(0.0f, m_screenHeight - 38.0f),
glm::vec2(1.0f), 0.0f, fontColor);
m_spriteBatch.end();
m_spriteBatch.renderBatch();
}
<file_sep>/Ball Game/BallController.h
#pragma once
#include <iostream>
#include <vector>
#include "Ball.h"
enum class GravityDirection { NONE, UP, DOWN, LEFT, RIGHT };
class Grid;
class BallController
{
public:
BallController();
~BallController();
void updateBalls(std::vector<Ball>& balls, Grid* grid, float deltaTime, int maxX, int maxY);
void onMouseDown(glm::vec2 mouseCoords, std::vector<Ball>& balls);
void onMouseUp(glm::vec2 mouseCoords, std::vector<Ball>& balls);
void onMouseMove(glm::vec2 mouseCoords, std::vector<Ball>& balls);
void setGravityDirection(GravityDirection dir) { m_gravityDirection = dir; }
private:
void updateCollision(Grid* grid);
// Checks collision between two balls
void checkCollision(Ball& ball1, Ball& ball2);
// Checks collision between ball and vector of balls
void checkCollision(Ball* ball, std::vector<Ball*>& ballVector, int startingIndex);
bool isMouseOnBall(Ball& b, float mouseX, float mouseY);
glm::vec2 getGravity();
GravityDirection m_gravityDirection = GravityDirection::NONE;
int m_grabbedBall = -1;
glm::vec2 m_grabOffset;
glm::vec2 m_lastPos;
};
<file_sep>/Ball Game/Ball.cpp
#include "Ball.h"
Ball::Ball(float mass,
float radius,
const glm::vec2& position,
const glm::vec2& velocity,
unsigned int textureID,
const Bengine::ColorRGBA8& color)
{
this->mass = mass;
this->radius = radius;
this->position = position;
this->velocity = velocity;
this->textureID = textureID;
this->color = color;
}<file_sep>/Ball Game/BallRenderer.cpp
#include "BallRenderer.h"
void BallRenderer::renderBalls(Bengine::SpriteBatch& spriteBatch,
const std::vector<Ball>& balls,
const glm::mat4& projectionMatrix)
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Lazily initialize the program
if (m_program == nullptr) {
m_program = std::make_unique<Bengine::GLSLProgram>();
m_program->compileShaders("Shaders/textureShading.vert", "Shaders/textureShading.frag");
m_program->addAttribute("vertexPosition");
m_program->addAttribute("vertexColor");
m_program->addAttribute("vertexUV");
m_program->linkShaders();
}
m_program->use();
spriteBatch.begin();
// Make sure the shader uses texture 0
glActiveTexture(GL_TEXTURE0);
GLint textureUniform = m_program->getUniformLocation("mySampler");
glUniform1i(textureUniform, 0);
// Grab the camera matrix
GLint pUniform = m_program->getUniformLocation("P");
glUniformMatrix4fv(pUniform, 1, GL_FALSE, &projectionMatrix[0][0]);
for (auto& ball : balls) {
const glm::vec4 uvRect(0.0f, 0.0f, 1.0f, 1.0f);
const glm::vec4 destRect(ball.position.x - ball.radius, ball.position.y - ball.radius,
ball.radius * 2.0f, ball.radius * 2.0f);
spriteBatch.draw(destRect, uvRect, ball.textureID, 0.0f, ball.color);
}
spriteBatch.end();
spriteBatch.renderBatch();
m_program->unuse();
}
void MomentumRenderer::renderBalls(Bengine::SpriteBatch& spriteBatch,
const std::vector<Ball>& balls,
const glm::mat4& projectionMatrix)
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Lazily initialize the program
if (m_program == nullptr) {
m_program = std::make_unique<Bengine::GLSLProgram>();
m_program->compileShaders("Shaders/textureShading.vert", "Shaders/textureShading.frag");
m_program->addAttribute("vertexPosition");
m_program->addAttribute("vertexColor");
m_program->addAttribute("vertexUV");
m_program->linkShaders();
}
m_program->use();
spriteBatch.begin();
// Make sure the shader uses texture 0
glActiveTexture(GL_TEXTURE0);
GLint textureUniform = m_program->getUniformLocation("mySampler");
glUniform1i(textureUniform, 0);
// Grab the camera matrix
GLint pUniform = m_program->getUniformLocation("P");
glUniformMatrix4fv(pUniform, 1, GL_FALSE, &projectionMatrix[0][0]);
for (auto& ball : balls) {
const glm::vec4 uvRect(0.0f, 0.0f, 1.0f, 1.0f);
const glm::vec4 destRect(ball.position.x - ball.radius, ball.position.y - ball.radius,
ball.radius * 2.0f, ball.radius * 2.0f);
Bengine::ColorRGBA8 color;
GLubyte colorVal = (GLubyte)(glm::clamp(glm::length(ball.velocity) * ball.mass * 12, 0.0f, 255.0f));
color.r = colorVal;
color.g = colorVal;
color.b = colorVal;
color.a = colorVal;
spriteBatch.draw(destRect, uvRect, ball.textureID, 0.0f, color);
}
spriteBatch.end();
spriteBatch.renderBatch();
m_program->unuse();
}
VelocityRenderer::VelocityRenderer(int screenWidth, int screenHeight) :
m_screenWidth(screenWidth), m_screenHeight(screenHeight)
{
// Empty
}
void VelocityRenderer::renderBalls(Bengine::SpriteBatch& spriteBatch, const std::vector<Ball>& balls, const glm::mat4& projectionMatrix)
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Lazily initialize the program
if (m_program == nullptr) {
m_program = std::make_unique<Bengine::GLSLProgram>();
m_program->compileShaders("Shaders/textureShading.vert", "Shaders/textureShading.frag");
m_program->addAttribute("vertexPosition");
m_program->addAttribute("vertexColor");
m_program->addAttribute("vertexUV");
m_program->linkShaders();
}
m_program->use();
spriteBatch.begin();
// Make sure the shader uses texture 0
glActiveTexture(GL_TEXTURE0);
GLint textureUniform = m_program->getUniformLocation("mySampler");
glUniform1i(textureUniform, 0);
// Grab the camera matrix
GLint pUniform = m_program->getUniformLocation("P");
glUniformMatrix4fv(pUniform, 1, GL_FALSE, &projectionMatrix[0][0]);
for (auto& ball : balls) {
const glm::vec4 uvRect(0.0f, 0.0f, 1.0f, 1.0f);
const glm::vec4 destRect(ball.position.x - ball.radius, ball.position.y - ball.radius,
ball.radius * 2.0f, ball.radius * 2.0f);
float mult = 100.0f;
Bengine::ColorRGBA8 color;
GLubyte colorVal = (GLubyte)(glm::clamp(ball.velocity.x * mult, 0.0f, 255.0f));
color.r = 128;
color.g = (GLubyte)((ball.position.x / m_screenWidth) * 255.0f); // More green to the right
color.b = (GLubyte)((ball.position.x / m_screenHeight) * 255.0f); // More blue to the top
color.a = colorVal;
spriteBatch.draw(destRect, uvRect, ball.textureID, 0.0f, color);
}
spriteBatch.end();
spriteBatch.renderBatch();
m_program->unuse();
}
<file_sep>/README.md
A fun game/toy where you can mess around with balls! Made with C++ using OpenGL and SDL.
<file_sep>/Ball Game/Ball.h
#pragma once
#include <glm/glm.hpp>
#include <GL/glew.h>
#include <Bengine/Vertex.h>
struct Cell;
// POD
struct Ball {
Ball(float mass,
float radius,
const glm::vec2& position,
const glm::vec2& velocity,
unsigned int textureID,
const Bengine::ColorRGBA8& color);
float mass;
float radius;
glm::vec2 position;
glm::vec2 velocity;
unsigned int textureID = 0;
Bengine::ColorRGBA8 color;
Cell* ownerCell = nullptr;
int cellVectorIndex = -1;
};
<file_sep>/Ball Game/MainGame.h
#pragma once
#include <iostream>
#include <vector>
#include <memory>
#include <random>
#include <ctime>
#include <cmath>
#include <algorithm>
#include <Bengine/Bengine.h>
#include <Bengine/Camera2D.h>
#include <Bengine/SpriteBatch.h>
#include <Bengine/InputManager.h>
#include <Bengine/Window.h>
#include <Bengine/GLSLProgram.h>
#include <Bengine/Timing.h>
#include <Bengine/SpriteFont.h>
#include <Bengine/ResourceManager.h>
#include "Grid.h"
#include "Ball.h"
#include "BallController.h"
#include "BallRenderer.h"
enum class GameState { RUNNING, EXIT };
const int CELL_SIZE = 12;
class MainGame
{
public:
void run(); ///< Starts the game
~MainGame();
private:
void initSystems(); ///< Initializes all core systems
void initShaders();
void initRenderers();
void initBalls(); ///< Initializes all of the balls
void resetKeys();
void gameLoop(); ///< The loop to keep the game running
void update(float deltaTime); ///< Updates everything
void processInput(); ///< Processes input from the user
void drawGame(); ///< Draws the game
void drawHud();
GameState m_gameState = GameState::RUNNING; ///< The state of the game
int m_screenWidth = 1920;
int m_screenHeight = 1080;
int m_currentRenderer = 0;
std::unique_ptr<Grid> m_grid; ///< Grid for spatal partitioning for collisions
std::vector<Ball> m_balls; ///< All of the balls
BallController m_ballController; ///< Ball controller
std::vector<BallRenderer*> m_ballRenderers;
Bengine::Window m_window; ///< The main window
Bengine::Camera2D m_camera; ///< Renders the scene
Bengine::SpriteBatch m_spriteBatch; ///< Renders all the balls
std::unique_ptr<Bengine::SpriteFont> m_spriteFont; ///< For font rendering
Bengine::InputManager m_inputManager; ///< Handles all inputs
Bengine::GLSLProgram m_textureProgram; ///< Shader for textures
Bengine::FPSLimiter m_fpsLimiter; ///< Limits and controls fps
float m_fps = 0.0f;
};
<file_sep>/Ball Game/BallRenderer.h
#pragma once
#include <Bengine/SpriteBatch.h>
#include <Bengine/GLSLProgram.h>
#include <memory>
#include "Ball.h"
class BallRenderer
{
public:
virtual void renderBalls(Bengine::SpriteBatch& spriteBatch,
const std::vector<Ball>& balls,
const glm::mat4& projectionMatrix);
protected:
std::unique_ptr<Bengine::GLSLProgram> m_program = nullptr;
};
class MomentumRenderer : public BallRenderer {
public:
virtual void renderBalls(Bengine::SpriteBatch& spriteBatch,
const std::vector<Ball>& balls,
const glm::mat4& projectionMatrix) override;
};
class VelocityRenderer : public BallRenderer {
public:
VelocityRenderer(int screenWidth, int screenHeight);
virtual void renderBalls(Bengine::SpriteBatch& spriteBatch,
const std::vector<Ball>& balls,
const glm::mat4& projectionMatrix) override;
private:
int m_screenWidth;
int m_screenHeight;
}; | 234ef6d67675b26d393fecf5a7a6bf3e11083daf | [
"Markdown",
"C",
"C++"
] | 8 | C++ | Zentryn/Ball-Game | ff321909b353dba6877bb1788aaed7372c655286 | 8a3dd0299843b4adee9db33a78310ab28fecc977 |
refs/heads/master | <repo_name>JTan04/Final-Project-Computer-Graphics<file_sep>/src/main.cpp
/*
Base code
Currently will make 2 FBOs and textures (only uses one in base code)
and writes out frame as a .png (Texture_output.png)
Winter 2017 - ZJW (Piddington texture write)
2017 integration with pitch and yaw camera lab (set up for texture mapping lab)
*/
#include <iostream>
#include <glad/glad.h>
#include "GLSL.h"
#include "Program.h"
#include "MatrixStack.h"
#include "Shape.h"
#include "WindowManager.h"
#include "GLTextureWriter.h"
// value_ptr for glm
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "stb_image.h"
#include "tiny_obj_loader.h"
using namespace std;
using namespace glm;
vector<vec3> positions(20);
vector<int> hit(20);
vector<float> explosion(20);
vec3 ballPos;
class Application : public EventCallbacks
{
public:
// Public variables
float time = 0;
float speed = 0;
float theta = 0;
float phi = 0;
float radius = 1;
float x,y,z;
float xs,ys,zs;
const float PI = 3.14159;
float shoot = 0;
float explode = 0;
WindowManager * windowManager = nullptr;
// Our shader program
std::shared_ptr<Program> prog;
std::shared_ptr<Program> texProg;
std::shared_ptr<Program> cubeProg;
shared_ptr<Shape> cube;
// Shape to be used (from obj file)
shared_ptr<Shape> shape;
shared_ptr<Shape> target;
//ground plane info
GLuint GrndBuffObj, GrndNorBuffObj, GrndTexBuffObj, GIndxBuffObj;
int gGiboLen;
// Contains vertex information for OpenGL
GLuint VertexArrayID;
// Data necessary to give our triangle to OpenGL
GLuint VertexBufferID;
//geometry for texture render
GLuint quad_VertexArrayID;
GLuint quad_vertexbuffer;
//reference to texture FBO
GLuint frameBuf[2];
GLuint texBuf[2];
GLuint depthBuf;
unsigned int cubeMapTexture;
bool FirstTime = true;
bool Moving = false;
int gMat = 0;
float cTheta = 0;
bool mouseDown = false;
bool thrown = false;
//for world
vec3 gDTrans = vec3(0);
float gDScale = 1.0;
void keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
if(key == GLFW_KEY_ESCAPE && (action == GLFW_PRESS || action == GLFW_REPEAT))
{
glfwSetWindowShouldClose(window, GL_TRUE);
}
else if (key == GLFW_KEY_M && (action == GLFW_PRESS || action == GLFW_REPEAT))
{
gMat = (gMat + 1) % 4;
}
else if (key == GLFW_KEY_A && (action == GLFW_PRESS || action == GLFW_REPEAT))
{
theta += 5*PI / 180;
}
else if (key == GLFW_KEY_D && (action == GLFW_PRESS || action == GLFW_REPEAT))
{
theta -= 5*PI / 180;
}
}
void scrollCallback(GLFWwindow* window, double deltaX, double deltaY)
{
// Set yaw based on deltaX
theta += (float) deltaX / 10;
// Cap pitch at 20 deg
phi -= (float) deltaY / 10;
if (phi > 0.936332)
phi = 0.936332;
else if (phi < -0.936332)
phi = -0.936332;
}
void mouseCallback(GLFWwindow *window, int button, int action, int mods)
{
double posX, posY;
if (action == GLFW_PRESS)
{
mouseDown = true;
glfwGetCursorPos(window, &posX, &posY);
Moving = true;
}
if (action == GLFW_RELEASE)
{
thrown = true;
mouseDown = false;
}
}
void resizeCallback(GLFWwindow *window, int width, int height)
{
glViewport(0, 0, width, height);
}
unsigned int createSky(string dir, vector<string> faces) {
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
int width, height, nrChannels;
stbi_set_flip_vertically_on_load(false);
for(GLuint i = 0; i < faces.size(); i++) {
unsigned char *data =
stbi_load((dir+faces[i]).c_str(), &width, &height, &nrChannels, 0);
if (data) {
glTexImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
} else {
std::cout << "failed to load: " << (dir+faces[i]).c_str() << std::endl;
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
cout << " creating cube map any errors : " << glGetError() << endl;
return textureID;
}
void initTex(const std::string& resourceDirectory)
{
vector<std::string> faces {
"drakeq_rt.tga",
"drakeq_lf.tga",
"drakeq_up.tga",
"drakeq_dn.tga",
"drakeq_ft.tga",
"drakeq_bk.tga"
};
cubeMapTexture = createSky(resourceDirectory + "/cracks/", faces);
}
void init(const std::string& resourceDirectory)
{
int width, height;
glfwGetFramebufferSize(windowManager->getHandle(), &width, &height);
GLSL::checkVersion();
cTheta = 0;
// Set background color.
glClearColor(.12f, .34f, .56f, 1.0f);
// Enable z-buffer test.
glEnable(GL_DEPTH_TEST);
// Initialize the GLSL program.
prog = make_shared<Program>();
prog->setVerbose(true);
prog->setShaderNames(
resourceDirectory + "/simple_vert.glsl",
resourceDirectory + "/simple_frag.glsl");
if (! prog->init())
{
std::cerr << "One or more shaders failed to compile... exiting!" << std::endl;
exit(1);
}
prog->addUniform("P");
prog->addUniform("MV");
prog->addUniform("MatAmb");
prog->addUniform("MatDif");
prog->addUniform("view");
prog->addAttribute("vertPos");
prog->addAttribute("vertNor");
prog->addAttribute("vertTex");
//create two frame buffer objects to toggle between
glGenFramebuffers(2, frameBuf);
glGenTextures(2, texBuf);
glGenRenderbuffers(1, &depthBuf);
createFBO(frameBuf[0], texBuf[0]);
//set up depth necessary as rendering a mesh that needs depth test
glBindRenderbuffer(GL_RENDERBUFFER, depthBuf);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuf);
//more FBO set up
GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, DrawBuffers);
//create another FBO so we can swap back and forth
createFBO(frameBuf[1], texBuf[1]);
//this one doesn't need depth
//set up the shaders to blur the FBO just a placeholder pass thru now
//next lab modify and possibly add other shaders to complete blur
texProg = make_shared<Program>();
texProg->setVerbose(true);
texProg->setShaderNames(
resourceDirectory + "/pass_vert.glsl",
resourceDirectory + "/tex_fragH.glsl");
if (! texProg->init())
{
std::cerr << "One or more shaders failed to compile... exiting!" << std::endl;
exit(1);
}
texProg->addUniform("texBuf");
texProg->addAttribute("vertPos");
texProg->addAttribute("vertTex");
texProg->addAttribute("vertNor");
texProg->addUniform("dir");
initTex(resourceDirectory);
cubeProg = make_shared<Program>();
cubeProg->setVerbose(true);
cubeProg->setShaderNames(
resourceDirectory + "/cube_vert.glsl",
resourceDirectory + "/cube_frag.glsl");
if (! cubeProg->init())
{
std::cerr << "One or more shaders failed to compile... exiting!" << std::endl;
exit(1);
}
cubeProg->addUniform("P");
cubeProg->addUniform("M");
cubeProg->addUniform("V");
cubeProg->addUniform("view");
cubeProg->addAttribute("vertPos");
}
void initGeom(const std::string& resourceDirectory)
{
vector<tinyobj::shape_t> TOshapes;
vector<tinyobj::material_t> objMaterials;
string errStr;
// Initialize the obj mesh VBOs etc
shape = make_shared<Shape>();
shape->loadMesh(resourceDirectory + "/sphere.obj");
shape->resize();
shape->init();
//Initialize the geometry to render a quad to the screen
initQuad();
// Initialize the obj mesh VBOs etc
target = make_shared<Shape>();
target->loadMesh(resourceDirectory + "/cube.obj");
target->resize();
target->init();
//Initialize the geometry to render a quad to the screen
initQuad();
cube = make_shared<Shape>();
cube->loadMesh(resourceDirectory + "/cube.obj");
cube->resize();
cube->init();
}
/**** geometry set up for a quad *****/
void initQuad()
{
//now set up a simple quad for rendering FBO
glGenVertexArrays(1, &quad_VertexArrayID);
glBindVertexArray(quad_VertexArrayID);
static const GLfloat g_quad_vertex_buffer_data[] =
{
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
-1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
};
glGenBuffers(1, &quad_vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW);
for (int i = 0; i<20; i++) {
positions[i] = glm::vec3(rand() % 20 - 10, rand() % 20 - 10, rand() % 20 - 10);
}
float g_groundSize = 20;
float g_groundY = -1.5;
// A x-z plane at y = g_groundY of dim[-g_groundSize, g_groundSize]^2
float GrndPos[] = {
-g_groundSize, g_groundY, -g_groundSize,
-g_groundSize, g_groundY, g_groundSize,
g_groundSize, g_groundY, g_groundSize,
g_groundSize, g_groundY, -g_groundSize
};
float GrndNorm[] = {
0, 1, 0,
0, 1, 0,
0, 1, 0,
0, 1, 0,
0, 1, 0,
0, 1, 0
};
float GrndTex[] = {
0, 0, // back
0, 1,
1, 1,
1, 0
};
unsigned short idx[] = {0, 1, 2, 0, 2, 3};
GLuint VertexArrayID;
//generate the VAO
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
gGiboLen = 6;
glGenBuffers(1, &GrndBuffObj);
glBindBuffer(GL_ARRAY_BUFFER, GrndBuffObj);
glBufferData(GL_ARRAY_BUFFER, sizeof(GrndPos), GrndPos, GL_STATIC_DRAW);
glGenBuffers(1, &GrndNorBuffObj);
glBindBuffer(GL_ARRAY_BUFFER, GrndNorBuffObj);
glBufferData(GL_ARRAY_BUFFER, sizeof(GrndNorm), GrndNorm, GL_STATIC_DRAW);
glGenBuffers(1, &GrndTexBuffObj);
glBindBuffer(GL_ARRAY_BUFFER, GrndTexBuffObj);
glBufferData(GL_ARRAY_BUFFER, sizeof(GrndTex), GrndTex, GL_STATIC_DRAW);
glGenBuffers(1, &GIndxBuffObj);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, GIndxBuffObj);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(idx), idx, GL_STATIC_DRAW);
}
/* Helper function to create the framebuffer object and
associated texture to write to */
void createFBO(GLuint& fb, GLuint& tex)
{
//initialize FBO
int width, height;
glfwGetFramebufferSize(windowManager->getHandle(), &width, &height);
//set up framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, fb);
//set up texture
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
cout << "Error setting up frame buffer - exiting" << endl;
exit(0);
}
}
// To complete image processing on the specificed texture
// Right now just draws large quad to the screen that is texture mapped
// with the prior scene image - next lab we will process
void ProcessImage(GLuint inTex)
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, inTex);
// example applying of 'drawing' the FBO texture - change shaders
texProg->bind();
glUniform1i(texProg->getUniform("texBuf"), 0);
glUniform2f(texProg->getUniform("dir"), -1, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void *) 0);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(0);
texProg->unbind();
}
vec3 calculateTrajectory(vec3 initialVelocity, float gravityInY, float time){
vec3 outDisplacement;
outDisplacement.x = initialVelocity.x * time;
outDisplacement.z = initialVelocity.z * time;
float timeSquared = time * time;
outDisplacement.y = (initialVelocity.y * time) + 0.5*(gravityInY * timeSquared);
return outDisplacement;
}
bool checkCollision(vec3 ball, vec3 cube){
float dx = ball.x - cube.x;
float dy = ball.y - cube.y;
float dz = ball.z - cube.z;
float distance = sqrt(dx*dx + dy*dy + dz*dz);
if(distance <= 1.3f){
return true;
}
return false;
}
int cur;
void render()
{
// Get current frame buffer size.
int width, height;
glfwGetFramebufferSize(windowManager->getHandle(), &width, &height);
glViewport(0, 0, width, height);
if (Moving)
{
//set up to render to buffer
glBindFramebuffer(GL_FRAMEBUFFER, frameBuf[0]);
}
else
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
// Clear framebuffer.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* Leave this code to just draw the meshes alone */
float aspect = width/(float)height;
// Setup yaw and pitch of camera for lookAt()
vec3 eye = vec3(0, 0 ,0);
x = radius*cos(phi)*cos(theta);
y = radius*sin(phi);
z = radius*cos(phi)*sin(theta);
vec3 center = vec3(x, y, z);
vec3 up = vec3(0, 1, 0);
// Create the matrix stacks
auto P = make_shared<MatrixStack>();
auto MV = make_shared<MatrixStack>();
// Apply perspective projection.
P->pushMatrix();
P->perspective(45.0f, aspect, 0.01f, 100.0f);
//Draw our scene - two meshes - right now to a texture
prog->bind();
glUniformMatrix4fv(prog->getUniform("P"), 1, GL_FALSE, value_ptr(P->topMatrix()));
// globl transforms for 'camera' (you will fix this now!)
MV->pushMatrix();
MV->loadIdentity();
/* draw left mesh */
MV->pushMatrix();
MV->scale(vec3(0.01, 0.01, 0.01));
MV->translate(vec3(0, 0, 0));
MV->rotate(-theta, vec3(0,1,0));
MV->translate(vec3(2, -1, 0));
SetMaterial(3);
glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE,value_ptr(MV->topMatrix()) );
glUniformMatrix4fv(prog->getUniform("view"), 1, GL_FALSE,value_ptr(lookAt(eye, center, up)));
if(!thrown){
shape->draw(prog);
}
MV->popMatrix();
MV->popMatrix();
P->popMatrix();
prog->unbind();
P->pushMatrix();
P->perspective(45.0f, aspect, 0.01f, 100.0f);
prog->bind();
glUniformMatrix4fv(prog->getUniform("P"), 1, GL_FALSE, value_ptr(P->topMatrix()));
// globl transforms for 'camera' (you will fix this now!)
MV->pushMatrix();
MV->loadIdentity();
//draw the ball that gets shot
MV->pushMatrix();
MV->scale(vec3(0.01, 0.01, 0.01));
MV->translate(vec3(0, 0, 0));
MV->translate(vec3(0, 0, 0));
vec3 yeet = calculateTrajectory(vec3(xs,ys,zs) * shoot, -.0018, time);
ballPos = yeet/10.0f;
MV->translate(yeet);
SetMaterial(3);
glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE,value_ptr(MV->topMatrix()) );
glUniformMatrix4fv(prog->getUniform("view"), 1, GL_FALSE,value_ptr(lookAt(eye, center, up)));
shape->draw(prog);
MV->popMatrix();
MV->popMatrix();
P->popMatrix();
prog->unbind();
P->pushMatrix();
P->perspective(45.0f, aspect, 0.01f, 100.0f);
prog->bind();
glUniformMatrix4fv(prog->getUniform("P"), 1, GL_FALSE, value_ptr(P->topMatrix()));
// globl transforms for 'camera' (you will fix this now!)
MV->pushMatrix();
MV->loadIdentity();
//draw 20 cubes made of 8 different cubes
for (int i = 0; i < 20; i++)
{
MV->pushMatrix();
MV->translate((positions[i]/10.0f));
MV->scale(vec3(0.05, 0.05, 0.05));
if(checkCollision(ballPos, positions[i] + vec3(.5,.5,.5)) || hit[i] == 1){
hit[i] = 1;
cur = i;
vec3 yeet = calculateTrajectory(vec3(xs, ys, zs) * explode, -.003, explosion[i]);
explosion[i] += 0.5;
MV->translate(yeet);
MV->rotate(explosion[i]/20, vec3(0, 1, 0));
MV->rotate(explosion[i]/20, vec3(0, 0, 1));
}
SetMaterial(i%4);
glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE,value_ptr(MV->topMatrix()) );
glUniformMatrix4fv(prog->getUniform("view"), 1, GL_FALSE,value_ptr(lookAt(eye, center, up)));
target->draw(prog);
MV->popMatrix();
MV->pushMatrix();
MV->translate(positions[i]/10.0f);
MV->translate(vec3(0.1, 0, 0));
MV->scale(vec3(0.05, 0.05, 0.05));
if(checkCollision(ballPos, positions[i]) || hit[i] == 1){
yeet = calculateTrajectory(vec3(xs+positions[i].x/5.0f,ys,zs) * explode, -.003, explosion[i]);
MV->translate(yeet);
MV->rotate(-explosion[i]/20, vec3(1, 0, 0));
MV->rotate(explosion[i]/20, vec3(0, 0, 1));
}
SetMaterial(i%4);
glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE,value_ptr(MV->topMatrix()) );
glUniformMatrix4fv(prog->getUniform("view"), 1, GL_FALSE,value_ptr(lookAt(eye, center, up)));
target->draw(prog);
MV->popMatrix();
MV->pushMatrix();
MV->translate(positions[i]/10.0f);
MV->translate(vec3(0, 0.1, 0));
MV->scale(vec3(0.05, 0.05, 0.05));
if(checkCollision(ballPos, positions[i]) || hit[i] == 1){
yeet = calculateTrajectory(vec3(xs,ys+positions[i].y/5.0f,zs) * explode, -.003, explosion[i]);
MV->translate(yeet);
MV->rotate(explosion[i]/20, vec3(0, 1, 0));
MV->rotate(-explosion[i]/20, vec3(1, 0, 0));
}
SetMaterial(i%4);
glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE,value_ptr(MV->topMatrix()) );
glUniformMatrix4fv(prog->getUniform("view"), 1, GL_FALSE,value_ptr(lookAt(eye, center, up)));
target->draw(prog);
MV->popMatrix();
MV->pushMatrix();
MV->translate(positions[i]/10.0f);
MV->translate(vec3(0, 0, 0.1));
MV->scale(vec3(0.05, 0.05, 0.05));
if(checkCollision(ballPos, positions[i]) || hit[i] == 1){
yeet = calculateTrajectory(vec3(xs,ys,zs+positions[i].z/5.0f) * explode, -.003, explosion[i]);
MV->translate(yeet);
MV->rotate(-explosion[i]/20, vec3(1, 0, 0));
MV->rotate(-explosion[i]/20, vec3(0, 1, 0));
}
SetMaterial(i%4);
glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE,value_ptr(MV->topMatrix()) );
glUniformMatrix4fv(prog->getUniform("view"), 1, GL_FALSE,value_ptr(lookAt(eye, center, up)));
target->draw(prog);
MV->popMatrix();
MV->pushMatrix();
MV->translate(positions[i]/10.0f);
MV->translate(vec3(0.1, 0, 0.1));
MV->scale(vec3(0.05, 0.05, 0.05));
if(checkCollision(ballPos, positions[i]) || hit[i] == 1){
yeet = calculateTrajectory(vec3(xs+positions[i].x/5.0f,ys,zs+positions[i].z/5.0f) * explode, -.003, explosion[i]);
MV->translate(yeet);
MV->rotate(explosion[i]/20, vec3(0, 0, 1));
MV->rotate(-explosion[i]/20, vec3(0, 1, 0));
}
SetMaterial(i%4);
glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE,value_ptr(MV->topMatrix()) );
glUniformMatrix4fv(prog->getUniform("view"), 1, GL_FALSE,value_ptr(lookAt(eye, center, up)));
target->draw(prog);
MV->popMatrix();
MV->pushMatrix();
MV->translate(positions[i]/10.0f);
MV->translate(vec3(0.1, 0.1, 0.1));
MV->scale(vec3(0.05, 0.05, 0.05));
if(checkCollision(ballPos, positions[i]) || hit[i] == 1){
yeet = calculateTrajectory(vec3(xs+positions[i].x/5.0f,ys+positions[i].y/10.0f,zs+positions[i].z/5.0f) * explode, -.003, explosion[i]);
MV->translate(yeet);
MV->rotate(explosion[i]/20, vec3(1, 0, 0));
MV->rotate(explosion[i]/20, vec3(0, 0, 1));
}
SetMaterial(i%4);
glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE,value_ptr(MV->topMatrix()) );
glUniformMatrix4fv(prog->getUniform("view"), 1, GL_FALSE,value_ptr(lookAt(eye, center, up)));
target->draw(prog);
MV->popMatrix();
MV->pushMatrix();
MV->translate(positions[i]/10.0f);
MV->translate(vec3(0, 0.1, 0.1));
MV->scale(vec3(0.05, 0.05, 0.05));
if(checkCollision(ballPos, positions[i]) || hit[i] == 1){
yeet = calculateTrajectory(vec3(xs,ys+positions[i].y/5.0f,zs+positions[i].z/5.0f) * explode, -.003, explosion[i]);
MV->translate(yeet);
MV->rotate(-explosion[i]/20, vec3(0, 0, 1));
MV->rotate(-explosion[i]/20, vec3(1, 0, 0));
}
SetMaterial(i%4);
glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE,value_ptr(MV->topMatrix()) );
glUniformMatrix4fv(prog->getUniform("view"), 1, GL_FALSE,value_ptr(lookAt(eye, center, up)));
target->draw(prog);
MV->popMatrix();
MV->pushMatrix();
MV->translate(positions[i]/10.0f);
MV->translate(vec3(0.1, 0.1, 0));
MV->scale(vec3(0.05, 0.05, 0.05));
if(checkCollision(ballPos, positions[i]) || hit[i] == 1){
yeet = calculateTrajectory(vec3(xs+positions[i].x/5.0f,ys+positions[i].y/5.0f,zs) * explode, -.003, explosion[i]);
MV->translate(yeet);
MV->rotate(-explosion[i]/20, vec3(0, 1, 0));
MV->rotate(explosion[i]/20, vec3(0, 0, 1));
}
SetMaterial(i%4);
glUniformMatrix4fv(prog->getUniform("MV"), 1, GL_FALSE,value_ptr(MV->topMatrix()) );
glUniformMatrix4fv(prog->getUniform("view"), 1, GL_FALSE,value_ptr(lookAt(eye, center, up)));
target->draw(prog);
MV->popMatrix();
}
MV->popMatrix();
prog->unbind();
cubeProg->bind();
glUniformMatrix4fv(cubeProg->getUniform("P"), 1, GL_FALSE, value_ptr(P->topMatrix()));
mat4 ident(1.0);
glDepthFunc(GL_LEQUAL);
MV->pushMatrix();
MV->loadIdentity();
MV->rotate(radians(theta), vec3(0, 1, 0));
MV->translate(vec3(0, 0.0, 0));
MV->scale(50.0);
glUniformMatrix4fv(cubeProg->getUniform("V"), 1, GL_FALSE,value_ptr(MV->topMatrix()) );
glUniformMatrix4fv(cubeProg->getUniform("M"), 1, GL_FALSE,value_ptr(ident));
glUniformMatrix4fv(cubeProg->getUniform("view"), 1, GL_FALSE,value_ptr(lookAt(eye, center, up)));
glBindTexture(GL_TEXTURE_CUBE_MAP, cubeMapTexture);
cube->draw(texProg);
glDepthFunc(GL_LESS);
MV->popMatrix();
cubeProg->unbind();
P->popMatrix();
if (mouseDown){
speed += 0.001;
explode = speed/2.0f;
xs = x;
ys = y;
zs = z;
}
if (!mouseDown && speed > 0.0)
{
shoot = speed;
if(time > 500){
thrown = false;
Moving = false;
time=0;
shoot = 0;
speed = 0;
explode = 0;
hit[cur] = 0;
explosion[cur] = 0;
}else{
time++;
}
for (int i = 0; i < 3; i ++)
{
//set up framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, frameBuf[(i+1)%2]);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//set up texture
ProcessImage(texBuf[i%2]);
}
/* now draw the actual output */
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
ProcessImage(texBuf[1]);
}
}
// helper function to set materials for shading
void SetMaterial(int i)
{
switch (i)
{
case 0: //shiny blue plastic
glUniform3f(prog->getUniform("MatAmb"), 0.02f, 0.04f, 0.2f);
glUniform3f(prog->getUniform("MatDif"), 0.0f, 0.16f, 0.9f);
break;
case 1: // flat grey
glUniform3f(prog->getUniform("MatAmb"), 0.13f, 0.13f, 0.14f);
glUniform3f(prog->getUniform("MatDif"), 0.3f, 0.3f, 0.4f);
break;
case 2: //brass
glUniform3f(prog->getUniform("MatAmb"), 0.3294f, 0.2235f, 0.02745f);
glUniform3f(prog->getUniform("MatDif"), 0.7804f, 0.5686f, 0.11373f);
break;
case 3: //copper
glUniform3f(prog->getUniform("MatAmb"), 0.1913f, 0.0735f, 0.0225f);
glUniform3f(prog->getUniform("MatDif"), 0.7038f, 0.27048f, 0.0828f);
break;
}
}
};
int main(int argc, char **argv)
{
// Where the resources are loaded from
std::string resourceDir = "../resources";
if (argc >= 2)
{
resourceDir = argv[1];
}
Application *application = new Application();
// Your main will always include a similar set up to establish your window
// and GL context, etc.
WindowManager *windowManager = new WindowManager();
windowManager->init(1000, 800);
windowManager->setEventCallbacks(application);
application->windowManager = windowManager;
// This is the code that will likely change program to program as you
// may need to initialize or set up different data and state
application->init(resourceDir);
application->initGeom(resourceDir);
// Loop until the user closes the window.
while (! glfwWindowShouldClose(windowManager->getHandle()))
{
// Render scene.
application->render();
// Swap front and back buffers.
glfwSwapBuffers(windowManager->getHandle());
// Poll for and process events.
glfwPollEvents();
}
// Quit program.
windowManager->shutdown();
return 0;
}
<file_sep>/README.md
<NAME>
Final Project
For my project I created a game where you shoot targets with a ball. When hit, the targets fracture into 8 different pieces. The files that I handed in cointain the nessecary code for collision detection, parabolic curve, and fracturing. In the recources folder, there is a cracks folder which contains the faces for the skybox.
Execution:
* mkdir build
* cd build
* cmake ..
* make -j4
* ./FinalProject
| 66766e9c80fd4b94e02f023ea8a61b2839c71ab5 | [
"Markdown",
"C++"
] | 2 | C++ | JTan04/Final-Project-Computer-Graphics | cbad54996feb7497feece60b072421302746d073 | 276f63abb0653964bf412486fe923cf092e3f57f |
refs/heads/master | <file_sep>/* What are the three longest trips on rainy days? */
-- Setup rainy days query
WITH
rainy
AS (
SELECT Date
from weather
WHERE Events='Rain'
)
-- Main Query
SELECT
trip_id
,duration
fROM trips
JOIN rainy ON rainy.Date=date(trips.start_date)
GROUP BY trip_id
ORDER BY duration DESC
LIMIT 3
/*Which station is empty most often? */
SELECT
status.station_id
,stations.name
,COUNT(timestamp) as Seconds_Elapsed
from status
JOIN stations ON `status`.station_id=stations.station_id
WHERE bikes_available=0
GROUP BY status.station_id
ORDER BY Seconds_Elapsed DESC
LIMIT 1
/*Return a list of stations with a count of number of trips starting at that station but ordered by dock count */
SELECT
trips.start_station
,COUNT(trips.trip_id) as Trip_Count
,stations.dockcount
from trips
JOIN stations ON trips.start_station=stations.name
GROUP BY trips.start_station
ORDER BY stations.dockcount desc
/* (Challenge) What's the length of the longest trip for each day it rains anywhere? */
-- Setup rainy days query
WITH
rainy
AS (
SELECT Date
from weather
WHERE Events='Rain'
)
-- Main Query
SELECT
trips.start_date as `Date`
,MAX(duration) as `Longest_trip`
fROM trips
JOIN rainy ON rainy.Date=date(trips.start_date)
-- Need to group by day
GROUP BY date(trips.start_date)
ORDER BY trips.start_date<file_sep>version : '2'
services:
spark:
build:
context: .
container_name: spark_01
ports:
- "7788:7788"
volumes:
- ./src:/home/ds
<file_sep>/*What was the hottest day in our data set? Where was that?What was the hottest day in our data set? Where was that? */
SELECT MAX(MaxTemperatureF) as Hottest_Temp
,ZIP
,Date
from weather
/*How many trips started at each station? */
SELECT COUNT(trip_id) as Num_Trips
,start_station
from trips
GROUP BY start_station
/* Whats the shortest trip that happened? */
SELECT trip_id
,MIN(duration) as Shortest_Trip
from trips
/* What is the average trip duration, by end station */
SELECT AVG(duration) as Avg_Duration
, end_station
from trips
GROUP BY end_station<file_sep>/*What's the most expensive listing? What else can you tell me about the listing? */
SELECT
MAX(listings.price) as Price
,name
,neighbourhood
,property_type
,room_type
,accommodates
,bedrooms
,bathrooms
,minimum_nights
,maximum_nights
from listings
/*What neighborhoods seem to be the most popular? */
-- Define popular by listing count
SELECT
neighbourhood
,COUNT(id) as Listing_Count
from listings
WHERE neighbourhood != ''
GROUP BY neighbourhood
ORDER BY Listing_Count desc
limit 10
/*What time of year is the cheapest time to go to your city? What about the busiest? */
-- Will do a group by Date week, and then count of listings and then average price.
-- May-June is cheapest time to come to city
-- May-June is also the busiest based on number of listings during that time.
SELECT
calendar.date
,week(calendar.date) as Week_Number
,COUNT(calendar.listing_id) as Number_of_Listings
,AVG(calendar.price) as Average_Price
from calendar
GROUP BY week(calendar.date)<file_sep># Data-Science-Bootcamp
Thinkful Data Science Bootcamp
<file_sep>/* IDs and durations for all trips of duration greater than 500, ordered by duration: */
SELECT
trips.trip_id
,trips.duration
from trips
WHERE trips.duration > 500
ORDER BY trips.duration desc
/*Every column of the stations table for station id 84 */
SELECT *
FROM stations
WHERE station_id=84
/* The min temperatures of all the occurrences of rain in zip 94301 */
SELECT MinTemperatureF
from weather
WHERE zip = 94301 and Events = 'Rain'<file_sep>################## Imports ##############################
# Importing in each cell because of the kernel restarts.
import scrapy
import re
from scrapy.crawler import CrawlerProcess
import numpy as np
import pandas as pd
from pandas.io.json import json_normalize
################### Create Crawler ######################
class GlassdoorSpider(scrapy.Spider):
# Naming the spider is important if you are running more than one spider of
# this class simultaneously.
name = "Glassdoor_Simple"
# URL(s) to start with.
start_urls = [
'https://www.glassdoor.com/Interview/Facebook-Interview-Questions-E40772.htm?filter.jobTitleFTS=Data+Scientist',
]
# Use XPath to parse the response we get.
def parse(self, response):
# Iterate over every review class element on the page.
# Get all the reviews objects for the page
#Extract the different infomration
for review in response.xpath('//*[starts-with(@id, "InterviewReview_")]'):
# Yield a dictionary with the values we want.
yield {
# This is the code to choose what we want to extract
# You can modify this with other Xpath expressions to extract other information from the site
'interview_questions': review.xpath('.//div[3]/div/div[2]/div[2]/div/div/ul/li/span/text()').extract(),
'answers' : review.xpath('.//div[3]/div/div[2]/div[2]/div/div/ul/li/span/a/text()').extract(),
'answer_links' : review.xpath('.//div[3]/div/div[2]/div[2]/div/div/ul/li/span/a/@href').extract(),
'helpful': review.xpath('.//div[4]/div/div[3]/span/@data-count').extract_first(),
}
next_page = response.xpath('//*[@id="FooterPageNav"]/div[2]/ul/li[7]/a/@href').extract()
if next_page:
next_page = next_page[0]
next_page_url = 'https://www.glassdoor.com' + next_page
print(next_page_url)
# Request the next page and recursively parse it the same way we did above
yield scrapy.Request(next_page_url, callback=self.parse)
# Tell the script how to run the crawler by passing in settings.
process = CrawlerProcess({
'FEED_FORMAT': 'json', # Store data in JSON format.
'FEED_URI': 'data.json', # Name our storage file.
'LOG_ENABLED': False , # Turn off logging for now.
'ROBOTSTXT_OBEY': True,
'USER_AGENT': 'BrandynAdderleyCrawler (<EMAIL>)',
'AUTOTHROTTLE_ENABLED': True,
'HTTPCACHE_ENABLED': True
})
# Start the crawler with our spider.
process.crawl(GlassdoorSpider)
process.start()
print('Success!')
####################### Build DataFrame ###############################
# Turn into DataFrame
glassdoor_df = pd.read_json('data.json', orient='records')
glassdoor_df.head()
| f9208caa3170debce0127ea89c98cfb7e6efd047 | [
"Markdown",
"SQL",
"Python",
"YAML"
] | 7 | SQL | madderle/Data-Science-Bootcamp | ce5277b69d58b4e1033f83829d9b6a9a6c060eaa | 0c6f1a3ebe986bf634f96027782ecaef0819b5c9 |
refs/heads/master | <file_sep>#randomly generates 10000 X-coordinates
x=runif(10000)
#randomly generates 10000 Y-coordinates
y=runif(10000)
#generates the distance of point (x,y) from centre(0.5,0.5)
distance=sqrt((x-0.5)^2+(y-0.5)^2)
#finds the proportion of points inside the circle to the total number of points or points inside square
ratio = length(which(distance<=0.5))/length(distance)
#the ratio is multiplied by 4 to get the value of pi as per the equation stated above
val=ratio*4
val
| 3e26742762a1870b55b25f7cd708159645659d3a | [
"R"
] | 1 | R | dixitomkar1809/Monte-Carlo-Estimates-with-R | b540714ffe29d84f8d2527fa151e1d2af0907686 | da145441776210b9d1fab113a21316f475d719c0 |
refs/heads/master | <file_sep>__author__ = 'rohitanand'
width = int(input("Enter width : "))
height = int(input("Enter height : "))
print("Perimeter is : " + str(2*width + 2*height))<file_sep>__author__ = 'rohitanand'
print ( ((5-2)**2 + (6-2)**2)**0.5 )<file_sep>__author__ = 'rohitanand'
print (2*3.14*8)<file_sep>__author__ = 'rohitanand'
import math
present_value = int(input("Enter amount : "))
annual_rate = int(input("Enter rate : "))
years = int(input("Enter year : "))
print(present_value * ((1 + 0.01 * annual_rate)**years))
<file_sep>__author__ = 'rohitanand'
print ("<NAME> is " + str(52) + " years old.")
<file_sep>__author__ = 'rohitanand'
hours = int(input("Enter hours : "))
minutes = int(input("Enter minutes : "))
seconds = int(input("Enter seconds : "))
print(hours*60*60 + minutes * 60 + seconds)<file_sep>__author__ = 'rohitanand'
mile = 13
feetInMiles = 5280
print(mile * feetInMiles)
<file_sep>__author__ = 'rohitanand'
print(7*60*60 + 21*60 + 37)<file_sep>__author__ = 'rohitanand'
print ("My name is" + " Joe" + " Warren" + ".")<file_sep>__author__ = 'rohitanand'
print (2*4 + 2*7)<file_sep>__author__ = 'rohitanand'
import math
radius = int(input("Enter radius : "))
print ("Area is : " + str(2 * math.pi * radius ))
<file_sep>__author__ = 'rohitanand'
import math
radius = int(input("Enter radius : "))
print ("Area of circle is " + str(math.pi * radius * radius))
<file_sep>__author__ = 'rohitanand'
miles = int(input("Enter miles : "))
feet = 5280
print (miles * feet)
<file_sep>__author__ = 'rohitanand'
print (3.14 * 8 * 8)<file_sep>__author__ = 'rohitanand'
print (1000*(1+0.01*7)**10) | c336881ed9e8651994a371c60b6a44fda67d0724 | [
"Python"
] | 15 | Python | dnanatihor/Coursera | 9834d2285c00df1ced6e0246310f494f54a86817 | 3b88f03f97e982797accd5883fe5081af6379da1 |
refs/heads/master | <repo_name>georgianaursachi/TW<file_sep>/Scholarly HTML/Scholarly HTML.html
<!DOCTYPE html>
<!-- saved from url=(0031)http://scholarly.vernacular.io/ -->
<html lang="ro">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<title>ConDr Documentatie</title>
<link rel="stylesheet" href="./Scholarly HTML — Markedly Smart_files/scholarly.css">
<link rel="stylesheet" href="./Scholarly HTML — Markedly Smart_files/prism-coy.css">
<script src="./Scholarly HTML — Markedly Smart_files/prism.js.descărcare" defer=""></script>
<script type="text/javascript">
try {
var AG_onLoad = function(func) {
if (document.readyState === "complete" || document.readyState === "interactive") func();
else if (document.addEventListener) document.addEventListener("DOMContentLoaded", func);
else if (document.attachEvent) document.attachEvent("DOMContentLoaded", func)
};
var AG_removeElementById = function(id) {
var element = document.getElementById(id);
if (element && element.parentNode) {
element.parentNode.removeChild(element);
}
};
var AG_removeElementBySelector = function(selector) {
if (!document.querySelectorAll) {
return;
}
var nodes = document.querySelectorAll(selector);
if (nodes) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i] && nodes[i].parentNode) {
nodes[i].parentNode.removeChild(nodes[i]);
}
}
}
};
var AG_each = function(selector, fn) {
if (!document.querySelectorAll) return;
var elements = document.querySelectorAll(selector);
for (var i = 0; i < elements.length; i++) {
fn(elements[i]);
};
};
var AG_removeParent = function(el, fn) {
while (el && el.parentNode) {
if (fn(el)) {
el.parentNode.removeChild(el);
return;
}
el = el.parentNode;
}
};
} catch (ex) {
console.error('Error executing AG js: ' + ex);
}
</script>
</head>
<body prefix="">
<header>
<p class="title">ConDr</p>
<p class="subtitle">Documentatie</p>
</header>
<article id="what" typeof="schema:ScholarlyArticle" resource="#">
<h1>ConDr</h1>
<section>
<ol>
<li property="schema:author" typeof="sa:ContributorRole">
<a property="schema:author" typeof="schema:Person">
<span property="schema:givenName"><NAME> </span>
<span property="schema:familyName">Însurățelu</span>
</a>
<sup property="sa:roleContactPoint" typeof="schema:ContactPoint">
<a property="schema:email" href="mailto:<EMAIL>" title="corresponding author">✉</a>
</sup>
</li>
<li property="schema:contributor" typeof="sa:ContributorRole">
<a property="schema:contributor" typeof="schema:Person">
<span property="schema:givenName">Georgiana</span>
<span property="schema:familyName">Ursachi</span>
</a>
<sup property="sa:roleContactPoint" typeof="schema:ContactPoint">
<a property="schema:email" href="mailto:<EMAIL>" title="corresponding author">✉</a>
</li>
</ol>
<ol>
<li id="scienceai">
<a href="https://www.info.uaic.ro" typeof="schema:Corporation">
<span property="schema:name">FII</span>
</a>
</li>
</ol>
</section>
<section typeof="sa:Abstract" id="abstract">
<h2>Abstract</h2>
<p>
Aplicația web are rolul de a ajuta consumatorul să ia o decizie informată cu privire la cumpărarea unui produs alimentar.
</p>
<h2>Cuvinte cheie</h2>
<p>
ConDr, baza de date, consumator, produse alimentare, Euri, reteta, feedback
</p>
</section>
<section typeof="sa:MaterialsAndMethods" id="motivation">
<h2>Descriere proiect/ Motivație</h2>
<aside typeof="schema:WPSideBar">
<p>
<strong>Nou</strong>: te poți alătura echipei noastre
<a href="https://github.com/georgianaursachi/TW">ConDr</a> pentru a ne ajuta să dezvoltăm aplicația.
</p>
<p>
Această aplicație este încă în dezvoltare așa ca simte-te liber să te alături echipei noastre sau să ne trimiți ideile tale prin e-mail.
</p>
</aside>
<p>
Un utilizator va putea folosi aplicatia web doar cu ajutorul unui cont. In cazul in care nu are, atunci isi va putea creea unul. Crearea unui cont consta in introducerea unui nume si e-mail valid(unic, care nu mai exista in baza de date). Ulterior, odata ce si-a creat contul isi poate adauga la profilul sau boli si/sau alergii, eventual, chiar si o poza de profil si o descriere. Consumatorul va putea cauta un produs in baza de date(cu ajutorul unui cod de bare, care poate fi introdus de la tastatura sau denumirea produsului ). Drept rezultat va primi denumirea produsului si valorile nutritionale(sare, zahar, grasimi, fibre etc.) ale acestuia, dar si un sfat daca sa il cumpere sau nu(generat pe baza bolilor consumatorului).
</p>
<p>
O mare problema a citirii etichetei unui produs este intelegerea ingredientelor(Euri),
dar mai ales ce efecte au asupra organismului uman. Asadar, utilizatorul
va putea cauta un ingredient(dupa nr. CEE, exemplu E-122, sau denumirea sa,
ex: Azorubina). Va primi raspuns cu gradul de toxicitate si o mica descriere. De
asemenea, el comenta despre acel produs.
</p>
<p>
In plus, utilizatorul va putea primi idei de retete pe e-mail, la cerere, retetele fiind alese in functie de bolile/lipsurile utilizatorului.
</p>
<p>
Țelurile noastre sunt:
</p>
<ul>
<li>
Să informăm cumparatorul cu privire la produsele existente pe piață.
</li>
<li>
Să oferim un sfat in funcție de bolile și alergiile lui.
</li>
<li>
În concluzie, să educăm utilizatorii să mănânce mai sănătos.
</li>
</ul>
</section>
<section typeof="sa:Results" id="definition">
<h2>Tehnologii utilizate</h2>
<h3>Php</h3>
<p>
PHP este un limbaj de programare. Numele PHP provine din limba engleză și este un acronim recursiv : Php: Hypertext Preprocessor. Folosit inițial pentru a produce pagini web dinamice, este folosit pe scară largă în dezvoltarea paginilor și aplicațiilor web. Se folosește în principal înglobat în codul HTML, dar începând de la versiunea 4.3.0 se poate folosi și în mod „linie de comandă” (CLI), permițând crearea de aplicații independente. Este unul din cele mai importante limbaje de programare web open-source și server-side, existând versiuni disponibile pentru majoritatea web serverelor și pentru toate sistemele de operare.
</p>
<p>
Am ales php deoarece este unul din cele mai răspândite limbaje de prgramare pentru web.
</p>
<ul>
<li>Fast Load Time – PHP are viteză mare de încărcare. </li>
<li>Software - PHP este open source, deci gratis.</li>
<li>Baze de date - PHP este flexibil in ceea ce privește coexiunea cu o bază de date.</li>
</ul>
<h3>HTML5/CSS3</h3>
<p>
HTML5 este un limbaj pentru structurarea și prezentarea conținutului pentru World Wide Web. HTML5 introduce un număr de noi elemente și atribute care reflectă utilizarea tipică a unui site modern.
</p>
<p>
CSS (Cascading Style Sheets) este un standard pentru formatarea elementelor unui document HTML. CSS3 reprezintă un upgrade ce aduce câteva atribute noi și ajută la dezvoltarea noilor concepte in webdesign.
</p>
<h3>Oracle</h3>
<p>
Oracle este un sistem de gestiune a bazelor de date relaționale, ce stochează informațiile sub formă de tabele.
</p>
<p>
Am ales să folosim Oracle deoarece:
</p>
<ul>
<li>Aplicația noastră web se bazează pe o bază de date relatională.</li>
<li>Permite indexarea valorilor pentru o căutare mai rapidă a infomațiilor.</li>
<li>Respectă proprietățile ACID(atomicitate, consistență, izolare, durabilitate).</li>
<li>Este o bază de date tranzacțională.</li>
</ul>
<section id="file-headers">
<h3>Arhitectura aplicației</h3>
<h2>Laravel framework</h2>
<p>
Laravel este un framework web gratis si open-source. Este folosit pentru dezvoltarea aplicațiilor web care urmeaza modelul arhitectural model–view–controller (MVC).
</p>
<p>
MVC este un model arhitectural utilizat în ingineria software. Succesul modelului se datoreaza
izolarii logicii de business fat,a de considerentele interfet, ei cu utilizatorul, rezultând
o aplicat, ie unde aspectul vizual sau/s, i nivelele inferioare ale regulilor de
business sunt mai us,or de modificat, fara a afecta alte nivele.
</p>
<figure typeof="sa:Image">
<img src="./Scholarly HTML — Markedly Smart_files/mvc_diagram_with_routes.png" width="880" height="655">
<figcaption>
Un utilizator face o cerere la un Controller si primește raspuns un View.
</figcaption>
</figure>
</section>
<section id="article">
<h3>Detalii de implementare</h3>
<h2>Baza de date</h2>
<p>
De multe ori este este mult mai rapid să executam anumite funcții in baza de date, ci nu aplicație, din cauza transferului mare de date pe rețea.
</p>
<p>
O astfel de funcție care este implementată în baza de date este, și doar apelată din aplicație este:
</p>
<pre>
<code>create or replace FUNCTION recomandare_reteta(p_user_id NUMBER) return number AS</code>
<code> v_random_number NUMBER;</code>
<code> v_count_retete NUMBER;</code>
<code> v_reteta_id NUMBER;</code>
<code> BEGIN</code>
<code> SELECT COUNT(1) INTO v_count_retete FROM RECIPES;</code>
<code> v_reteta_id := 0;</code>
<code> WHILE (v_reteta_id = 0) LOOP</code>
<code> v_random_number := TRUNC(DBMS_RANDOM.VALUE(1, v_count_retete + 1));</code>
<code> IF email_recipes(p_user_id, v_random_number) = 1 THEN</code>
<code> v_reteta_id := v_random_number;</code>
<code> END IF;</code>
<code> END LOOP;</code>
<code> RETURN v_reteta_id;</code>
<code> END </code>
</pre>
<h2>Implementare MVC</h2>
<ol>
<li><p>
Model Comment:
</p>
<pre>
<code>class Comment extends Model</code>
<code> {</code>
<code> protected $table = 'FEEDBACK'; //we store our comments in this tabel</code>
<code> protected $fillable = ['id', 'user_id', 'product_id', 'rating',</code>
<code> 'message', 'created_at', 'updated_at']; //these are the columns of the table</code>
<code> public function user(){</code>
<code> return $this->belongsTo('App\User', 'user_id', 'id');</code>
<code> }</code>
<code> }</code>
</pre>
<p>Aici se definesc proprietățile modelului si legatura lui cu baza de date.</p>
</li>
<li>
<p>
Controller pentru Comment:
</p>
<pre>
<code>class CommentsController extends Controller</code>
<code> {</code>
<code> public function addComment($product_name){</code>
<code> $product = Product::where('product_name', $product_name)->get(); </code>
<code> Comment::create([</code>
<code> 'user_id'=> Auth::user()->id,</code>
<code> 'product_id'=> $product->first()->id,</code>
<code> 'message' => request('comentariu')</code>
<code> ]);</code>
<code> }</code>
<code> return back();</code>
<code> }</code>
</pre>
<p>
În controller se efectuează operațiile cerute de user.
</p>
</li>
<li>
<p>
View pentru Comment:
</p>
<p>
In view se face afișarea datelor returnate de controller.
</p>
</li>
</ol>
</section>
<section id="hunk-elements">
<h3>Acțuni ale utilizatorului</h3>
<ol>
<li>Isi creeaza un cont pe aplicatie si se conecteaza</li>
<li>Poate vizualiza toate categoriile de E-uri, cat si alimentele/produsele alimentare
care exista in baza de date (din "Meniu")</li>
<li>Acceseaza motorul de cautare, alegand cum doreste sa faca cautarea(prin
introducerea codului de bare de la tastatura sau prin introducerea denumirii unui anumit produs/aditiv alimentar/
ingredient)</li>
<li>Odata gasit produsul, utilizatorul primeste informatii referitoare la acel produs(
cat zahar, carbohidrati etc are produsul) si implicit i se va comunica
daca acesta este, sau nu, potrivit pentru profilul lui.</li>
<li>Adauga comentarii.</li>
</ol>
</section>
</section>
</article>
<footer>
<p>
<a href="https://github.com/georgianaursachi/TW">Proiect realizat in cadrul FII, pentru materia TW</a>
</p>
</footer>
</body>
</html>
<file_sep>/ConDr/public/js/main.js
/*
Arcana by HTML5 UP
html5up.net | @ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
*/
/*Table*/
$(document).ready(function() {
var table = $('#table');
// Table bordered
$('#table-bordered').change(function() {
var value = $( this ).val();
table.removeClass('table-bordered').addClass(value);
});
// Table striped
$('#table-striped').change(function() {
var value = $( this ).val();
table.removeClass('table-striped').addClass(value);
});
// Table hover
$('#table-hover').change(function() {
var value = $( this ).val();
table.removeClass('table-hover').addClass(value);
});
// Table color
$('#table-color').change(function() {
var value = $(this).val();
table.removeClass(/^table-mc-/).addClass(value);
});
});
(function(removeClass) {
jQuery.fn.removeClass = function( value ) {
if ( value && typeof value.test === "function" ) {
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 && elem.className ) {
var classNames = elem.className.split( /\s+/ );
for ( var n = classNames.length; n--; ) {
if ( value.test(classNames[n]) ) {
classNames.splice(n, 1);
}
}
elem.className = jQuery.trim( classNames.join(" ") );
}
}
} else {
removeClass.call(this, value);
}
return this;
}
})(jQuery.fn.removeClass);
(function($) {
skel.breakpoints({
wide: '(max-width: 1680px)',
normal: '(max-width: 1280px)',
narrow: '(max-width: 980px)',
narrower: '(max-width: 840px)',
mobile: '(max-width: 736px)',
mobilep: '(max-width: 480px)'
});
$(window).scroll(function() {
$(window).scroll(function() {
space = $(window).innerHeight() - $('.fab').offsetTop + $('.fab').offsetHeight;
if(space < 200){
$('.fab').css('margin-bottom', '150px');
}
})
});
$(function() {
var $window = $(window),
$body = $('body');
// Disable animations/transitions until the page has loaded.
$body.addClass('is-loading');
$window.on('load', function() {
$body.removeClass('is-loading');
});
// Fix: Placeholder polyfill.
$('form').placeholder();
// Prioritize "important" elements on narrower.
skel.on('+narrower -narrower', function() {
$.prioritize(
'.important\\28 narrower\\29',
skel.breakpoint('narrower').active
);
});
// Dropdowns.
$('#nav > ul').dropotron({
offsetY: -15,
hoverDelay: 0,
alignment: 'center'
});
// Off-Canvas Navigation.
// Title Bar.
$(
'<div id="titleBar">' +
'<a href="#navPanel" class="toggle"></a>' +
'<span class="title">' + $('#logo').html() + '</span>' +
'</div>'
)
.appendTo($body);
// Navigation Panel.
$(
'<div id="navPanel">' +
'<nav>' +
$('#nav').navList() +
'</nav>' +
'</div>'
)
.appendTo($body)
.panel({
delay: 500,
hideOnClick: true,
hideOnSwipe: true,
resetScroll: true,
resetForms: true,
side: 'left',
target: $body,
visibleClass: 'navPanel-visible'
});
// Fix: Remove navPanel transitions on WP<10 (poor/buggy performance).
if (skel.vars.os == 'wp' && skel.vars.osVersion < 10)
$('#titleBar, #navPanel, #page-wrapper')
.css('transition', 'none');
});
})(jQuery);
$(document).ready(function() {
$('select').material_select();
});<file_sep>/ConDr/app/Diseases.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Diseases extends Model
{
public $timestamps = false;//our table DISEASES doesn't have created_at and updated_at columns as expected
protected $fillable = ['id', 'disease_name', 'description', 'salt', 'sugar', 'fats', 'carbohydrate', 'fiber', 'protein', 'calories', 'saturates'];
/**
*many to many relationship between Users and Diseases
*/
public function diseases(){
return $this->belongsToMany('App\Diseases', 'user_disease', 'user_id', 'disease_id');
}
}
<file_sep>/ConDr/app/Http/Controllers/CommentsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Comment;
use App\Product;
use Auth;
class CommentsController extends Controller
{
public function addComment($product_name){
$product = Product::where('product_name', $product_name)->get();
Comment::create([
'user_id'=> Auth::user()->id,
'product_id'=> $product->first()->id,
'message' => request('comentariu')
]
);
return back();
}
}
<file_sep>/ConDr/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
//Enumber route
Route::get('/euri', 'PostsController@euri');
Route::get('/euri/{name}', 'PostsController@euri_name');
//Products routes
Route::get('/produse', 'PostsController@produse');
Route::get('/produse/{name}', 'PostsController@produse_name')->name('/produse/{name}');
Route::post('/produse/{name}/comentarii', 'CommentsController@addComment');
//Contact route
Route::get('/contact', ['as' => 'contact', 'uses' => 'PostsController@getContact']);
Route::post('contact', ['as' => 'contact_form', 'uses' => 'PostsController@postContact']);
//Add product route
Route::get('/adauga', 'PostsController@adauga');
Route::post('/adauga', ['as' => 'adauga', 'uses' => 'PostsController@adaugaProdus']);
//Profile route
Route::get('/profil', 'PostsController@profil');
Route::get('/profil', 'PostsController@profil_table');
Route::post('/profil', 'PostsController@settings');
//Settings route
Route::get('/setari', 'PostsController@setari');
Route::get('/setari', 'PostsController@profil_table_settings');
Route::get('/setari/boli/{name}', 'PostsController@destroy')->name('/setari/boli/{name}');
Route::get('/setari/alergeni/{name}', 'PostsController@delete_allergen')->name('/setari/alergeni/{name}');
//Contact routes
Route::get('/contact', ['as' => 'contact', 'uses' => 'PostsController@getContact']);
Route::post('contact', ['as' => 'contact_form', 'uses' => 'PostsController@postContact']);
//Authentication routes
Route::get('auth/login', 'Auth\LoginController@showLoginForm');
Route::post('auth/login', 'Auth\LoginController@login');
Route::get('auth/logout', 'Auth\LoginController@logout');
Route::post('auth/logout', 'Auth\LoginController@logout');
//Registration routes
Route::get('auth/register', 'Auth\RegisterController@showRegistrationForm');
Route::post('auth/register', 'Auth\RegisterController@register');
//Reset password routes
Route::get('passwords/reset_password', 'Auth\ForgotPasswordController@showLinkRequestForm');
Route::post('passwords/reset_password', 'Auth\ForgotPasswordController@sendResetLinkEmail');
//Home route
Route::get('/', 'HomeController@index')->name('index');
<file_sep>/ConDr/app/Allergen.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Allergen extends Model
{
public $timestamps = false;//our table ALLERGENS doesn't have created_at and updated_at columns as expected
protected $table = 'ALLERGENS';
/**
*many to many relationship between Products and Allergens
*/
public function allergens(){
return $this->belongsToMany('App\Allergen', 'allergens_products', 'allergen_id', 'product_id');
}
/**
*many to many relationship between Users and Allergens
*/
public function userAllergens(){
return $this->belongsToMany('App\Allergen', 'allergens_users', 'user_id', 'allergen_id');
}
}
<file_sep>/ConDr/app/Recipes.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Recipes extends Model
{
protected $table = 'RECIPES';
public $timestamps = false;
protected $fillable = ['id', 'recipe_name', 'description', 'method_of_preparation', 'salt', 'sugar', 'fats', 'carbohydrate', 'fiber', 'protein', 'calories', 'saturates'];
}
<file_sep>/ConDr/app/Http/Controllers/TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class TestController extends Controller{
public function test(){
$enr=DB::select('select name from enumber');
return view('posts.welcome',compact('enr'));
}
}
<file_sep>/ConDr/app/Enumber.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Charts;
class Enumber extends Model
{
protected $table = 'ENUMBER';//our table name=ENUMBER not ENUMBERS
public $timestamps = false;//our table PRODUCTS doesn't have created_at and updated_at columns as expected
public $incrementing = false;
public function chart(){
$distribution = Enumber::orderBy('distribution', 'desc')
->take(10)
->get();
$chart = Charts::create('bar', 'highcharts')
->title('Distributia E-urilor in produse')
->elementLabel('Proporție')
->labels($distribution->pluck('id'))
->values($distribution->pluck('distribution'))
->dimensions(0,0)
->responsive(true);
return $chart;
}
/**
*many to many relationship between Products and Enumber
*/
public function products(){
return $this->belongsToMany('App\Product', 'enumber_products', 'enumber_id', 'products_id');
}
}
<file_sep>/ConDr/app/Comment.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'FEEDBACK'; //we store our comments in this tabel
protected $fillable = ['id', 'user_id', 'product_id', 'rating', 'message', 'created_at', 'updated_at']; //these are the columns of the table
public function user(){
return $this->belongsTo('App\User', 'user_id', 'id');
}
}
<file_sep>/ConDr/app/Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public $timestamps = false; //our table PRODUCTS doesn't have created_at and updated_at columns as expected
/**
*many to many relationship between Products and Enumber
*/
public function enumbers(){
return $this->belongsToMany('App\Enumber', 'enumber_products', 'products_id', 'enumber_id');
}
/**
*many to many relationship between Products and Allergens
*/
public function allergens(){
return $this->belongsToMany('App\Allergen', 'allergens_products', 'product_id', 'allergen_id');
}
/**
*a product has many comments
*/
public function comments(){
return $this->hasMany('App\Comment', 'product_id' );
}
}
<file_sep>/README.md
# TW-ConDr project
Baza de date va fi parte dintr-o aplicatie web care va ajuta consumatorul sa ia o decizie informata asupra cumpararii unui produs alimentar.
Un utilizator va putea folosi aplicatia web doar cu ajutorul unui cont. In cazul in care nu are, atunci isi va putea creea unul. Crearea unui cont consta in introducerea unui nume si e-mail valid(unic, care nu mai exista in baza de date), precum si completarea campurilor referitoare la bolile/alergiile pe care le are utilizatorul. Ulterior, odata ce si-a creat contul isi poate adauga la profilul sau (alte) boli si alergii, eventual, chiar si o poza de profil. Consumatorul va putea cauta un produs in baza de date(cu ajutorul unui cod de bare, care poate fi introdus de la tastatura sau fotografiat si incarcat pe site). Drept rezultat va primi denumirea produsului si valorile nutritionale(sare, zahar, grasimi, fibre etc.) ale acestuia, dar si un sfat daca sa il cumpere sau nu(generat pe baza bolilor consumatorului), atasandu-i si un link catre un site de unde l-ar putea achizitiona. O mare problema a citirii etichetei unui produs este intelegerea ingredientelor(Euri), dar mai ales ce efecte au asupra organismului uman. Asadar, utilizatorul va putea cauta un ingredient(dupa nr. CEE, exemplu E-122, sau denumirea sa, ex: Azorubina). Va primi raspuns cu gradul de toxicitate si o mica descriere. De asemenea, el poate aprecia(prin rating) sau comenta despre acel produs doar o singura data.
In plus, utilizatorul va putea primi idei de retete pe e-mail, intr-un interval orar setat de acesta(odata la una/doua zile, sau daca nu doreste, se poate dezabona de la acest serviciu), retetele fiind alese in functie de bolile/lipsurile utilizatorului.
Pentru un utilizator nelogat, acesta nu va beneficia de toate aceste facilitati, ci doar de motorul de cautare al site-ului, unde va putea introduce codul de bare/numele produsului/numele ingredientului/denumirea aditivilor alimentari, si va facilita de informatiile pe care le ofera site-ul despre acestea.
<file_sep>/ConDr/app/User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name', 'last_name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'token',
];
public function getAuthPassword()
{
return $this->passwd;
}
public function diseases()
{
return $this->belongsToMany('App\Diseases', 'user_disease', 'user_id', 'disease_id');
}
public function allergens()
{
return $this->belongsToMany('App\Allergen', 'allergens_users', 'user_id', 'allergen_id');
}
}
<file_sep>/ConDr/app/Http/Controllers/PostsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Charts;
use Image;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
use App\Enumber;
use App\Product;
use App\Diseases;
use App\Allergen;
use App\User;
use App\Http\Requests\ContactFormRequest;
use Mail;
use App\Recipes;
use Input;
use App\Comment;
class PostsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function euri(){
$chart = (new Enumber)->chart();
return view('posts.euri', compact('chart'));
}
public function euri_name($input, Request $request){
$input = $request->input('euri');
$input = '%'.$input.'%';
$enumber = Enumber::whereRaw('UPPER(id) like UPPER(?)', array( $input))
->orWhereRaw('UPPER(name) like UPPER(?)', array( $input))
->get();
$chart = (new Enumber)->chart();
return view('posts.euri-name',compact ('enumber','chart'));
}
public function produse(){
return view('posts.produse');
}
public function produse_name($input, Request $request){
$input = $request->input('produs');
$user = Auth::user();
$id = $user->id;
if(is_numeric($input))
$products = Product::with('enumbers')
->with('allergens')
->with('comments')
->where('bar_code',$input)
->get();
else
$products = Product::with('enumbers')
->with('allergens')
->with('comments')
->whereRaw('UPPER(product_name) like UPPER(?)', array( $input.'%'))
//->orWhere('bar_code',$input)
->get();
$userAllergens = Allergen::with('allergens')
->join('allergens_users', 'allergens.id', '=', 'allergens_users.allergen_id')
->where('allergens_users.user_id', '=', $id)
->get();
//for advice
if(count($products)>0){
$advice = DB::selectOne("select USERPACKAGE.VALIDATE_PRODUCT(".$products->first()->id.",".$id." ) as value from dual");
switch ($advice->value) {
case -1: $adviceMessage = "Acest produs conține prea multa sare pentru dumneavoastră!"; break;
case -2: $adviceMessage = "Acest produs conține prea mult zahăr pentru dumneavoastră!"; break;
case -3: $adviceMessage = "Acest produs conține prea multe grăsimi pentru dumneavoastră!"; break;
case -4: $adviceMessage = "Acest produs conține prea mulți carbohidrați pentru dumneavoastră!"; break;
case -5: $adviceMessage = "Acest produs conține prea multe fibre pentru dumneavoastră!"; break;
case -6: $adviceMessage = "Acest produs conține prea multe proteine pentru dumneavoastră!"; break;
case -7: $adviceMessage = "Acest produs conține prea multe grăsimi grasimi saturate pentru dumneavoastră!"; break;
default:
$adviceMessage = "Acest produs nu reprezinta riscuri pentru bolile dumnevoastra!"; break;}
}
else $adviceMessage= "null";
//for recomanded product
$recomandation = DB::selectOne("select RECOMANDARI_PRODUS(".$id." ) as value from dual");
$productRecomandation = Product::where('id', $recomandation->value)->get();
return view('posts.produse-name', compact('products', 'userAllergens', 'adviceMessage', 'productRecomandation'));
}
public function getContact(){
return view('posts.contact');
}
public function postContact(ContactFormRequest $request){
$data = array(
'email' => $request->email,
'subject' => $request->subject,
'bodyMessage' => $request->message
);
Mail::send('emails.contact', $data, function($message) use ($data){
$message->from($data['email']);
$message->to('<EMAIL>');
$message->subject($data['subject']);
});
return \Redirect::route('contact')->with('message', 'Mulțumim pentru e-mail!');
}
public function adauga(){
return view('posts.adauga');
}
public function adaugaProdus(Request $request){
$product = new product;
$product->product_name = $request->name;
$product->category = $request->categories;
$product->bar_code = $request->barCode;
$product->description = $request->desricption;
$product->salt = $request->salt;
$product->sugar = $request->sugar;
$product->fats = $request->fats;
$product->carbohydrate = $request->carbs;
$product->fiber = $request->fibers;
$product->protein = $request->proteins;
$product->calories = $request->calories;
$product->saturates = $request->saturates;
$product->save();
if($request->lapte){
$a1 = Allergen::where('name', 'lapte')->get();
$product->allergens()->attach($a1->first());
}
if($request->ou){
$a2 = Allergen::where('name', 'oua')->get();
$product->allergens()->attach($a2->first());
}
if($request->peste){
$a3 = Allergen::where('name', 'peste')->get();
$product->allergens()->attach($a3->first());
}
if($request->crustacee){
$a4 = Allergen::where('name', 'crustacee')->get();
$product->allergens()->attach($a4->first());
}
if($request->moluste){
$a5 = Allergen::where('name', 'moluste')->get();
$product->allergens()->attach($a5->first());
}
if($request->arahide){
$a6 = Allergen::where('name', 'arahide')->get();
$product->allergens()->attach($a6->first());
}
if($request->nuci){
$a7 = Allergen::where('name', 'nuci')->get();
$product->allergens()->attach($a7->first());
}
if($request->migdale){
$a8 = Allergen::where('name', 'migdale')->get();
$product->allergens()->attach($a8->first());
}
if($request->alune){
$a9 = Allergen::where('name', 'alune')->get();
$product->allergens()->attach($a9->first());
}
if($request->caju){
$a10 = Allergen::where('name', 'caju')->get();
$product->allergens()->attach($a10->first());
}
if($request->pecan){
$a11 = Allergen::where('name', 'pecan')->get();
$product->allergens()->attach($a11->first());
}
if($request->brazils){
$a12 = Allergen::where('name', 'brazils')->get();
$product->allergens()->attach($a12->first());
}
if($request->fistic){
$a13 = Allergen::where('name', 'fistic')->get();
$product->allergens()->attach($a13->first());
}
if($request->nuci_de_macadamia){
$a14 = Allergen::where('name', 'nuci de macadamia')->get();
$product->allergens()->attach($a14->first());
}
if($request->nuci_de_Q){
$a15 = Allergen::where('name', 'nuci de Queensland')->get();
$product->allergens()->attach($a15->first());
}
if($request->seminte_susan){
$a16 = Allergen::where('name', 'seminte susan')->get();
$product->allergens()->attach($a16->first());
}
if($request->cereale){
$a17 = Allergen::where('name', 'cereale care contin gluten')->get();
$product->allergens()->attach($a17->first());
}
if($request->soia){
$a18 = Allergen::where('name', 'soia')->get();
$product->allergens()->attach($a18->first());
}
if($request->telina){
$a19 = Allergen::where('name', 'telina')->get();
$product->allergens()->attach($a19->first());
}
if($request->mustar){
$a20 = Allergen::where('name', 'mustar')->get();
$product->allergens()->attach($a20->first());
}
if($request->lupin){
$a21 = Allergen::where('name', 'lupin')->get();
$product->allergens()->attach($a21->first());
}
if($request->dioxid){
$a22 = Allergen::where('name', 'dixiod de sulf si sulfiti')->get();
$product->allergens()->attach($a22->first());
}
return back();
}
public function test(){
return view('posts.test');
}
public function profil(){
return view('posts.profil');
}
public function profil_table(){
$user = Auth::user();
$id = $user->id;
$diseases = Diseases::with('diseases')
->join('user_disease', 'diseases.id', '=', 'user_disease.disease_id')
->where('user_disease.user_id', '=', $id)
->get();
$allergens = Allergen::with('allergens')
->join('allergens_users', 'allergens.id', '=', 'allergens_users.allergen_id')
->where('allergens_users.user_id', '=', $id)
->get();
return view('posts.profil', compact('diseases','allergens'));
}
public function profil_table_settings(){
$users = User::with('diseases')
->with('allergens')
->where('id', Auth::user()->id)
->get();
$disease = DB::table('diseases')->orderBy('disease_name')->get();
$allergens = DB::table('allergens')->orderBy('name')->get();
return view('posts.setari', compact('users', 'disease', 'allergens'));
}
public function destroy($disease_name){
$d = Diseases::where('disease_name', $disease_name)->get();
DB::delete('delete from user_disease where user_id = ? AND disease_id = ?', array(Auth::user()->id, $d->first()->id));
return back();
}
public function delete_allergen($allergen_name){
$a = Allergen::where('name', $allergen_name)->get();
DB::delete('delete from allergens_users where user_id = ? AND allergen_id = ?', array(Auth::user()->id, $a->first()->id));
return back();
}
public function settings(Request $request){
$user = Auth::user();
//Handle the user upload avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->save( public_path('/uploads/avatars/' . $filename) );
$user->avatar = $filename;
$user->save();
}
//Add user description
if ($request->has('description')) {
$description = $request->input('description');
$user->description = $description;
$user->save();
}
//Find if checkbox is checked and send recipe via e-mail
if($request->input('c1')){
$recipe_id = DB::selectOne("select RECOMANDARE_RETETA(".$user->id.") as value from dual");
$recipes = Recipes::where('id', $recipe_id->value)->get();
$data = array(
'email' => $user->email,
'subject' => 'Recomandare rețete',
'recipe_name' => $recipes->first()->recipe_name,
'description' => $recipes->first()->description,
'method_of_preparation' => $recipes->first()->method_of_preparation,
'picture' => $recipes->first()->picture
);
Mail::send('emails.recipes', $data, function($message) use ($data) {
// Set the receiver and subject of the mail.
$message->to($data['email']);
// Set the sender
$message->from('<EMAIL>', 'ConDr');
$message->subject($data['subject']);
});
}
//add user disease
if ($request->has('disease_name')){
$disease = $request->disease_name;
$d = Diseases::where('disease_name', $disease)->get();
if(count(DB::table('user_disease')->where([['user_id',Auth::user()->id],['disease_id', $d->first()->id],])->get()) == 0 )
DB::table('user_disease')->insert(['user_id' => Auth::user()->id, 'disease_id' => $d->first()->id]);
}
//add user allergen
if ($request->has('allergen_name')){
$allergen = $request->allergen_name;
$a = Allergen::where('name', $allergen)->get();
if(count(DB::table('allergens_users')->where([['user_id',Auth::user()->id],['allergen_id', $a->first()->id],])->get()) == 0)
DB::table('allergens_users')->insert(
['user_id' => Auth::user()->id, 'allergen_id' => $a->first()->id]);
}
return $this->profil_table();
}
public function setari(){
return view('posts.setari');
}
}
<file_sep>/contributing.md
Cum sa contribui?
Fiecare membru isi va crea un branch nou in care va face modificarile dorite.
Atunci cand doreste sa le upload-eze se va asifura ca totul este functional si va explica cat mai in detaliu modificarile aduse
| ac236d7afce62a2d35787067de04a3b897ff62cc | [
"JavaScript",
"Markdown",
"HTML",
"PHP"
] | 15 | HTML | georgianaursachi/TW | 8020d256b7b6a46c0c5c266951551c62d213b9e9 | 925915f93d4f6bcf8aac19bb92edfeab804b15c6 |
refs/heads/master | <repo_name>kamil-iskra/EdytorXML<file_sep>/README.md
# EdytorXML
My first Windows 8 app

<file_sep>/EdytorXML_New/Plik.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;
namespace EdytorXML_New
{
class Plik
{
private string zawartosc; // zawartość TextBoxa
// obiekty przechowujące strukturę pliku xml
XDocument xDokument;
XmlDocument xmlDokument;
StorageFile plik;
// Zmienna pomocnicza sygnalizująca wystąpienie wyjątku
bool isException;
// Konstruktor inicjalizuje pola klasy
public Plik()
{
zawartosc = null;
xDokument = null;
xmlDokument = null;
plik = null;
isException = false;
}
// Zapis pliku
public async void zapisz(TextBox textBox)
{
// Użycie FileSavePickera w celu zapisania pliku w wybranej przez użytkownika lokalizacji
FileSavePicker savePicker = new FileSavePicker();
// Domyślna lokalizacja - DocumentsLibrary
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
// Typ pliku - dozwolony tylko format XML
savePicker.FileTypeChoices.Add("XML File", new List<string>() { ".xml" });
// Sugerowana domyślna nazwa pliku
savePicker.SuggestedFileName = "Nowy";
plik = await savePicker.PickSaveFileAsync();
// Sprawdzenie czy użytkownik wskazał plik do zapisu
if (plik != null)
{
try
{
// Zapisanie zawartości textboxa do zmiennej oraz parsowanie do obiektu XDocument
zawartosc = textBox.Text;
xDokument = XDocument.Parse(zawartosc);
// Zapis pliku przy użyciu strumienia
using (IRandomAccessStream fileStream = await plik.OpenAsync(FileAccessMode.ReadWrite))
{
using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
{
using (DataWriter dataWriter = new DataWriter(outputStream))
{
dataWriter.WriteString(xDokument.ToString());
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
await outputStream.FlushAsync();
}
}
}
catch (Exception e)
{
// Sygnalizacja wystąpienia wyjątku
isException = true;
}
// Obsługa wyjątku
if (isException)
{
// Wyświetlenie wiadomości w oknie dialogowym
var messageDialog = new MessageDialog("Nieprawidłowa struktura pliku XML. Plik nie został zapisany.");
await messageDialog.ShowAsync();
}
}
}
// Odczyt z pliku
public async void wczytaj(TextBox textBox)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.List;
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add(".xml");
plik = await openPicker.PickSingleFileAsync();
// Sprawdzenie czy użytkownik wybrał plik do wczytania
if (plik != null)
{
// Próba załadowania textboxa wczytanym plikiem
try
{
xmlDokument = await XmlDocument.LoadFromFileAsync(plik);
zawartosc = xmlDokument.GetXml();
xDokument = XDocument.Parse(zawartosc);
textBox.Text = xDokument.ToString();
}
catch (Exception e)
{
isException = true;
}
if (isException)
{
var messageDialog = new MessageDialog("Nieprawidłowa struktura pliku XML. Wybierz inny plik");
await messageDialog.ShowAsync();
isException = false;
}
}
}
}
}
| 6a942a5de78c6dbf2023cd1b9cf24b667df88ba7 | [
"Markdown",
"C#"
] | 2 | Markdown | kamil-iskra/EdytorXML | 5d10de0897fc9c5ea40e4cec8f19e68a80db627d | b4541d65319d8b3310d6e10ad52c292a7063b2f7 |
refs/heads/master | <repo_name>Hunter-Dolan/Midrange<file_sep>/demodulation/trainer.go
package demodulation
import "math"
type trainer struct {
demodulator *Demodulator
carrierActivePowers []float64
carrierInactivePowers []float64
carrierActivePowerAverage float64
carrierInactivePowerAverage float64
}
func (t *trainer) train() {
evenFrame := t.demodulator.carrierPowerAtFrame(0)
oddFrame := t.demodulator.carrierPowerAtFrame(1)
t.carrierActivePowers = make([]float64, t.demodulator.carrierCount)
t.carrierInactivePowers = make([]float64, t.demodulator.carrierCount)
activeSum := 0.0
inactiveSum := 0.0
for i, evenFrameValue := range evenFrame {
oddFrameValue := oddFrame[i]
carrierEven := i % 2
activePower := evenFrameValue
inactivePower := oddFrameValue
if carrierEven == 1 {
activePower = oddFrameValue
inactivePower = evenFrameValue
}
t.carrierActivePowers[i] = activePower
t.carrierInactivePowers[i] = inactivePower
activeSum += activePower
inactiveSum += inactivePower
}
t.carrierActivePowerAverage = activeSum / float64(t.demodulator.carrierCount)
t.carrierInactivePowerAverage = inactiveSum / float64(t.demodulator.carrierCount)
}
func (t *trainer) determineValueAndConfidence(power float64, carrierIndex int) (bool, float64) {
activeDistance := math.Abs(power - t.carrierActivePowerAverage)
inactiveDistance := math.Abs(power - t.carrierInactivePowerAverage)
activeCarrierPower := t.carrierActivePowers[carrierIndex]
inactiveCarrierPower := t.carrierInactivePowers[carrierIndex]
activeCarrierDistance := math.Abs(power - activeCarrierPower)
inactiveCarrierDistance := math.Abs(power - inactiveCarrierPower)
value := activeDistance < inactiveDistance
confidence := math.Abs((activeDistance + activeCarrierDistance) - (inactiveDistance + inactiveCarrierDistance))
return value, confidence
}
<file_sep>/transmission/modulation.go
package transmission
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"math"
"strconv"
"github.com/Hunter-Dolan/midrange/modulation"
"github.com/Hunter-Dolan/midrange/options"
"github.com/Hunter-Dolan/midrange/utils"
)
func (t *Transmission) SetData(data string) {
dataBytes := []byte(data)
dataBytes = compress(dataBytes)
t.dataLength = len(dataBytes) * 8
t.originalDataLength = len(data) * 8
packetCount := math.Ceil(float64(t.dataLength) / float64(options.PacketDataLength))
t.data = make([]*packet, int(packetCount))
for packetIndex := range t.data {
p := packet{}
leftEnd := int(packetIndex * options.PacketDataLengthBytes)
rightEnd := int(leftEnd + options.PacketDataLengthBytes)
if rightEnd > len(dataBytes) {
rightEnd = len(dataBytes)
}
p.setBytes(dataBytes[leftEnd:rightEnd])
t.data[packetIndex] = &p
}
t.generateHeaderPacket()
}
func (t *Transmission) generateHeaderPacket() {
dataLengthBin, dataLengthBool := t.dataLengthBin()
checksumBin, checksumBool := t.checksumBin()
bytes := []byte((dataLengthBin + checksumBin)[:])
bin := append(dataLengthBool, checksumBool...)
p := packet{}
p.data = &bin
p.calculateHash(bytes)
p.replicateHash(options.HeaderChecksumRedundancy)
t.header = &p
}
func (t *Transmission) checksumBin() (string, []bool) {
checksum := []byte{}
for _, packet := range t.data {
checksum = append(checksum, packet.hashBytes...)
}
checksumBin := utils.BinEncode(checksum)
checksumBinByte := utils.BoolToByteBin(checksumBin)
sha1DataFull := sha1.Sum(checksumBinByte)
sha1Data := sha1DataFull[:options.HeaderTransmissionChecksumLength/8]
sha1Int, _ := strconv.ParseInt(hex.EncodeToString(sha1Data), 16, 64)
sha1Bin := strconv.FormatInt(sha1Int, 2)
sha1Bin = utils.LeftPad(sha1Bin, options.HeaderTransmissionChecksumLength)
sha1Dec := strconv.FormatInt(sha1Int, 10)
fmt.Println("Transmission Hash:", sha1Dec)
return sha1Bin, utils.BoolBinEncode(sha1Bin)
}
func (t *Transmission) dataLengthBin() (string, []bool) {
dataLength := 0
for _, packet := range t.data {
dataLength += len(*packet.data)
}
t.dataLength = dataLength
headerDataLengthInteger := int64(dataLength)
headerDataLengthBin := strconv.FormatInt(headerDataLengthInteger, 2)
headerDataLengthBin = utils.LeftPad(headerDataLengthBin, options.HeaderDataLengthIntegerBitLength)
headerDataLengthDec := strconv.FormatInt(headerDataLengthInteger, 10)
fmt.Println("Data Length:", headerDataLengthDec)
return headerDataLengthBin, utils.BoolBinEncode(headerDataLengthBin)
}
func (t *Transmission) allData() *[]bool {
data := t.header.packetData()
for _, packet := range t.data {
data = append(data, packet.packetData()...)
}
carrierSpacing := float64(t.options.OMFSKConstant) / (float64(t.options.FrameDuration) / 1000.0)
carrierCount := int(math.Floor(float64(t.options.Bandwidth) / carrierSpacing))
fullLength := int(math.Ceil(float64(len(data))/float64(carrierCount))) * carrierCount
paddingAmount := fullLength - len(data)
for i := 0; i < paddingAmount; i++ {
data = append(data, false)
}
data = interleave(data)
return &data
}
func (t *Transmission) modulate() {
if t.modulator == nil {
t.modulator = &modulation.Modulator{}
t.modulator.Options = t.options
allData := t.allData()
t.modulator.SetData(allData)
}
t.modulator.Reset()
duration := float64(t.modulator.FrameCount()*t.options.FrameDuration) / 1000
fmt.Println(t.originalDataLength, "bits to transfer")
fmt.Println(duration, "second transfer time")
fmt.Println(int64(float64(t.dataLength)/duration), "bps real")
fmt.Println(int64(float64(t.originalDataLength)/duration), "bps effective")
}
func (t *Transmission) BuildWav(filename string) {
t.modulate()
t.modulator.BuildWav(filename)
}
func (t *Transmission) Wave() []float64 {
t.modulate()
return t.modulator.FullWave()
}
<file_sep>/matcher/frame_bank.go
package matcher
import "github.com/Hunter-Dolan/midrange/frame"
// Matcher is a base for matching
type Matcher struct {
frames []*frame.Frame
options *Options
}
// Options configures the matcher
type Options struct {
*frame.GenerationOptions
NFFTPower int
}
// NewMatcher creates a new matcher
func NewMatcher(frameGeneratingOptions *Options) *Matcher {
matcher := Matcher{}
matcher.options = frameGeneratingOptions
return &matcher
}
<file_sep>/utils/bin_encode.go
package utils
import "fmt"
func BinEncode(s []byte) []bool {
binArray := make([]bool, len(s)*8)
binIndex := 0
for _, c := range s {
binary := fmt.Sprintf("%b", c)
binaryLen := len(binary)
padAmount := 8 - binaryLen
for i := 0; i < padAmount; i++ {
binArray[binIndex] = false
binIndex++
}
for _, bit := range binary {
binArray[binIndex] = bit == '1'
binIndex++
}
}
return binArray
}
func BinEncodeWithPad(s []byte, pad int) []bool {
bin := BinEncode(s)
paddedBin := make([]bool, pad-len(bin))
paddedBin = append(paddedBin, bin...)
return paddedBin
}
func BoolBinEncode(s string) []bool {
bin := make([]bool, len(s))
for i, value := range s {
bin[i] = value == '1'
}
return bin
}
<file_sep>/modulation/wav.go
package modulation
import (
"fmt"
"math"
"math/rand"
"os"
"github.com/Hunter-Dolan/midrange/options"
"github.com/go-audio/aiff"
"github.com/go-audio/audio"
)
func (m *Modulator) BuildWav(filename string) {
randomNoiseStartDuration := 0 //(rand.Intn(5) + 2) * 1000
randomNoiseEndDuration := 0 //(rand.Intn(5) + 2) * 1000
rate := m.Options.Kilobitrate * 1000
bitDepth := options.BitDepth
//fmt.Println(randomNoiseStartDuration)
randomNoiseStartBits := rate * (randomNoiseStartDuration / 1000)
randomNoiseEndBits := rate * (randomNoiseEndDuration / 1000)
file, err := os.Create(filename)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
buffer := audio.IntBuffer{}
buffer.Format = &audio.Format{}
buffer.Format.NumChannels = 1
buffer.Format.SampleRate = rate
encoder := aiff.NewEncoder(file, buffer.Format.SampleRate, bitDepth, buffer.Format.NumChannels)
wave := m.FullWave()
buffer.Data = make([]int, len(wave)+randomNoiseStartBits+randomNoiseEndBits)
scaler := float64(math.Pow(2, float64(bitDepth-1)))
offset := 0
for i := 0; i < randomNoiseStartBits; i++ {
noiseAmplitude := (scaler / float64(100.0)) * float64(m.Options.NoiseLevel)
noise := noiseAmplitude * rand.Float64()
buffer.Data[offset] = int(noise)
offset++
}
for _, amplitude := range wave {
buffer.Data[offset] = int(amplitude)
offset++
}
for i := 0; i < randomNoiseEndBits; i++ {
noiseAmplitude := (scaler / float64(100.0)) * float64(m.Options.NoiseLevel)
noise := noiseAmplitude * rand.Float64()
buffer.Data[offset] = int(noise)
offset++
}
encoder.Write(&buffer)
encoder.Close()
}
<file_sep>/modulation/modulator.go
package modulation
import (
"fmt"
"math"
"math/rand"
"github.com/Hunter-Dolan/midrange/options"
)
type Modulator struct {
Options *options.Options
carrierCount int
carrierSpacing float64
data *[]bool
dataLength int
frameCount int
frameIndex int
CachedWave *[]float64
}
func (m *Modulator) SetData(data *[]bool) {
m.data = data
m.setup()
}
func (m *Modulator) NextWave() *[]float64 {
frame := m.buildFrame(m.frameIndex)
m.frameIndex++
return frame.wave()
}
func (m *Modulator) FullWave() []float64 {
if m.CachedWave == nil {
numberOfFrames := int64(m.FrameCount())
sampleRate := int64(m.Options.Kilobitrate * 1000)
numberOfSamplesPerFrame := int64(float64(sampleRate) * (float64(m.Options.FrameDuration) / float64(1000.0)))
offsetSamples := numberOfSamplesPerFrame
numberOfSamples := (numberOfSamplesPerFrame * numberOfFrames)
if options.OffsetGroups != 1 {
numberOfSamples = (numberOfSamplesPerFrame * numberOfFrames) + offsetSamples
}
fullWave := make([]float64, numberOfSamples)
carrierData := make([][]float64, m.carrierCount)
ts := 1 / float64(sampleRate)
for i := int(0); i < int(numberOfFrames); i++ {
frame := m.buildFrame(i)
for carrierIndex, freq := range frame.allCarriers() {
carrierData[carrierIndex] = append(carrierData[carrierIndex], freq)
}
}
scaler := float64(math.Pow(2, float64(options.BitDepth-2)))
signalScaler := scaler
guard := int64(numberOfSamplesPerFrame - (numberOfSamplesPerFrame / options.GuardDivisor))
fmt.Println("Generating Phases")
for phase := int64(0); phase < numberOfSamples; phase++ {
amplitude := float64(0.0)
carrierCount := 0
if phase%10000 == 0 {
fmt.Println("Phase:", phase, int((float64(phase)/float64(numberOfSamples))*100.0), "%")
}
for carrierIndex, frequencies := range carrierData {
offsetIndex := int64(carrierIndex % options.OffsetGroups)
carrierOffset := int64(0)
if offsetIndex != 0 {
carrierOffset = int64(int64(offsetSamples/(options.OffsetGroups)) * int64(offsetIndex))
}
frequencyIndex := phase - carrierOffset
if frequencyIndex >= 0 && frequencyIndex < (numberOfSamplesPerFrame*numberOfFrames) {
frameIndex := frequencyIndex / numberOfSamplesPerFrame
frequency := frequencies[frameIndex]
if frequency != -1.0 && frequencyIndex < ((frameIndex+1)*numberOfSamplesPerFrame)-guard {
amplitude += (math.Sin(float64(phase) * ts * frequency * 2 * (math.Pi)))
carrierCount++
}
}
}
if carrierCount != 0 {
amplitude = amplitude / float64(carrierCount)
}
noise := float64(0)
scaler := float64(signalScaler)
if m.Options.NoiseLevel != 0 {
noiseAmplitude := (scaler / float64(100.0)) * float64(m.Options.NoiseLevel)
scaler = scaler - noiseAmplitude
noise = noiseAmplitude * rand.Float64()
}
fullWave[phase] = (amplitude * scaler) + noise
}
fmt.Println("wave generated")
m.CachedWave = &fullWave
}
return *m.CachedWave
}
func (m *Modulator) Reset() {
m.frameIndex = 0
}
func (m *Modulator) FrameCount() int {
return m.frameCount
}
func (m *Modulator) setup() {
m.carrierSpacing = float64(m.Options.OMFSKConstant) / (float64(m.Options.FrameDuration) / 1000.0)
m.carrierCount = int(math.Floor(float64(m.Options.Bandwidth) / m.carrierSpacing))
m.dataLength = len(*m.data)
m.frameCount = int(math.Ceil(float64(m.dataLength)/float64(m.carrierCount)) + 2)
m.frameIndex = 0
fmt.Println((m.carrierCount * (1000 / m.Options.FrameDuration)), "baud")
}
func (m *Modulator) buildHeaderFrame(frameIndex int) frame {
data := make([]bool, m.carrierCount)
for i := 0; i < m.carrierCount; i++ {
data[i] = i%2 == frameIndex
}
f := frame{}
f.data = data
f.carrierSpacing = m.carrierSpacing
f.frameIndex = frameIndex
f.options = m.Options
f.header = true
return f
}
func (m Modulator) buildFrame(frameIndex int) frame {
if frameIndex <= 1 {
return m.buildHeaderFrame(frameIndex)
}
leftEnd := m.carrierCount * (frameIndex - 2)
rightEnd := int(leftEnd + m.carrierCount)
if rightEnd > m.dataLength {
rightEnd = m.dataLength - 1
}
data := (*m.data)[leftEnd:rightEnd]
f := frame{}
f.data = data
//fmt.Println(data)
f.carrierSpacing = m.carrierSpacing
f.frameIndex = frameIndex
f.options = m.Options
return f
}
<file_sep>/utils/left_pad.go
package utils
func LeftPad(str string, length int) string {
return LeftPadWithByte(str, length, "0")
}
func LeftPadWithByte(str string, length int, paddingByte string) string {
padding := ""
paddingAmount := length - len(str)
for i := 0; i < paddingAmount; i++ {
padding += paddingByte
}
return padding + str
}
<file_sep>/options/constants.go
package options
const HeaderDataLengthIntegerBitLength = 20
const HeaderTransmissionChecksumLength = 32
const HeaderChecksumRedundancy = 2
const PacketTotalLength = 256
const PacketChecksumLength = 32
const PacketChecksumLengthBytes = PacketChecksumLength / 8
const PacketDataLength = PacketTotalLength - PacketChecksumLength
const PacketDataLengthBytes = PacketDataLength / 8
const HeaderLengthBits = HeaderTransmissionChecksumLength + HeaderDataLengthIntegerBitLength + (HeaderChecksumRedundancy * PacketChecksumLength)
const HeaderLengthWithoutRedundancy = HeaderTransmissionChecksumLength + HeaderDataLengthIntegerBitLength
const MaxCorrectionRoundsHashValidated = 12
const MaxCorrectionRoundsHashNotValidated = 12
const BitDepth = 32
const OffsetGroups = 1
const GuardDivisor = 1
const HeaderInterval = 2
<file_sep>/transmission/packet.go
package transmission
import (
"crypto/sha1"
"github.com/Hunter-Dolan/midrange/fec"
"github.com/Hunter-Dolan/midrange/options"
"github.com/Hunter-Dolan/midrange/utils"
)
type packet struct {
data *[]bool
hash *[]bool
hashBytes []byte
hashConfidenceCollection *fec.DataConfidenceCollection
dataConfidenceCollection *fec.DataConfidenceCollection
}
func (p *packet) setBytes(b []byte) {
binaryData := utils.BinEncode(b)
p.data = &binaryData
p.calculateHash(b)
}
func (p *packet) calculateHash(b []byte) {
sha1Data := sha1.Sum(b)
p.hashBytes = sha1Data[:options.PacketChecksumLengthBytes]
binaryHash := utils.BinEncode(p.hashBytes)
p.hash = &binaryHash
}
func (p *packet) replicateHash(level int) {
data := *p.data
for i := 0; i < level; i++ {
data = append(data, (*p.hash)...)
}
p.data = &data
}
func (p *packet) packetData() []bool {
packetData := append(*p.data, *p.hash...)
return packetData
}
<file_sep>/transmission/interleaver.go
package transmission
import "math"
func interleave(data []bool) []bool {
dataLength := len(data)
rounds := int(math.Floor(float64(dataLength / 4)))
for round := 0; round < rounds; round++ {
shiftedData := make([]bool, dataLength)
for index := range data {
offset := int(math.Floor(float64(index / 2)))
odd := index % 2
if odd == 1 {
shiftedData[index] = data[offset]
} else {
shiftedData[index] = data[dataLength-1-offset]
}
}
data = shiftedData
}
return data
}
<file_sep>/demodulation/decompress.go
package demodulation
import (
"bytes"
"log"
"github.com/ulikunitz/xz"
)
func decompress(data []byte) []byte {
buf := bytes.NewReader(data)
r, err := xz.NewReader(buf)
if err != nil {
log.Fatalf("NewReader error %s", err)
}
var reader bytes.Buffer
reader.ReadFrom(r)
return reader.Bytes()
}
<file_sep>/fec/deinterleaver.go
package fec
import "math"
func (d *DataConfidenceCollection) Deinterleave() {
confidence := d.confidence
data := d.data
dataLength := len(data)
dataOdd := dataLength % 2
rounds := int(math.Floor(float64(dataLength / 4)))
for round := 0; round < rounds; round++ {
shiftedData := make([]bool, dataLength)
shiftedConfidence := make([]float64, dataLength)
for index := range data {
pastMidpoint := (float64(index+1) / float64(dataLength)) > float64(0.5)
var shiftedIndex int
if pastMidpoint {
shiftedIndex = (dataLength - (index+1-int(math.Floor(float64(dataLength)/2.0)))*2)
if dataOdd == 1 {
shiftedIndex++
}
} else {
shiftedIndex = index*2 + 1
}
shiftedData[index] = data[shiftedIndex]
shiftedConfidence[index] = confidence[shiftedIndex]
}
data = shiftedData
confidence = shiftedConfidence
}
d.data = data
d.confidence = confidence
}
<file_sep>/transmission/demodulation.go
package transmission
import "github.com/Hunter-Dolan/midrange/demodulation"
func (t *Transmission) SetWave64(wave []float64) {
t.wave = &wave
t.demodulate()
}
func (t *Transmission) SetWave(wave []float32) {
float64Wave := make([]float64, len(wave))
for i, amp := range wave {
float64Wave[i] = float64(amp)
}
t.wave = &float64Wave
t.demodulate()
}
func (t *Transmission) Data() []byte {
return t.demodulator.Data()
}
func (t *Transmission) demodulate() {
if t.demodulator == nil {
t.demodulator = &demodulation.Demodulator{}
t.demodulator.Options = t.options
start := 0
end := len(*t.wave)
wave := (*t.wave)[start:end]
t.demodulator.SetWave(&wave)
}
}
<file_sep>/demodulation/demodulator.go
package demodulation
import (
"crypto/sha1"
"fmt"
"math"
"os"
"github.com/Hunter-Dolan/midrange/fec"
"github.com/Hunter-Dolan/midrange/options"
"github.com/Hunter-Dolan/midrange/utils"
)
type Demodulator struct {
Options *options.Options
carrierCount int
carrierSpacing float64
frames []*frame
confidenceCollection fec.DataConfidenceCollection
wave *[]float64
waveLength int
trainer trainer
dataLength int
header *header
packets []*packet
}
func (d *Demodulator) SetWave(wave *[]float64) {
d.wave = wave
d.setup()
}
func (d *Demodulator) Data() []byte {
data := []byte{}
for _, packet := range d.packets {
dataBytes := utils.BinDecode(packet.data.Data())
data = append(data, dataBytes...)
}
data = decompress(data)
return data
}
func (d *Demodulator) setup() {
d.carrierSpacing = float64(d.Options.OMFSKConstant) / (float64(d.Options.FrameDuration) / 1000.0)
d.carrierCount = int(math.Floor(float64(d.Options.Bandwidth) / d.carrierSpacing))
d.waveLength = len(*d.wave)
d.train()
d.demodulateFrames()
d.buildHeader()
d.buildPackets()
d.correctPacketHashes()
d.correctPackets()
}
func (d *Demodulator) train() {
d.trainer = trainer{}
d.trainer.demodulator = d
d.trainer.train()
}
func (d *Demodulator) demodulateFrames() {
fmt.Println("Demodulating Frames")
sampleRate := int64(d.Options.Kilobitrate * 1000)
numberOfSamplesPerFrame := int(float64(sampleRate) * (float64(d.Options.FrameDuration) / float64(1000)))
numberOfFrames := int(math.Floor(float64(d.waveLength/numberOfSamplesPerFrame))) - 2
if options.OffsetGroups != 1 {
numberOfFrames = numberOfFrames - 1
}
d.frames = make([]*frame, numberOfFrames)
d.confidenceCollection = fec.DataConfidenceCollection{}
for index := range d.frames {
f := frame{}
f.index = index + 2
f.demodulator = d
d.frames[index] = &f
f.demodulate()
d.confidenceCollection.Append(f.confidenceCollection)
}
d.dataLength = d.confidenceCollection.Length()
d.confidenceCollection.Deinterleave()
}
func (d *Demodulator) buildHeader() {
fmt.Println("Decoding Header")
confidenceCollection := d.confidenceCollection.Slice(0, options.HeaderLengthWithoutRedundancy)
hashCollection := d.confidenceCollection.Slice(options.HeaderLengthBits, options.PacketChecksumLength)
for i := 0; i < options.HeaderChecksumRedundancy; i++ {
offset := options.HeaderLengthWithoutRedundancy + (i * options.PacketChecksumLength)
redundantChecksum := d.confidenceCollection.Slice(offset, options.PacketChecksumLength)
hashCollection.AddRedundantCollection(redundantChecksum)
}
hashCollection.CorrectDataWithRedundancy()
d.header = &header{}
d.header.demodulator = d
d.header.data = confidenceCollection
d.header.hash = hashCollection
d.header.correct()
d.header.parse()
}
func (d *Demodulator) buildPackets() {
fmt.Println("Decoding Packets")
headerLength := d.header.Length()
packetCount := (d.header.dataLength / options.PacketDataLength) + 1
fmt.Println(packetCount, options.PacketTotalLength, (d.confidenceCollection.Length() - headerLength))
d.packets = make([]*packet, packetCount)
for i := range d.packets {
offset := headerLength + (i * options.PacketTotalLength)
packetTotalData := d.confidenceCollection.Slice(offset, options.PacketTotalLength)
packet := packet{}
dataLength := options.PacketDataLength
if i == packetCount-1 {
dataLength = d.header.dataLength - (i * options.PacketDataLength)
fmt.Println(packetTotalData.Length(), dataLength)
fmt.Println(d.header.dataLength, i*options.PacketDataLength)
fmt.Println("__")
}
packet.data = packetTotalData.Slice(0, dataLength)
packet.hash = packetTotalData.Slice(dataLength, options.PacketChecksumLength)
d.packets[i] = &packet
}
}
func (d *Demodulator) correctPacketHashes() {
fmt.Println("Decoding Packet Hashes")
hashCollection := fec.DataConfidenceCollection{}
for _, packet := range d.packets {
hashCollection.Append(packet.hash)
}
hash := d.header.transmissionHash
hashCollection.HashVerifier = func(data []bool, hash []bool) bool {
dataByte := utils.BoolToByteBin(data)
sha1DataFull := sha1.Sum(dataByte)
sha1Data := sha1DataFull[:options.HeaderTransmissionChecksumLength/8]
boolBinHash := utils.BinEncodeWithPad(sha1Data, options.HeaderTransmissionChecksumLength)
match := true
for i, value := range hash {
if boolBinHash[i] != value {
match = false
break
}
}
return match
}
if !hashCollection.CorrectData(hash, true) {
fmt.Println("Could not decode packet hashes")
os.Exit(0)
}
for i, packet := range d.packets {
packet.hash = hashCollection.Slice(i*options.PacketChecksumLength, options.PacketChecksumLength)
}
}
func (d *Demodulator) correctPackets() {
fmt.Println("Correcting Packets")
for _, packet := range d.packets {
packet.Correct()
}
}
<file_sep>/utils/bool_to_bin.go
package utils
func BoolToBin(boolean []bool) string {
result := ""
for _, value := range boolean {
if value {
result += "1"
} else {
result += "0"
}
}
return result
}
func BoolToByteBin(boolean []bool) []byte {
result := make([]byte, len(boolean))
for i, value := range boolean {
if value {
result[i] = '1'
} else {
result[i] = '0'
}
}
return result
}
<file_sep>/transmission/compresson.go
package transmission
import (
"bytes"
"log"
"github.com/ulikunitz/xz"
)
func compress(data []byte) []byte {
var buf bytes.Buffer
// compress text
w, err := xz.NewWriter(&buf)
if err != nil {
log.Fatalf("xz.NewWriter error %s", err)
}
w.Write(data)
if err := w.Close(); err != nil {
log.Fatalf("w.Close error %s", err)
}
return buf.Bytes()
}
<file_sep>/fec/data_confidence_collection.go
package fec
import "sort"
type DataConfidenceCollection struct {
data []bool
confidence []float64
redundantCollections []*DataConfidenceCollection
maxConfidence float64
HashVerifier func(data []bool, hash []bool) bool
}
func (d *DataConfidenceCollection) Add(bit bool, bitConfidence float64) {
d.data = append(d.data, bit)
d.confidence = append(d.confidence, bitConfidence)
}
func (d DataConfidenceCollection) Data() []bool {
return d.data
}
func (d DataConfidenceCollection) Get(index int) (bool, float64) {
boolBit := d.data[index]
confidence := d.confidence[index]
return boolBit, confidence
}
func (d DataConfidenceCollection) Length() int {
return len(d.data)
}
func (d DataConfidenceCollection) LeastConfidentBitIndexes(number int) []int {
sortedConfidences := make([]float64, len(d.confidence))
for i, confidence := range d.confidence {
sortedConfidences[i] = confidence
}
sort.Float64s(sortedConfidences)
returnData := []int{}
for _, confidence := range sortedConfidences {
index := -1
for i, unsortedConfidence := range d.confidence {
if unsortedConfidence == confidence {
index = i
}
}
returnData = append(returnData, index)
if len(returnData) >= number {
break
}
}
return returnData
}
func (d DataConfidenceCollection) copy() *DataConfidenceCollection {
return &d
}
func (d *DataConfidenceCollection) Append(appendage *DataConfidenceCollection) {
d.data = append(d.data, appendage.data...)
d.confidence = append(d.confidence, appendage.confidence...)
}
func (d *DataConfidenceCollection) Slice(leftEnd, length int) *DataConfidenceCollection {
slice := DataConfidenceCollection{}
rightEnd := int(leftEnd + length)
dataLength := len(d.data)
if rightEnd > dataLength {
rightEnd = dataLength - 1
}
slice.data = d.data[leftEnd:rightEnd]
slice.confidence = d.confidence[leftEnd:rightEnd]
return &slice
}
<file_sep>/transaction/transaction.go
package transaction
import (
"fmt"
"math"
"github.com/Hunter-Dolan/midrange/frame"
)
// Transaction is the base transaction structure
type Transaction struct {
Frames []*frame.Frame
BaseFrequency int
FrameDuration int
Kilobitrate int
Bandwidth int
OMFSKConstant float64
carrierCount int
carrierSpacing float64
wave []float64
// Debug
NoiseLevel int
}
// NewTransaction creates a new transaction
func NewTransaction() *Transaction {
t := Transaction{}
t.BaseFrequency = 50000
t.FrameDuration = 500
t.Kilobitrate = 96 * 2
t.Bandwidth = 1000
t.OMFSKConstant = 1.0
return &t
}
// AddFrame appends a frame to the transaction
func (t *Transaction) AddFrame(f *frame.Frame) {
t.Frames = append(t.Frames, f)
}
func stringToBin(s string) string {
binaryString := ""
for _, c := range s {
binary := fmt.Sprintf("%b", c)
binaryLen := len(binary)
padAmount := 8 - binaryLen
for i := 0; i < padAmount; i++ {
binary = "0" + binary
}
binaryString += binary
}
return binaryString
}
func (t *Transaction) determineCarrierCount() {
t.carrierSpacing = float64(t.OMFSKConstant) / (float64(t.FrameDuration) / 1000.0)
t.carrierCount = int(math.Floor(float64(t.Bandwidth) / t.carrierSpacing))
}
// SetData sets the data for the transaction
func (t *Transaction) SetData(s string) {
t.determineCarrierCount()
bin := stringToBin(s)
binLength := len(bin)
frameData := []int{}
frameSum := 0
for i, binaryBit := range bin {
carrierIndex := i % t.carrierCount
bit := int(binaryBit) - 48
frameData = append(frameData, bit)
frameSum += bit
if carrierIndex == (t.carrierCount-1) || i == (binLength-1) {
byteLength := len(frameData) / 8
byteOffset := len(t.Frames) * byteLength
fmt.Println(frameData, s[byteOffset:byteLength+byteOffset], frameSum)
f := frame.NewFrame(frameData...)
t.AddFrame(f)
frameData = []int{}
frameSum = 0
}
}
}
func (t *Transaction) buildHeader() {
headers := frame.NewHeaderFrames(t.FrameGenerationOptions())
t.Frames = append(headers, t.Frames...)
}
func (t Transaction) FrameGenerationOptions() *frame.GenerationOptions {
frameOptions := frame.GenerationOptions{}
frameOptions.Duration = int64(t.FrameDuration)
frameOptions.BaseFrequency = t.BaseFrequency
frameOptions.SampleRate = int64(t.Kilobitrate * 1000)
frameOptions.CarrierCount = t.carrierCount
frameOptions.CarrierSpacing = t.carrierSpacing
frameOptions.NoiseLevel = t.NoiseLevel
return &frameOptions
}
func (t *Transaction) Wave() []float64 {
if t.wave == nil {
t.buildHeader()
wave := []float64{}
fmt.Println(float64(t.carrierCount)*(1000.0/float64(t.FrameDuration)), "Bits/second")
fmt.Println(t.carrierCount, "Carriers")
numFrames := len(t.Frames)
waveIndex := int64(0)
frameOptions := t.FrameGenerationOptions()
for frameIndex := 0; frameIndex < numFrames; frameIndex++ {
frame := t.Frames[frameIndex]
waveIndex = frame.Generate(frameOptions, waveIndex)
wave = append(wave, frame.Wave...)
}
fmt.Println(numFrames, "Frames")
t.wave = wave
}
return t.wave
}
<file_sep>/demodulation/header.go
package demodulation
import (
"fmt"
"os"
"strconv"
"github.com/Hunter-Dolan/midrange/fec"
"github.com/Hunter-Dolan/midrange/options"
"github.com/Hunter-Dolan/midrange/utils"
)
type header struct {
packet
demodulator *Demodulator
transmissionHash *fec.DataConfidenceCollection
dataLength int
}
func (h *header) correct() bool {
h.data.HashVerifier = func(data []bool, hash []bool) bool {
valid := fec.SHA1DirectBinVerifier(data, hash)
if valid {
intLength := options.HeaderDataLengthIntegerBitLength
dataLengthBool := data[:intLength]
dataLengthBin := utils.BoolToBin(dataLengthBool)
dataLengthDec, _ := strconv.ParseInt(dataLengthBin, 2, 64)
dataLength := int(dataLengthDec)
approxBitsMax := ((h.demodulator.dataLength - options.HeaderLengthBits) / options.PacketTotalLength) * options.PacketDataLength
approxBitsMin := approxBitsMax - h.demodulator.carrierCount
if dataLength <= approxBitsMax && dataLength > approxBitsMin {
return true
}
}
return false
}
correct := h.data.CorrectData(h.hash, true)
if !correct {
correct = h.data.CorrectData(h.hash, false)
if !correct {
fmt.Println("Unable to decode header")
os.Exit(0)
}
}
return correct
}
func (h *header) parse() {
boolData := h.data.Data()
intLength := options.HeaderDataLengthIntegerBitLength
checkLength := options.HeaderTransmissionChecksumLength
dataLengthBool := boolData[:intLength]
dataLengthBin := utils.BoolToBin(dataLengthBool)
dataLengthDec, _ := strconv.ParseInt(dataLengthBin, 2, 64)
h.dataLength = int(dataLengthDec)
h.transmissionHash = h.data.Slice(intLength, checkLength)
}
func (p *header) Length() int {
return options.HeaderLengthBits + options.PacketChecksumLength
}
<file_sep>/modulation/frame.go
package modulation
import (
"math"
"math/rand"
"github.com/Hunter-Dolan/midrange/options"
)
type frame struct {
data []bool
carrierSpacing float64
frameIndex int
header bool
offset int
options *options.Options
}
func (f frame) wave() *[]float64 {
carriers := f.carriers()
carrierCount := len(carriers)
sampleRate := int64(f.options.Kilobitrate * 1000)
numSamples := int64(float64(sampleRate) / float64(1000.0) * float64(f.options.FrameDuration))
ts := 1 / float64(sampleRate)
wave := make([]float64, numSamples)
startIndex := numSamples * int64(f.frameIndex)
for i := int64(0); i < numSamples; i++ {
amplitude := float64(0)
if carrierCount != 0 {
p := float64(i+startIndex) * ts
for carrierIndex := int64(0); carrierIndex < int64(carrierCount); carrierIndex++ {
freq := carriers[carrierIndex]
amplitude += (math.Sin(p * freq * 2 * (math.Pi)))
}
amplitude = (amplitude / float64(carrierCount))
}
noise := float64(0)
scaler := float64(math.Pow(2, float64(options.BitDepth-1)))
if f.options.NoiseLevel != 0 {
noiseAmplitude := (scaler / float64(100.0)) * float64(f.options.NoiseLevel)
scaler = scaler - noiseAmplitude
noise = noiseAmplitude * rand.Float64()
}
wave[i] = amplitude*scaler + noise
}
return &wave
}
func (f frame) allCarriers() []float64 {
var carriers = []float64{}
for index, bit := range f.data {
if bit {
freq := float64(index)*f.carrierSpacing + float64(f.options.BaseFrequency)
carriers = append(carriers, freq)
} else {
carriers = append(carriers, -1.0)
}
}
return carriers
}
func (f frame) carriers() []float64 {
var carriers = []float64{}
for index := range f.data {
if f.data[index] {
freq := float64(index)*f.carrierSpacing + float64(f.options.BaseFrequency)
carriers = append(carriers, freq)
}
}
return carriers
}
<file_sep>/transmission/transmission.go
package transmission
import (
"github.com/Hunter-Dolan/midrange/demodulation"
"github.com/Hunter-Dolan/midrange/modulation"
"github.com/Hunter-Dolan/midrange/options"
)
type Transmission struct {
header *packet
data []*packet
dataLength int
originalDataLength int
wave *[]float64
modulator *modulation.Modulator
demodulator *demodulation.Demodulator
options *options.Options
}
func NewTransmission() *Transmission {
t := Transmission{}
return &t
}
func (t *Transmission) SetOptions(options options.Options) {
t.options = &options
}
func (t Transmission) CachedWave() []float64 {
return *t.modulator.CachedWave
}
<file_sep>/fec/corrector.go
package fec
import (
"fmt"
"math"
"strconv"
"github.com/Hunter-Dolan/midrange/options"
"github.com/Hunter-Dolan/midrange/utils"
)
func (d *DataConfidenceCollection) CorrectData(hash *DataConfidenceCollection, hashValidated bool) bool {
// Check to see if the data is valid
if d.verifyHash(hash) {
return true
}
maxRounds := options.MaxCorrectionRoundsHashValidated
if !hashValidated {
maxRounds = options.MaxCorrectionRoundsHashNotValidated
}
originalHash := hash.copy()
valid := false
for round := 0; round < maxRounds; round++ {
if round != 0 {
fmt.Println("Corrector Round:", round)
}
bits := possibleBinarySlicesWithNumberOfBits(round + 1)
bitsLen := len(bits)
//par.ForInterleaved(0, uint(bitsLen-1), 1, func(index uint) {
for index := 0; index < bitsLen; index++ {
if !valid {
localValid := false
data := d
dataBits := bits[index]
// First Attempt to flip only data bits
data.swapLeastConfidentBitsWithBits(dataBits)
if data.verifyHash(originalHash) {
localValid = true
}
if !localValid && !hashValidated {
// Next Attempt to flip hash bits as well
for _, hashBits := range bits {
hash.swapLeastConfidentBitsWithBits(hashBits)
if data.verifyHash(hash) {
localValid = true
break
}
}
}
if localValid {
d.data = data.data
d.confidence = data.confidence
valid = true
}
}
//})
}
if valid {
break
}
}
return valid
}
func (data DataConfidenceCollection) verifyHash(hash *DataConfidenceCollection) bool {
if data.HashVerifier != nil {
return data.HashVerifier(data.data, hash.data)
}
equal := true
for i, value := range data.data {
if value != hash.data[i] {
equal = false
break
}
}
return equal
}
func (data *DataConfidenceCollection) swapLeastConfidentBitsWithBits(bits []bool) {
bitLength := len(bits)
swapIndexes := data.LeastConfidentBitIndexes(bitLength)
for bitIndex, dataIndex := range swapIndexes {
data.data[dataIndex] = bits[bitIndex]
}
}
func possibleBinarySlicesWithNumberOfBits(bitCount int) [][]bool {
sliceSize := int(math.Pow(2, float64(bitCount)))
offset := 0
if bitCount > 1 {
offset = int(math.Pow(2, float64(bitCount-1)))
sliceSize -= offset
}
possiblities := make([][]bool, sliceSize)
for i := range possiblities {
bin := strconv.FormatInt(int64(i+offset), 2)
bin = utils.LeftPad(bin, bitCount)
boolBin := make([]bool, bitCount)
for index, value := range bin {
boolBin[index] = value == '1'
}
possiblities[i] = boolBin
}
return possiblities
}
<file_sep>/utils/bin_decode.go
package utils
import "strconv"
func BinDecode(binary []bool) []byte {
bitLength := 8
byteCount := len(binary) / bitLength
byteArray := make([]byte, byteCount)
for byteIndex := 0; byteIndex < byteCount; byteIndex++ {
offset := byteIndex * bitLength
boolBits := binary[offset : offset+bitLength]
bits := ""
for _, boolBit := range boolBits {
if boolBit {
bits += "1"
} else {
bits += "0"
}
}
i, _ := strconv.ParseInt(bits, 2, 64)
byteArray[byteIndex] = byte(i)
}
return byteArray
}
<file_sep>/demodulation/frame.go
package demodulation
import (
"github.com/Hunter-Dolan/midrange/fec"
)
type frame struct {
index int
demodulator *Demodulator
confidenceCollection *fec.DataConfidenceCollection
}
func (f *frame) demodulate() {
powers := f.demodulator.carrierPowerAtFrame(f.index)
trainer := f.demodulator.trainer
f.confidenceCollection = &fec.DataConfidenceCollection{}
for carrierIndex, power := range powers {
value, confidence := trainer.determineValueAndConfidence(power, carrierIndex)
f.confidenceCollection.Add(value, confidence)
}
//fmt.Println(f.confidenceCollection.Data())
}
<file_sep>/options/options.go
package options
type Options struct {
BaseFrequency int
FrameDuration int
Kilobitrate int
Bandwidth int
OMFSKConstant float64
NFFTPower float64
// Debug
NoiseLevel int
}
<file_sep>/matcher/matcher.go
package matcher
import (
"fmt"
"math"
"strconv"
"strings"
"github.com/Hunter-Dolan/midrange/frame"
"github.com/mjibson/go-dsp/spectral"
)
var carrierActive []float64
var carrierResting []float64
var carrierActiveAvg float64
var carrierRestingAvg float64
// FindProbableMatch returns the most likely match for a wave
func (b *Matcher) findProbableMatch(wave []float64, frameIndex int) *frame.Frame {
frame := &frame.Frame{}
nfft := math.Pow(2, float64(b.options.NFFTPower))
//topCandidate := b.frames[0]
// Perform Pwelch on wave
fs := float64(b.options.SampleRate)
opts := &spectral.PwelchOptions{
NFFT: int(nfft),
}
guardOffset := int((float64(len(wave)) / 100.0) * 0.0)
guardedWave := wave[guardOffset : len(wave)-1]
powers, frequencies := spectral.Pwelch(guardedWave, fs, opts)
carriers := b.options.Carriers()
numberOfCarriers := len(carriers)
minimumCarrierAdjusted := float64(carriers[0] - 5)
maximumCarrierAdjusted := float64(carriers[numberOfCarriers-1] + 5)
carriersFound := 0
minimumDistance := float64(-1)
searchingCarrier := carriers[0]
locatedCarrierValues := make([]float64, numberOfCarriers)
for i, frequency := range frequencies {
if frequency < maximumCarrierAdjusted && frequency > minimumCarrierAdjusted {
distance := math.Abs(frequency - float64(searchingCarrier))
headerPacket := frameIndex <= 1
power := powers[i-1]
if minimumDistance < distance && minimumDistance != float64(-1) {
if headerPacket {
evenFrame := frameIndex%2 == 0
evenCarrier := carriersFound%2 == 0
if evenFrame && evenCarrier || !evenFrame && !evenCarrier {
carrierActive[carriersFound] = power
} else {
carrierResting[carriersFound] = power
}
} else {
activePower := carrierActiveAvg // carrierActive[carriersFound]
inactivePower := carrierRestingAvg
activeCarrierDistance := math.Abs(activePower - power)
restingCarrierDistance := math.Abs(inactivePower - power)
value := 1
if activeCarrierDistance/2 > restingCarrierDistance {
value = 0
}
frame.Data = append(frame.Data, value)
}
locatedCarrierValues[carriersFound] = powers[i-1]
carriersFound++
if carriersFound < numberOfCarriers {
searchingCarrier = carriers[carriersFound]
minimumDistance = float64(-1)
} else {
break
}
} else {
minimumDistance = distance
}
}
}
//fmt.Println(frame.Data)
//ioutil.WriteFile("data.csv", []byte(csvData), 0644)
return frame
}
// Match decodes matched frames
func (b *Matcher) match(wave []float64) []*frame.Frame {
frames := []*frame.Frame{}
waveLength := int64(len(wave))
options := b.options
frameLength := int64(float64(options.SampleRate) / float64(1000.0) * float64(options.Duration))
numberOfFrames := waveLength / frameLength
carrierActive = make([]float64, options.CarrierCount)
carrierResting = make([]float64, options.CarrierCount)
for i := int64(0); i < numberOfFrames; i++ {
offset := i * frameLength
frameWave := wave[offset : offset+frameLength]
frameIndex := len(frames)
frame := b.findProbableMatch(frameWave, frameIndex)
if frameIndex <= 1 {
frame.HeaderPacket = true
if frameIndex == 1 {
carrierActiveAvg = float64(0)
carrierRestingAvg = float64(0)
for i, active := range carrierActive {
resting := carrierResting[i]
carrierActiveAvg += active
carrierRestingAvg += resting
}
carrierActiveAvg = carrierActiveAvg / float64(len(carrierActive))
carrierRestingAvg = carrierActiveAvg / 4 //carrierRestingAvg / float64(len(carrierResting))
fmt.Println(carrierActiveAvg, carrierRestingAvg)
}
}
frames = append(frames, frame)
}
return frames
}
func (b *Matcher) Decode(wave []float64) string {
frames := b.match(wave)
binary := ""
for _, frame := range frames {
if frame.HeaderPacket == false {
frameBinary := ""
frameDataLen := len(frame.Data)
padAmount := b.options.CarrierCount - frameDataLen
for i := 0; i < padAmount; i++ {
frameBinary += "0"
}
for _, bit := range frame.Data {
frameBinary += strconv.Itoa(bit)
}
binary += frameBinary
}
}
//fmt.Println(binary)
bitLength := 8
byteCount := len(binary) / bitLength
byteArray := make([]byte, byteCount)
for byteIndex := 0; byteIndex < byteCount; byteIndex++ {
offset := byteIndex * bitLength
bits := binary[offset : offset+bitLength]
i, _ := strconv.ParseInt(bits, 2, 64)
byteArray[byteIndex] = byte(i)
}
/*
var buffer bytes.Buffer
r, err := gzip.NewReader(&buffer)
if err != nil {
fmt.Println(err)
}
r.Read(byteArray)
r.Close()
return buffer.String()*/
return strings.TrimSpace(string(byteArray[:]))
}
<file_sep>/readme.md
# Midrange
Work in progress.
Disclaimer: Midrange still is under very active development. You probably shouldn't use it for anything yet. The protocol, packet structure, modulation techniques, and demodulation techniques will change.
Midrange is also very slow right now. The only focus is the speed, spectral efficiency, and reliability of transmitting large amounts of data in high noise environments.
Midrange focuses extensively on being the new digital standard for HF radio communications.
It is currently being Developed by <NAME>, and software engineer and not a ham radio operator.
Anyone who wants to provide assistance, comments, questions, concerns, etc can feel free to contact him directly at <EMAIL>.
# Goals
HF radio bands allow for intercontinental communication between radios at very low power through the use of skywave propagation. The unique properties of frequencies in this band have been exploited since the early days of radio communications.
Midrange's goal is to provide a new open standard for HF digital communications.
Midrange will be able to offer a high bitrate on a very low bandwidth channel. With adaptive symbol rates, advanced forward error correction, Midrange signals can still be decoded slightly below the noise floor.
The goals of midrange are as follows:
Open Header System:
- Provide an open header standard that will allow midrange to evolve in the future and maintain reverse compatibility. Headers will be modulated at a low bit rate in order to ensure decodablity under even under weak signal conditions. And will provide:
- 4 bit Modulation Code: The type of modulation the data will be encoded with. Codes 0-4 will be designated for future midrange development while 5-14 will be designated for alternate (non midrange) modulation schemes. Finally code 15 will be reserved for future use (most likely to allow for extension bits to be added to the header for an even greater modulation set)
- 12 bit Modulation Configuration
- 42 bit Call Sign
- 8 bit length of transmission in quarter seconds (not applicable in beacon mode)
- 16 bit checksum
- Enable automatic link establishment
- Enable frequency sharing (using TDM)
Midrange 1:
- Use the open header system
- Enable both beacon communications, 1 to 1 communications, and n to n communications
- Capable of transmitting up to 1 bit per hz
- Capable of being decoded at or even below the noise floor (at a lower bit rate)
- Highly configurable (configurable bandwidth, carrier count, frame rate, amplitude levels, etc)
- Able to use forward error correction to correct a large number of bits
- Can be modulated and demodulated with a SoundCard (no special hardware)
- Is able to mitigate multipath, high noise, doppler shift, and other problems commonly experienced on the HF band
- Able to be used on any mode of transport including walki talki, sound and microphone, fm radio, etc.
Midrange 2:
- Employs all features of Midrange 1
- Capable of being decoded well below the noise floor (at a very low bit rate)
- Capable of transmitting up to 2.5 bits for every 1hz of bandwidth
Midrange 3:
- Employs all of the features of Midrange 2
- Enables communications to be shared on the same band (through the use of FDM and TDM)
- Enables a real time communication registry that will allow frequencies to be scheduled for transmissions
Overall Vision:
Midrange will be used to connect the furthest reaches of the globe. It will be used as an alternative to costly satellite systems, expensive and monopolized high rate proprietary HF modes. It does not intend to, will it be able to, compete with high rate modes in the VHF and UHF spectrum.
Potential Applications include:
- HAM Communications (including digital audio)
- Maritime Communications
- Remote Research Communications
- Commercial Trunked Communication Services
<file_sep>/demodulation/pwelch.go
package demodulation
import (
"math"
"github.com/Hunter-Dolan/midrange/options"
"github.com/mjibson/go-dsp/spectral"
)
/*
// A test function to determine the best nftt value
func (d *Demodulator) carrierPowerAtFrame(frameIndex int) []float64 {
bestValue := 9999999999999.0
offset := 0.0001
start := 16.837
iteration := 0
best := 0.000
// 53.70708024275132
for {
testValue := start + (offset * float64(iteration))
fmt.Println("Testing:", testValue)
powers := make([][]float64, options.OffsetGroups)
frequencies := make([][]float64, options.OffsetGroups)
sampleRate := int64(d.Options.Kilobitrate * 1000)
numberOfSamplesPerFrame := int(float64(sampleRate) * (float64(d.Options.FrameDuration) / float64(1000.0)))
for offsetIndex := range powers {
offsetAmount := 0
if options.OffsetGroups != 1 {
offsetAmount = (numberOfSamplesPerFrame / int(options.OffsetGroups)) * offsetIndex
}
leftEnd := int(frameIndex*numberOfSamplesPerFrame) + offsetAmount
guard := numberOfSamplesPerFrame - (numberOfSamplesPerFrame / options.GuardDivisor)
rightEnd := (int(leftEnd+numberOfSamplesPerFrame) + offsetAmount) - guard
waveLength := d.waveLength
//fmt.Println(frameIndex, offsetAmount, leftEnd, rightEnd, waveLength)
if rightEnd > waveLength {
rightEnd = waveLength - 1
}
segment := (*d.wave)[leftEnd:rightEnd]
//nfft := math.Pow(2, d.Options.NFFTPower)
// nfft := math.Pow(2, testValue)
// Perform Pwelch on wave
fs := float64(d.Options.Kilobitrate * 1000)
opts := &spectral.PwelchOptions{
//NFFT: int(math.Pow(2, 17.0)),
NFFT: int(math.Pow(2, testValue)),
}
offsetPowers, offsetFrequencies := spectral.Pwelch(segment, fs, opts)
powers[offsetIndex] = offsetPowers
frequencies[offsetIndex] = offsetFrequencies
}
carriers := d.carrierFrequencies()
numberOfCarriers := len(carriers)
minimumCarrierAdjusted := float64(carriers[0] - 5)
maximumCarrierAdjusted := float64(carriers[numberOfCarriers-1] + 5)
carriersFound := 0
locatedCarrierValues := make([]float64, numberOfCarriers)
totalDist := 0.0
for i, searchingCarrier := range carriers {
groupIndex := i % options.OffsetGroups
groupFrequencies := frequencies[groupIndex]
minimumDistance := float64(-1)
for i, frequency := range groupFrequencies {
if frequency < maximumCarrierAdjusted && frequency > minimumCarrierAdjusted {
distance := math.Abs(frequency - float64(searchingCarrier))
if minimumDistance < distance && minimumDistance != float64(-1) {
locatedCarrierValues[carriersFound] = powers[groupIndex][i-1]
totalDist += math.Abs(searchingCarrier - groupFrequencies[i-1])
carriersFound++
break
} else {
minimumDistance = distance
}
}
}
}
fmt.Println(totalDist)
if bestValue > totalDist {
fmt.Println("So far Best:", start+(offset*float64(iteration-1)))
//break
best = start + (offset * float64(iteration-1))
bestValue = totalDist
}
iteration++
if iteration > 100 {
break
}
}
fmt.Println("Aboslute Best:", best, bestValue)
os.Exit(0)
return []float64{}
}
/*/
func (d *Demodulator) carrierPowerAtFrame(frameIndex int) []float64 {
powers := make([][]float64, options.OffsetGroups)
frequencies := make([][]float64, options.OffsetGroups)
sampleRate := int64(d.Options.Kilobitrate * 1000)
numberOfSamplesPerFrame := int(float64(sampleRate) * (float64(d.Options.FrameDuration) / float64(1000.0)))
for offsetIndex := range powers {
offsetAmount := 0
if options.OffsetGroups != 1 {
offsetAmount = (numberOfSamplesPerFrame / int(options.OffsetGroups)) * offsetIndex
}
leftEnd := int(frameIndex*numberOfSamplesPerFrame) + offsetAmount
guard := numberOfSamplesPerFrame - (numberOfSamplesPerFrame / options.GuardDivisor)
rightEnd := (int(leftEnd+numberOfSamplesPerFrame) + offsetAmount) - guard
waveLength := d.waveLength
//fmt.Println(frameIndex, offsetAmount, leftEnd, rightEnd, waveLength)
if rightEnd > waveLength {
rightEnd = waveLength - 1
}
segment := (*d.wave)[leftEnd:rightEnd]
nfft := math.Pow(2, d.Options.NFFTPower)
pad := math.Pow(2, d.Options.NFFTPower)
// Perform Pwelch on wave
fs := float64(d.Options.Kilobitrate * 1000)
opts := &spectral.PwelchOptions{
NFFT: int(nfft),
Pad: int(pad),
}
offsetPowers, offsetFrequencies := spectral.Pwelch(segment, fs, opts)
powers[offsetIndex] = offsetPowers
frequencies[offsetIndex] = offsetFrequencies
}
carriers := d.carrierFrequencies()
numberOfCarriers := len(carriers)
minimumCarrierAdjusted := float64(carriers[0] - 5)
maximumCarrierAdjusted := float64(carriers[numberOfCarriers-1] + 5)
carriersFound := 0
locatedCarrierValues := make([]float64, numberOfCarriers)
for i, searchingCarrier := range carriers {
groupIndex := i % options.OffsetGroups
groupFrequencies := frequencies[groupIndex]
minimumDistance := float64(-1)
for i, frequency := range groupFrequencies {
if frequency < maximumCarrierAdjusted && frequency > minimumCarrierAdjusted {
distance := math.Abs(frequency - float64(searchingCarrier))
if minimumDistance < distance && minimumDistance != float64(-1) {
locatedCarrierValues[carriersFound] = powers[groupIndex][i-1]
//fmt.Println(groupFrequencies[i-1], searchingCarrier)
carriersFound++
break
} else {
minimumDistance = distance
}
}
}
}
//fmt.Println(locatedCarrierValues)
return locatedCarrierValues
}
//*/
func (d *Demodulator) carrierFrequencies() []float64 {
var carriers = make([]float64, d.carrierCount)
for index := range carriers {
freq := float64(index)*d.carrierSpacing + float64(d.Options.BaseFrequency)
carriers[index] = freq
}
return carriers
}
<file_sep>/fec/redundancy.go
package fec
import "math"
func (d *DataConfidenceCollection) AddRedundantCollection(redundant *DataConfidenceCollection) {
d.redundantCollections = append(d.redundantCollections, redundant)
}
func (d *DataConfidenceCollection) CorrectDataWithRedundancy() {
for i, value := range d.data {
zeroConfidence := 0.0
oneConfidence := 0.0
zeroCount := 0
oneCount := 0
if value {
oneConfidence += d.confidence[i]
oneCount++
} else {
zeroConfidence += d.confidence[i]
zeroCount++
}
for _, redundantCollection := range d.redundantCollections {
value := redundantCollection.data[i]
if value {
oneConfidence += d.confidence[i]
oneCount++
} else {
zeroConfidence += d.confidence[i]
zeroCount++
}
}
if oneCount > zeroCount {
d.data[i] = true
} else {
d.data[i] = false
}
d.confidence[i] = math.Abs(oneConfidence - zeroConfidence)
}
}
<file_sep>/demodulation/packet.go
package demodulation
import (
"crypto/sha1"
"github.com/Hunter-Dolan/midrange/fec"
"github.com/Hunter-Dolan/midrange/options"
"github.com/Hunter-Dolan/midrange/utils"
)
type packet struct {
data *fec.DataConfidenceCollection
hash *fec.DataConfidenceCollection
}
func (p *packet) Correct() bool {
p.data.HashVerifier = func(data []bool, hash []bool) bool {
dataByte := utils.BinDecode(data)
sha1DataFull := sha1.Sum(dataByte)
sha1Data := sha1DataFull[:options.PacketChecksumLength/8]
boolBinHash := utils.BinEncodeWithPad(sha1Data, options.PacketChecksumLength)
match := true
for i, value := range hash {
if boolBinHash[i] != value {
match = false
break
}
}
return match
}
return p.data.CorrectData(p.hash, true)
}
func (p *packet) Length() int {
return p.data.Length() + p.hash.Length()
}
<file_sep>/fec/verifiers.go
package fec
import (
"crypto/sha1"
"github.com/Hunter-Dolan/midrange/options"
"github.com/Hunter-Dolan/midrange/utils"
)
func SHA1DirectBinVerifier(data []bool, hash []bool) bool {
dataByte := utils.BoolToByteBin(data)
sha1DataFull := sha1.Sum(dataByte)
sha1Data := sha1DataFull[:options.PacketChecksumLength/8]
boolBinHash := utils.BinEncodeWithPad(sha1Data, options.PacketChecksumLength)
match := true
for i, value := range hash {
if boolBinHash[i] != value {
match = false
break
}
}
return match
}
<file_sep>/frame/frame.go
package frame
import (
"fmt"
"math"
"math/rand"
)
// Frame is the base structure for a transaction frame
type Frame struct {
Data []int
SignalFrequency int
Wave []float64
HeaderPacket bool
}
// GenerationOptions is the base option
type GenerationOptions struct {
CarrierCount int
CarrierSpacing float64
Duration int64
SampleRate int64
BaseFrequency int
NoiseLevel int
}
// NewFrame creates a new frame
func NewFrame(data ...int) *Frame {
frame := Frame{}
frame.Data = data
frame.SignalFrequency = -1
return &frame
}
// NewHeaderFrames creates the header frames
func NewHeaderFrames(options *GenerationOptions) []*Frame {
evenData := make([]int, options.CarrierCount)
oddData := make([]int, options.CarrierCount)
for i := 0; i < options.CarrierCount; i++ {
even := i%2 == 0
if even {
evenData[i] = 1
oddData[i] = 0
} else {
evenData[i] = 0
oddData[i] = 1
}
}
evenFrame := NewFrame(evenData...)
evenFrame.SignalFrequency = 300
oddFrame := NewFrame(oddData...)
oddFrame.SignalFrequency = 300
return []*Frame{evenFrame, oddFrame}
}
func (f Frame) carriers(options *GenerationOptions) []float64 {
var carriers = []float64{}
//if f.SignalFrequency != -1 {
// carriers[float64(f.SignalFrequency)] = 1
//≈}
for index := range f.Data {
if f.Data[index] == 1 {
freq := float64(index)*options.CarrierSpacing + float64(options.BaseFrequency)
carriers = append(carriers, freq)
}
}
return carriers
}
// Generate creates the wave
func (f *Frame) Generate(options *GenerationOptions, startIndex int64) int64 {
carriers := f.carriers(options)
carrierCount := len(carriers)
numSamples := int64(float64(options.SampleRate) / float64(1000.0) * float64(options.Duration))
ts := 1 / float64(options.SampleRate)
f.Wave = make([]float64, numSamples)
fmt.Println(carriers)
for i := int64(0); i < numSamples; i++ {
amplitude := float64(0)
p := float64(i+startIndex) * ts
for carrierIndex := int64(0); carrierIndex < int64(carrierCount); carrierIndex++ {
freq := carriers[carrierIndex]
amplitude += (math.Sin(p * freq * 2 * (math.Pi)))
}
amplitude = (amplitude / float64(carrierCount))
noise := float64(0)
scaler := float64(32767.0)
if options.NoiseLevel != 0 {
noiseAmplitude := (scaler / float64(100.0)) * float64(options.NoiseLevel)
scaler = scaler - noiseAmplitude
noise = noiseAmplitude * rand.Float64()
}
f.Wave[i] = amplitude*scaler + noise
}
return startIndex + numSamples
}
func (o *GenerationOptions) Carriers() []float64 {
frequencies := make([]float64, o.CarrierCount)
for i := 0; i < o.CarrierCount; i++ {
frequencies[i] = (float64(i) * o.CarrierSpacing) + float64(o.BaseFrequency)
}
return frequencies
}
<file_sep>/main.go
package main
import (
"fmt"
"os"
"github.com/Hunter-Dolan/midrange/options"
"github.com/Hunter-Dolan/midrange/transmission"
"github.com/go-audio/aiff"
)
func main() {
options := options.Options{}
options.BaseFrequency = 75
options.FrameDuration = 500
options.Kilobitrate = 96 * 2
options.Bandwidth = 8000
options.NoiseLevel = 0 //30
options.OMFSKConstant = 1.41
options.NFFTPower = 17 // 16.8782 - ((options.OMFSKConstant - 1.5) * 0.0041000000000011)
sentTransmission := transmission.NewTransmission()
sentTransmission.SetOptions(options)
data := `
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
`
sentTransmission.SetData(data)
//sentTransmission.BuildWav("tone.aiff")
// open file
toneWav, _ := os.Open("tone.aiff")
wavReader := aiff.NewDecoder(toneWav)
buffer, _ := wavReader.FullPCMBuffer()
signal := buffer.AsFloatBuffer().Data
recievedTransmission := transmission.NewTransmission()
recievedTransmission.SetOptions(options)
recievedTransmission.SetWave64(signal)
fmt.Println(string(recievedTransmission.Data()[:]))
fmt.Println("Transfer successful: ", string(recievedTransmission.Data()[:]))
}
| 418946301558df2ddf4e67edd5dbb931505764c9 | [
"Markdown",
"Go"
] | 33 | Go | Hunter-Dolan/Midrange | 6529675f6320e54926c8dc142eed8fb13916265a | 80a8eec7248308cf7ecbcfdd17b7b68166a31752 |
refs/heads/master | <file_sep>'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ReactWX = require('../../ReactWX');
var _ReactWX2 = _interopRequireDefault(_ReactWX);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// eslint-disable-next-line
var now = Date.now();
function RightNav() {
this.state = {
toView: 'index12',
scrollTop: 0
};
}
RightNav = _ReactWX2.default.miniCreateClass(RightNav, _ReactWX2.default.Component, {
scroll: function (e) {
let height = e.detail.scrollTop;
let index = parseInt(height / this.props.itemHeight);
this.props.scrollLeftTab(index);
},
render: function () {
var h = _ReactWX2.default.createElement;
return h('view', { className: 'nav_right' }, this.props.data.length > 0 && this.props.data[this.props.index].tree.nodes ? h('scroll-view', { 'class': 'scroll-view', 'scroll-y': true, 'scroll-into-view': this.props.toView, 'scroll-with-animation': true, onScroll: this.scroll.bind(this), 'scroll-top': this.props.scrollTop, 'data-scroll-uid': 'e842875', 'data-class-uid': 'c783008', 'data-instance-uid': this.props.instanceUid }, this.props.data.map(function (item, i981) {
return h('view', { key: item.id, 'class': 'nav_right_content', id: 'index' + item.id }, h('view', { 'class': 'nav_right_title' }, item.tree.desc), item.tree.nodes.map(function (item, i1281) {
return h('view', { className: 'nav_right_items', key: item.desc }, h('navigator', { url: '../list/index?brand=' + item.desc + '&typeid=' + this.props.data[this.props.index].id }, h('view', { className: 'right_items' }, item.logo ? h('image', { src: item.logo }) : h('image', { src: 'http://temp.im/50x30' }), item.desc && h('text', null, item.desc))));
}, this));
}, this)) : h('view', null, '\u6682\u65E0\u6570\u636E'));;
},
classUid: 'c783008'
}, {});
exports.default = RightNav;<file_sep>import React from '@react';
class Cursor extends React.Component {
render() {
return (
<div
src="https://www.baidu.com/img/baidu_jgylogo3.gif"
style={{
position: 'absolute',
left: this.props.mouse.x,
top: this.props.mouse.y
}}
>cursor</div>
);
}
}
export default Cursor;
<file_sep>'use strict';
var _ReactWX = require('ReactWX');
var _ReactWX2 = _interopRequireDefault(_ReactWX);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
import './pages/my/index';
import './pages/classify/index';
import './pages/cart/index';
import './pages/details/index';
import './pages/brand/index';
import './pages/list/index';
*/
function Demo() {
this.globalData = {
userInfo: null
};
}
Demo = _ReactWX2.default.miniCreateClass(Demo, _ReactWX2.default.Component, {
onLaunch: function () {
// eslint-disable-next-line
console.log('App launched');
//调用登录接口
wx.login({
success: function (r) {
if (r.code) {
// eslint-disable-next-line
let code = r.code;
wx.getUserInfo({
success: function () {
// console.log('res', res);
}
});
}
}
});
},
classUid: 'c1986'
}, {});
// eslint-disable-next-line
App(new Demo());<file_sep>import React from '@react';
class LotteryDraw extends React.Component {
constructor(props) {
super();
this.state = {
animationData: {},
awardsList: [],
awardData: props.awardData || [],
btnDisabled: ''
};
}
getLottery() {
var that = this;
// 抽奖逻辑
var awardIndex =
this.props.awardIndex !== undefined
? this.props.awardIndex
: Math.floor(Math.random() * this.state.awardData.length);
// 获取奖品配置
var awardsConfig = this.state.awardData;
// 旋转抽奖
let runDegs = 360 * 8 - awardIndex * (360 / awardsConfig.length);
// 初始化
var animationInit = wx.createAnimation({
duration: 1
});
animationInit.rotate(0).step();
this.setState({ animationData: animationInit.export(), btnDisabled: 'disabled' });
// 开始抽奖
setTimeout(function() {
var animationRun = wx.createAnimation({
duration: 3000,
timingFunction: 'ease'
});
animationRun.rotate(runDegs).step();
that.setState({ animationData: animationRun.export() });
}, 300);
// 中奖提示
setTimeout(function() {
wx.showModal({
title: '恭喜',
content: '获得' + awardsConfig[awardIndex].name,
showCancel: false,
success: function() {
that.props.onOk();
}
});
that.setState({
btnDisabled: ''
});
}, 3300);
}
componentDidMount() {
// 初始化奖品数据
let defaultConfig = [
{ index: 0, name: '1元红包' },
{ index: 1, name: '5元话费' },
{ index: 2, name: '6元红包' },
{ index: 3, name: '8元红包' },
{ index: 4, name: '10元话费' },
{ index: 5, name: '10元红包' }
];
let config;
if (!this.state.awardData.length) {
config = defaultConfig;
this.setState({ awardData: defaultConfig });
} else {
config = this.state.awardData;
}
// 绘制转盘
var len = config.length,
rotateDeg = 360 / len / 2 + 90,
html = [],
turnNum = 1 / len; // 文字旋转 turn 值
var ctx = wx.createContext();
for (var i = 0; i < len; i++) {
// 保存当前状态
ctx.save();
// 开始一条新路径
ctx.beginPath();
// 位移到圆心,下面需要围绕圆心旋转
ctx.translate(150, 150);
// 从(0, 0)坐标开始定义一条新的子路径
ctx.moveTo(0, 0);
// 旋转弧度,需将角度转换为弧度,使用 degrees * Math.PI/180 公式进行计算。
ctx.rotate((((360 / len) * i - rotateDeg) * Math.PI) / 180);
// 绘制圆弧
ctx.arc(0, 0, 150, 0, (2 * Math.PI) / len, false);
// 颜色间隔
if (i % 2 == 0) {
ctx.setFillStyle('rgba(255,184,32,.1)');
} else {
ctx.setFillStyle('rgba(255,203,63,.1)');
}
// 填充扇形
ctx.fill();
// 绘制边框
ctx.setLineWidth(0.5);
ctx.setStrokeStyle('rgba(228,55,14,.1)');
ctx.stroke();
// 恢复前一个状态
ctx.restore();
// 奖项列表
html.push({
turn: i * turnNum + 'turn',
lineTurn: i * turnNum + turnNum / 2 + 'turn',
award: config[i].name
});
}
this.setState({
awardsList: html
});
}
render() {
return (
<div class="canvas-container">
<div animation={this.state.animationData} class="canvas-content">
<canvas
style="width: 300px; height: 300px;"
class="canvas-element"
canvas-id="lotteryCanvas"
/>
<div class="canvas-line">
{this.state.awardsList.map(function(item, index) {
return (
<div
class="canvas-litem"
key={index}
style={{
'-webkit-transform': 'rotate(' + item.lineTurn + ')',
transform: 'rotate(' + item.lineTurn + ')'
}}
/>
);
})}
</div>
<div class="canvas-list">
{this.state.awardsList.map(function(item, index) {
return (
<div class="canvas-item" key={index}>
<div
class="canvas-item-text"
style={{
'-webkit-transform': 'rotate(' + item.turn + ')',
transform: 'rotate(' + item.turn + ')'
}}
>
{item.award}
</div>
</div>
);
})}
</div>
</div>
<div onTap={this.getLottery.bind(this)} class={'canvas-btn ' + this.state.btnDisabled}>
抽奖
</div>
</div>
);
}
}
export default LotteryDraw;
<file_sep>import React from '@react';
import MouseTracker from '@components/MouseTracker/index';
import Cursor from '@components/Cursor/index';
class P extends React.Component {
constructor() {
super();
this.state = { };
}
render() {
return (
<div>
<MouseTracker render={(state)=>{
return <div>render props<Cursor mouse={state} /></div>;
}} />
</div>
);
}
}
export default P;
<file_sep>'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ReactWX = require('../../ReactWX');
var _ReactWX2 = _interopRequireDefault(_ReactWX);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Brand() {
this.state = {
brandList: {
brand: []
}
};
}
Brand = _ReactWX2.default.miniCreateClass(Brand, _ReactWX2.default.Component, {
componentWillMount: function () {
//sliderList
var that = this;
wx.request({
url: 'http://yapi.demo.qunar.com/mock/17668/wemall/venues/getBrandAndType',
method: 'GET',
data: {},
header: {
Accept: 'application/json'
},
success: function (res) {
that.setState({
brandList: res.data
});
}
});
},
render: function () {
var h = _ReactWX2.default.createElement;
return h('view', { 'class': 'chat-container' }, this.state.brandList.brand.map(function (item, i998) {
return h('view', {
className: 'brand_item' }, h('navigator', { url: '../list/index?brand=' + 11 + '&typeid=' + 12 }, h('image', { src: item.pic, className: 'pic' }), h('view', { className: 'right_cont' }, h('text', { className: 'name' }, item.chinesename), h('text', { className: 'brief' }, item.brief), h('text', { className: 'price' }, ' \uFFE5', item.minprice, ' \u5143/\u4EF6\u8D77 '))));
}, this));;
},
classUid: 'c512020'
}, {});
Page(_ReactWX2.default.createPage(Brand, 'pages/brand/index'));
exports.default = Brand;<file_sep>'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ReactWX = require('../../ReactWX');
var _ReactWX2 = _interopRequireDefault(_ReactWX);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// eslint-disable-next-line
var app = getApp();
function MY() {
this.state = {
userInfo: {},
show: true,
userListInfo: [{
icon: '../../assets/images/iconfont-dingdan.png',
text: '我的订单',
isunread: true,
unreadNum: 2
}, {
icon: '../../assets/images/iconfont-card.png',
text: '我的代金券',
isunread: false,
unreadNum: 2
}, {
icon: '../../assets/images/iconfont-icontuan.png',
text: '我的拼团',
isunread: true,
unreadNum: 1
}, {
icon: '../../assets/images/iconfont-shouhuodizhi.png',
text: '收货地址管理'
}, {
icon: '../../assets/images/iconfont-kefu.png',
text: '联系客服'
}, {
icon: '../../assets/images/iconfont-help.png',
text: '常见问题'
}]
};
}
MY = _ReactWX2.default.miniCreateClass(MY, _ReactWX2.default.Component, {
componentWillMount: function () {
// console.log(app)
// var that = this;
// app.getUserInfo(function(userInfo) {
// console.log('userInfo', userInfo);
// that.setData({
// userInfo: userInfo
// });
// });
},
show: function (text) {
wx.showToast({
title: text,
icon: 'success',
duration: 2000
});
},
getUserInfo: function (e) {
this.setState({
userInfo: e.userInfo,
show: false
});
},
render: function () {
var h = _ReactWX2.default.createElement;
return h('view', { className: 'chat-container' }, h('view', { className: 'userinfo' }, this.state.show ? h('button', { 'open-type': 'getUserInfo', onGetuserInfo: this.getUserInfo, 'data-getuserinfo-uid': 'e23052337', 'data-class-uid': 'c993844', 'data-instance-uid': this.props.instanceUid }, '\u83B7\u53D6\u7528\u6237\u767B\u5F55\u4FE1\u606F') : h('view', null, h('image', { className: 'userinfo-avatar', src: this.state.userInfo.avatarUrl, 'background-size': 'cover' }), h('view', { className: 'userinfo-nickname' }, this.state.userInfo.nickName))), h('view', { className: 'info_list' }, this.state.userListInfo.map(function (item, i2916) {
return h('view', { className: 'weui_cell', key: item.text, onTap: this.show.bind(this, item.text), 'data-tap-uid': 'e30613100', 'data-class-uid': 'c993844', 'data-instance-uid': this.props.instanceUid, 'data-key': i2916 }, h('view', { className: 'weui_cell_hd' }, h('image', { src: item.icon })), h('view', { 'class': 'weui_cell_bd' }, h('view', {
'class': 'weui_cell_bd_p' }, ' ', item.text, ' ')), item.isunread && h('view', { className: 'badge' }, item.unreadNum), h('view', { 'class': 'with_arrow' }, h('image', { src: '../../assets/images/icon-arrowdown.png' })));
}, this)));;
},
classUid: 'c993844'
}, {});
Page(_ReactWX2.default.createPage(MY, 'pages/my/index'));
exports.default = MY;<file_sep>import React from '@react';
class MouseTracker extends React.Component {
constructor(props) {
super(props);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.state = { x: 4, y: 5 };
}
handleMouseMove(event) {
var e;
if (event.type== 'touchmove'){
e = event.touches[0];
} else {
e = event;
}
this.setState({
x: e.pageX,
y: e.pageY
});
}
render() {
return (
<div style={{ height: '100%' }} onTouchMove={this.handleMouseMove}>
<h1>Move the mouse around!</h1>
<p>The current mouse position{this.props.renderUid} is ({this.state.x}, {this.state.y})</p>
<p>{this.props.render(this.state)}</p>
</div>
);
}
}
export default MouseTracker;<file_sep>'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ReactWX = require('../../ReactWX');
var _ReactWX2 = _interopRequireDefault(_ReactWX);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Dialog() {
this.state = {
title: '弹窗',
content: '弹窗内容1111',
cancelText: '取消',
okText: '确定'
};
}
Dialog = _ReactWX2.default.miniCreateClass(Dialog, _ReactWX2.default.Component, {
render: function () {
var h = _ReactWX2.default.createElement;
return h('view', { hidden: this.props.visible }, h('view', { className: 'ys-mask' }), h('view', { className: 'ys-dialog' }, h('view', { className: 'ys-dialog-title' }, this.state.title), h('view', { className: 'ys-dialog-content' }, this.state.content), h('view', { className: 'ys-dialog-bottom' }, h('button', { 'class': 'ys-dialog-btn', onTap: this.props.onCanel, 'data-tap-uid': 'e695721', 'data-class-uid': 'c29960', 'data-instance-uid': this.props.instanceUid }, this.state.cancelText), h('view', { 'class': 'ys-dialog-btn ys-dialog-ok-btn', onTap: this.props.onOk, 'data-tap-uid': 'e823846', 'data-class-uid': 'c29960', 'data-instance-uid': this.props.instanceUid }, this.state.okText))));;
},
classUid: 'c29960'
}, {});
exports.default = Dialog; | 90206b3c4a5d8e3ccc0e12cede2cbe0e681af97a | [
"JavaScript"
] | 9 | JavaScript | gandao/anu | 26d9ec5de75985c8fe867cf97802c645ea81ff5f | 80b02875fcd9f0df77c15e19f58c2ca99dd20c08 |
refs/heads/master | <file_sep>(function () {
/**
* Gives app undo/redo capabilities
*
* currently history doesn't block on actions
* blocking on actions helps with correctness as the cost
* of responsiveness which is a costly trade off.
*/
angular.
module('undo').
service('history', history).
value('maxHistory', 100);
history.$inject = ['action', 'maxHistory'];
function history (action, maxHistory) {
var self = this;
var undoStack = [];
var redoStack = [];
self.add = add;
self.redo = redo;
self.undo = undo;
self.clear = clear;
self.hasUndo = hasUndo;
self.hasRedo = hasRedo;
/**
* Adds an item to the undo queue invoking it
* @param command - routine to execute
* @param inverse - inverse routine to store in undo queue
* @returns {*} - result from invoking @param command
*/
function add (command, inverse) {
redoStack = [];
return transfer([action(command, inverse)], undoStack).redo();
}
/**
* redo an action
*/
function redo () {
transfer(redoStack, undoStack).redo();
}
/**
* undo an action
*/
function undo () {
transfer(undoStack, redoStack).undo();
}
/**
* Clears all history
*/
function clear () {
undoStack = [];
redoStack = [];
}
/**
* Indicates if a redo action is available
* @returns {int} - number of actions available
* permissible as boolean
*/
function hasRedo () {
return redoStack.length;
}
/**
* Indicates if an undo action is available
* @returns {int} - number of actions available
* permissible as boolean
*/
function hasUndo () {
return undoStack.length;
}
/**
* Transfers one stack-like to another while returning the item
*
* @param from - a stack-like to pop
* @param to - a stack-like to push onto
* @returns {*} - item that was moved
*/
function transfer (from, to) {
if (from.length === 0) {
throw new Error('No actions left');
} else if (to.length > maxHistory) {
to.shift()
}
var actionable = from.pop();
to.push(actionable);
return actionable;
}
}
})();<file_sep>#Angular Undo
### a lightweight history for model and api changes
Angular undo gives the ability to undo/redo state changes in your angular app. It can affect local or remote state
## Getting Started
* Bower install: `bower install angular-undo`
* Import the module from your app.js `angular.module('undo', []);`
* Add to your list of depencies `angular.module('<your module>', [..., 'undo']);`
## Examples
* RESTful Endpoints. Create (POST) to a resource, undo (DELETE) with the ID that is returned
* a <-> b PUT or PATCH. Changing a single field or a group of object properties in an API.
* a <-> b local state changes. Changing the state of anything in the app
### example of undo/redo API resource creation/deletion
```javascript
var url = 'www.example.com/resource';
var data = { foo: 'bar' };
function createResource (data) {
return function () {
return $http.post(url, data);
};
}
// id is a promise injected by history
function deleteResource (id) {
id.then(function () {
$http.delete(url, id);
}
}
// invokes create
history.add(createResource(data), deleteResource);
// invokes delete
history.undo();
// invokes create (new resource)
history.redo();
```
### example of updating an API with patch
```javascript
function onChange (prop) {
history.add(update($scope.collection[prop]), update(old[prop]));
}
function update (value) {
return function () {
this.message = prop + ' edited';
var data = {};
data[prop] = value;
// Custom Angular Resource PATCH
api.update(data);
}
}
```
## Resources
[Slide deck](http://www.slideshare.net/kwoolfm/temporal-composability)
See also:
* [angular-undo-redo](https://github.com/bobey/angular-undo-redo) an Object Oriented approach
* [chronology.js](https://github.com/wout/chronology.js) a microjs library
<file_sep>(function () {
/**
* The Command Pattern allows for undo and redo in our application.
* see https://en.wikipedia.org/wiki/Command_pattern#Javascript
*
* An action will be a future as it could rely on a response from an original action.
* For example POST to /resource returns and id that is needed for DELETE /resource/id
*
* A routine is simply a function to be executed.
*
* All routines will enjoy:
* Given the result from their inverse action as an argument in the form of a promise
* It's a good idea to return the result in a consumable format to your counter part
* this.message, a human readable string to be displayed and set by the routine
*/
angular.
module('undo').
factory('action', action);
action.$inject = ['$q'];
function action($q) {
/**
* @param routine - action to perform
* @param (inverse) - optional, reverse action
* @returns {{redo: *, undo: *, redoMessage: String, undoMessage: String}}
*/
return function (routine, inverse) {
var redoResult = {}
, undoResult = {}
, redoCtx = { message: 'applying generic action' }
, undoCtx = { message: 'undoing generic action' };
handleMissingRoutine();
handleOptionalInverse();
return {
redo: redo,
undo: undo,
getRedoMessage: function () {
return redoCtx.message;
},
getUndoMessage: function () {
return undoCtx.message;
}
};
function redo () {
redoResult = $q.when(execute(routine, redoCtx, undoResult));
}
function undo () {
undoResult = $q.when(execute(inverse, undoCtx, redoResult));
}
/**
* Execute undo / redo with a context
*
* @param action - method to invoke
* @param context - containing property message
* @param prevResult - passed in as an argument
* @returns {deferred} - result of method invocation
*/
function execute (action, context, prevResult) {
return action.call(context, prevResult);
}
/**
* Ensure routine must be a function
*/
function handleMissingRoutine () {
if (!_.isFunction(routine)) {
throw new Exception('Cannot create an action from ' + ftn);
}
}
/**
* If no inverse is not specified or invalid, create a dummy one.
*/
function handleOptionalInverse () {
if (!_.isFunction(inverse)) {
inverse = function () {
this.message = 'Cannot undo previous action.';
};
}
}
}
}
})(); | 61bbc3b3ab0aec713249f8eff40670f773fb366e | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | kwoolfm/angular-undo.git | a023f48e3ab1a8d9abdaecb330919889167a315f | 7e8b69ec47ecadefb72de0dce052e31c6786a405 |
refs/heads/master | <file_sep>import cPickle
import numpy as np
from collections import defaultdict, OrderedDict
import theano
import theano.tensor as T
import re
import warnings
import sys
import pdb
def ReLU(x):
y = T.maximum(0.0, x)
return(y)
def Sigmoid(x):
y = T.nnet.sigmoid(x)
return(y)
def Tanh(x):
y = T.tanh(x)
return(y)
def Iden(x):
y = x
return(y)
def clean_str(string, TREC=False):
"""
Tokenization/string cleaning for all datasets except for SST.
Every dataset is lower cased except for TREC
"""
string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
string = re.sub(r"\'s", " \'s", string)
string = re.sub(r"\'ve", " \'ve", string)
string = re.sub(r"n\'t", " n\'t", string)
string = re.sub(r"\'re", " \'re", string)
string = re.sub(r"\'d", " \'d", string)
string = re.sub(r"\'ll", " \'ll", string)
string = re.sub(r",", " , ", string)
string = re.sub(r"!", " ! ", string)
string = re.sub(r"\(", " \( ", string)
string = re.sub(r"\)", " \) ", string)
string = re.sub(r"\?", " \? ", string)
string = re.sub(r"\s{2,}", " ", string)
return string.strip() if TREC else string.strip().lower()
def load_bin_vec(fname, vocab):
"""
Loads 300x1 word vecs from Google (Mikolov) word2vec
"""
word_vecs = {}
with open(fname, "rb") as f:
header = f.readline()
vocab_size, layer1_size = map(int, header.split())
binary_len = np.dtype('float32').itemsize * layer1_size
for line in xrange(vocab_size):
word = []
while True:
ch = f.read(1)
if ch == ' ':
word = ''.join(word)
break
if ch != '\n':
word.append(ch)
if word in vocab:
word_vecs[word] = np.fromstring(f.read(binary_len), dtype='float32')
else:
f.read(binary_len)
return word_vecs
def clean_str(string, TREC=False):
"""
Tokenization/string cleaning for all datasets except for SST.
Every dataset is lower cased except for TREC
"""
string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
string = re.sub(r"\'s", " \'s", string)
string = re.sub(r"\'ve", " \'ve", string)
string = re.sub(r"n\'t", " n\'t", string)
string = re.sub(r"\'re", " \'re", string)
string = re.sub(r"\'d", " \'d", string)
string = re.sub(r"\'ll", " \'ll", string)
string = re.sub(r",", " , ", string)
string = re.sub(r"!", " ! ", string)
string = re.sub(r"\(", " \( ", string)
string = re.sub(r"\)", " \) ", string)
string = re.sub(r"\?", " \? ", string)
string = re.sub(r"\s{2,}", " ", string)
return string.strip() if TREC else string.strip().lower()
def load_bin_vec(fname, vocab):
"""
Loads 300x1 word vecs from Google (Mikolov) word2vec
"""
word_vecs = {}
with open(fname, "rb") as f:
header = f.readline()
vocab_size, layer1_size = map(int, header.split())
binary_len = np.dtype('float32').itemsize * layer1_size
for line in xrange(vocab_size):
word = []
while True:
ch = f.read(1)
if ch == ' ':
word = ''.join(word)
break
if ch != '\n':
word.append(ch)
if word in vocab:
word_vecs[word] = np.fromstring(f.read(binary_len), dtype='float32')
else:
f.read(binary_len)
return word_vecs
def get_idx_from_sent(sent, word_idx_map, max_l=51, k=300, filter_h=5):
"""
Transforms sentence into a list of indices. Pad with zeroes.
"""
x = []
pad = filter_h - 1
for i in xrange(pad):
x.append(0)
words = sent.split()
for word in words:
if word in word_idx_map:
x.append(word_idx_map[word])
while len(x) < max_l+2*pad:
x.append(0)
return x
def make_idx_data_cv(revs, word_idx_map, cv, max_l=51, k=300, filter_h=5):
"""
Transforms sentences into a 2-d matrix.
"""
train, test = [], []
for rev in revs:
sent = get_idx_from_sent(rev["text"], word_idx_map, max_l, k, filter_h)
sent.append(rev["y"])
if rev["split"]==cv:
test.append(sent)
else:
train.append(sent)
train = np.array(train,dtype="int")
test = np.array(test,dtype="int")
return [train, test]
if __name__=="__main__":
print "loading data...",
x = cPickle.load(open("mr.p","rb"))
revs, W, W2, word_idx_map, vocab = x[0], x[1], x[2], x[3], x[4]
print "data loaded!"
non_static=False
execfile("conv_net_classes.py")
U = W
savedparams = cPickle.load(open('classifier.save','rb'))
filter_hs=[3,4,5]
conv_non_linear="relu"
hidden_units=[100,2]
dropout_rate=[0.5]
activations=[Iden]
img_h = 56 + 4 + 4
img_w = 300
rng = np.random.RandomState(3435)
batch_size=50
filter_w = img_w
feature_maps = hidden_units[0]
filter_shapes = []
pool_sizes = []
for filter_h in filter_hs:
filter_shapes.append((feature_maps, 1, filter_h, filter_w))
pool_sizes.append((img_h-filter_h+1, img_w-filter_w+1))
#define model architecture
index = T.lscalar()
x = T.matrix('x')
y = T.ivector('y')
Words = theano.shared(value = U, name = "Words")
zero_vec_tensor = T.vector()
zero_vec = np.zeros(img_w)
set_zero = theano.function([zero_vec_tensor], updates=[(Words, T.set_subtensor(Words[0,:], zero_vec_tensor))],allow_input_downcast=True)
layer0_input = Words[T.cast(x.flatten(),dtype="int32")].reshape((x.shape[0],1,x.shape[1],Words.shape[1]))
conv_layers = []
layer1_inputs = []
for i in xrange(len(filter_hs)):
filter_shape = filter_shapes[i]
pool_size = pool_sizes[i]
conv_layer = LeNetConvPoolLayer(rng, input=layer0_input,image_shape=(batch_size, 1, img_h, img_w),
filter_shape=filter_shape, poolsize=pool_size, non_linear=conv_non_linear)
layer1_input = conv_layer.output.flatten(2)
conv_layers.append(conv_layer)
layer1_inputs.append(layer1_input)
layer1_input = T.concatenate(layer1_inputs,1)
hidden_units[0] = feature_maps*len(filter_hs)
classifier = MLPDropout(rng, input=layer1_input, layer_sizes=hidden_units, activations=activations, dropout_rates=dropout_rate)
classifier.params[0].set_value(savedparams[0])
classifier.params[1].set_value(savedparams[1])
k = 2
for conv_layer in conv_layers:
conv_layer.params[0].set_value( savedparams[k])
conv_layer.params[1].set_value( savedparams[k+1])
k = k + 2
datasets = make_idx_data_cv(revs, word_idx_map, 1, max_l=56,k=300, filter_h=5)
test_set_x = datasets[1][:,:img_h]
test_set_y = np.asarray(datasets[1][:,-1],"int32")
test_pred_layers = []
test_size = 1
test_layer0_input = Words[T.cast(x.flatten(),dtype="int32")].reshape((test_size,1,img_h,Words.shape[1]))
for conv_layer in conv_layers:
test_layer0_output = conv_layer.predict(test_layer0_input, test_size)
test_pred_layers.append(test_layer0_output.flatten(2))
test_layer1_input = T.concatenate(test_pred_layers, 1)
test_y_pred = classifier.predict_p(test_layer1_input)
#test_error = T.mean(T.neq(test_y_pred, y))
test_model_all = theano.function([x],test_y_pred,allow_input_downcast=True)
#test_loss = test_model_all(test_set_x,test_set_y)
#test_perf = 1- test_loss
#print test_perf
w2v_file = "word2vec.bin"
line = "this is terrible."
rev = []
rev.append(line.strip())
orig_rev = clean_str(" ".join(rev))
datum = [{"y":1,
"text": orig_rev,
"num_words": len(orig_rev.split())}]
sent = get_idx_from_sent(orig_rev, word_idx_map, 56, k, filter_h)
#yvalue
sent.append(1)
test = np.array([sent],dtype="int")
test_set_x = test[:,:img_h]
test_set_y = np.asarray(test[:,-1],"int32")
test_loss = test_model_all(test_set_x)
#test_perf = 1- test_loss
print test_loss
| c3cea30ddd469aad137a2012617e6305209826f3 | [
"Python"
] | 1 | Python | LucasEstevam/CNN_sentence | fa9dbdd622ea3555e1eaff13fe4799eb1ec5dd80 | 5c61fc561094c2cc0988c1db23c433b69c2df7a1 |
refs/heads/master | <repo_name>Beatz748/cpp02<file_sep>/ex01/Fixed.hpp
#ifndef FIXED_HPP
#define FIXED_HPP
# include <iostream>
# include <cmath>
class Fixed
{
private:
int value_;
static const int bits_ = 8;
public:
Fixed(void);
Fixed(const int val);
Fixed(const float val);
~Fixed(void);
Fixed(const Fixed &right);
Fixed& operator=(const Fixed &right);
int getRawBits(void) const;
void setRawBits(int const raw);
int toInt(void) const;
float toFloat(void) const;
};
std::ostream& operator<<(std::ostream& stream, Fixed const& right);
#endif
<file_sep>/ex01/Fixed.cpp
# include "Fixed.hpp"
Fixed::Fixed()
{
value_ = 0;
std::cout << "Default constructor called" << std::endl;
}
Fixed::Fixed(int const raw)
{
std::cout << "Int constructor called" << std::endl;
value_ = raw << bits_;
}
Fixed::~Fixed()
{
std::cout << "Destructor called" << std::endl;
}
void Fixed::setRawBits(int const raw)
{
value_ = raw;
}
int Fixed::getRawBits(void) const
{
std::cout << "getRawBits member function called" << std::endl;
return (value_);
}
Fixed& Fixed::operator=(const Fixed &right)
{
std::cout << "Assignation operator called" << std::endl;
value_ = right.value_;
return (*this);
}
Fixed::Fixed(const float val)
{
std::cout << "Float constructor called" << std::endl;
value_ = roundf(val * (1 << bits_));
}
Fixed::Fixed(const Fixed &right)
{
std::cout << "Copy constructor called" << std::endl;
*this = right;
}
float Fixed::toFloat(void) const
{
return (((float)(value_) / (1 << bits_)));
}
int Fixed::toInt(void) const
{
return ((int)(value_ >> bits_));
}
std::ostream& operator<<(std::ostream& stream, Fixed const& fixed)
{
stream << fixed.toFloat();
return stream;
}
<file_sep>/ex00/Fixed.hpp
#ifndef FIXED_HPP
#define FIXED_HPP
# include <string>
# include <iostream>
class Fixed
{
private:
int value_;
static const int bits_ = 8;
public:
Fixed();
~Fixed();
Fixed(Fixed &right);
Fixed& operator=(Fixed &right);
int getRawBits(void) const;
void setRawBits(int const raw);
};
#endif
| d9e89574f682e387510b4146c60def152adaff69 | [
"C++"
] | 3 | C++ | Beatz748/cpp02 | 5346a88a6583508a0ce5d0aa5e8b25a1718163f8 | f26b13c245f1aad49a7a58be209b9b444ac62924 |
refs/heads/main | <file_sep>package Week3Day1Assignment;
public class StudentInfo {
// overloading
public void getStudentInfo(int id) {
System.out.println("ID of the student: "+id);
}
public void getStudentInfo(int id,String name) {
System.out.println("ID of the student: "+id);
System.out.println("Name of the student: "+name);
}
public void getStudentInfo(String email,long phonenumber) {
System.out.println("emailId of the student: "+email);
System.out.println("phonenumber of the student: "+phonenumber);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
StudentInfo obj = new StudentInfo();
obj.getStudentInfo(8);
obj.getStudentInfo(2, "rashmi");
obj.getStudentInfo("<EMAIL>", 963852741);
}
}
| a5d05943c0d07d7b5785aa2bdf940a8c8f555f7d | [
"Java"
] | 1 | Java | RashmiNedumaran/Week3Day1Assingment | 6d04294b2327aea31cabe18e9106d70fb614eadf | 34b3de0b16d2d8b73f459169cc0f74f3a81f59a7 |
refs/heads/master | <file_sep>module.exports = function longestConsecutiveLength(array) {
if (array.length == 0) {
return 0;
}
let newObject = {};
let maxConsecutive = [];
function convertToObject () {
array.forEach(element => {
newObject[element] = element;
});
}
function searchNeighborPLus (e) {
let neighbor = 0;
let ePlusOne = e + 1;
if (newObject[ePlusOne]) {
neighbor = ePlusOne;
}
return neighbor;
}
function searchNeighborMinus (e) {
let neighbor = 0;
let eMinusOne = e - 1;
if (newObject[eMinusOne]) {
neighbor = eMinusOne;
}
return neighbor;
}
function search() {
for(let k in newObject) {
let key = +k;
let maybeMaxConsecutive = [key];
let neighborPlus = searchNeighborPLus(key);
let neighborMinus = searchNeighborMinus(key);
delete newObject[k];
while (neighborPlus != 0) {
maybeMaxConsecutive.push(neighborPlus);
let newNeighborPlus = searchNeighborPLus(neighborPlus);
delete newObject[neighborPlus];
neighborPlus = newNeighborPlus;
}
while (neighborMinus != 0) {
maybeMaxConsecutive.push(neighborMinus);
let newNeighborMinus = searchNeighborPLus(neighborMinus);
delete newObject[neighborMinus];
neighborMinus = newNeighborMinus;
}
if (maybeMaxConsecutive.length > maxConsecutive.length) {
maxConsecutive = maybeMaxConsecutive;
}
}
}
convertToObject();
search();
return maxConsecutive.length;
}
| d73fcd34bf9e88bfb7d1adbc36ed45dceaffb854 | [
"JavaScript"
] | 1 | JavaScript | SergeySkakun/longest-consecutive-sequence | 168670f025a9dd5c406d707ca521d6fcc89a1f6b | b9ed0361d0d2e6765b42adf832446555ae6d25ba |
refs/heads/master | <repo_name>NodyHub/brix-provision<file_sep>/02_k8s/init.sh
#!/bin/bash
# Bootstrab K8s
sudo kubeadm init --pod-network-cidr=10.10.0.0/16 --apiserver-cert-extra-sans=k8sm1.home
# Apply Network Overlay
kubectl apply -f https://docs.projectcalico.org/v3.9/manifests/calico.yaml
# local-path-storage with auto provisioning of pv on GlusterFS
kubectl create -f https://raw.githubusercontent.com/NodyHub/local-path-provisioner/master/deploy/local-path-storage.yaml
exit 0
<file_sep>/03_helm/init.sh
#!/bin/bash
# install helm on deployer and add repo
curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3
chmod 700 get_helm.sh
./get_helm.sh
rm get_helm.sh
helm repo add stable https://kubernetes-charts.storage.googleapis.com
helm repo update
# Install SW loadbalancer MetalLB
kubectl create ns metallb
helm install metallb stable/metallb --values metallb-values.yaml --namespace metallb
# Install ingress controller Traefik
kubectl create ns traefik
helm install traefik stable/traefik --values traefik-values.yaml --namespace traefik
# Install default registry within the cluster
kubectl create ns registry
helm install registry ./registry --namespace registry
exit 0
<file_sep>/01_glusterfs/setup.sh
#!/bin/bash
# Jede node
mkfs.xfs -f -i size=512 /dev/sda3
echo "/dev/sda3 /export/sda3 xfs defaults 0 0" >> /etc/fstab
mkdir -p /export/sda3 && mount -a && mkdir -p /export/sda3/brick
# Master Node
gluster volume create gv0 replica 4 k8sm1.home:/export/sda3/brick k8sn1.home:/export/sda3/brick k8sn2.home:/export/sda3/brick k8sn3.home:/export/sda3/brick
gluster volume start gv0
# jede node:
mount -t glusterfs 127.0.0.1:/gv0 /mnt
echo "127.0.0.1:/gv0 /data glusterfs defaults,_netdev 0 0" >> /etc/fstab
exit 0
<file_sep>/README.md
# Gigabyte BRIX provisioning scripts
## Ansibile TODO's
- Integrate manual steps from:
- GlusterFS
- K8s
- Cluster internal services
## GlusterFS TODO's
- Integrate GlusterFS security features, e.g., source IP verfication!?
## K8s TODO's
- Deploy PSP
- Deploy default NSP
- Create user provisioning script that hat limited access to namespace only
- Integrate Logging & Monitoring Solution
## Helm TODO's
- Integrate Istio!?
<file_sep>/00_ansible/init.sh
#!/bin/bash
# Create Ansible SSH key
[ ! -d keys ] && mkdir keys
[ ! -f keys/id_rsa ] && ssh-keygen -f keys/id_rsa -t rsa -N '' -C 'ansible-provision'
exit 0
| 42e0cea4625dd33cb734ed55de22e4ebd7498c5d | [
"Markdown",
"Shell"
] | 5 | Shell | NodyHub/brix-provision | 98704d62ba6c8b85d3316d6e1028d932af18bfec | e1d6a5930d875d664b27060c7c38139d0bf37b3e |
refs/heads/master | <repo_name>freshmemes/internetspeedsasset<file_sep>/script.R
# Messing around with some different data viz on internet speeds.
# Idea 1. Line graph of top 5 current fastest countries and the US, average speeds plotted over time.
# Idea 2. Similar to Idea 1, but with top 5 fastest and top 5 slowest U.S. states.
# Idea 3. Map of U.S. Showing states' internet user concentrations (as proportion of total state population) in an elevation/gradient format.
# Idea 4. Map of U.S. showing states with fastest internet.
library(tidyverse)
library(readr)
library(stringr)
# library(readxl)
# library(lubridate)
# connect to plotly API ----------------------------------------------------------------------------------
# library(plotly)
# Sys.setenv("plotly_username" = "freshmemes")
# Sys.setenv("plotly_api_key" = "<KEY>")
# Idea 1. ------------------------------------------------------------------------------------------------
spdata <- as.tibble(read.csv("us_speeds_over_time.csv"))
spdata2 <- spdata %>%
gather(country, speed, UNITED.STATES:FINLAND)
spdata2$country = stringr::str_replace(spdata2$country, "\\.", "\\ ")
spdata3 <- spdata2 %>%
mutate(speed = speed / 1000) %>%
filter(stringr::str_detect(Quarter, "(^Q4)|(17$)")) %>%
mutate(Quarter = stringr::str_replace(Quarter, "^Q(4|1)\\ ", "20")) %>%
rename(year = Quarter) %>%
mutate(year = as.numeric(year))
ggplot(spdata3, aes(year, speed, color = country)) +
geom_line(size = 1) +
geom_point() +
labs(title = "Historical Average Speeds of Current Top 5 Fastest Countries and the U.S.") +
scale_x_continuous(breaks = c(2008, 2010, 2012, 2014, 2016))
# Idea 1. Optional (create and upload plotly) ------------------------------------------------------------
# p <- plotly::plot_ly(data = spdata3, x = ~year, y = ~speed, color = ~country, mode = 'lines+markers', type = 'scatter') %>%
# layout(title = 'Historical Average Speeds of Current Top 5 Fastest Countries and the U.S.')
# plotly_POST(p, filename = "countries_speeds_over_time", sharing = "public")
# Idea 2. ------------------------------------------------------------------------------------------------
states <- as.tibble(read.csv("states_speeds_over_time.csv"))
stnames <- c("District of Columbia", "Delaware", "Massachusetts", "Rhode Island", "Maryland", "Kentucky", "Arkansas", "Mississippi", "New Mexico", "Idaho")
states2 <- states %>%
gather(state, speed, U.S....ALABAMA:U.S....WYOMING)
states2$state = stringr::str_replace(states2$state, "U\\.S(\\.{4})", "")
states2$state = stringr::str_replace_all(states2$state, "\\.", "\\ ")
states3 <- states2 %>%
mutate(state = paste0(substring(state, 1, 1), tolower(substring(state, 2, str_length(state)))))
states3$state = stringr::str_replace(states3$state, "District of columbia", "District of Columbia")
states3$state = stringr::str_replace(states3$state, "Rhode island", "Rhode Island")
states3$state = stringr::str_replace(states3$state, "New mexico", "New Mexico")
states3 <- states3 %>%
filter(state %in% stnames) %>%
filter(stringr::str_detect(Quarter, "(^Q4)|(17$)")) %>%
mutate(Quarter = stringr::str_replace(Quarter, "^Q(4|1)\\ ", "20")) %>%
rename(year = Quarter) %>%
mutate(year = as.numeric(year))
ggplot(states3, aes(year, speed, color = state)) +
geom_line(size = 1) +
geom_point() +
labs(title = "Historical Average Speeds of Current Fastest and Slowest States") +
scale_x_continuous(breaks = c(2008, 2010, 2012, 2014, 2016))
# Idea 2. Optional (create and upload plotly) ------------------------------------------------------------
# p2 <- plotly::plot_ly(data = states3, x = ~year, y = ~speed, color = ~state, mode = 'lines+markers', type = 'scatter') %>%
# layout(title = 'Historical Average Speeds of Current Top 5 Fastest and Slowest States')
# plotly_POST(p2, filename = "states_speeds_over_time", sharing = "public")
| 59c77b6ccf13edab99fc60d01320b230d3b18a9d | [
"R"
] | 1 | R | freshmemes/internetspeedsasset | a53ddbdcee58f071c6404303d86101b394cc21b7 | acab22a83c03353e9eb7e8f772e8ea7b18514d78 |
refs/heads/master | <file_sep>import os
import urllib.request
from flask import Flask, flash, request, redirect, url_for, render_template
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
from wtforms import SubmitField
from flask_bootstrap import Bootstrap
from werkzeug.utils import secure_filename
from predictor import run_predictor
app = Flask(__name__)
UPLOAD_FOLDER = 'static/uploads/'
ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif']
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SECRET_KEY'] = '<KEY>'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
#try if UPLOAD_FOLDER exists, otherwise create it
if os.path.exists(UPLOAD_FOLDER) == False:
os.makedirs(UPLOAD_FOLDER)
# Flask-Bootstrap requires this line
Bootstrap(app)
class UploadForm(FlaskForm):
validators = [
FileRequired(message='There was no file!'),
FileAllowed(ALLOWED_EXTENSIONS, message='Not a supported extension...')
]
file = FileField('', validators=validators)
submit = SubmitField(label='Upload')
@app.route('/', methods=['GET', 'POST'])
def upload_form():
form = UploadForm()
if request.method == 'POST' and form.validate_on_submit():
file = request.files['file']
filename = secure_filename(file.filename)
print(filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
flash('Image successfully uploaded!')
results = run_predictor(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return render_template('upload.html', filename=filename, results=results, form=form)
else:
return render_template('upload.html', form=form)
@app.route('/display/<filename>')
def display_image(filename):
return redirect(url_for('static', filename='uploads/' + filename), code=301)
if __name__ == "__main__":
app.run()<file_sep># Dog-Breed-Predictor

Dog-Breed-Predictor is a Python-3 Flask API that runs locally on your computer.
Once started, you have to navigate to __localhost:5000__ (__127.0.0.1:5000__) with your web browser.
A web interface will be displayed asking to upload a picture of a dog.
Once the picture is uploaded, a Convolutional Neural Network will predict the breed of the dog and the results will be displayed on the web page.
## More Information
The Convolutional Neural Network used here is the bottom part of the Xception model from the Keras library.
After a Global Average Pooling layer, a fully connected one has been added with 120 units (for the 120 dog breeds) and a softmax activation function. The network has first been trained on the Standford Dog Dataset, the base model being freezed. Then a fine tunning step, on the same dataset, has been performed with a low learning rate, un-freezing the last convolutional bloc of the base model. The network reached an accuracy of 0.83 on the test set.
## Installation
- To run the application, first download the entire repository. If you are cloning the repository with git, you will have to use git LFS (Large File Storage) as one of the file is above 100 MB. In both cases, make sure that the _xception_120_breeds_fine_tuned.h5_ file is properly downloaded (around 120 MB).
- Once downloaded, it is recommended to create and activate a virtual environment using Python `venv`.
On Windows, inside the repository you just downloaded, use the command:
```
python -m venv env
.\env\Scripts\activate
```
- Once the environment activated, you have to install the packages listed in _requirements.txt_. You can do so using `pip`:
```
pip install -r requirements.txt
```
- You can finally run the application. Note that you may need admin rights to do so.
```
python flask_app.py
```
- A local server will be launched on port __5000__ by default. Navigate to it with your browser.
You can then use the interface to upload picture and ask the model to determine the dog breed.
## Notes
All the submitted picture will be copied inside the _static\uploads_ folder, in the repository containing the Flask application. No cleaning is performed by the application once you closed it. You will have to manually delete the pictures to save disk space.
## Licence
This is a Free Software.
<file_sep># -*- coding: utf-8 -*-
"""
Dog Breed Predictor
"""
import numpy as np
from keras.models import load_model
from keras.preprocessing.image import load_img, img_to_array
from tensorflow.keras import applications
TARGET_SIZE = (224,224)
DOG_BREEDS = np.array(['Chihuahua', 'Japanese_spaniel', 'Maltese_dog', 'Pekinese', 'Shih_Tzu', 'Blenheim_spaniel',
'papillon', 'toy_terrier', 'Rhodesian_ridgeback', 'Afghan_hound', 'basset', 'beagle', 'bloodhound',
'bluetick', 'black_and_tan_coonhound', 'Walker_hound', 'English_foxhound', 'redbone', 'borzoi',
'Irish_wolfhound', 'Italian_greyhound', 'whippet', 'Ibizan_hound', 'Norwegian_elkhound', 'otterhound',
'Saluki', 'Scottish_deerhound', 'Weimaraner', 'Staffordshire_bullterrier', 'American_Staffordshire_terrier',
'Bedlington_terrier', 'Border_terrier', 'Kerry_blue_terrier', 'Irish_terrier', 'Norfolk_terrier',
'Norwich_terrier', 'Yorkshire_terrier', 'wire_haired_fox_terrier', 'Lakeland_terrier', 'Sealyham_terrier',
'Airedale', 'cairn', 'Australian_terrier', 'Dandie_Dinmont', 'Boston_bull', 'miniature_schnauzer',
'giant_schnauzer', 'standard_schnauzer', 'Scotch_terrier', 'Tibetan_terrier', 'silky_terrier',
'soft_coated_wheaten_terrier', 'West_Highland_white_terrier', 'Lhasa', 'flat_coated_retriever',
'curly_coated_retriever', 'golden_retriever', 'Labrador_retriever', 'Chesapeake_Bay_retriever',
'German_short_haired_pointer', 'vizsla', 'English_setter', 'Irish_setter', 'Gordon_setter',
'Brittany_spaniel', 'clumber', 'English_springer', 'Welsh_springer_spaniel', 'cocker_spaniel',
'Sussex_spaniel', 'Irish_water_spaniel', 'kuvasz', 'schipperke', 'groenendael', 'malinois', 'briard',
'kelpie', 'komondor', 'Old_English_sheepdog', 'Shetland_sheepdog', 'collie', 'Border_collie',
'Bouvier_des_Flandres', 'Rottweiler', 'German_shepherd', 'Doberman', 'miniature_pinscher',
'Greater_Swiss_Mountain_dog', 'Bernese_mountain_dog', 'Appenzeller', 'EntleBucher', 'boxer',
'bull_mastiff', 'Tibetan_mastiff', 'French_bulldog', 'Great_Dane', 'Saint_Bernard', 'Eskimo_dog',
'malamute', 'Siberian_husky', 'affenpinscher', 'basenji', 'pug', 'Leonberg', 'Newfoundland',
'Great_Pyrenees', 'Samoyed', 'Pomeranian', 'chow', 'keeshond', 'Brabancon_griffon', 'Pembroke',
'Cardigan', 'toy_poodle', 'miniature_poodle', 'standard_poodle', 'Mexican_hairless', 'dingo',
'dhole', 'African_hunting_dog'])
MODEL = load_model("xception_120_breeds_fine_tuned.h5")
def load_picture(img_path):
img = load_img(img_path, target_size=TARGET_SIZE)
img_array = img_to_array(img, dtype='float16')
return img_array
def preprocess(img_array):
#apply model preprocess_input function
processed_img = applications.xception.preprocess_input(img_array)
#reshape it to 4 dimensions
processed_img = np.reshape(processed_img, (1,*TARGET_SIZE,3))
return processed_img
def predict_breed(img):
#requires a picture that has already been processed
pred = MODEL.predict(img)[0]
return pred
def translate_predictions(pred):
#returns top 5 probabilities, with breed names
top_5 = np.argsort(pred)[-5:][::-1]
probas = pred[top_5]
breeds = DOG_BREEDS[top_5]
return probas, breeds
def run_predictor(img_path):
#all-in-one wrapper
img_array = load_picture(img_path)
processed_img = preprocess(img_array)
preds = predict_breed(processed_img)
probas, breeds = translate_predictions(preds)
return probas, breeds
| 7847b2035d6b88cf6a296ba641cb13dcdc79d8d6 | [
"Markdown",
"Python"
] | 3 | Python | LudovicBrossard/Dog-Breed-Predictor | 4c9e903e984076855cd9489f34e53185e860b66a | d76046d95d95caf4d375e09e0f55d8c1d63315f4 |
refs/heads/master | <repo_name>epixelcz/hltv-api-json<file_sep>/index.js
const { HLTV } = require('hltv');
const express = require('express');
const app = express();
//console.log(HLTV.getTeamRanking({year: '2018'}));
/* LOGIN */
app.use((req, res, next) => {
const auth = {
login: 'api',
password: '<PASSWORD>'
};
const b64auth = (req.headers.authorization || '').split(' ')[1] || '';
const [login, password] = new Buffer(b64auth, 'base64').toString().split(':');
if (!login || !password || login !== auth.login || password !== <PASSWORD>) {
res.set('WWW-Authenticate', 'Basic realm="401"');
res.status(401).send('Authentication required.');
return;
}
next();
});
/*
¨* MATCH STATS
*/
app.get('/match', (req, res) => {
HLTV.getMatches().then((out) => {
res.send(out);
});
});
app.get('/match/stats/:from(*)/:to(*)', (req, res) => {
const { from, to } = req.params;
HLTV.getMatchesStats({startDate: from, endDate: to}).then((out) => {
res.send(out);
});
});
app.get('/match/:matchID(*)/stats', (req, res) => {
const { matchID } = req.params;
var id = parseInt(matchID);
console.log(id + " " + (typeof id));
if((typeof id) === "number") {
HLTV.getMatchStats({id: id}).then(out => {
res.send(out);
});
}else{
res.send("Error");
}
});
app.get('/match/:matchID(*)', (req, res) => {
const { matchID } = req.params;
var id = parseInt(matchID);
console.log(id + " " + (typeof id));
if((typeof id) === "number") {
HLTV.getMatch({id: id}).then(out => {
res.send(out);
});
}else{
res.send("Error");
}
});
/*
* Team stats
*/
app.get('/team/:teamID(*)/stats', (req, res) => {
const { teamID } = req.params;
var id = parseInt(teamID);
console.log(id + " " + (typeof id));
if((typeof id) === "number") {
HLTV.getTeamStats({id: id}).then(out => {
res.send(out);
});
}else{
res.send("Error");
}
});
app.get('/team/:teamID(*)', (req, res) => {
const { teamID } = req.params;
var id = parseInt(teamID);
console.log(id + " " + (typeof id));
if((typeof id) === "number") {
HLTV.getTeam({id: id}).then(out => {
res.send(out);
});
}else{
res.send("Error");
}
});
/*
* Player stats
*/
app.get('/player/:playerID(*)/stats', (req, res) => {
const { playerID } = req.params;
var id = parseInt(playerID);
console.log(id + " " + (typeof id));
if((typeof id) === "number") {
HLTV.getPlayerStats({id: id}).then(out => {
res.send(out);
});
}else{
res.send("Error");
}
});
app.get('/player/:playerID(*)', (req, res) => {
const { playerID } = req.params;
var id = parseInt(playerID);
console.log(id + " " + (typeof id));
if((typeof id) === "number") {
HLTV.getPlayer({id: id}).then(out => {
res.send(out);
});
}else{
res.send("Error");
}
});
app.get('/player/stats/:from(*)/:to(*)', (req, res) => {
const { from, to } = req.params;
HLTV.getPlayerRanking({startDate: from, endDate: to}).then((out) => {
res.send(out);
});
});
/*
* Event
*/
app.get('/event/:event(*)', (req, res) => {
const { event } = req.params;
var id = parseInt(event);
console.log(id + " " + (typeof id));
if((typeof id) === "number") {
HLTV.getEvent({id: id}).then(out => {
res.send(out);
});
}else{
res.send("Error");
}
});
app.listen(8080, () => console.log('running suss...'))
<file_sep>/README.md
# Web based API on the unofficial HLTV Node.js API
https://github.com/gigobyte/HLTV
## URLs
every link corresponding with function
__/match -> HLTV.getMatches()__
---
__/match/stats/:from(*)/:to(*) --> HLTV.getMatchesStats({startDate: '2017-07-10', endDate: '2017-07-18'})__
---
__/match/:matchID(*)/stats --> HLTV.getMatchStats({id: 62979})__
---
__/match/:matchID(*) --> HLTV.getMatch({id: 2306295})__
---
__/team/:teamID(*)/stats --> HLTV.getTeamStats({id: 6137})__
---
__/team/:teamID(*) --> HLTV.getTeam({id: 6137})__
---
__/player/:playerID(*)/stats --> HLTV.getPlayerStats({id: 7998})__
---
__/player/:playerID(*) --> HLTV.getPlayer({id: 6137})__
---
__/player/stats/:from(*)/:to(*) --> HLTV.getPlayerRanking({startDate: '2018-07-01', endDate: '2018-10-01'})__
---
__/event/:event(*) --> HLTV.getEvent({id: 3389})__ | c5271e5fff6958fa77f3f20b5085ac1106609ef7 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | epixelcz/hltv-api-json | fdd1299eb47cb1439f64e842744d6ab045d88e55 | e820b0c81bf0e756aba791079418f48f72712dea |
refs/heads/master | <repo_name>cannelflow/MyCodeLearning<file_sep>/The-Complete-Web-Developer-Course/08 PHP/10/script.js
/*globals $:false */
$("form").submit(function (e) {
var error = "";
if($("#email").val() === ""){
error += "<p>Email Field Is Required !</p>";
}
if($("#sub").val() === ""){
error += "<p>Subject Field Is Required !</p>";
}
if($("#msg").val() === ""){
error += "<p>Message Field Is Required !</p>";
}
if(error !== ""){
$("#error").html('<div class="alert alert-danger"><strong>There Were Error(s) In Your Form : </strong>'+ error +'</div>');
return false;
}else{
return true;
}
});<file_sep>/The-Complete-Web-Developer-Course/08 PHP/05/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Loop</title>
</head>
<body>
<?php
//for loop
for($a = 0; $a < 10; $a++){
echo ("Number : $a <br> ");
}
echo("<br>");
//print even number
for ($a = 2; $a <= 30; $a++) {
if($a % 2 == 0){
echo ("Number Is : $a <br>");
}
}
echo("<br>");
//count 10 to 0
for($a = 10; $a > 0; $a--){
echo ("Number : $a <br> ");
}
echo("<br>");
//loop through array
$myCity = array("Delhi","Raipur","Jaipur","Kolkata");
for($i = 0; $i < sizeof($myCity); $i++){
echo ($myCity[$i]."<br>");
}
echo("<br>");
//loop through array
$myTown = array("Delhi","Raipur","Jaipur","Kolkata","NCR");
forEach($myTown as $key => $value){
echo ("Array Item $key "." Is $value <br>");
}
echo("<br>");
?>
</body>
</html><file_sep>/The Web Developer BootCamp/24 Intermediate Express/01 Templates/app.js
/* jshint node: true */
var express = require('express');
var app = express();
//======================
// Routes
//======================
app.get('/', function (req, res) {
res.render('home.ejs');
});
app.get('/fallinlovewith/:thing', function (req, res) {
var thing = req.params.thing;
res.render('love.ejs',{thingVar: thing});
});
//======================
// Server
//======================
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});<file_sep>/Data-Viz/Dashing-D3/README.md
<h1>Refrence Used</h1>
<a href="https://www.dashingd3js.com/table-of-contents" target="_blank">D3 Tutorial</a>
<file_sep>/The Web Developer BootCamp/12 Object/Movie DB/script.js
/*global prompt,alert,console*/
/*jslint plusplus: true */
var movieDB = [
{
title: "Dark Night",
rating: 4.5,
watched: false
},
{
title: "Pulp Fiction",
rating: 4.7,
watched: true
},
{
title: "Eagles Eye",
rating: 4.1,
watched: true
},
{
title: "<NAME>",
rating: 4.1,
watched: true
}
];
//var i;
//for (i = 0; i < movieDB.length; i++) {
// var result = "You Have ";
// if (movieDB[i].watched === true) {
// result += 'Watched ';
// } else {
// result += 'Not Seen ';
// }
// console.log(result += movieDB[i].title + " And Rating Is " + movieDB[i].rating + " Star");
//}
//movieDB.forEach(function (movie) {
// 'use strict';
// var result = "You Have";
// if (movie.watched === true) {
// result += "Watched ";
// } else {
// result += "Not Seen ";
// }
// result += movie.title + 'And Rating Is ' + movie.rating + " Star";
// console.log(result);
//});
function makeResult(movie) {
'use strict';
var result = "You Have";
if (movie.watched === true) {
result += "Watched ";
} else {
result += "Not Seen ";
}
result += movie.title + 'And Rating Is ' + movie.rating + " Star";
return result;
}
movieDB.forEach(function (movie) {
'use strict';
console.log(makeResult(movie));
});<file_sep>/The-Complete-Web-Developer-Course/08 PHP/04/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>If Statement</title>
</head>
<body>
<?php
$age = 22;
if($age < 25){
echo ("You Are Too Young!!");
} else {
echo("Proceed With Caution");
}
?>
</body>
</html><file_sep>/React/Medium/A-Dead-Simple-Tutorial/README.md
<a href="https://medium.com/the-redge-says/a-dead-simple-tutorial-on-how-to-use-react-js-for-those-who-know-html-css-and-some-javascript-9540426a67de#.mrnipva51" target="_blank">Refrenced Used</a>
<file_sep>/Node-Express/Node.js-for-.NET-Developers/07 View Engine/README.md
# 03 View Engine
<file_sep>/Node-Express/Rapid-Node/05 Async Code/app.js
var maxTime = 1000;
var evenDoubler = function (n, callback) {
waitTime = Math.floor(Math.random() * (maxTime + 1));
if (n % 2 !== 0) {
setTimeout(function () {
callback(new Error("Odd input"));
}, waitTime);
} else {
setTimeout(function () {
callback(null, n * 2, waitTime)
}, waitTime);
}
}
var handleResult = function (err, result, time) {
if (err) {
console.log("Error : " + err.message)
} else {
console.log("Error : " + result + " Time Is " + time);
}
}
var count = 0;
for (var i = 0; i < 10; i++) {
console.log("Calling For Value : " + i);
evenDoubler(i, handleResult);
}
console.log("-----");<file_sep>/The Web Developer BootCamp/09 Control Flow/Gussing Game/script.js
/*global prompt,alert,console*/
var num = 7;
//below will give string
var gussedNum = Number(prompt("Guess A Number"));
if (gussedNum < num) {
console.log("Too Low Guess Again");
} else if (gussedNum > num) {
console.log("Too High Guess Again!");
} else {
console.log("Correct");
}
<file_sep>/Node-Express/Node-Js-Tutorial/03 Event Loop/app.js
var events = require('events');
var eventEmitter = new events.EventEmitter();
var ringBell = function ringBell() {
console.log('ring ring ring : Door Opened');
eventEmitter.emit('doorClose');
}
eventEmitter.on('doorOpen', ringBell);
eventEmitter.on('doorClose', function() {
console.log('Ding Dong Ding : Door Closed');
});
eventEmitter.emit('doorOpen')
<file_sep>/The Web Developer BootCamp/24 Intermediate Express/05 Post Req2/app.js
/* jshint node: true */
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var friends = ['A','B','C','D','E'];
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
//set dir for public file like css ans js
app.use(express.static("public"));
// set the view engine to ejs
app.set('view engine', 'ejs');
// render index page
app.get('/', function(req, res) {
res.render('pages/index');
});
//render friends page
app.get('/friends', function(req, res) {
res.render('pages/friends',{friends:friends});
});
//post friend list
app.post('/addfriend', function(req, res) {
var name = req.body.name;
friends.push(name);
res.redirect('/friends');
});
app.listen(8080);
console.log('8080 is the magic port');<file_sep>/Node-Express/Zero-To-Hero/06 Streams/README.md
# 06 Streams
<file_sep>/The Web Developer BootCamp/17 Advanced Jquery/script.js
/* jshint browser: true */
/*globals $:false */
<file_sep>/React/WebPack/README.md
<h1>All File For Webpack SetUp</h1>
<h2>Steps For Createting WebPack Server</h2>
<ul>
<li>npm init -y</li>
<li>npm i -S react react-dom</li>
<li>npm i -D babel-core babel-loader babel-preset-es2015 babel-preset-react react-ho
t-loader webpack webpack-dev-server</li>
<li>npm i -g webpack webpack-dev-server</li>
<li>touch webpack.config.js</li>
</ul>
<file_sep>/Node-Express/Rapid-Node/README.md
<a href="https://www.udemy.com/nodejs-tutorial-from-scratch-by-examples/learn/v4/" target="_blank">Rapid Node</a>
<file_sep>/Node-Express/TutorialPoint-Node/12 Rest API/server2.js
var express = require('express');
var app = express();
var fs = require('fs');
var user = {
"user4" : {
"name" : "mohit",
"password" : "<PASSWORD>",
"profession" : "teacher",
"id": 4
}
}
app.get('/addUser',function(req,res) {
fs.readFile(__dirname+"/"+"user.json",function(err,data) {
data = JSON.parse(data);
data["user4"] = user["user4"];
console.log(data);
res.end(JSON.stringify(data));
});
})
var server = app.listen(8080, function () {
var host = server.address().address
var port = server.address().port
console.log("Server Started At Port "+ port)
})
<file_sep>/The Web Developer BootCamp/18 To Do/ToDo/Assets/js/script.js
/* jshint browser: true */
/*globals $:false */
/*striketrough when todo finished*/
$('ul').on('click','li', function (e) {
$(this).toggleClass('completed');
e.stopPropagation();
});
/*Delete finished todo*/
$('ul').on('click','span', function (e) {
$(this).parent().fadeOut('slow', function () {
$(this).remove();
});
e.stopPropagation();
});
/*add new todo*/
$('input').on('change',function (e) {
var newToDo = $(this).val();
$('ul').append('<li><span><i class="fa fa-trash" aria-hidden="true"></i></span> '+newToDo+'</li>');
e.stopPropagation();
});
/*fadetoggle in plus button*/
$('.fa-plus-square').on('click',function (e) {
$('input').fadeToggle();
e.stopPropagation();
});<file_sep>/Node-Express/Node.js-for-.NET-Developers/03 Folder Dependency/README.md
# 03 Folder Dependency
<file_sep>/Node-Express/Rapid-Node/08 Using Local Module/app.js
var app1 = require("./LModule/app1.js");
console.log(app1.hello());
console.log(app1.hello1());
console.log(app1.sum(1,2,3,4,5,6,7,8,9));<file_sep>/Node-Express/TutorialPoint-Node/08 Global/app1.js
function hello() {
console.log("Hello World !!!");
}
var t = setTimeout(hello,2000);
clearTimeout(t);
<file_sep>/Node-Express/Web Developement/03 Module/app.js
var myUtils = require('./app1.js');
myUtils.msg("Print Message Call");
myUtils.date("Print With Date Message Class");
<file_sep>/Data-Viz/Learning-D3/README.md
<h1>Refrence Used</h1>
<a href="https://www.youtube.com/playlist?list=PLillGF-RfqbY8Vy_G5WxXwhZx4eXI6Oea" target="_blank">Learning D3</a>
<file_sep>/Node-Express/Zero-To-Hero/README.md
<a href="https://www.youtube.com/watch?v=czmulJ9NBP0" target="_blank">Zero To Hero</a>
<file_sep>/React/Build-With-React/README.md
<a href="http://buildwithreact.com/tutorial" target="_blank">Referenced Used !!</a>
<file_sep>/The-Complete-Web-Developer-Course/08 PHP/10/index.php
<?php
//print_r($_POST);
$error = "";
$message = "";
if($_POST){
//check if fields are empty
if(!$_POST["email"]){
$error .= "An Email Address Is Required ! <br>";
}
if(!$_POST["sub"]){
$error .= "Subject Is Required ! <br>";
}
if(!$_POST["msg"]){
$error .= "Message Is Required ! <br>";
}
//check if email is valid
if($_POST["email"] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {
$error .= "Email Is Invalid ! <br>";
}
//display after form submission
if($error !==""){
$error = ('<div class="alert alert-danger"><strong>There Were Error(s) In Your Form :<br> </strong>'. $error .'</div>');
} else {
$to = $_POST["email"];
$subject = $_POST["sub"];
$txt = $_POST["msg"];
$headers = "From: <EMAIL>";
if(mail($to,$subject,$txt,$headers)){
$message = ('<div class="alert alert-success"><strong>Form Submitted Successfully<br> </strong></div>');
}else {
$error = ('<div class="alert alert-danger"><strong>You Got An Error Try Again<br> </strong></div>');
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Get In Touch!</h1>
<p id="error"><?php echo $error.$message ; ?></p>
<form method="post">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" placeholder="Email" name="email">
<small class="text-muted">We Will Never Your Email With Any One Else.</small>
</div>
<div class="form-group">
<label for="sub">Subject</label>
<input type="text" class="form-control" id="sub" placeholder="Subject" name="sub">
</div>
<div class="form-group">
<label for="msg">What Would You Like To Ask</label>
<textarea class="form-control" rows="3" id="msg" name="msg"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script type="text/javascript" src="script.js">
</script>
</body>
</html><file_sep>/Node-Express/Node-Js-Tutorial/README.md
<a href="http://www.tutorialspoint.com/nodejs/index.htm" target="_blank">Tutorials Point</a>
<file_sep>/The Web Developer BootCamp/24 Intermediate Express/03 Custome/app.js
/* jshint node: true */
var express = require('express');
var app = express();
//======================
//serve from public dir
//======================
app.use(express.static("public"));
//======================
//set view engine
//======================
app.set("view engine","ejs");
//======================
// Routes
//======================
app.get('/', function (req, res) {
res.render('home');
});
app.get('/fallinlovewith/:thing', function (req, res) {
var thing = req.params.thing;
res.render('love',{thingVar: thing});
});
app.get('/post', function (req, res) {
var post = [{title:"Post 1",author:"Author 1"},
{title:"Post 2",author:"Author 2"},
{title:"Post 3",author:"Author 3"},
{title:"Post 4",author:"Author 4"}];
res.render('post',{posts:post});
});
//======================
// Server
//======================
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});<file_sep>/Node-Express/README.md
<h1>Node JS Learning</h1>
<file_sep>/The-Complete-Web-Developer-Course/08 PHP/02/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Variable</title>
</head>
<body>
<?php
$name = "cannelflow";
echo("<p>My Name Is $name <br></p>");
$first = "Hello";
$second = "<NAME>";
echo("$first"." "."$second"."<br>");
$num = 23;
echo("My Age Is $num"."<br>");
$isTrue = true;
echo("Yes It Is : $isTrue"."<br>");
$variableName = "name";
echo($$variableName."<br>");
?>
</body>
</html><file_sep>/React/PluralSight/README.md
<h1>Plural Sight</h1>
<file_sep>/Node-Express/Node.js-for-.NET-Developers/09 Razor Like/README.md
# 06 Razor Like
<file_sep>/Interactive-Data-Viz/README.md
<h1>Refrence Used</h1>
<a href="http://freecomputerbooks.com/Interactive-Data-Visualization-for-the-Web.html" target="_blank">Data Viz Foe Web</a>
<file_sep>/Node-Express/Zero-To-Hero/04 CallBack Insanity/README.md
# 04 CallBack Insanity
<file_sep>/Data-Viz/ScatterPlot-Demo/README.md
<h1>Some Exercise For Learning ScatterPlot</h1>
<file_sep>/Node-Express/Web Developement/05 Connect/app1.js
var connect = require("connect");
var util = require('util');
var port = 8080;
var interceptorFunction = function(req,res,next) {
console.log(util.format('Request For %s with method %s',req.url,req.method));
next();
}
var server = connect()
.use('/log',interceptorFunction)
.use(function(req, res) {
res.end("Hello From Connect");
})
.listen(port, function() {
console.log("Server Is Running At Port : " + port);
});
<file_sep>/Node-Express/Node.js-for-.NET-Developers/05 The Board/server.js
var http = require('http');
var port = process.env.port || 1337;
var server = http.createServer(function (req, res) {
console.log("Requested Url Is : " + req.url);
res.writeHead(200, { "Content-Type": "text/html" });
res.write("<html><body><h1>"+req.url+"</h1></body></html>");
res.end();
});
server.listen(port);
console.log("Server Started At Port " + port);<file_sep>/Node-Express/Zero-To-Hero/05 Hello World TCP/README.md
# 05 Hello World TCP
<file_sep>/Node-Express/TutorialPoint-Node/07 File System/main.js
var fs = require('fs');
console.log('going to open a file');
fs.open('input.txt','r+',function (err,fd) {
if (err) {
console.log("Handle Me !!!");
} else {
console.log("Success !!!");
}
});
<file_sep>/Node-Express/TutorialPoint-Node/04 Event Emitter/app.js
var events = require('events');
var eventEmitter = new events.EventEmitter();
var event1 = function event1() {
console.log("event1 Executed");
}
var event2 = function event2() {
console.log("event2 Executed");
}
//3.bind another connection
eventEmitter.addListener('connection', event1)
//2.bind the connection with function
eventEmitter.on('connection', event2)
//4.add a eventListner
var eventListner = events.EventEmitter.listenerCount(eventEmitter, 'connection');
console.log("Currently Active Event :" + eventListner);
//1.fired an event name connection
eventEmitter.emit('connection');
//5.now remove event1
eventEmitter.removeListener('connection',event1);
console.log("event1 Stops");
//6.again fire an event
eventEmitter.emit('connection');
//7. listen to active event
var eventListner = events.EventEmitter.listenerCount(eventEmitter, 'connection');
console.log("Currently Active Event :" + eventListner);
<file_sep>/Node-Express/Node.js-for-.NET-Developers/06 Introducing Express/server.js
var express = require('express');
var http = require('http');
var app = express();
//define port
var port = process.env.port || 1337;
//create server
var server = http.createServer(app);
//methods
app.get("/", function (req,res) {
res.send("<html><body><h1>Express</h1></body></html>");
});
app.get("/api/user", function (req, res) {
res.set({"Content-Type":"application/json"});
res.send({name:"cannelflow",isValid:false,group:"Admin"});
});
server.listen(port);
console.log("Server Started At Port " + port);<file_sep>/Node-Express/Zero-To-Hero/08 Express Rest/README.md
# 08 Express Rest
<file_sep>/The-Complete-Web-Developer-Course/08 PHP/11/new.php
<?
echo("Im From Another File");
?><file_sep>/The Web Developer BootCamp/12 Object/script.js
/*global prompt,alert,console*/
/*jslint plusplus: true */
<file_sep>/The Web Developer BootCamp/16 Intro To Jqurey/Exercise 01/script.js
/* jshint browser: true */
/*globals $:false */
$('div').css('background','purple');
$('div.highlight').css('width','200px');
$('div#third').css('border','2px solid orange');
$('div:first').css('color','pink');<file_sep>/The Web Developer BootCamp/25 Working With API/01 Request/app.js
/* jshint node: true */
var request = require('request');
//request url
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body); // Show the HTML for the Google homepage.
}
});
app.listen(8080);
console.log('8080 is the magic port');<file_sep>/The Web Developer BootCamp/19 Optional Project/02/PataTap/Assets/js/script.js
/* jshint browser: true */
/*globals $:false */
//create circle
for (var x = 0; x <= 1000; x += 100) {
for (var y =0; y <=1000; y +=100) {
var myCircle = new Path.Circle(new Point(x, y), 10);
myCircle.fillColor = 'red';
}
}<file_sep>/Node-Express/Node.js-for-.NET-Developers/README.md
<a href="https://app.pluralsight.com/library/courses/nodejs-dotnet-developers/table-of-contents" target="_blank">Node.js for .NET Developers</a>
<file_sep>/The Web Developer BootCamp/22 Node/02 NodeEcho/echo.js
function echo (str,num) {
for (var i = 0;i < num; i++) {
console.log(str);
}
}
echo('hello',5);
echo('hi',7);<file_sep>/JavaScript/Basics-of-Programming-with-JavaScript/README.md
<a href="https://app.pluralsight.com/library/courses/javascript-programming-basics/table-of-contents" target="_blank">Basics of Programming with JavaScript</a>
<file_sep>/The-Complete-Web-Developer-Course/08 PHP/07/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Get Method</title>
</head>
<body>
<?php
//get the value from url by priniting $_GET array
// print_r($_GET);
// echo("<br>");
//
//echo the value after
echo($_GET["name"]);
echo("<br>");
echo($_GET["city"]);
?>
<form>
<input type="text" name="name" placeholder="name">
<br>
<input type="text" name="city" placeholder="city">
<br>
<input type="submit">
</form>
</body>
</html><file_sep>/React/Big-Binary/README.md
<h1>Refrenced Used</h1>
<ul>
<li><a href="https://www.youtube.com/playlist?list=PL3mbwkbZ12RLfnRbL6HYEdObqzbMGu24B">Big Bibary</a></li>
</ul>
<file_sep>/JavaScript/JavaScript-Understanding-the-Weird-Parts/README.md
<a href="https://www.udemy.com/understand-javascript/learn/v4/content" target="_blank">JavaScript: Understanding the Weird Parts<a>
<file_sep>/The Web Developer BootCamp/13 DOM Manupulation/script.js
/*global prompt,alert,console*/
/*jslint plusplus: true */
var logo = document.querySelector("img");
console.log(logo.getAttribute("src"));
logo.setAttribute("src", "http://www.fropky.com/uploads/2016/jul/Ileana/Ileana-001.jpg");<file_sep>/Node-Express/Node.js-for-.NET-Developers/02 Moduler Way/app.js
var abc = require('./msg.js');
console.log("Hello World From app.js")
console.log(abc.msg());
console.log(abc.msg1.name +" From "+ abc.msg1.place);<file_sep>/JavaScript/JavaScript-Understanding-the-Weird-Parts/B3_GlobalEnvironment/Starter/app.js
var a = 'Hello Cannelflow';
function b() {};
<file_sep>/Node-Express/TutorialPoint-Node/11 Express/server1.js
var express = require('express');
var port = 8080;
var app = express();
app.use(express.static('public'));
app.get('/',function(req,res) {
console.log("Requested For : " + req.url);
res.send("Hello World !!!");
});
var server = app.listen(port, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at ", host, port)
})
<file_sep>/The Web Developer BootCamp/09 Control Flow/For Ex/script.js
/*global prompt,alert,console*/
/*jslint plusplus: true */
/*
var count;
for (count = 0; count < 6; count++) {
console.log(count);
}
//similar in while loop
var num = 0;
while (num < 6) {
console.log(num);
num++;
}
*/
var str = 'Hello World';
var count;
for (count = 0; count < str.length; count++) {
console.log(str[count]);
}
//with while loop
var num = 0;
while (num < str.length) {
console.log(str[num]);
num++;
}<file_sep>/The Web Developer BootCamp/08 Intro To Javascript/script.js
/*global prompt,alert,console*/
var age = prompt('Enter Your Age');
console.log('You Had Lived ' + age * 365.25 + 'Days');<file_sep>/Udacity/JavaScript-Basic/README.md
<a href="https://classroom.udacity.com/courses/ud804/lessons/1946788554/concepts/25505685350923" target="_blank">Javascript Basic</a>
<file_sep>/Node-Express/Rapid-Node/05 Async Code/README.md
# 05 Async Code
<file_sep>/The Web Developer BootCamp/14 Advanced DOM Manupulation/01/script.js
/*global prompt,alert,console*/
/*jslint plusplus: true */
var btn = document.querySelector("button");
var body = document.querySelector("body");
//var isPurple = false;
//btn.addEventListener('click', function () {
// 'use strict';
// if (isPurple) {
// body.style.background = "white";
// } else {
// body.style.background = "purple";
// }
// isPurple = !isPurple;
//});
btn.addEventListener('click', function () {
'use strict';
body.classList.toggle("purple");
});<file_sep>/Node-Express/Node.js-for-.NET-Developers/01 Hello World/01 Hello World/app.js
console.log('Hello world');
var abc = function () {
return ("Check & Mate")
}
console.log(abc());
var abc = {
name: "cannelflow",
place:"Delhi"
}
console.log("Hello I'm "+ abc.name+" From "+abc.place)<file_sep>/Node-Express/Rapid-Node/07 Using 3rd Party Module/app.js
var http = require("http");
var moment = require("moment");
var server = http.createServer(function (req, res) {
var now = moment(new Date());
var date = now.format("D MMM YYYY");
var year = now.format("YYYY");
var month = now.format("MMMM");
var time = now.format("HH:mm");
res.write("<p>Today's date is " + date + "</p>");
res.write("<p>The year is " + year + "</p>");
res.write("<p>The month is " + month + "</p>");
res.write("<p>The time is " + time + "</p>");
res.end();
}).listen(8080);
<file_sep>/React/LevelUpTuts/README.md
<h1>Refrence Used</h1>
<a href="https://www.youtube.com/playlist?list=PLLnpHn493BHFfs3Uj5tvx17mXk4B4ws4p">Level Up Tuts</a>
<file_sep>/The Web Developer BootCamp/11 Array/01/script.js
/*global prompt,alert,console*/
/*jslint plusplus: true */
var arr = ["A", "B", "C", "D", "E"];
var i;
console.log("By For Loop");
for (i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
console.log("By forEach Loop");
arr.forEach(function (arr) {
console.log(arr);
});<file_sep>/React/WebPack/index.js
var React = require('react');
var ReactDOM = require('react-dom');
var Home = require('component/app');
var Main = React.createClass({
render: function() {
return (
<div>
<h1 className="text-primary">Hello {this.state.name}</h1>
</div>
);
}
});
ReactDOM.render(
<Home />,
document.querySelector('#app')
);
<file_sep>/The Web Developer BootCamp/11 Array/ToDo App/script.js
/*global prompt,alert,console*/
/*jslint plusplus: true */
var toDo = [];
var input = prompt("What Would You Like To Do");
while (input !== 'quit') {
if (input === 'list') {
console.log(toDo);
} else if (input === 'new') {
var newVal = prompt("Enter Your ToDo List Now");
toDo.push(newVal);
}
var input = prompt("What Would You Like To Do");
}
console.log("You Quit The App Thanks For Using !!!");<file_sep>/The-Complete-Web-Developer-Course/08 PHP/11/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Get In Touch!</h1>
<?php
include("new.php");
echo file_get_contents("http://www.smashingmagazine.com/2012/08/23/how-to-become-a-top-wordpress-developer/");
?>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script type="text/javascript" src="script.js">
</script>
</body>
</html><file_sep>/Node-Express/Building-Web-Applications/02 First App/app.js
var express = require('express');
var app = express();
var port = 8080;
app.listen(port, function(err) {
console.log("Server Is Running At Port: " + port);
});
<file_sep>/React/PluralSight/React-Fundamental/README.md
<a href="https://app.pluralsight.com/library/courses/react-fundamentals" target="_blank">Refrenced Used</a>
<file_sep>/Node-Express/Node.js-for-.NET-Developers/10 Controller/README.md
# 06 Controller
<file_sep>/Node-Express/TutorialPoint-Node/02 Callback/app.js
var fs = require('fs');
//Sync Way Means Programme Blocks Everthing Untill It Finished
var data = fs.readFileSync('index.txt');
console.log("OutPut From Sync Way : " + data.toString());
//Async Way Programme don't wait to finish
fs.readFile('index.txt', 'utf-8', function(err, data) {
if (err) {
console.log("You HAVE tO dEAL wITH mE fIRST");
}
console.log("OutPut From ASync Way : " + data);
})
console.log("Programme Ended");
<file_sep>/React/PluralSight/React-Fundamental/Author-Quiz/README.md
<h1>Author Quiz Developement</h1>
<file_sep>/Node-Express/TutorialPoint-Node/08 Global/app.js
//console.log(__filename);
//console.log(__dirname);
function hello() {
console.log("Hello World !!!");
}
var t = setTimeout(hello,2000);
<file_sep>/The Web Developer BootCamp/22 Node/03 NodeAverage/grader.js
function average (arr) {
var sum = 0;
for (var i = 0;i < arr.length; i++) {
sum += arr[i];
}
console.log(Math.round(sum/arr.length));
}
average([10,20]);
average([25,25]);
<file_sep>/The Web Developer BootCamp/10 Function/Function Problem Set/script.js
/*global prompt,alert,console*/
/*jslint plusplus: true */
console.log('Function To Check For Even');
function isEven(num) {
"use strict";
if (num % 2 === 0) {
return true;
} else {
return false;
}
}
isEven(4);
isEven(21);
isEven(68);
isEven(333);
console.log('Function To Get Factorial Of Number');
function fact(num) {
"use strict";
if (num < 1) {
return 1;
} else {
return num * fact(num - 1);
}
}
fact(5);
fact(2);
fact(10);
fact(0);
console.log('Replace Character In A String');
function rep(str) {
"use strict";
if (str.indexOf('-') > 0) {
return str.replace(/-/g, '_');
} else {
return str;
}
}
rep("hello-world");
rep('Hello');<file_sep>/Udacity/README.md
<a href="https://www.udacity.com/" target="_blank">Udacity</a>
<file_sep>/Node-Express/Node.js-for-.NET-Developers/05 The Board/README.md
# 01 The Board
<file_sep>/Node-Express/Rapid-Node/08 Using Local Module/README.md
# 08 Using Local Module
<file_sep>/JavaScript/Advanced-Javascript/README.md
<a href="https://app.pluralsight.com/library/courses/advanced-javascript/table-of-contents" target="_blank">Advanced JavaScript
by <NAME></a>
<file_sep>/Node-Express/Rapid-Node/04 Node Event Loop/app.js
console.log('Hello 1');
setTimeout(function () {
console.log("Hello 2");
}, 1000);
console.log("Hello 3");<file_sep>/Node-Express/Building-Web-Applications/README.md
<a href="https://app.pluralsight.com/library/courses/nodejs-express-web-applications/table-of-contents" target="_blank">Building Web Applications with Node.js and Express 4.0</a>
<file_sep>/Data-Viz/Let-s-Make-A-Bar-Chart/README.md
<h1>Refrence Used</h1>
<a href="https://bost.ocks.org/mike/bar/" target="_blank">Lets Make A Bar Chart</a>
<file_sep>/The-Complete-Web-Developer-Course/08 PHP/07/prime.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Get Method</title>
</head>
<body>
<?php
//get the value from url by priniting $_GET array
// print_r($_GET);
// echo("<br>");
// echo($_GET["num"]);
//check if input filled is empty
if(is_numeric($_GET["num"]) && $_GET["num"] > 0 && $_GET["num"] == round($_GET["num"], 0)){
$i = 2;
$isPrime = true;
while($i < $_GET["num"]){
if($_GET["num"] % $i == 0){
//number is not prime
$isPrime = false;
}
$i++;
}
if($isPrime){
echo($_GET["num"]." Is A Prime Number");
} else {
echo($_GET["num"]." Is Not A Prime Number");
}
}else{
echo("Please Enter Positive Whole Number");
}
?>
<form>
<input type="text" name="num" placeholder="number">
<br>
<input type="submit">
</form>
</body>
</html><file_sep>/React/To-Do-App/README.md
<h1>Refrence Used</h1>
<a href="https://www.youtube.com/watch?v=IR6smI_YJDE" target"_blank">React Tutorial</a>
<file_sep>/Data-Viz/Force-Directed-Graph-Demo/README.md
<h1>Different Example Of Bar Chart</h1>
<a href="http://bl.ocks.org/sathomas/11550728" target="_blank">Refrence Used</a>
<file_sep>/The-Complete-Web-Developer-Course/08 PHP/12/index.php
<?php
$error = "";
$weather = "";
if(array_key_exists('city', $_GET)){
//remove spaces from url
$city = str_replace(' ', '',$_GET["city"]);
//check if url exists or not
$file_headers = @get_headers('http://www.weather-forecast.com/locations/'.$city.'/forecasts/latest');
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$error = "City Could Not Found !!";
} else {
//get content of requested url
$forecastPage = file_get_contents('http://www.weather-forecast.com/locations/'.$city.'/forecasts/latest');
//get data which we required
$pageArray = explode('3 Day Weather Forecast Summary:</b><span class="read-more-small"><span class="read-more-content"> <span class="phrase">',$forecastPage);
//check if we are getting the required data
if(sizeof($pageArray) > 1){
$secondPage = explode('</span></span></span>',$pageArray[1]);
//check if we are getting the required data
if (sizeof($secondPage) >1) {
//pass it to html
$weather = $secondPage[0];
} else {
$error = "City Could Not Found !!";
}
} else {
$error = "City Could Not Found !!";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Weather App</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container text-center">
<h1>What's The Weather</h1>
<form method="get">
<fieldset class="form-group">
<label for="city">Enter The Name Of The City</label>
<input type="text" class="form-control" id="city" placeholder="Eg. London,Tokyo" name="city" value="<?php
if(array_key_exists('city', $_GET)){ echo $city; }
?>">
</fieldset>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<div class="result">
<?php
if($weather){
echo ('<div class="alert alert-success" role="alert">'. $weather .'</div>');
} else if ($error){
echo ('<div class="alert alert-danger" role="alert">'. $error .'</div>');
}
?>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep>/Data-Viz/Bar-Chart-Demo/README.md
<h1>Defferent Example Of Bar Chart</h1>
<file_sep>/Node-Express/Zero-To-Hero/07 Basic Express/README.md
# 07 Basic Express
<file_sep>/The Web Developer BootCamp/13 DOM Manupulation/03/script.js
/*global prompt,alert,console*/
/*jslint plusplus: true */
var one = document.querySelector("#first");
var two = document.getElementById("first");
var three = document.getElementsByClassName("special");
var four = document.getElementsByTagName("p");<file_sep>/Node-Express/Rapid-Node/02 Hello World Server/README.md
# 02 Hello World Server
<file_sep>/The Web Developer BootCamp/26 Yelp Camp Basic/01 Version/app.js
/* jshint node: true */
var express = require('express');
//var bodyParser = require('body-parser');
//var request = require('request');
var app = express();
// parse application/x-www-form-urlencoded
//app.use(bodyParser.urlencoded({
// extended: false
//}));
//temprory database
var campground = [
{name:"India",image:"https://farm4.staticflickr.com/3270/2617191414_c5d8a25a94.jpg"},
{name:"Austrelia",image:"https://farm6.staticflickr.com/5181/5641024448_04fefbb64d.jpg"},
{name:"America",image:"https://farm3.staticflickr.com/2464/3694344957_14180103ed.jpg"},
{name:"France",image:"https://farm2.staticflickr.com/1281/4684194306_18ebcdb01c.jpg"}
];
//set dir for public file like css and js
app.use(express.static("public"));
// set the view engine to ejs
app.set('view engine', 'ejs');
//render index page
app.get('/', function (req, res) {
res.render('pages/index');
});
// render campground page
app.get('/campground', function (req, res) {
res.render('pages/campground',{data:campground});
});
//start server with message
app.listen(8080);
console.log('8080 is the magic port');<file_sep>/The Web Developer BootCamp/23 Express/04 Exercise/app.js
var express = require('express');
var app = express();
//==============
// Route
//==============
app.get('/', function (req, res) {
res.send('Hi there welcome to my assignment');
});
app.get('/speak/:animal', function (req, res) {
var sounds = {
pig:"Oink",
cow:"Moo",
dog:"Woof Woof",
cat:"Meow Meow"
}
var animal = req.params.animal.toLowerCase();
var sound = sounds[animal];
res.send("The " +animal+" Says " + sound);
});
app.get('/repeat/:msg/:times', function (req, res) {
var val = req.params.msg;
var num = Number(req.params.times);
var result = "";
for (var i =0; i <= num; i++) {
result += val + " ";
}
res.send(result);
});
app.get('*', function (req, res) {
res.send("Sorry Page Not Found!!");
});
//==============
// Server
//==============
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});<file_sep>/Node-Express/Rapid-Node/06 Using Core Module/app.js
var os = require("os");
console.log("OS Type: " + os.type());
console.log("OS Platform: " + os.platform());
console.log("OS CPU Architecture: " + os.arch());
console.log("OS Release: " + os.release());
console.log("OS Uptime (seconds): " + os.uptime());
<file_sep>/The Web Developer BootCamp/15 Color Game/01/script.js
/* jshint browser: true */
var numSquare = 6;
var colors = selectColor(numSquare);
var pickedColor = pickColor();
var square = document.querySelectorAll(".square");
var colorMatch = document.querySelector(".pickedColor");
var textResult = document.querySelector(".textResult");
var h1 = document.querySelector("h1");
var resetButton = document.querySelector(".reset");
var mode = document.querySelectorAll('.mode');
var i;
for (i = 0; i < square.length; i++) {
//add different color to square
square[i].style.background = colors[i];
//add eventlistner to square
square[i].addEventListener('click', squareClick);
}
colorMatch.textContent = pickedColor;
//logic for reset button
resetButton.addEventListener('click', function () {
reset();
});
//pick random color from color array
function pickColor() {
var randNumber = Math.floor(Math.random() * colors.length);
return colors[randNumber];
}
//check if guess is true or false
function squareClick() {
/*jshint validthis:true */
'use strict';
var selectedColor = (this.style.background);
if (selectedColor === pickedColor) {
squareColor(selectedColor);
h1.style.background = selectedColor;
resetButton.textContent = "Play Again?";
} else {
this.style.background = 'rgb(52, 73, 94)';
textResult.textContent = "Try Again";
}
}
//check if guess is true or false
function squareColor(selectedColor) {
'use strict';
for (i = 0; i < square.length; i++) {
square[i].style.background = selectedColor;
}
textResult.textContent = "Correct";
}
//generate color array
function selectColor(num) {
var arr = [];
for (i = 0; i < num; i++) {
arr.push(randomColor());
}
return arr;
}
//generate random color
function randomColor() {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + ", " + g + ", " + b + ")";
}
//logic for mode
for (i = 0; i < mode.length; i++) {
mode[i].addEventListener('click',abc);
}
function abc () {
mode[0].classList.remove('selected');
mode[1].classList.remove('selected');
this.classList.add('selected');
this.textContent === 'Easy' ? numSquare = 3 : numSquare = 6;
reset();
}
function reset() {
colors = selectColor(numSquare);
// change color for square
for (i = 0; i < square.length; i++) {
if (colors[i]) {
square[i].style.display = 'block';
square[i].style.background = colors[i];
} else {
square[i].style.display = 'none';
}
}
//change color display
pickedColor = pickColor();
colorMatch.textContent = pickedColor;
//change background color of display
h1.style.background = '#22A7F0';
textResult.textContent = "";
resetButton.textContent = "New Colors";
}<file_sep>/React/PluralSight/Reactjs-Getting-Started/README.md
<a href="https://app.pluralsight.com/library/courses/react-js-getting-started/table-of-contents" target="_blank">React.js: Getting Started</a>
<file_sep>/Data-Viz/Curran/Intro-To-D3/README.md
<h1>Refrence Used !!!</h1>
<a href="https://github.com/curran/screencasts/tree/gh-pages/introToD3" target="_blank"><h1> Intro To D3</h1></a>
<file_sep>/Node-Express/Web Developement/README.md
<a href="https://app.pluralsight.com/library/courses/expressjs" target="_blank">Web Developement With Express JS</a>
<file_sep>/Node-Express/Zero-To-Hero/09 Node ChatRoom/README.md
# 09 Node ChatRoom
<file_sep>/React/React.js-Introduction/README.md
<a href="http://reactfordesigners.com/labs/reactjs-introduction-for-people-who-know-just-enough-jquery-to-get-by/">Refrenced Used</a>
<file_sep>/The-Complete-Web-Developer-Course/08 PHP/09/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Send Mail</title>
</head>
<body>
<?php
$to = "<EMAIL>";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: <EMAIL>";
if(mail($to,$subject,$txt,$headers)){
echo("Successfull");
}else {
echo("Error");
}
?>
</body>
</html><file_sep>/React/Learning-React.js/README.md
<a href="https://scotch.io/tutorials/learning-react-getting-started-and-concepts" target="_blank">Refrenced Used</a>
<file_sep>/Node-Express/Zero-To-Hero/03 File IO/README.md
# 03 File IO
<file_sep>/The-Complete-Web-Developer-Course/README.md
<a href="#" target="_blank">The Complete Web Developer Course<a>
<file_sep>/React/Medium/README.md
<h1>Refrenced Used In This Tutorials Are </h1>
<p>https://medium.com/learning-new-stuff/learn-react-js-in-7-min-92a1ef023003#.wr92orh12</p>
<p>https://medium.com/learning-new-stuff/building-your-first-react-js-app-d53b0c98dc#.ai4x5gxhu</p>
<p>https://medium.com/learning-new-stuff/building-your-second-react-js-app-eb66924b3774#.pddx3rs71</p>
<file_sep>/The-Complete-Web-Developer-Course/08 PHP/08/user.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post Method</title>
</head>
<body>
<?php
//get the value from post method
// print_r($_POST)
// echo($_POST["name"]);
if($_POST){
$userName = array("cannelflow","lowshoulder","skyway","<PASSWORD>way");
$isKnown = false;
foreach($userName as $key => $value){
if($_POST["name"] == $value){
$isKnown = true;
}
}
if($isKnown){
echo("Hello ".$_POST["name"]." Welcome Here ");
} else {
echo("Hello ".$_POST["name"]." Please Login");
}
}
?>
<form action="" method="post">
<input type="text" name="name" placeholder="name">
<input type="submit">
</form>
</body>
</html><file_sep>/React/Reactjs-Programme-React-Fundamental/README.md
<a href="http://reactjsprogram.teachable.com/courses/reactjsfundamentals" target="_blank">Refrenced Used</a>
<file_sep>/Node-Express/Node.js-for-.NET-Developers/03 Folder Dependency/component/index.js
module.exports = function (a) {
return ("Hello " + a);
}
<file_sep>/The Web Developer BootCamp/22 Node/01 Node/hello.js
for (var i = 0;i < 6;i++) {
console.log(i);
}
<file_sep>/Node-Express/Rapid-Node/03 JS Callback/README.md
# 03 JS Callback
<file_sep>/The Web Developer BootCamp/09 Control Flow/01/script.js
/*global prompt,alert,console*/
var age = 25;
if (age < 0) {
console.log("You Are Not Born Yet!");
}
if (age === 21) {
console.log("Happy 21st Birth Day!!");
}
if (age % 2 !== 0) {
console.log("Your Age Is Odd!");
}
if (Math.sqrt(age) % 1 === 0) {
console.log("Your Age Is Perfect Square!");
} else {
console.log("Do Anything You Like!");
}
<file_sep>/The Web Developer BootCamp/14 Advanced DOM Manupulation/02 Exercise/script.js
/*global prompt,alert,console*/
/*jslint plusplus: true */
var button1 = document.querySelector(".button1");
var button2 = document.querySelector(".button2");
var p1Display = document.querySelector(".p1display");
var p2Display = document.querySelector(".p2display");
var reset = document.querySelector(".reset");
var setVal = document.querySelector(".setVal");
var winVal = document.querySelector(".maxVal");
var val1 = 0;
var val2 = 0;
var maxVal = 5;
var gameOver = false;
function reUse() {
'use strict';
val1 = 0;
val2 = 0;
p1Display.textContent = 0;
p2Display.textContent = 0;
p1Display.classList.remove("win");
p2Display.classList.remove("win");
gameOver = false;
}
button1.addEventListener('click', function () {
'use strict';
if (gameOver === false) {
val1++;
if (val1 === maxVal) {
p1Display.classList.add("win");
gameOver = true;
}
p1Display.textContent = val1;
}
});
button2.addEventListener('click', function () {
'use strict';
if (gameOver === false) {
val2++;
if (val2 === maxVal) {
p2Display.classList.add("win");
gameOver = true;
}
p2Display.textContent = val2;
}
});
reset.addEventListener('click', function () {
'use strict';
reUse();
});
setVal.addEventListener('change', function () {
'use strict';
winVal.textContent = setVal.value;
maxVal = Number(setVal.value);
reUse();
});
<file_sep>/The Web Developer BootCamp/09 Control Flow/03/script.js
/*global prompt,alert,console*/
/*
var answer = prompt("Are We There Yet");
if (answer === 'yes') {
console.log('We Made It!!');
} else {
var answer = prompt("Are We There Yet");
}
*/
/*
var answer = prompt("Are We There Yet");
//while answer is not equal to yes
while (answer !== 'yes' && answer !== 'yeah') {
var answer = prompt("Are We There Yet");
}
alert('We Made It!!');
*/
var answer = prompt("Are We There Yet");
while (answer.indexOf('yes') === -1) {
var answer = prompt("Are We There Yet");
}
alert('We Made It!!');
<file_sep>/Data-Viz/D3.js-tutorial/README.md
<h1>Refrence Used</h1>
<a href="https://www.youtube.com/playlist?list=PL6il2r9i3BqH9PmbOf5wA5E1wOG3FT22p" target="_blank">D3js Tutorial Youtube</a>
<file_sep>/The-Complete-Web-Developer-Course/08 PHP/06/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>While Loops</title>
</head>
<body>
<?php
$a = 0;
while($a < 10){
echo("$a <br>");
$a++;
}
echo("<br>");
$a = 5;
while($a <= 50){
echo("$a <br>");
$a+=5;
}
echo("<br>");
$i = 0;
$cars = array("Volvo", "BMW", "Toyota");
while ($i < sizeof($cars)){
echo("$cars[$i] <br>");
$i++;
}
echo("<br>");
?>
</body>
</html><file_sep>/Data-Viz/Curran/README.md
<h1>Refrence Used !!!</h1>
<a href="https://github.com/curran/screencasts" target=""_blank><h2><NAME></h2></a>
<file_sep>/The-Complete-Web-Developer-Course/08 PHP/08/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post Method</title>
</head>
<body>
<?php
//get the value from post method
print_r($_POST)
?>
<form action="" method="post">
<input type="text" name="name" placeholder="name">
<input type="submit">
</form>
</body>
</html><file_sep>/React/Facebook/FB-Tutorial/README.md
<a href="http://facebook.github.io/react/docs/tutorial.html" target="_blank">Tutorial</a>
<file_sep>/Node-Express/Rapid-Node/06 Using Core Module/README.md
# 06 Using Core Module
<file_sep>/Node-Express/TutorialPoint-Node/README.md
<a href="http://www.tutorialspoint.com/nodejs/index.htm" target="_blank">TutorialPoint</a>
<file_sep>/React/Facebook/README.md
<h1>FaceBook Official Documentation</h1>
<file_sep>/Node-Express/Code-For-Geek/README.md
<a href="https://codeforgeek.com/2014/10/express-complete-tutorial-part-1/" target="_blank">Gode For Geek</a>
<file_sep>/Node-Express/Zero-To-Hero/02 Hello World HTTP/README.md
# 02 Hello World HTTP
<file_sep>/JavaScript/README.md
#My JavaScript Learning
<file_sep>/React/React-JS-with-ES5-for-Beginners/README.md
<a href="https://www.youtube.com/playlist?list=PLIGDNOJWiL1_ndMWBpMvo8oAXuR7bjnWM" target="_blank">Resource Used</a>
<file_sep>/Node-Express/Node.js-for-.NET-Developers/08 Web Form/README.md
# 04 Web Form
<file_sep>/Node-Express/Rapid-Node/04 Node Event Loop/README.md
# 04 Node Event Loop
<file_sep>/Data-Viz/Scott-Murray/README.md
<h1>Refrence Used !!!</h1>
<a href="http://alignedleft.com/tutorials/d3" target="_blank"><h1><NAME></h1></a>
<file_sep>/Node-Express/Node.js-for-.NET-Developers/02 Moduler Way/README.md
# 02 Moduler Way
<file_sep>/The Web Developer BootCamp/11 Array/ToDo App V2/script.js
/*global prompt,alert,console*/
/*jslint plusplus: true */
var toDo = [];
var input = prompt("What Would You Like To Do");
while (input !== 'quit') {
if (input === 'list') {
toList();
} else if (input === 'new') {
toNew();
} else if (input === 'delete') {
toDelete();
}
var input = prompt("What Would You Like To Do");
}
console.log("You Quit The App Thanks For Using !!!");
function toList() {
console.log('**********');
toDo.forEach(function (todo, index) {
console.log(index + ': ' + todo);
});
console.log('**********');
}
function toNew() {
var newVal = prompt("Enter Your ToDo List Now");
toDo.push(newVal);
console.log("Successfully Added");
}
function toDelete() {
var num = prompt("Which Index You Want To Delete");
toDo.splice(num, 1);
console.log("Deleted SuccessFully");
}<file_sep>/Node-Express/Node.js-for-.NET-Developers/06 Introducing Express/README.md
# 06 Introducing Express
<file_sep>/Node-Express/Rapid-Node/07 Using 3rd Party Module/README.md
# 07 Using 3rd Party Module
<file_sep>/The-Complete-Web-Developer-Course/08 PHP/03/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Array</title>
</head>
<body>
<?php
//simple array
$myArray = array("A","B","C","D","E");
print_r($myArray);
echo("<br>");
echo($myArray[1]);
$myArray[1] = "E";
echo("<br>");
print_r($myArray);
//associative array
$anotherArray = array(
"name"=>"cannelflow",
"age"=>20,
"city"=>"delhi",
);
print_r($myArray);
echo("<br>");
echo($anotherArray["name"]);
echo("<br>");
//length of an array
echo (sizeof($myArray));
echo("<br>");
echo (sizeof($anotherArray));
echo("<br>");
//add an item to array
$myArray[] = "E"; //End
$anotherArray["sex"] = "M";//End
print_r($myArray);
echo("<br>");
print_r($anotherArray);
echo("<br>");
//remove an item
unset($anotherArray["name"]);
print_r($anotherArray);
echo("<br>");
unset($myArray[2]);
print_r($myArray);
echo("<br>");
?>
</body>
</html><file_sep>/Node-Express/Node.js-for-.NET-Developers/04 npm/README.md
# 04 npm
| 0c8729f2a1bb262235419c0516c31edd4141b048 | [
"JavaScript",
"Markdown",
"PHP"
] | 135 | JavaScript | cannelflow/MyCodeLearning | 89ab293ff37ec023058056d11aefd41e933aff99 | 16a39944cde953b9baac94328cabc420fda0b634 |
refs/heads/master | <repo_name>yortus/monotask<file_sep>/src/index.ts
import create from './create';
export default {create};
export {create};
<file_sep>/src/create.ts
import AsyncLocalStorage from './async-local-storage';
/**
* Creates a new serialised task queue. Use the returned function to
* wrap all functions whose calls are to be serialised into this queue.
*/
export default function create() {
// Async local storage is used to track which task is active, and to keep metadata about
// all tasks that have been called/initiated and whose results are awaited. Only one of
// these tasks is the current task. All other tasks are blocked waiting for it to finish.
const als = new AsyncLocalStorage<TaskInfo>();
// This special task represents the global calling scope for this task queue. I.e., it
// is used as the current task for callers that are not themselves inside a running task.
const GLOBAL_ENV = new TaskInfo();
// Return a decorator function that delays each call to its wrapped function
// in such a way that serialised execution guarantees are always maintained.
return function wrap<F extends (...args: any[]) => Promise<any>>(fn: F): F {
return (async function wrapped(...args: any[]) {
// The wrapped call will be treated as a subtask of the calling task.
// Top-level tasks are treated as subtasks of the special `GLOBAL_ENV` task.
let callingTask = als.data || GLOBAL_ENV;
// Delay starting this subtask until the calling task has no other subtasks in progress.
// This ensures top-level tasks only start when there are no other top-level tasks running.
// It also correctly serialises nested subtasks that are started in the same tick. For example,
// when a parent task has code like `await Promise.all([sub1(), sub2(), sub3()])`.
let result = callingTask.noSubtasksPending.then(async () => {
// This subtask is cleared to start. Create metadata for it and mark it as the current task.
als.data = new TaskInfo();
// Execute the wrapped function and return its result (or reject with its error).
return fn(...args);
});
// When the subtask completes (or fails), then the calling task is ready for more subtasks.
// If a series of tasks are started synchronously, they will be chained into this promise
// and will execute serially as each prior one completes (or fails).
callingTask.noSubtasksPending = result.catch(() => undefined);
return result;
}) as F;
};
}
/** Metadata about a currently running task. All we need to know is whether it has currently running subtasks. */
class TaskInfo {
noSubtasksPending = Promise.resolve();
}
<file_sep>/src/async-local-storage.ts
import * as async_hooks from 'async_hooks';
import * as fs from 'fs';
/**
* Allows arbitrary user-defined data to be associated with an asynchronous execution context, similar to thread-local
* storage. The data associated with a context is inherited by all asynchronous execution contexts whose creation is
* causally triggered by that context. Data may be stored, retrieved, and replaced for the currently executing context
* using the `data` getter/setter.
*/
export default class AsyncLocalStorage<T extends object> {
constructor(options?: Partial<Options>) {
this.options = Object.assign({}, DEFAULT_OPTIONS, options);
this.items = new Map();
this.initAsyncHook();
}
dispose() {
this.asyncHook.disable();
this.items.clear();
}
get data(): T | undefined {
let asyncId = async_hooks.executionAsyncId();
return this.items.get(asyncId);
}
set data(value: T | undefined) {
// TODO: already init'ed child contexts won't see this change. Is that a bug or a feature?
let asyncId = async_hooks.executionAsyncId();
if (value === undefined) {
this.items.delete(asyncId);
}
else {
this.items.set(asyncId, value);
}
}
private options: Options;
private items: Map<number, T>;
private asyncHook: async_hooks.AsyncHook;
private initAsyncHook() {
this.asyncHook = async_hooks.createHook({
init: (asyncId, _, triggerAsyncId) => {
// Propagate items to new async contexts.
let item = this.items.get(triggerAsyncId);
if (item) this.items.set(asyncId, item);
if (this.options.trace) fs.writeSync(1, `--- INIT: ${this.items.size} items ---\n`);
},
destroy: asyncId => {
// Remove items for destroyed async contexts.
this.items.delete(asyncId);
if (this.options.trace) fs.writeSync(1, `--- DSTR: ${this.items.size} items ---\n`);
},
}).enable();
}
}
export interface Options {
trace: boolean;
}
const DEFAULT_OPTIONS: Options = {trace: false};
<file_sep>/examples/ex1.ts
// TODO: temp testing... remove...
// tslint:disable:no-console
import monotask from 'monotask';
// Create a new task queue. `mono` is a wrapper used to mark functions that will be part of this queue.
let mono = monotask.create();
// An ordinary async function that does some kind of work.
function asyncWork(name: string, duration: number) {
return new Promise(resolve => {
console.log(`Enter ${name}`);
setTimeout(() => {
console.log(`Leave ${name}`);
resolve();
}, duration);
});
}
// A wrapped version of the `asyncWork` function that only allows serialised execution.
const serialWork = mono(asyncWork);
// The main test code
(async function main() {
// Test normal (unserialised) behaviour for comparison
console.log('\n===== Not serialised =====');
await Promise.all([
asyncWork('Task 1', 50),
asyncWork('Task 2', 40),
asyncWork('Task 3', 50),
asyncWork('Task 4', 30),
]);
// Test serialised behaviour
console.log('\n===== Serialised =====');
await Promise.all([
serialWork('Task 1', 50),
serialWork('Task 2', 40),
serialWork('Task 3', 50),
serialWork('Task 4', 30),
]);
})();
// Output:
// ===== Not serialised =====
// Enter Task 1
// Enter Task 2
// Enter Task 3
// Enter Task 4
// Leave Task 4
// Leave Task 2
// Leave Task 1
// Leave Task 3
//
// ===== Serialised =====
// Enter Task 1
// Leave Task 1
// Enter Task 2
// Leave Task 2
// Enter Task 3
// Leave Task 3
// Enter Task 4
// Leave Task 4
<file_sep>/examples/ex2.ts
// TODO: temp testing... remove...
// tslint:disable:no-shadowed-variable
// tslint:disable:no-console
import monotask from 'monotask';
function wrap2(fn: Function) {
return mono(async (...args: any[]) => {
++depth;
let indent = ' '.repeat(depth - 1);
console.log(`${indent}ENTER ${fn.name}`);
let result = await fn(...args);
console.log(`${indent}LEAVE ${fn.name}`);
--depth;
return result;
});
}
let depth = 0;
let mono = monotask.create();
async function primary() {
await foo();
await bar();
await baz();
await Promise.all([
baz(),
foo(),
bar(),
bar(),
foo(),
]);
await baz();
}
const foo = wrap2(async function foo() {
await delay(10);
const foo1 = wrap2(async function foo1() {
await delay(20);
});
const foo2 = wrap2(async function foo2() {
await delay(30);
});
await Promise.all([foo2(), foo1()]);
await delay(10);
});
const bar = wrap2(async function bar() {
await delay(30);
});
const baz = wrap2(async function baz() {
await delay(40);
});
async function secondary() {
await Promise.all([
blah(),
quux(),
quux(),
]);
}
const quux = wrap2(async function quux() {
await delay(10);
const quux1 = wrap2(async function quux1() {
await delay(20);
});
const quux2 = wrap2(async function quux2() {
await delay(30);
});
await Promise.all([quux2(), quux1()]);
await delay(10);
});
const blah = wrap2(async function blah() {
await delay(30);
});
(async function main() {
let p = primary();
await delay(15);
let s = secondary();
await Promise.all([p, s]);
})();
function delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
<file_sep>/README.md
## Monotask
`monotask` provides a simple way to mark selected asynchronous functions as tasks belonging to a task queue. Calls to
such functions are automatically serialised so that they execute strictly one-at-a-time. Tasks within a task queue may
also call other tasks in a nested manner, in which case the behaviour is exactly like that of nested synchronous
function calls. That is, the outer task is suspended until the subtask completes, and then the outer task resumes.
An example use case is ensuring that commands in a CQRS system can only run one-at-a-time, while still allowing commands
to: (a) be ordinary functions, which clients call in an ordinary manner; (b) execute asynchronously, for example
querying a database as part of command validation; and (c) call other commands in a nested manner.
## Installation
```
npm install monotask
```
## Example Usage
```ts
import monotask from 'monotask';
// Create a new task queue. `mono` is a wrapper used to mark functions that will be part of this queue.
let mono = monotask.create();
// An ordinary async function that does some kind of work.
function asyncWork(name: string, duration: number) {
return new Promise(resolve => {
console.log(`Enter ${name}`);
setTimeout(() => {
console.log(`Leave ${name}`);
resolve();
}, duration);
});
}
// A wrapped version of the `asyncWork` function that only allows serialised execution.
const serialWork = mono(asyncWork);
// The main test code
(async function main() {
// Test normal (unserialised) behaviour for comparison
console.log('\n===== Not serialised =====');
await Promise.all([
asyncWork('Task 1', 50),
asyncWork('Task 2', 40),
asyncWork('Task 3', 50),
asyncWork('Task 4', 30),
]);
// Test serialised behaviour
console.log('\n===== Serialised =====');
await Promise.all([
serialWork('Task 1', 50),
serialWork('Task 2', 40),
serialWork('Task 3', 50),
serialWork('Task 4', 30),
]);
})();
// Output:
// ===== Not serialised =====
// Enter Task 1
// Enter Task 2
// Enter Task 3
// Enter Task 4
// Leave Task 4
// Leave Task 2
// Leave Task 1
// Leave Task 3
//
// ===== Serialised =====
// Enter Task 1
// Leave Task 1
// Enter Task 2
// Leave Task 2
// Enter Task 3
// Leave Task 3
// Enter Task 4
// Leave Task 4
```
## Remarks
- requires node v8.1 or above (due to dependence on `async_hooks` module).
- TypeScript declarations included
- assumes tasks don't return before they complete. E.g. the following task violates this assumption:
```ts
async function badTask() {
await doStuff(); // good
setTimeout(doStuffAfterReturn, 50); // bad
return;
}
```
| beb1a73aa5aef25b61d0213f5f42cb21c4dddb70 | [
"Markdown",
"TypeScript"
] | 6 | TypeScript | yortus/monotask | b8c8ac2d7a03f3f20f4865fbc4af02c5884345f5 | 8a386600cb8c49c5bd9517a05234a9aa4079c746 |
refs/heads/master | <file_sep>/*
export function someMutation (state) {
}
*/
// export const updateMessage = (state, payload) => {
// state.nav_message = payload
// }
// export const updateActiveLetters = (state, payload) => {
// state.active_letters = payload
// }
export const setLanguage = (state, payload) => {
state.language = payload
}
export const setItemKey = (state, payload) => {
state.itemKey = payload
}
<file_sep># linguisti
> Language Learning App
https://jpperlm.github.io/Blocks/
<file_sep>import Vue from 'vue'
import Router from 'vue-router'
import Splash from '@/components/Splash'
Vue.use(Router)
export default new Router({
// eslint-disable-next-line no-extra-boolean-cast
mode: window.location.href.includes('index.html') ? '' : 'history',
base: process.env.NODE_ENV === 'production'
? '/Blocks/'
: '/',
routes: [
{
path: '*',
name: 'Splash',
component: Splash
},
]
})
| df414f1bb6f372368480845f2b597f84ec6d362e | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | jpperlm/Blocks | 238702fa51a5ea6065a1ded213fd75b836bdd670 | 194748217895d973e5bcd95cd8f1b72b1bc93b09 |
refs/heads/master | <repo_name>powellquiring/bigimage<file_sep>/cfm/cformation/master.py
#!/usr/bin/python
from troposphere import (
GetAtt, Join, Output,
Parameter, Ref, Template, FindInMap
)
from troposphere.cloudformation import Stack
from awacs.aws import Allow, Statement, Action, Principal, Policy
from awacs.sts import AssumeRole
import firehose
import elasticsearch
import ingest
import cfnhelper
import codepipeline
import api_lambda
INGEST = True
ELASTICSEARCH = True
FIREHOSE = True
CODEPIPELINE = True
API_LAMBDA = True
def id():
return 'master.cfn.json'
def template(stackName='bigimage'):
'generate a template for this stack'
t = Template()
t.add_version()
t.add_description("bigImage master which calls out to child templates: Ingest, Elasticsearch, Firehose, ...")
templateBucket = t.add_parameter(Parameter(
'TemplateBucket',
Type='String',
Description='Bucket containing all of the templates for this stack, https address, example: https://s3-us-west-2.amazonaws.com/home433331399117/master.cfn.json'
))
codeBucket = t.add_parameter(Parameter(
'CodeBucket',
Type='String',
Description='Bucket containing all of the templates for this stack, simple bucket name, example: elasticbeanstalk-us-west-2-433331399117'
))
gitPersonalAccessToken = t.add_parameter(Parameter(
'GitPersonalAccessToken',
Type='String',
Description='Git personal access token required for codepipeline'
))
if ELASTICSEARCH:
elasticsearchStack = t.add_resource(Stack(
'ElasticsearchStack',
TemplateURL=Join('/', [Ref(templateBucket), elasticsearch.id()]),
))
# propogate all outputs from the firehose template
cfnhelper.propogateNestedStackOutputs(t, elasticsearchStack, elasticsearch.template(), "Elasticsearch")
if FIREHOSE:
firehoseStack = t.add_resource(Stack(
'FirehoseStack',
TemplateURL=Join('/', [Ref(templateBucket), firehose.id()]),
Parameters={'DomainArn': GetAtt(elasticsearchStack, "Outputs.DomainArn")},
))
# propogate all outputs from the firehose template
cfnhelper.propogateNestedStackOutputs(t, firehoseStack, firehose.template(), "Firehose")
if INGEST:
ingestStack = t.add_resource(Stack(
'IngestStack',
TemplateURL=Join('/', [Ref(templateBucket), ingest.id()]),
Parameters={
'CodeBucket': Ref(codeBucket),
'DeliveryStreamName': GetAtt(firehoseStack, "Outputs.DeliveryStreamName"),
},
))
# propogate all outputs from the firehose template
cfnhelper.propogateNestedStackOutputs(t, ingestStack, ingest.template(), "Ingest")
if API_LAMBDA:
apiStack = t.add_resource(Stack(
'ApiStack',
TemplateURL=Join('/', [Ref(templateBucket), api_lambda.id()]),
))
cfnhelper.propogateNestedStackOutputs(t, apiStack, api_lambda.template(), "External")
if CODEPIPELINE:
codepipelineStack = t.add_resource(Stack(
'CodepipelineStack',
TemplateURL=Join('/', [Ref(templateBucket), codepipeline.id()]),
Parameters={
'ExternalApiEndpointkeyword': GetAtt(apiStack, "Outputs.ApiEndpointkeyword"),
'IngestApplicationName': GetAtt(ingestStack, "Outputs.ApplicationName"),
'IngestEnvironmentName': GetAtt(ingestStack, "Outputs.EnvironmentName"),
'GitPersonalAccessToken': Ref(gitPersonalAccessToken),
},
))
cfnhelper.propogateNestedStackOutputs(t, codepipelineStack, codepipeline.template(), "Codepipeline")
return t
if __name__ == "__main__":
print(template('foo').to_json())
<file_sep>/cfm/cformation/api_lambda.py
#!/usr/bin/python
from troposphere import Template, Parameter, Ref, Output, Join, Tags, GetAtt, AWS_REGION
from troposphere.iam import Role
from troposphere.iam import PolicyType as IAMPolicy
from troposphere.iam import Policy as TropospherePolicy
from awacs.aws import Allow, Statement, Action, Principal, Policy
from awacs.sts import AssumeRole
from troposphere_early_release.awslambda import Environment, Function, Code
from troposphere.apigateway import RestApi, Method
from troposphere.apigateway import Resource, MethodResponse
from troposphere.apigateway import Integration, IntegrationResponse
from troposphere.apigateway import Deployment, StageDescription, MethodSetting
from troposphere.apigateway import ApiKey, StageKey
import os
import cfnhelper
REST_API = True # can turn off for testing
STAGE_NAME = 'v1'
def id():
return 'api_lambda.cfn.json'
def fileAsString(fileName):
'Return the string that is in a sibling file'
cwd = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
with open(os.path.join(cwd, fileName), 'r') as myfile:
ret=myfile.read()
return ret
def jsonFunctionStringApiGatewayMapping():
return fileAsString('api_gateway_mapping.json')
def lambdaFunctionKeyword():
return fileAsString('lambda_keyword.py')
def template(stackName='bigimage'):
t = Template()
t.add_version('2010-09-09')
t.add_description('api gateway connected to the lambda functions that read stuff like elasticsearch')
# lambda function ----------------------------------------------------------
# must be parameters
elasticsearchUrl = 'https://search-bigimage-2gtgp2nq3ztfednwgnd6ma626i.us-west-2.es.amazonaws.com'
elasticsearchIndex = 'indexname'
# could be parameters
memorySize = '128'
timeout = '60'
# join these two together to make region specific access to lambda functions at stack creation time
# for example (notice us-west-2) arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions
apiGateway = "arn:aws:apigateway"
apiLambda = "lambda:path/2015-03-31/functions"
lambdaFunctionsJoin = Join(":", [apiGateway, Ref(AWS_REGION), apiLambda])
# read the lambda function from a file
codeString=lambdaFunctionKeyword()
apiRequestTemplateString=jsonFunctionStringApiGatewayMapping()
####### delete me end
# Create the role with a trust relationship that allows lambda or the api gateway to assume the role
lambdaExecutionRole = t.add_resource(Role(
"LambdaExecutionRole",
AssumeRolePolicyDocument=Policy(
Version="2012-10-17",
Statement=[
Statement(
Effect=Allow,
Action=[AssumeRole],
Principal=Principal(
"Service", [
'lambda.amazonaws.com',
'apigateway.amazonaws.com',
]
)
)
]
),
Path="/",
Policies=[TropospherePolicy(
"LambdaExecutionPolicy",
PolicyName="LambdaExecutionPolicy",
PolicyDocument=Policy(
Statement=[
Statement(
Effect=Allow,
NotAction=Action("iam", "*"),
Resource=["*"],),
]
),
)],
))
keywordFunction = t.add_resource(Function(
"KeywordFunction",
Code=Code(
ZipFile=codeString
),
Description='convert word parameter to keywords, pull the records with the keywords from elasticsearch',
Environment=Environment(Variables={
'ELASTICSEARCH_URL': elasticsearchUrl,
'ELASTICSEARCH_INDEX': elasticsearchIndex,
}),
#FunctionName=generated
Handler="index.lambda_handler",
Role=GetAtt(lambdaExecutionRole, "Arn"),
Runtime="python2.7",
MemorySize=memorySize,
Timeout=timeout,
))
# Create an HTTP GET rest api method for the keywordFunction Lambda resource
uri=Join("/", [
lambdaFunctionsJoin,
GetAtt(keywordFunction, "Arn"),
'invocations', # TODO why isn't this pathPart=keyword?
])
# api gateway ----------------------------------------------------------
if REST_API:
# Create the Api Gateway
rest_api = t.add_resource(RestApi(
stackName + "restapi",
Name=stackName + "restapi",
))
# Create the api resource (.ie a path) /keyword
pathPart = 'keyword'
resource = t.add_resource(Resource(
"KeywordSearchResource",
RestApiId=Ref(rest_api),
PathPart=pathPart,
ParentId=GetAtt(rest_api, "RootResourceId"), # / is created when the RestApi is added
))
methodRequestQuerystringWord = 'method.request.querystring.word'
restApiKeywordGetMethod = t.add_resource(Method(
"KeywordGET",
ApiKeyRequired=False,
AuthorizationType="NONE",
#AuthorizerId
DependsOn=keywordFunction.name, # not part of the API?
HttpMethod="GET",
RequestParameters={
methodRequestQuerystringWord: True,
},
RestApiId=Ref(rest_api),
ResourceId=Ref(resource),
Integration=Integration(
CacheKeyParameters=[methodRequestQuerystringWord],
Credentials=GetAtt(lambdaExecutionRole, "Arn"),
Type="AWS_PROXY",
IntegrationHttpMethod='POST', #TODO changed from GET
IntegrationResponses=[
IntegrationResponse(
#ResponseTemplates={ #TODO added
# "application/json": None # null not allowed
#},
StatusCode='200'
),
],
PassthroughBehavior='WHEN_NO_MATCH', # TODO specified default
RequestTemplates={'application/json': apiRequestTemplateString},
Uri=uri,
),
MethodResponses=[
MethodResponse(
ResponseModels={"application/json": "Empty"},
StatusCode='200'
)
],
))
# Create a deployment
deployment = t.add_resource(Deployment(
"%sDeployment" % STAGE_NAME,
DependsOn=restApiKeywordGetMethod.name,
RestApiId=Ref(rest_api),
StageDescription=StageDescription(
CacheClusterEnabled=True, # : (bool, False),
CacheClusterSize="0.5", # : (basestring, False),
CacheDataEncrypted=False, # : (bool, False),
#CacheTtlInSeconds=30, # : (positive_integer, False),
#CachingEnabled=True, # : (bool, False),
#ClientCertificateId= : (basestring, False),
#DataTraceEnabled=False, # : (bool, False),
Description="Cached stage ttl=30, cache size = 0.5G", # : (basestring, False),
#LoggingLevel= : (basestring, False),
MethodSettings=[MethodSetting(
#CacheDataEncrypted=False, #: (bool, False),
CacheTtlInSeconds=30, #": (positive_integer, False),
CachingEnabled=True, #": (bool, False),
#DataTraceEnabled= False, #": (bool, False),
HttpMethod='*', # : (basestring, True),
#LoggingLevel= "OFF", #: (basestring, False),
#MetricsEnabled=False, # : (bool, False),
ResourcePath='/*', # : (basestring, True),
#ThrottlingBurstLimit=2000, # : (positive_integer, False),
#ThrottlingRateLimit=1000, # : (positive_integer, False)
)],
MetricsEnabled=False, # : (bool, False),
StageName=STAGE_NAME, # : (basestring, False),
#ThrottlingBurstLimit= : (positive_integer, False),
#ThrottlingRateLimit= : (positive_integer, False),
#Variables= : (dict, False)
),
StageName=STAGE_NAME
))
#key = t.add_resource(ApiKey(
# "ApiKey",
# StageKeys=[StageKey(
# RestApiId=Ref(rest_api),
# StageName=STAGE_NAME
# )]
#))
# Add the deployment endpoint as an output
outputs = []
if REST_API:
outputs.append(Output(
"ApiEndpoint" + pathPart,
Value=Join("", [
"https://",
Ref(rest_api),
".execute-api.",
Ref(AWS_REGION),
".amazonaws.com/",
STAGE_NAME,
"/",
pathPart,
]),
Description="Endpoint for this stage of the api"
))
outputs.append(Output(
"LambdaEndpoint",
Value=uri,
Description="Lambda calculated endpoint"
))
t.add_output(outputs)
return t
if __name__ == "__main__":
print(template().to_json())
<file_sep>/cfm/cformation/lambda_keyword.py
import json
import os
import urllib2
import time
print('Loading elasticsearch keyword function')
#ELASTICSEARCH_URL = "https://search-bigimage-2gtgp2nq3ztfednwgnd6ma626i.us-west-2.es.amazonaws.com"
ELASTICSEARCH_URL = os.environ['ELASTICSEARCH_URL']
def extractImages(tweet):
'return a list of some of the images in a tweet'
ret = []
for media in tweet.get('_source', {}).get('entities', {}).get('media', {}):
for key in ['media_url', 'media_url_https']:
if key in media:
ret.append(media[key])
return ret
def extractVideos(tweet):
'return a list of videos of the images in a tweet'
ret = []
for media in tweet.get('_source', {}).get('extended_entities', {}).get('media', {}):
for variant in media.get('video_info', {}).get('variants', {}):
ret.append(variant)
return ret
def condensedTweets(word):
urlString = ELASTICSEARCH_URL + '/indexname/_search'
data = {
"query": {
"query_string" : {
"query":word,
"analyze_wildcard":True
}
}
}
request = urllib2.Request(urlString, json.dumps(data))
f = urllib2.urlopen(request)
resultString = f.read()
result = json.loads(resultString)
ret=[]
allTweets=[]
for tweet in result['hits']['hits']:
allTweets.append(tweet)
tweetEntry = {}
tweetEntry['text'] = tweet['_source']['text']
id = tweet['_source']['id']
tweetEntry['url'] = 'https://twitter.com/_/status/' + str(id)
tweetEntry['videos'] = extractVideos(tweet)
tweetEntry['images'] = extractImages(tweet)
ret.append(tweetEntry)
return {'ret': ret, 'tweets': allTweets}
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
SLEEP = 5
print("TODO leeping seconds:", SLEEP)
time.sleep(SLEEP)
context_vars = dict(vars(context))
keys = list(context_vars.keys())
queryStringParameters = event.get('queryStringParameters', {})
if queryStringParameters is None:
queryStringParameters = {}
word = queryStringParameters.get('word', 'coffee')
tweets = condensedTweets(word)
for key in keys:
try:
json.dumps(context_vars[key])
except:
print('delete:', key)
context_vars.pop(key)
body = json.dumps({'ret':tweets, 'version': '2.2', '~environ': dict(os.environ), '~event': event, '~context': context_vars})
ret = {
"statusCode": 200,
"headers": { "Access-Control-Allow-Origin": "*"},
"body": body,
}
return ret
<file_sep>/python-v1/application/requirements.txt
boto==2.44.0
boto3==1.4.2
botocore==1.4.87
click==6.6
docutils==0.13.1
Flask==0.11.1
futures==3.0.5
itsdangerous==0.24
Jinja2==2.8
jmespath==0.9.0
MarkupSafe==0.23
oauthlib==2.0.1
python-dateutil==2.6.0
requests==2.12.4
requests-oauthlib==0.7.0
s3transfer==0.1.10
six==1.10.0
tweepy==3.5.0
Werkzeug==0.11.11
<file_sep>/cfm/requirements.txt
awacs==0.6.0
boto3==1.4.3
botocore==1.4.91
docutils==0.13.1
futures==3.0.5
jmespath==0.9.0
python-dateutil==2.6.0
s3transfer==0.1.10
six==1.10.0
troposphere==1.9.0
<file_sep>/cfm/sourceme
#!/bin/bash
source .env/bin/activate
<file_sep>/browser/build.bash
#!/bin/bash
set -ex
env
ls -l
npm install -g create-react-app
npm install
npm run build
cd build
ls -l
aws s3 rm s3://$BROWSER_S3_REF --recursive
aws s3 cp . s3://$BROWSER_S3_REF --recursive
<file_sep>/python-v1/application/application.py
#!/usr/bin/env python
VERSION = "2.6"
# To work the following environment variables must be set:
# * StackName - twitter credentials are stored in the the aws system manager parameter store prefixed by this name (see TWITTER_VARIABLES)
# * DeliveryStreamName - firehose delivery stream name
#
# The aws system manager parameter store must have the StackName prefixed secure string values
# identified in TWITTER_VARIABLES below: $StackName_TWITTER_CONSUMER_KEY, like bigimage_TWITTER_CONSUMER_KEY for example
from flask import Flask, jsonify
import boto.utils
import boto3
import os
import threading, time
import requests
import sys
from pprint import pprint
TWITTER_VARIABLES = ['TWITTER_CONSUMER_KEY', 'TWITTER_CONSUMER_SECRET', 'TWITTER_ACCESS_TOKEN', 'TWITTER_ACCESS_SECRET']
firehose = boto3.client('firehose')
application = Flask(__name__)
main = True
STACK_NAME = os.environ.get('StackName')
if STACK_NAME is None:
print "StackName not in environment, quitting"
quit()
print "STACK_NAME:", STACK_NAME
DELIVERY_STREAM_NAME = os.environ.get('DeliveryStreamName')
if DELIVERY_STREAM_NAME is None:
print "DeliveryStreamName not in environment, quitting"
quit()
print "DELIVERY_STREAM_NAME:", DELIVERY_STREAM_NAME
fetchedStreams = firehose.list_delivery_streams()
print "firehose streams:", fetchedStreams
fetchedStreamNames = fetchedStreams['DeliveryStreamNames']
if not (DELIVERY_STREAM_NAME in fetchedStreamNames):
print "Delivery stream not found, looking for:", DELIVERY_STREAM_NAME
print "Existing stream names:", fetchedStreamNames
quit()
def stackName(name):
"turn a environment variable name into a stack specific name"
return STACK_NAME + "_" + name
def namedTwitterVariables():
"return the stack named twitter variables"
ret = []
for name in TWITTER_VARIABLES:
ret.append(stackName(name))
return ret
def verifyTwitterCreds():
"veriy that all of the twitter variables for this stack exist"
stackNameValue={}
names = namedTwitterVariables()
ssm = boto3.client('ssm')
ret = ssm.get_parameters(Names=names, WithDecryption=True)
parameters = ret[u'Parameters']
for parameter in parameters:
print("found name:", parameter['Name'])
stackNameValue[parameter['Name']] = parameter['Value']
invalidParameters = ret['InvalidParameters']
if len(invalidParameters) > 0:
print("ERROR: missing the following aws secure string, system manager, parameter store, parameters:", str(invalidParameters))
quit()
return stackNameValue
def isAws():
'Return True if the program is running on an ec2 instance'
ret = False
try:
with open("/sys/hypervisor/uuid") as f:
c = f.read(3)
if c == "ec2":
ret = True
finally:
return ret
def metadata():
'Return the metadata dictionary or the string "none" if there is no metadata'
if isAws():
return boto.utils.get_instance_metadata()
else:
return "none"
jsonArray = [
{
'metadata': metadata()
}
]
tweetCount = 0
@application.route('/', defaults={'path': '/'}, methods=['GET'])
@application.route('/<path:path>', methods=['GET'])
def dump(path):
return jsonify({'~env': dict(os.environ), '~metadata': jsonArray, '~errorStatus': errorStatuses, 'tweetCount': tweetCount, 'env StackName': STACK_NAME, 'env DeliveryStreamName': DELIVERY_STREAM_NAME, 'path': path, 'main': main, 'version': VERSION})
##################### twitter ###################
import tweepy
from tweepy import Stream
from tweepy.streaming import StreamListener
import json
from threading import Thread
# override _start to fix <control>-C
class MyStream(Stream):
def _start(self, async):
print "MyListener, _start"
self.running = True
if async:
self._thread = Thread(target=self._run)
self._thread.daemon = True # this is the only change I want to make so that <contro>-C works
self._thread.start()
else:
self._run()
errorStatuses=[]
def logErrorStatus(status):
try:
# verify that it can be encoded as json
json.dumps(status)
except:
# not json
print "logErrorStatus", {'type': str(type(status)), 'value': str(status)}
errorStatuses.insert(0, {'type': str(type(status)), 'value': str(status)})
else:
print "logErrorStatus", status
errorStatuses.insert(0, status)
def process_status_firehose(status):
js = process_status(status)
ret = firehose.put_record(DeliveryStreamName=DELIVERY_STREAM_NAME, Record={'Data': js})
print "ret:", ret
return ret
def process_status(status):
print type(status)
j = json.loads(status)
js = json.dumps(j) + "\n"
newstatus = json.loads(js)
print json.dumps(newstatus, indent=4, sort_keys=True)
return js
def process_friend(friend):
#pprint(vars(friend))
print friend.name, friend.screen_name
class MyListener(StreamListener):
def on_data(self, data):
global tweetCount
tweetCount += 1
process_status_firehose(data)
return True
def on_error(self, status):
print("Error, status:", status)
logErrorStatus(status)
return True
stackNameValue = verifyTwitterCreds()
auth = tweepy.OAuthHandler(stackNameValue[stackName('TWITTER_CONSUMER_KEY')], stackNameValue[stackName('TWITTER_CONSUMER_SECRET')])
auth.set_access_token(stackNameValue[stackName('TWITTER_ACCESS_TOKEN')], stackNameValue[stackName('TWITTER_ACCESS_SECRET')])
api = tweepy.API(auth)
def testingTweepy():
# Iterate through all of the authenticated user's friends
for friend in tweepy.Cursor(api.friends).items():
# Process the friend here
process_friend(friend)
# Iterate through the first 200 statuses in the friends timeline
for status in tweepy.Cursor(api.home_timeline).items(100):
# Process the status here
process_status(status)
twitter_stream = MyStream(auth, MyListener())
tracks = [
'#peoplewhomademy2016',
]
follows = [
'@powellquiring',
]
def handleTwitter():
while True:
try:
#twitter_stream.filter(track=tracks, async=True)
#twitter_stream.filter(follow=follows, async=True)
print "handleTwitter userstream"
twitter_stream.userstream(_with='following')
except requests.exceptions.ConnectionError as ex:
print "twitter userstream ConnectionError exception:", ex
logErrorStatus(ex)
except Exception as ex:
print "twitter userstream Exception, type:", type(ex), "exception:", ex
logErrorStatus(ex)
except:
ex = sys.exc_info()[0]
print "twitter userstream unexpected, type:", type(ex), "exception:", ex
logErrorStatus(ex)
time.sleep(5)
##################### twitter start ###################
t = threading.Thread(target=handleTwitter)
t.daemon = True
t.start()
##################### application start ###################
if __name__ == '__main__':
application.run()
else:
main = False
<file_sep>/cfm/cformation/cfnhelper.py
from troposphere import Output, GetAtt, Join, Ref
STAGE = 'prod'
def propogateNestedStackOutputs(t, nestedStack, nestedTemplate, prefixString):
'propoage all fo the ouptuts of the nestedStack assuming they were provided by the nestedTemplate'
for k in nestedTemplate.outputs:
output = nestedTemplate.outputs[k]
t.add_output(Output(
prefixString + k,
Description=output.Description,
Value=GetAtt(nestedStack, "Outputs." + k),
))
def s3BucketArn(bucketReference):
return Join("", ["arn:aws:s3:::", Ref(bucketReference)])
<file_sep>/ibm/README.md
# ibm blue mix
Experience with bluemix
## template
No infrastructure as code templates.
It is required that I write a script to create/destroy/change infrastructure by hand
### python script
Search: aws python api for provisioning services.
Top hit: boto3 - I used this on aws, it worked great.
Search: ibm bluemix python api for provisioning services.
Hits: cloud foundry apps written in python. No provisioning support.
Bummer
### shell script
cf api https://api.ng.bluemix.net
cf login
cf create-service compose-for-elasticsearch Standard my-compose-for-elasticsearch-service
cf bind-service compose-elasticsearch-helloworld-nodejs my-compose-for-elasticsearch-service
failed to provision ES
cf dsk -f bigimage-messagehub creds
cf ds -f bigimage-messagehub
bx service create messagehub standard bigimage-messagehub
cf csk bigimage-messagehub creds
cf delete -f bigimage-ingest
cf delete-orphaned-routes -f
cd ibm/ingest
cf push; # will fail, keep going
~/thhatwitter.bash bigimage-ingest
cf push
cf logs --recent bigimage-ingest
cf map-route bigimage-ingest mybluemix.net --hostname bigimage-ingest
open https://bigimage-ingest.mybluemix.net
https://developer.ibm.com/messaging/2016/12/05/updated-message-hub-samples/ - blog post on nodejs usage
# Details
Provisioned using the docs here and it failed: https://github.com/IBM-Bluemix/compose-elasticsearch-helloworld-nodejs
Opened the ticket, got email from "softlayer". What is softlayer? I was using Bluemix.
There are two featured links in the provisioned message hub service:
* Message Connect that was deleted a month ago.
* Streaming analytics that requires a VMWare image to demonstrate (are you kidding me)
Why are there two command lines: bx and cf with overlapping functionality? This is making the system harder to learn.
host name is truncated by the cf routes command - can not delete it
cf routes
Getting routes for org <EMAIL> / space Powell as <EMAIL> ...
space host domain port path type apps service
Powell message-hub-chat-setaceous-qt mybluemix.net
~/work/github.com/powellquiring/bigimage/ibm/ingest$ cf dsk -f 'Compose for Elasticsearch-83' 'Credentials-1'
Deleting key Credentials-1 for service instance Compose for Elasticsearch-83 as <EMAIL>...
OK
Service instance Compose for Elasticsearch-83 does not exist.
~/work/github.com/powellquiring/bigimage/ibm/ingest$ cf s
Getting services in org <EMAIL> / space Powell as <EMAIL>...
OK
name service plan bound apps last operation
Compose for Elasticsearch-7c compose-for-elasticsearch Standard create succeeded
Compose for Elasticsearch-83 compose-for-elasticsearch Standard create succeeded
Compose for MongoDB-ps compose-for-mongodb Standard create succeeded
~/work/github.com/powellquiring/bigimage/ibm/ingest$ cf ds -f 'Compose for Elasticsearch-83'
Deleting service Compose for Elasticsearch-83 in org <EMAIL> / space Powell as <EMAIL>...
FAILED
Cannot delete service instance, service keys and bindings must first be deleted
~/work/github.com/powellquiring/bigimage/ibm/ingest$
<file_sep>/python-v1/build/build.py
from os import path
import glob
import zipfile
import os
import sys
import hashlib
def globbed_files(dir):
"must be a glob.txt file in this dir"
with open(path.join(dir, 'glob.txt')) as f:
lines = f.read().splitlines()
# add all of the globbed entries to the files set (unique)
files = set()
for g in lines:
files_in_glob = glob.glob(path.join(dir, g))
files |= set(files_in_glob)
return sorted(files)
def hash_zip_file(zip_file_name):
# BUF_SIZE is totally arbitrary, change for your app!
BUF_SIZE = 65536 # lets read stuff in 64kb chunks!
sha1 = hashlib.sha1()
zip = zipfile.ZipFile(zip_file_name, "r")
for name in zip.namelist():
data = zip.read(name)
sha1.update(data)
zip.close()
return sha1.hexdigest()
def zip_file_add_comment(zip_file_name, comment):
"add a comment to zip file"
zip = zipfile.ZipFile(zip_file_name, "a")
zip.comment = comment
zip.close()
def zip_file_remove_comment(zip_file_name):
"add a comment to zip file"
zip = zipfile.ZipFile(zip_file_name, "a")
zip.comment = ""
zip.close()
def build(zip_file_name):
'build the application and store it in zip_file_name return the hash based on the file contents (not the comment)'
build_dir = path.dirname(path.realpath(__file__)) # my directory is the build directory
root_dir = path.dirname(build_dir) # root contains root/build (build_dir) and root/application
application_dir = path.join(root_dir, 'application')
files = globbed_files(application_dir)
zip = zipfile.ZipFile(zip_file_name, "w")
zip.comment = ""
for f in files:
zip_name = path.relpath(f, application_dir)
if path.isfile(f):
zip.write(f, zip_name)
zip.close()
hash = hash_zip_file(zip_file_name)
zip_file_add_comment(zip_file_name, "the comment")
zip_file_remove_comment(zip_file_name)
return hash
<file_sep>/README.md
# bigimage - big data image processing
Read the ppt slide deck that describes the applicaion in a lot of detail with some pictures. In Summary:
* Twitter and git credential secrets need to be kept securely.
Set the following environment variables and execute: aws/run.py -creds
* TWITTER_CONSUMER_KEY
* TWITTER_CONSUMER_SECRET
* TWITTER_ACCESS_TOKEN
* TWITTER_ACCESS_SECRET
* GIT_PERSONAL_ACCESS_TOKEN
* A run script that will create the infrastructure utilizing the teamplate mechanism for the cloud provider (cfm/run.py)
* In aws open cloudeformation see the stacks created, the main stack has the default name: bigimage
* Delete the main stack at any time to delete most resources, s3 buckets are configured not to be deleted (non empty s3 buckets will fail to delete by cformation)
* see the output section of the main cloudformation stack, See the kibana link for elastisearch, ingestURL for the twitter reader, and the CodepipelineBrowserS3WebsiteUrl for the application
* An automated build system (codepipeline steps that call out to codebuild actions) any future updates to the github project will re-build.
For example change the file python-v1/application/application.py VERSION string and take a look at the ingestURL.
* Tweet reader python program (python-v1) that reads tweets and writes into a pipe in bursts that would exceed capacity directly writing to elasticsearch
* Drain the pipe into elasticsearch
* A curl command like the following would retrieve data from elastic search after the index is created (
curl -XGET 'https://search-bigimage-2gtgp2nq3ztfednwgnd6ma626i.us-west-2.es.amazonaws.com/indexname/_search?pretty' -d'
{
"query": {
"query_string" : {
"query":"sous",
"analyze_wildcard":true
}
}
}'
# Restricting access to credentials
The above credentials are only accessible to those that have access to my aws account.
If the account is used for a project with lots of users then all the users would have access to the creds.
I ran the following test to verify that the --key-id parameter could be used to restrict access to a smaller set of users by using IAM policies.
A role assigned to the twitter ingest app would need to have access to the kms key as well.
Create a yesuser and nouser and give them ssm capabilities.
Created a kms key "deleteme" in us-west-2.
When creating the key give yesuser all of the capabilities to use the key (nouser gets nothing)
The arn is included in the commands below
Test creating with yes user and get with yesuser and no user. nouser should have access:
aws ssm put-parameter --name nokey --value secret --type SecureString
aws ssm get-parameters --names nokey --with-decryption
Test again using the --key-id arn that only the yesuser has access and verify that the nouser can not get to this key:
aws ssm put-parameter --name yeskey --value secret2 --type SecureString --key-id arn:aws:kms:us-west-2:433331399117:key/c92ffcf8-1d03-40ce-80ca-9ccf7f648ea2
aws ssm get-parameters --names yeskey --with-decryption
Create access keys for each user. Something like the following:
yesuser
export AWS_ACCESS_KEY_ID=<KEY>
export AWS_SECRET_ACCESS_KEY=<KEY>
PS1='yes $'
nouser
export AWS_ACCESS_KEY_ID=AKIAJOSHBLTHBTDQPSYA
export AWS_SECRET_ACCESS_KEY=<KEY>
PS1='no $'
<file_sep>/cfm/cformation/ingest.py
#!/usr/bin/python
from troposphere import (
GetAtt, Join, Output,
Parameter, Ref, Tags, Template, FindInMap
)
from troposphere.elasticbeanstalk import (
Application, ApplicationVersion, ConfigurationTemplate, Environment,
SourceBundle, OptionSettings
)
from troposphere.iam import Role, InstanceProfile
from troposphere.iam import PolicyType as IAMPolicy
from awacs.aws import Allow, Statement, Action, Principal, Policy
from awacs.sts import AssumeRole
import cfnhelper
AWS_DEFAULT_REGION = 'us-west-2'
VERSION = "_21" #TODO
# choose python or docker
BEANSTALK_DOCKER = False
def getBeanstalkEnvironment():
if BEANSTALK_DOCKER:
raise 'this has not been tested'
return {
'SolutionStackName': "64bit Amazon Linux 2016.09 v2.2.0 running Docker 1.11.2",
'Description': "Docker Elastic Beanstalk"
}
else:
return {
'SolutionStackName': "64bit Amazon Linux 2016.09 v2.2.0 running Python 2.7",
'Description': "Python Elastic Beanstalk"
}
def id():
return 'ingest.cfn.json'
def template(stackName='bigimage'):
'return the troposphere Template for the ingest beanstalk'
t = Template()
t.add_version()
t.add_description("twitter ingest template")
codeBucket = t.add_parameter(Parameter(
'CodeBucket',
Type='String',
Description='Bucket containing all of the templates for this stack, simple bucket name, example: elasticbeanstalk-us-west-2-433331399117'
))
keyname = t.add_parameter(Parameter(
"KeyName",
Description="Name of an existing EC2 KeyPair to enable SSH access to "
"the AWS Elastic Beanstalk instance",
Type="AWS::EC2::KeyPair::KeyName",
ConstraintDescription="must be the name of an existing EC2 KeyPair.",
Default="pics"
))
deliveryStreamName = t.add_parameter(Parameter(
"DeliveryStreamName",
Type='String',
Description="Firehose delivery stream name",
))
# Create the role with a trust relationship that allows an ec2 service to assume a role
role = t.add_resource(Role(
"IngestRole",
AssumeRolePolicyDocument=Policy(
Statement=[
Statement(
Effect=Allow, Action=[AssumeRole],
Principal=Principal(
"Service", [
'ec2.amazonaws.com'
]
)
)
]
),
Path="/",
))
# Add a policy directly to the role (a policy in the policy view is not created)
t.add_resource(IAMPolicy(
"IngestRolePolicy",
PolicyName="IngestRolePolicy",
PolicyDocument=Policy(
Statement=[
Statement(Effect=Allow, NotAction=Action("iam", "*"),
Resource=["*"])
]
),
Roles=[Ref(role)],
))
# Create an instance profile role that can be used to attach the embedded role to the ec2 instance
ec2InstanceProfile = t.add_resource(InstanceProfile(
"IngestInstanceProfile",
Path="/",
Roles=[Ref(role)],
))
# dynamically generated application name: stackname-IngestApplication-uid
ingestApplication = t.add_resource(Application(
"IngestApplication",
Description="Elasticbeanstalk based ingest application",
))
# dynamically generate aplication version: stackname-ingestapplicationversion-uid
ingestApplicationVersion = t.add_resource(ApplicationVersion(
"IngestApplicationVersion",
Description="Version 2.x",
ApplicationName=Ref(ingestApplication),
SourceBundle=SourceBundle(
S3Bucket=Ref(codeBucket),
S3Key="python-v1" + ".zip" #TODO kludge see similar kludge in run.py
#S3Key="python-v1" + VERSION + ".zip" #TODO kludge see similar kludge in run.py
),
))
# add an application with a dynamically generated application name, a ssh key, and the instance profile
ebEnvironment = getBeanstalkEnvironment()
ingestApplicationTemplate = t.add_resource(ConfigurationTemplate(
"IngestConfigurationTemplate",
Description="Template with dynamic generated name, " + ebEnvironment['Description'] + ", ssh access, and instance profile containing the IAM role",
ApplicationName=Ref(ingestApplication),
SolutionStackName=ebEnvironment['SolutionStackName'],
OptionSettings=[
OptionSettings(
Namespace="aws:autoscaling:launchconfiguration",
OptionName="EC2KeyName",
Value=Ref(keyname),
),
OptionSettings(
Namespace="aws:autoscaling:launchconfiguration",
OptionName="IamInstanceProfile",
Value=Ref(ec2InstanceProfile),
),
OptionSettings(
Namespace="aws:elasticbeanstalk:application:environment",
OptionName="DeliveryStreamName",
Value=Ref(deliveryStreamName),
),
OptionSettings(
Namespace="aws:elasticbeanstalk:application:environment",
OptionName="StackName",
Value=stackName,
),
OptionSettings(
Namespace="aws:elasticbeanstalk:application:environment",
OptionName="AWS_DEFAULT_REGION",
Value=AWS_DEFAULT_REGION,
),
],
))
# add the environment
ingestEnvironment = t.add_resource(Environment(
"IngestEnvironment",
Description="AWS Elastic Beanstalk Environment",
ApplicationName=Ref(ingestApplication),
TemplateName=Ref(ingestApplicationTemplate),
VersionLabel=Ref(ingestApplicationVersion),
Tags=Tags(stage=cfnhelper.STAGE),
))
# handle to the results
t.add_output(
Output(
"URL",
Description="URL of the AWS Elastic Beanstalk Environment",
Value=Join("", ["http://", GetAtt(ingestEnvironment, "EndpointURL")])
)
)
t.add_output(
Output(
"ApplicationName",
Description="ingest beanstalk application name",
Value=Ref(ingestApplication),
)
)
t.add_output(
Output(
"EnvironmentName",
Description="ingest beanstalk environment name",
Value=Ref(ingestEnvironment),
)
)
return t
if __name__ == "__main__":
print(template().to_json())
<file_sep>/python-v1/aftergitclone.sh
#!/bin/bash
set -ex
cd application
virtualenv --no-site-packages --distribute .env && source .env/bin/activate && pip install -r requirements.txt
<file_sep>/python-v1/build/makeawszip.sh
#!/bin/bash
if [ $# -ne 1 ]; then
echo supply the full qualified output file name without the .zip suffix like /tmp/foo to generate /tmp/foo.zip
exit 1
fi
# name can be in the cwd
NAME="$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
echo $NAME
# cd to the DIR that contains this shell script, the files are next to this shell script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR
# put everything into the provided name
set -x
zip $NAME cron.yaml application.py requirements.txt
unzip -lv $NAME
<file_sep>/cfm/cformation/troposphere_early_release/README.md
# troposphere_early_release 12/29/2016
Code build was just created and hasn't been distributed via pip
<file_sep>/cfm/cformation/elasticsearch.py
#!/usr/bin/env python
from troposphere import Template, constants, Output, GetAtt, Tags, Join
from troposphere.elasticsearch import Domain, EBSOptions
from troposphere.elasticsearch import ElasticsearchClusterConfig
from troposphere.elasticsearch import SnapshotOptions
# not sure how to parameterize...
INSTANCE_TYPE = constants.ELASTICSEARCH_T2_SMALL
INSTANCE_TYPE = constants.ELASTICSEARCH_T2_MICRO
import cfnhelper
def id():
return 'elasticsearch.cfn.json'
def template(stackName='bigimage'):
domainName = stackName
t = Template()
t.add_description('Elasticsearch for ' + stackName)
es_domain = t.add_resource(Domain(
stackName + 'ElasticsearchDomain',
AccessPolicies={'Version': '2012-10-17',
'Statement': [{
'Effect': 'Allow',
'Principal': {
'AWS': '*'
},
'Action': 'es:*',
'Resource': '*'
}]},
AdvancedOptions={"rest.action.multi.allow_explicit_index": "true"},
DomainName=domainName,
EBSOptions=EBSOptions(EBSEnabled=True,
Iops=0,
VolumeSize=10,
VolumeType="gp2"),
ElasticsearchClusterConfig=ElasticsearchClusterConfig(
DedicatedMasterEnabled=False,
InstanceCount=1,
ZoneAwarenessEnabled=False,
InstanceType=INSTANCE_TYPE
),
ElasticsearchVersion='2.3',
SnapshotOptions=SnapshotOptions(AutomatedSnapshotStartHour=0),
Tags=Tags(stage=cfnhelper.STAGE),
))
# handle to the results
t.add_output(
Output(
"DomainName",
Description="Domain name like: bigimage. Needed as an endpiont for elasticsearch configuration",
Value=domainName,
)
)
t.add_output(
Output(
"DomainArn",
Description="The Amazon Resource Name (ARN) of the domain, such as arn:aws:es:us-west-2:123456789012:domain/mystack-elasti-1ab2cdefghij",
Value=GetAtt(es_domain, "DomainArn"),
)
)
t.add_output(
Output(
"DomainEndpoint",
Description="The domain-specific endpoint that is used to submit index, search, and data upload requests to an Amazon ES domain, such as search-mystack-elasti-1ab2cdefghij-ab1c2deckoyb3hofw7wpqa3cm.us-west-2.es.amazonaws.com",
Value=GetAtt(es_domain, "DomainEndpoint"),
)
)
t.add_output(
Output(
"DomainURL",
Description="The https domain-specific endpoint",
Value=Join("/", ["https:/", GetAtt(es_domain, "DomainEndpoint")]),
)
)
t.add_output(
Output(
"KibanaURL",
Description="The Kibana endpoint",
Value=Join("/", ["https:/", GetAtt(es_domain, "DomainEndpoint"),"_plugin/kibana/"]),
)
)
return t
if __name__ == "__main__":
print(template().to_json())
<file_sep>/cfm/README.md
#cfm aws Cloudformation Templates
* cformation - python trophosphere implementation of cloudformation templates
* run.py - script to create a bucket for the templates, generate the templates in the cformation/ directory
and copy the templates to the bucket. It also creates a code bucket and assembles the code and copies it to the code bucket.
It then runs the cloudformation.
Try ./run.py -h for more information
Set up your environment, one time:
pip install virtualenv
./afterclone.sh
Then each time you want to run the program in a new shell:
source ./sourceme
Then use it:
# build everything, copy, run, ... from scratch (delete it if it already exists)
./run.py -h
# codepipeline
* Create a personal access token (get it from powell?) [Aws from github](http://docs.aws.amazon.com/codepipeline/latest/userguide/troubleshooting.html#troubleshooting-gs2)
* Build - execute the run.py script
# More work
Take another look at:
http://docs.aws.amazon.com/firehose/latest/dev/controlling-access.html#using-iam-s3
<file_sep>/cfm/run.py
#!/usr/bin/env python
from __future__ import print_function
from string import Template
# run.py by default will delete cloudformation templates and buckets created by this script and create everything from scratch.
# other parameters (yet to be defined) will roll out a smaller change
import boto3
import botocore
import os
import argparse
import re
import tempfile
import shutil
import importlib
import cformation
from cformation import *
import json
# in the cformation directory
CFORMATION_TEMPLATES = [cformation.master, cformation.ingest, cformation.elasticsearch, cformation.firehose, cformation.codepipeline, cformation.api_lambda]
GIT_PERSONAL_ACCESS_TOKEN = 'GIT_PERSONAL_ACCESS_TOKEN'
SECRETS = set(['TWITTER_CONSUMER_KEY', 'TWITTER_CONSUMER_SECRET', 'TWITTER_ACCESS_TOKEN', 'TWITTER_ACCESS_SECRET', GIT_PERSONAL_ACCESS_TOKEN])
# command line parsing
parser = argparse.ArgumentParser(description="""Look at the switches below and notice the commands.
You can run any of these commands individually.
If none of the commands are specified then following commands will be run in order: -code, -codeupload, -template, -update.
Before the create or update commands are run the twitter credentials will be verified.
If twitter credential verification fails, fix the problem by setting the env variables and using the -p switch.
In addition it can be useful to execute -template followed by -update to make changes to the templates then update the existing stack.
The -name parameter can be used to create multiple stacks, you must use the same name to delete, update, etc.
""")
parser.add_argument('-delete', action='store_true', help='command: delete the buckets and the stack')
parser.add_argument('-code', action='store_true', help='command: generate code in temporary directory')
parser.add_argument('-codeupload', action='store_true', help='command: upload the code generated by the code command, create s3 bucket, upload code s3 bucket')
parser.add_argument('-template', action='store_true', help='command: generate cloudformation templates in the temporary directory, create cfn bucket, put the templates into the cfn bucket')
parser.add_argument('-create', action='store_true', help='command: create the stack from the cloud formation templates created with -template')
parser.add_argument('-update', action='store_true', help='command: update the stack (normally run with -template)')
parser.add_argument('-creds', action='store_true', help='command: store secrets, set these environment variables then use the -creds option to store them:' + str(SECRETS))
parser.add_argument('-credsprint', action='store_true', help='command: print the stored secrets use after -creds to see the restuls')
parser.add_argument('-n', action='store', default='bigimage', help='name any global objects, like s3 buckets, with this name')
parser.add_argument('-s', action='store_true', help='run silently')
args = parser.parse_args()
# globals for getting to boto3
clientSts = boto3.client('sts')
clientCloudformation = boto3.client('cloudformation')
clientS3 = boto3.client('s3')
s3 = boto3.resource('s3')
ssm = boto3.client('ssm')
# args
ARG_SILENT = args.s
ARG_NAME = args.n
# commands
ARG_DELETE = args.delete
ARG_CODE = args.code
ARG_CODEUPLOAD = args.codeupload
ARG_TEMPLATE = args.template
ARG_CREATE = args.create
ARG_UPDATE = args.update
ARG_CREDS = args.creds
ARG_CREDSPRINT = args.credsprint
if (not ARG_DELETE) and (not ARG_CODE) and (not ARG_TEMPLATE) and (not ARG_CREATE) and (not ARG_UPDATE) and (not ARG_CREDS) and (not ARG_CREDSPRINT):
ARG_CODE = True
ARG_CODEUPLOAD = True
ARG_TEMPLATE = True
ARG_CREATE = True
ARG_UPDATE = True
# constants
STACK_NAME=ARG_NAME
ACCOUNT_ID = clientSts.get_caller_identity()['Account']
S3_TEMPLATE_BUCKET = STACK_NAME + 'cfn' + ACCOUNT_ID # cloudformation template are generated in this script and kept here
S3_CODE_BUCKET=STACK_NAME + 'code' + ACCOUNT_ID # code is generated in this script and kept here
REGION = boto3.session.Session().region_name
MASTER_TEMPLATE='master.cfn.json'
def silentPrint(*args):
if not ARG_SILENT:
print(*args)
class NamedSecrets:
'''Manage a list of secrets for a specific stack name (see -n parameter) in the AWS parameter store
invoked secrets = NamedSecrets(name, secretSet) where name is the name of the stack and secretSet is a set of secrets to keep track of
'''
def __init__(self, name, secrets):
self.name = name
self.secrets = secrets
def _namedSecret(self, secret):
"return a named secret by prepending the name (see -n parameter) to the secret"
return self.name + "_" + secret
def _namedSecrets(self):
"return a set of named twitter variables"
ret = set()
for secret in self.secrets:
ret.add(self._namedSecret(secret))
return ret
def readVerifyRememberStoredSecrets(self):
"veriy that all of the secrets have been stored"
# only need to call this function one time, the results are remembered
if hasattr(self, 'namedSecretValues'):
return True
namedSecrets = list(self._namedSecrets())
ret = ssm.get_parameters(Names=namedSecrets, WithDecryption=True)
namedSecretValues = {}
parameters = ret[u'Parameters']
for parameter in parameters:
namedSecretValues[parameter['Name']] = parameter['Value']
invalidParameters = ret['InvalidParameters']
if len(invalidParameters) > 0:
print("missing system parameters:", str(invalidParameters))
return False
returnedNamedSecrets = set(namedSecretValues.keys())
if returnedNamedSecrets != self._namedSecrets():
print("all secrets not stored, crazy, secrets returned:", returnedNamedSecrets, "secrets expected:", self._namedSecrets())
return False
self.namedSecretValues = namedSecretValues
return True
def getRememberedSecretValue(self, secret):
"call after readVerifyRememberStoredSecrets() to return the value associated with a secret"
return self.namedSecretValues[self._namedSecret(secret)]
def storeSecrets(self):
"store the secrets as Simple System Management System Parameters, return false if something goes wrong"
ret = True
parameterStore = {}
for secret in self.secrets:
if not os.environ.has_key(secret):
print(secret, "not in environment")
ret = False
continue
value = os.environ[secret]
if value == "":
print(secret, "in environment but does not have a vlue")
ret = False
continue
parameterStore[self._namedSecret(secret)] = value
if not ret:
return False
for secret in parameterStore:
value = parameterStore[secret]
ssm.put_parameter(Name=secret, Value=value, Type='SecureString', Overwrite=True)
if not self.readVerifyRememberStoredSecrets():
return False
if not (parameterStore == self.namedSecretValues):
print("values stored do not match the environment variables, crazy")
return True
def masterTemplateParameters(secrets):
'return the master template parameters'
gitParameterValue = secrets.getRememberedSecretValue(GIT_PERSONAL_ACCESS_TOKEN)
MASTER_TEMPLATE_PARAMETERS=[{
'ParameterKey': 'TemplateBucket',
'ParameterValue': '{}/{}'.format(clientS3.meta.endpoint_url, S3_TEMPLATE_BUCKET),
'UsePreviousValue': False
},{
'ParameterKey': 'CodeBucket',
'ParameterValue': S3_CODE_BUCKET,
'UsePreviousValue': False
},{
'ParameterKey': 'GitPersonalAccessToken',
'ParameterValue': gitParameterValue,
'UsePreviousValue': False
}]
return MASTER_TEMPLATE_PARAMETERS
# each module must have id() and template() functions.
# id() will return the name of the json file that should be generated
# template() will return the trophoshpere template
TROPHOSPHERE_NAME_TEMPLATE = {}
for moduleName in CFORMATION_TEMPLATES:
TROPHOSPHERE_NAME_TEMPLATE.update({moduleName.id(): moduleName.template(STACK_NAME)})
# directories that contain a makeawszip command that will create a zip
MAKEAWSZIP_DIRS = ['python-v1']
def bucketCreate(bucket):
bucket.create(CreateBucketConfiguration={'LocationConstraint': REGION}, GrantRead='uri="http://acs.amazonaws.com/groups/global/AllUsers"')
def bucketDelete(bucketName):
'return a new bucket, clean all keys in bucket and delete if they currently exist'
silentPrint('deleting bucket:', bucketName)
bucket = s3.Bucket(bucketName)
try:
for key in bucket.objects.all():
key.delete()
silentPrint('delete key, bucket:', key.bucket_name, 'key:', key.key)
bucket.delete()
silentPrint('deleted bucket:', bucket.name)
except:
pass
return bucket
def bucketExists(bucket):
'return True if the bucket exists'
return bucket in s3.buckets.all()
def bucketNew(bucket):
'create a new bucket'
bucketCreate(bucket)
bucket_policy = s3.BucketPolicy(bucket.name)
policy=Template('''{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AddPerm",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::$bucket/*"
}
]
}
''').substitute(bucket=S3_TEMPLATE_BUCKET)
silentPrint("s3 teamplate bucket policy:", policy)
bucket_policy.put(Policy=policy)
silentPrint('create bucket:', bucket.name)
return bucket
def bucketPopulate(tempDir, bucket):
'populate the bucket with the cf.json files in this directory'
for key in TROPHOSPHERE_NAME_TEMPLATE:
localFile = os.path.join(tempDir, key)
silentPrint("upload:", localFile, "url:", s3Url(bucket, key))
bucket.upload_file(localFile, key)
def generateCfn(outputDir):
'generate the cloudformation templates for all the *.cfn.py files in this directory'
for key, template in TROPHOSPHERE_NAME_TEMPLATE.iteritems():
outputFile = open(os.path.join(outputDir, key), "w")
outputFile.write(template.to_json())
def stackWait(stackName, waitName):
silentPrint("waiting for cloudformation stack to be", waitName, "stack:", stackName)
waiter = clientCloudformation.get_waiter(waitName)
waiter.wait(StackName=stackName)
def stackCreateWait(stackName):
stackWait(stackName, 'stack_create_complete')
def stackUpdateWait(stackName):
stackWait(stackName, 'stack_update_complete')
def stackDeleteWait(stackName):
stackWait(stackName, 'stack_delete_complete')
def stackDelete(stackName):
try:
silentPrint("delete stack:", stackName)
clientCloudformation.delete_stack(StackName=stackName)
stackDeleteWait(stackName)
except:
return
def s3Url(s3Bucket, s3Key):
return '{}/{}/{}'.format(clientS3.meta.endpoint_url, s3Bucket.name, s3Key)
def stackCreate(stackName, templateBucket, s3MasterKey, cfnParameters):
url = s3Url(templateBucket, s3MasterKey)
response = clientCloudformation.create_stack(
StackName=stackName,
TemplateURL=url,
Parameters=cfnParameters,
#DisableRollback=True|False,
#TimeoutInMinutes=123,
#NotificationARNs=[
# 'string',
#],
Capabilities=[
'CAPABILITY_IAM'
],
#ResourceTypes=[
# 'string',
#],
#RoleARN='string',
#OnFailure='DO_NOTHING'|'ROLLBACK'|'DELETE',
#StackPolicyBody='string',
#StackPolicyURL='string',
Tags=[
{
'Key': 'project',
'Value': STACK_NAME,
},
]
)
stackCreateWait(stackName)
def stackUpdate(stackName, templateBucket, s3MasterKey, cfnParameters):
url = s3Url(templateBucket, s3MasterKey)
response = clientCloudformation.update_stack(
StackName=stackName,
TemplateURL=url,
UsePreviousTemplate=False,
# StackPolicyDuringUpdateBody
Parameters=cfnParameters,
#DisableRollback=True|False,
#TimeoutInMinutes=123,
#NotificationARNs=[
# 'string',
#],
Capabilities=[
'CAPABILITY_IAM'
],
#ResourceTypes=[
# 'string',
#],
#RoleARN='string',
#OnFailure='DO_NOTHING'|'ROLLBACK'|'DELETE',
#StackPolicyBody='string',
#StackPolicyURL='string',
Tags=[
{
'Key': 'project',
'Value': STACK_NAME,
},
]
)
stackUpdateWait(stackName)
def stackCreateChangeSet(stackName, templateBucket, s3MasterKey, cfnParameters):
url = s3Url(templateBucket, s3MasterKey)
response = clientCloudformation.create_change_set(
ChangeSetName='changeSetName',
# ClientToken='string',
#Description='string',
ChangeSetType='UPDATE',
#
StackName=stackName,
TemplateURL=url,
UsePreviousTemplate=False,
Parameters=cfnParameters,
#TimeoutInMinutes=123,
#NotificationARNs=[
# 'string',
#],
Capabilities=[
'CAPABILITY_IAM'
],
#ResourceTypes=[
# 'string',
#],
#RoleARN='string',
#OnFailure='DO_NOTHING'|'ROLLBACK'|'DELETE',
#StackPolicyBody='string',
#StackPolicyURL='string',
)
stackCreateWait(stackName)
import imp
def uploadProjectCode(bucket, inputDirBasename, outputDir):
'upload generated code from a project'
file = os.path.join(outputDir, inputDirBasename + ".zip")
key = os.path.basename(file)
silentPrint("upload:", file, "key:", key, "url:", s3Url(bucket, key))
# upload file
bucket.upload_file(file, key)
def uploadCode(outputDir, bucketName):
bucket = s3.Bucket(bucketName)
try:
bucketCreate(bucket)
bucket_versioning = s3.BucketVersioning(bucketName)
silentPrint("eable bucket_versioning:", bucket_versioning)
bucket_versioning.enable()
except:
pass
for inputDirBasename in MAKEAWSZIP_DIRS:
uploadProjectCode(bucket, inputDirBasename, outputDir)
def generateProjectCode(inputDirBasename, outputDir):
'call the inputDirBasename/build/build.py script to create a zip file to upload'
buildPath = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), inputDirBasename, "build", "build.py")
silentPrint('building code:', buildPath)
buildModule = imp.load_source("build", buildPath)
zip_file_name = os.path.join(outputDir, inputDirBasename + ".zip")
hash = buildModule.build(zip_file_name)
print(hash)
def generateCode(outputDir):
for inputDirBasename in MAKEAWSZIP_DIRS:
generateProjectCode(inputDirBasename, outputDir)
# commands --------------------------
secrets = NamedSecrets(ARG_NAME, SECRETS)
if ARG_CREDS:
silentPrint("command: creds")
if not secrets.storeSecrets():
quit()
if ARG_CREDSPRINT:
if not secrets.readVerifyRememberStoredSecrets():
quit()
print(secrets.namedSecretValues)
if ARG_DELETE:
silentPrint("command: delete")
stackDelete(STACK_NAME)
bucketDelete(S3_TEMPLATE_BUCKET)
bucketDelete(S3_CODE_BUCKET)
if False:
tempDir = tempfile.mkdtemp()
else:
tempDir = os.path.abspath("build")
silentPrint("temporary directory:", tempDir)
try:
shutil.rmtree(tempDir)
except:
pass
os.mkdir(tempDir)
# generate new code zips
if ARG_CODE:
silentPrint("command: code")
generateCode(tempDir)
if ARG_CODEUPLOAD:
silentPrint("command: codeupload")
uploadCode(tempDir, S3_CODE_BUCKET)
# populate template bucket with fresh templates. Generate them in the temporary directory then copy them to s3
templateBucket = s3.Bucket(S3_TEMPLATE_BUCKET)
if ARG_TEMPLATE:
silentPrint("command: template")
if not bucketExists(templateBucket):
bucketNew(templateBucket)
generateCfn(tempDir)
bucketPopulate(tempDir, templateBucket)
# both set then create if it does not exist and update otherwise
if ARG_CREATE and ARG_UPDATE:
try:
stack = clientCloudformation.describe_stacks(StackName=ARG_NAME)
silentPrint("stack exists, update stack")
ARG_CREATE = False # found the stack, update do not create
except botocore.exceptions.ClientError as ex:
if ("Stack with id" in str(ex)) and ("does not exist" in str(ex)):
silentPrint("stack does not exist, create stack")
ARG_UPDATE = False # stack does not exist, create the stack
else:
raise ex
if ARG_CREATE:
silentPrint("command: create")
if not secrets.readVerifyRememberStoredSecrets():
quit()
stackCreate(STACK_NAME, templateBucket, MASTER_TEMPLATE, masterTemplateParameters(secrets))
if ARG_UPDATE:
silentPrint("command: update")
if not secrets.readVerifyRememberStoredSecrets():
quit()
stackUpdate(STACK_NAME, templateBucket, MASTER_TEMPLATE, masterTemplateParameters(secrets))
#if ARG_CHANGE_SET:
# print("not implemented yet")
# quit()
# stackCreateChangeSet(STACK_NAME, templateBucket, MASTER_TEMPLATE, masterTemplateParameters(secrets))
# quit()
print("temporary directory:", tempDir)
<file_sep>/python-v1/sourceme
#!/bin/bash
source application/.env/bin/activate
cd application
<file_sep>/ibm/ingest/app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
///////////////////////
// get the app environment from Cloud Foundry
// last 10 tweets
var createCache = function(length){
var pointer = 0, cache = [];
return {
push : function(item){
if (cache.length < length) {
pointer = cache.push(item) % length;
} else {
cache[pointer] = item;
pointer = (pointer +1) % length;
}
},
get : function(){
if (cache.length < length) {
return cache;
} else {
return cache.slice(pointer, length).concat(cache.slice(0, pointer));
}
}
};
};
var tweetBuffer = createCache(10);
var env = process.env;
console.log(JSON.stringify(env, null, ' '));
app.get('/dump', function (req, res) {
var dump = {
twitter: tweetBuffer.get(),
env: env
};
var dumpString = JSON.stringify(dump, null, ' ');
res.send('<h1>last 10 tweets and environment:</h1><pre>' + dumpString + "</pre>");
});
// twitter
if ((process.env.TWITTER_CONSUMER_KEY === undefined) ||
(process.env.TWITTER_CONSUMER_SECRET === undefined) ||
(process.env.TWITTER_ACCESS_TOKEN === undefined) ||
(process.env.TWITTER_ACCESS_SECRET === undefined)) {
console.log('need to set the TWITTER environment variables defined');
process.exit(-1);
}
var Twitter = require('twitter');
var client = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN,
access_token_secret: process.env.TWITTER_ACCESS_SECRET
});
var stream = client.stream('statuses/filter', {track: 'coffee,ibm,javascript'});
stream.on('data', function(event) {
if (event) {
tweetBuffer.push(event);
console.log(event && event.text);
}
});
stream.on('error', function(error) {
console.log(error);
throw error;
});
/////////////////////////////////////////////
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res/*, next*/) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
<file_sep>/cfm/cformation/codepipeline.py
#!/usr/bin/env python
from troposphere import Template, Ref, Join, GetAtt, Output, Tags, Parameter
from troposphere.iam import Role
from troposphere.iam import Policy as TropospherePolicy
from awacs.aws import Allow, Statement, Action, Principal, Policy
from awacs.sts import AssumeRole
from troposphere.codepipeline import (
Pipeline, Stages, Actions, ActionTypeID, OutputArtifacts, InputArtifacts,
ArtifactStore, DisableInboundStageTransitions)
from troposphere.s3 import (Bucket, BucketPolicy, PublicRead, WebsiteConfiguration)
# TODO change this line and module when codebuild is released by troposphere
from troposphere_early_release.codebuild import Artifacts, Environment, EnvironmentVariable, Source, Project
import cfnhelper
CODEPIPELINE = 'CODEPIPELINE'
BROWSER_NAME = 'Browser'
CODE_PIPELINE = True
CODE_BUILD = True
CODE_BUILD_BROWSER = True
def id():
return 'codepipeline.cfn.json'
def template(stackName='bigimage'):
t = Template()
t.add_description('Codepipeline and codebuild for ' + stackName)
externalApiEndpointkeyword = t.add_parameter(Parameter(
"ExternalApiEndpointkeyword",
Description="Endpoint for this stage of the api",
Type="String"
))
ingestApplicationName = t.add_parameter(Parameter(
"IngestApplicationName",
Description="ingest beanstalk application name",
Type="String"
))
ingestEnvironmentName = t.add_parameter(Parameter(
"IngestEnvironmentName",
Description="ingest beanstalk environment name",
Type="String"
))
gitPersonalAccessToken = t.add_parameter(Parameter(
'GitPersonalAccessToken',
Type='String',
Description='Git personal access token required for codepipeline'
))
# Create the role with a trust relationship that allows codebuild to assume the role
# TODO the code build role runs the run.py to do the complete roll out and needs lots of privileges, the pipeline does not
codeRole = t.add_resource(Role(
"CodeRole",
AssumeRolePolicyDocument=Policy(
Version="2012-10-17",
Statement=[
Statement(
Sid="",
Effect=Allow,
Action=[AssumeRole],
Principal=Principal(
"Service", [
'codebuild.amazonaws.com',
'codepipeline.amazonaws.com',
]
)
)
]
),
Path="/",
Policies=[TropospherePolicy(
"CodebuildAndCodepipelinePolicy",
PolicyName="CodebuildAndCodepipelinePolicy",
PolicyDocument=Policy(
Statement=[
Statement(
Effect=Allow,
Action=[Action("*")],
Resource=["*"],
),
]
),
)],
))
codebuildRoleArn = GetAtt(codeRole, "Arn")
# codebuild to execute run.py to deploy cloud and create ingest zip -------------------
artifacts = Artifacts(Type=CODEPIPELINE)
environment = Environment(
ComputeType='BUILD_GENERAL1_SMALL',
Image='aws/codebuild/python:2.7.12',
Type='LINUX_CONTAINER',
EnvironmentVariables=[],
)
source = Source(Type=CODEPIPELINE)
codeBuildProject = Project(
stackName + "CodeBuildProject",
Artifacts=artifacts,
Environment=environment,
Name=stackName,
ServiceRole=codebuildRoleArn,
Source=source,
)
if CODE_BUILD:
codeBuildProjectResource = t.add_resource(codeBuildProject)
# codebuild to build browser application and write to s3 -------------------
browserBucket = t.add_resource(Bucket(
"BrowserBucket",
AccessControl=PublicRead,
DeletionPolicy='Retain',
Tags=Tags(stage=cfnhelper.STAGE),
WebsiteConfiguration=WebsiteConfiguration(
IndexDocument='index.html',
),
))
browserS3Ref = Ref(browserBucket)
browserS3WebsiteUrl = GetAtt(browserBucket, "WebsiteURL")
browserS3Arn = cfnhelper.s3BucketArn(browserBucket)
browserBucketPolicy = t.add_resource(BucketPolicy(
"BrowserBucketPolicy",
Bucket=Ref(browserBucket),
PolicyDocument={
"Version": "2012-10-17",
"Statement": [Statement(
Effect=Allow,
Sid="AddPerm",
Principal=Principal('*'),
Resource=[
Join("/", [
browserS3Arn,
'*',
]),
],
Action=[Action("s3", "GetObject")],
)],
}
))
environmentBrowser = Environment(
ComputeType='BUILD_GENERAL1_SMALL',
Image='aws/codebuild/nodejs:7.0.0',
Type='LINUX_CONTAINER',
EnvironmentVariables=[
EnvironmentVariable(Name='REACT_APP_API_ENDPOINT_URL', Value=Ref(externalApiEndpointkeyword)),
EnvironmentVariable(Name='BROWSER_S3_WEBSITE_URL', Value=browserS3WebsiteUrl),
EnvironmentVariable(Name='BROWSER_S3_REF', Value=browserS3Ref),
EnvironmentVariable(Name='BROWSER_S3_ARN', Value=browserS3Arn),
],
)
buildSpec = '''
# aws codebuild configuration file
version: 0.1
environment_variables:
plaintext:
ENVTESTITVALUE: "value"
phases:
build:
commands:
- cd browser && bash build.bash
'''
sourceBrowser = Source(Type=CODEPIPELINE, BuildSpec=buildSpec)
browserBuildProject = Project(
stackName + "BrowserBuildProject",
Artifacts=artifacts,
Environment=environmentBrowser,
Name=stackName + BROWSER_NAME,
ServiceRole=codebuildRoleArn,
Source=sourceBrowser,
)
if CODE_BUILD_BROWSER:
browserBuildProjectResource = t.add_resource(browserBuildProject)
# codepipeline -------------------
codepipelineBucket = t.add_resource(Bucket(
"codepipelineBucket",
AccessControl=PublicRead,
DeletionPolicy='Retain',
Tags=Tags(stage=cfnhelper.STAGE),
))
if CODE_PIPELINE:
gitArtifactName="MyApp"
ingestArtifactName="MyBuiltApp"
sourceAction = Actions(
Name="SourceAction",
ActionTypeId=ActionTypeID(
Category="Source",
Owner="ThirdParty",
Version="1",
Provider="GitHub"
),
OutputArtifacts=[
OutputArtifacts(
Name=gitArtifactName
)
],
Configuration={
"Owner": "powellquiring",
"Repo": "bigimage",
"Branch": "master",
"OAuthToken": Ref(gitPersonalAccessToken),
},
RunOrder="1"
)
buildIngestAction = Actions(
Name="buildIngestDeployCfn",
InputArtifacts=[
InputArtifacts(
Name=gitArtifactName
)
],
OutputArtifacts=[
OutputArtifacts(
Name=ingestArtifactName
)
],
ActionTypeId=ActionTypeID(
Category="Build",
Owner="AWS",
Version="1",
Provider="CodeBuild"
),
Configuration={
"ProjectName": stackName,
},
RunOrder="1"
)
buildBrowserS3Action = Actions(
Name="buildBrowser",
InputArtifacts=[
InputArtifacts(
Name=gitArtifactName
)
],
OutputArtifacts=[
OutputArtifacts(
Name="BrowserOutput"
)
],
ActionTypeId=ActionTypeID(
Category="Build",
Owner="AWS",
Version="1",
Provider="CodeBuild"
),
Configuration={
"ProjectName": browserBuildProject.Name,
},
RunOrder="2"
)
DeployIngestAction = Actions(
Name="deploybeanstalk",
InputArtifacts=[
InputArtifacts(
Name=ingestArtifactName
)
],
ActionTypeId=ActionTypeID(
Category="Deploy",
Owner="AWS",
Version="1",
Provider="ElasticBeanstalk"
),
Configuration={
"ApplicationName": Ref(ingestApplicationName),
"EnvironmentName": Ref(ingestEnvironmentName),
},
RunOrder="1"
)
buildActions = []
if CODE_BUILD:
buildActions.append(buildIngestAction)
if CODE_BUILD_BROWSER:
buildActions.append(buildBrowserS3Action)
stages=[
Stages(Name="Source", Actions=[sourceAction]),
Stages( Name="BuildAllDeployCfn", Actions=buildActions),
]
if CODE_BUILD:
stages.append(Stages(Name="DeployIngestApplication", Actions=[DeployIngestAction]))
pipeline = t.add_resource(Pipeline(
stackName + "codepipeline",
Name=stackName,
RoleArn=codebuildRoleArn,
ArtifactStore=ArtifactStore(
Type="S3",
Location=Ref(codepipelineBucket)
),
#DisableInboundStageTransitions=[
# DisableInboundStageTransitions(
# StageName="Release",
# Reason="Disabling the transition until "
# "integration tests are completed"
# )
#]
Stages=stages,
))
t.add_output(Output(
"CodepipelineBucket",
Value=Ref(codepipelineBucket),
Description="codepipeline S3 bucket name",
))
if CODE_BUILD:
t.add_output(Output(
"CodebuildProject",
Value=Ref(codeBuildProjectResource),
Description="codebuild ingest project",
))
if CODE_BUILD_BROWSER:
t.add_output(Output(
"BrowserbuildProject",
Value=Ref(browserBuildProjectResource),
Description="browser codebuild project",
))
t.add_output(Output(
"BrowserS3WebsiteUrl",
Value=browserS3WebsiteUrl,
Description="browser s3 website url",
))
t.add_output(Output(
"CodebuildRoleArn",
Value=codebuildRoleArn,
Description="Codebuild role arn",
))
return t
if __name__ == "__main__":
print(template().to_json())
<file_sep>/browser/src/App.js
import React from 'react';
import logo from './logo.png';
import axios from 'axios';
import './App.css';
class Tweet extends React.Component {
render() {
var tweet = this.props.tweet
return (
<div key={tweet.text} className="tweet">
<a href={tweet.url}>
{tweet.text}
</a>
{tweet.images.map(function(image) {
return (
<div key={image}>
<a href={tweet.url}>
<img alt={tweet.text} src={image}/>
</a>
</div>
);
})}
</div>
)}
}
// sheet of twitter matches of the supplied input
class TwitterOutput extends React.Component {
constructor(props) {
super(props)
this.state = {tweets:[], source:props.source}
}
loadJobs(source) {
console.log("loadJobs:");
console.log("source:", source);
var th = this;
th.abortCurrentRequest();
var CancelToken = axios.CancelToken;
th.cancelTokenSource = CancelToken.source();
axios.get(source, {cancelToken:th.cancelTokenSource.token})
.then(function(result) {
console.dir(result)
delete th.cancelTokenSource;
th.setState({
tweets: result.data.ret.ret
});
})
.catch(function(err) {
if (err instanceof axios.Cancel) {
console.log("cancels are expected, see abortCurrentRequest()");
} else {
console.log("unexepected error from axios.get(source), source:", source, "err:")
console.dir(err);
}
});
}
componentDidMount() {
console.log("componentDidMount");
var source = this.state.source;
this.loadJobs(source);
}
componentWillReceiveProps(nextProps) {
console.log("componentWillReceiveProps:");
console.dir(nextProps);
this.setState(nextProps);
if (nextProps.hasOwnProperty('source')) {
this.setState({tweets:[]}); // tweets are unknown since the source has changed
this.loadJobs(nextProps.source);
}
}
abortCurrentRequest() {
if (this.hasOwnProperty('cancelTokenSource')) {
console.dir(this.cancelTokenSource);
this.cancelTokenSource.cancel();
delete this.cancelTokenSource;
}
}
componentWillUnmount() {
this.abortCurrentRequest()
}
render() {
console.log("output render")
return (
<div>
<h1>Tweets!</h1>
{this.state.tweets.map(function(tweet) {
return (
<Tweet key={tweet.url} tweet={tweet} />
);
})}
</div>
)
}
}
class TwitterInput extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {keyword: this.props.keyword}
}
handleChange(e) {
console.log("handleChange, value:", e.target.value)
this.setState({keyword: e.target.value});
}
handleSubmit(e) {
const keyword = this.state.keyword
console.log('A keyword submitted: ' + keyword);
this.props.onChange(keyword);
e.preventDefault()
}
render() {
const keyword = this.state.keyword;
return (
<form onSubmit={this.handleSubmit}>
<label>
Keyword:
<input type="text" value={keyword} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
// Single page app
class Page extends React.Component {
constructor(props) {
super(props);
this.handleKeywordChange = this.handleKeywordChange.bind(this);
this.state = {keyword: 'coffee'};
}
handleKeywordChange(keyword) {
console.log('handleKeywordChange:', keyword);
this.setState({keyword: keyword});
}
render() {
const word = this.state.keyword
const url = process.env.REACT_APP_API_ENDPOINT_URL + '?word=' + word
console.log('url:', url)
return (
<div>
<TwitterInput keyword={word} onChange={this.handleKeywordChange}/>
<TwitterOutput source={url}/>
</div>
)
}
}
class AppError extends React.Component {
render() {
return (
<div className="App">
<div className="App-error">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to Keyword</h2>
<p>before running or building this program you must set the environment variable that identifies the keyword URL. Something like this:</p>
<p></p>
<p>$export REACT_APP_API_ENDPOINT_URL=https://cr3fsvbvt3.execute-api.us-west-2.amazonaws.com/v1/keyword </p>
</div>
</div>
);
}
}
class App extends React.Component {
render() {
console.log("process.env.REACT_APP_API_ENDPOINT_URL:", process.env.REACT_APP_API_ENDPOINT_URL)
if (typeof process.env.REACT_APP_API_ENDPOINT_URL === 'undefined') {
return (<AppError/>);
}
var endpointUrl = process.env.REACT_APP_API_ENDPOINT_URL
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to Keyword</h2>
<p>endpoint: {endpointUrl}</p>
</div>
<Page source={endpointUrl}/>
</div>
);
}
}
export default App;
<file_sep>/cfm/cformation/cloudfront.py
#!/usr/bin/env python
from troposphere import Template, Ref, GetAtt, Output, Tags, Parameter
from troposphere.iam import Role
from troposphere.iam import Policy as TropospherePolicy
from awacs.aws import Allow, Statement, Action, Principal, Policy
from awacs.sts import AssumeRole
from troposphere.codepipeline import (
Pipeline, Stages, Actions, ActionTypeID, OutputArtifacts, InputArtifacts,
ArtifactStore, DisableInboundStageTransitions)
from troposphere.s3 import (Bucket, PublicRead)
import cfnhelper
def id():
return 'cloudfront.cfn.json'
def template(stackName='bigimage'):
t = Template()
t.add_description('Codepipeline and codebuild for ' + stackName)
# Create the role with a trust relationship that allows codebuild to assume the role
# TODO the code build role runs the run.py to do the complete roll out and needs lots of privileges, the pipeline does not
codeRole = t.add_resource(Role(
"CodeRole",
AssumeRolePolicyDocument=Policy(
Version="2012-10-17",
Statement=[
Statement(
Sid="",
Effect=Allow,
Action=[AssumeRole],
Principal=Principal(
"Service", [
'codebuild.amazonaws.com',
'codepipeline.amazonaws.com',
]
)
)
]
),
Path="/",
Policies=[TropospherePolicy(
"CodebuildAndCodepipelinePolicy",
PolicyName="CodebuildAndCodepipelinePolicy",
PolicyDocument=Policy(
Statement=[
Statement(
Effect=Allow,
Action=[Action("*")],
Resource=["*"],
),
]
),
)],
))
codebuildRoleArn = GetAtt(codeRole, "Arn")
# codebuild -------------------
artifacts = Artifacts(Type=CODEPIPELINE)
environment = Environment(
ComputeType='BUILD_GENERAL1_SMALL',
Image='aws/codebuild/python:2.7.12',
Type='LINUX_CONTAINER',
EnvironmentVariables=[],
)
# using CODEPIPELINE
if True:
source = Source(Type=CODEPIPELINE)
else:
source = Source(
Type="GITHUB",
Location="https://github.com/powellquiring/bigimage.git",
)
codeBuildProject = Project(
stackName + "CodeBuildProject",
Artifacts=artifacts,
Environment=environment,
Name=stackName,
ServiceRole=codebuildRoleArn,
Source=source,
)
t.add_resource(codeBuildProject)
# codepipeline -------------------
codepipelineBucket = t.add_resource(Bucket(
"codepipelineBucket",
AccessControl=PublicRead,
DeletionPolicy='Retain',
Tags=Tags(stage=cfnhelper.STAGE),
))
ingestApplicationName = t.add_parameter(Parameter(
"IngestApplicationName",
Description="ingest beanstalk application name",
Type="String"
))
ingestEnvironmentName = t.add_parameter(Parameter(
"IngestEnvironmentName",
Description="ingest beanstalk environment name",
Type="String"
))
gitPersonalAccessToken = t.add_parameter(Parameter(
'GitPersonalAccessToken',
Type='String',
Description='Git personal access token required for codepipeline'
))
pipeline = t.add_resource(Pipeline(
stackName + "codepipeline",
Name=stackName,
RoleArn=codebuildRoleArn,
ArtifactStore=ArtifactStore(
Type="S3",
Location=Ref(codepipelineBucket)
),
#DisableInboundStageTransitions=[
# DisableInboundStageTransitions(
# StageName="Release",
# Reason="Disabling the transition until "
# "integration tests are completed"
# )
#]
Stages=[
Stages(
Name="Source",
Actions=[
Actions(
Name="SourceAction",
ActionTypeId=ActionTypeID(
Category="Source",
Owner="ThirdParty",
Version="1",
Provider="GitHub"
),
OutputArtifacts=[
OutputArtifacts(
Name="MyApp"
)
],
Configuration={
"Owner": "powellquiring",
"Repo": "bigimage",
"Branch": "master",
"OAuthToken": Ref(gitPersonalAccessToken),
},
RunOrder="1"
)
]
),
Stages(
Name="BuildApplicationCloudformationTemplatesDeployCloudformationStack",
Actions=[
Actions(
Name="buildaction",
InputArtifacts=[
InputArtifacts(
Name="MyApp"
)
],
OutputArtifacts=[
OutputArtifacts(
Name="MyBuiltApp"
)
],
ActionTypeId=ActionTypeID(
Category="Build",
Owner="AWS",
Version="1",
Provider="CodeBuild"
),
Configuration={
"ProjectName": stackName,
},
RunOrder="1"
)
]
),
Stages(
Name="DeployIngestApplication",
Actions=[
Actions(
Name="deploybeanstalk",
InputArtifacts=[
InputArtifacts(
Name="MyBuiltApp"
)
],
ActionTypeId=ActionTypeID(
Category="Deploy",
Owner="AWS",
Version="1",
Provider="ElasticBeanstalk"
),
Configuration={
"ApplicationName": Ref(ingestApplicationName),
"EnvironmentName": Ref(ingestEnvironmentName),
},
RunOrder="1"
)
]
)
],
))
t.add_output(Output(
"CodepipelineBucket",
Value=Ref(codepipelineBucket),
Description="codepipeline S3 bucket name",
))
t.add_output(Output(
"CodebuildProject",
Value=Ref(codeBuildProject),
Description="codebuild ingest project",
))
t.add_output(Output(
"CodebuildRoleArn",
Value=codebuildRoleArn,
Description="Codebuild role arn",
))
return t
if __name__ == "__main__":
print(template().to_json())
<file_sep>/python-v1/README.md
# Ingest
Ingest program that reads from the twitter home for a user and writes to the firehose.
Environment variables documented in the application identify these external entities.
# Layout
Directories:
* application - the application
* build - the python program to build the zip file
# Usage
Use an virtual python environment. See [virtualenv](https://virtualenv.pypa.io/en/stable/userguide/):
pip install virtualenv
./afterclone.sh
source ./sourceme
./afterclone.sh will create a .env/ directory,
initialize the environment with the stuff needed from requirements.txt
source ./sourceme can be executed any time you need to initialize a new shell.
Your prompt should now contain (.env) as a reminder that you are working on the pything program.
It will also cd into the application/ directory to get you started.
Try `which python` to verify that python is coming from the .env directory
Once the firehose is running you can share it with a local application.
export StackName=bigimage
export DeliveryStreamName=bigimageTwitterDeliveryStream
<file_sep>/cfm/cformation/firehose.py
#!/usr/bin/python
from troposphere import Template, Parameter, Ref, Output, Tags, GetAtt
from troposphere.firehose import (
BufferingHints, CloudWatchLoggingOptions, CopyCommand, DeliveryStream,
EncryptionConfiguration, KMSEncryptionConfig, ElasticsearchDestinationConfiguration, S3Configuration, RetryOptions)
from troposphere.s3 import (Bucket, PublicRead)
from troposphere.iam import Role
from troposphere.iam import PolicyType as IAMPolicy
from troposphere.logs import LogGroup, LogStream
from awacs.aws import Allow, Statement, Action, Principal, Policy
from awacs.sts import AssumeRole
import cfnhelper
def id():
return 'firehose.cfn.json'
def template(stackName='bigimage'):
t = Template()
t.add_version('2010-09-09')
t.add_description('Kinesis firehose deliver twitter to elasticsearch')
s3bucket = t.add_resource(Bucket(
"firehose",
AccessControl=PublicRead,
DeletionPolicy='Retain',
Tags=Tags(stage=cfnhelper.STAGE),
))
domainArn = t.add_parameter(Parameter(
'DomainArn',
Type='String',
Description='Elasticsearch domain arn from the elasticsearch template'
))
FIREHOSE_LOG_GROUP = stackName + "FirehoseLogGroup"
logGroup = t.add_resource(LogGroup(
FIREHOSE_LOG_GROUP,
LogGroupName=FIREHOSE_LOG_GROUP,
RetentionInDays=7,
))
FIREHOSE_LOG_STREAM = stackName + "FirehoseLogStream"
logStream = t.add_resource(LogStream(
FIREHOSE_LOG_STREAM,
LogGroupName=Ref(logGroup),
LogStreamName=FIREHOSE_LOG_STREAM,
))
FIREHOSE_FILE_GROUP = stackName + "FirehoseFileGroup"
logFileGroup = t.add_resource(LogGroup(
FIREHOSE_FILE_GROUP,
LogGroupName=FIREHOSE_FILE_GROUP,
RetentionInDays=7,
))
FIREHOSE_FILE_STREAM = stackName + "FirehoseFileStream"
logFileStream = t.add_resource(LogStream(
FIREHOSE_FILE_STREAM,
LogGroupName=Ref(logFileGroup),
LogStreamName=FIREHOSE_FILE_STREAM,
))
# Create the role with a trust relationship that allows an ec2 service to assume a role
role = t.add_resource(Role(
"FirehoseRole",
AssumeRolePolicyDocument=Policy(
Version="2012-10-17",
Statement=[
Statement(
Sid="",
Effect=Allow,
Action=[AssumeRole],
Principal=Principal(
"Service", [
'firehose.amazonaws.com'
]
)
)
]
),
Path="/",
))
# Add a policy directly to the role (a policy in the policy view is not created)
t.add_resource(IAMPolicy(
"FirehoseRolePolicy",
PolicyName="FirehoseRolePolicy",
PolicyDocument=Policy(
Statement=[
Statement(
Effect=Allow,
NotAction=Action("iam", "*"),
Resource=["*"],),
]),
Roles=[Ref(role)],
))
fireHoseRoleArn = roleArn(role)
fireHoseBucketRoleArn = roleArn(role)
deliveryStreamId = stackName + 'TwitterDeliveryStream'
deliveryStreamName = deliveryStreamId
t.add_resource(DeliveryStream(
deliveryStreamId,
DeliveryStreamName=deliveryStreamName,
ElasticsearchDestinationConfiguration=ElasticsearchDestinationConfiguration(
BufferingHints=BufferingHints(
IntervalInSeconds=60,
SizeInMBs=1,
),
CloudWatchLoggingOptions=CloudWatchLoggingOptions(
Enabled=True,
LogGroupName=Ref(logGroup),
LogStreamName=Ref(logStream),
),
DomainARN=Ref(domainArn),
IndexName = 'indexname',
IndexRotationPeriod='NoRotation',
RetryOptions=RetryOptions(
DurationInSeconds=300,
),
RoleARN=fireHoseRoleArn,
S3BackupMode='AllDocuments',
S3Configuration=S3Configuration(
BucketARN=cfnhelper.s3BucketArn(s3bucket),
BufferingHints=BufferingHints(
IntervalInSeconds=60,
SizeInMBs=5,
),
CloudWatchLoggingOptions=CloudWatchLoggingOptions(
Enabled=True,
LogGroupName=Ref(logFileGroup),
LogStreamName=Ref(logFileStream),
),
CompressionFormat='UNCOMPRESSED',
# not required:
#EncryptionConfiguration=EncryptionConfiguration(
# KMSEncryptionConfig=KMSEncryptionConfig(
# AWSKMSKeyARN='aws-kms-key-arn'
# ),
# NoEncryptionConfig='NoEncryption',
#),
Prefix='',
RoleARN=fireHoseBucketRoleArn,
),
TypeName='testypename',
),
))
t.add_output(Output(
"S3",
Value=Ref(s3bucket),
Description="Firehose S3 bucket name",
))
t.add_output(Output(
"DeliveryStreamName",
Value=deliveryStreamName,
Description="Firehose delivery stream name",
))
t.add_output(Output(
"RoleArn",
Value=fireHoseRoleArn,
Description="Firehose role arn",
))
t.add_output(Output(
"BucketRoleArn",
Value=fireHoseBucketRoleArn,
Description="Firehose bucket role arn",
))
return t
def roleArn(roleReference):
return GetAtt(roleReference, "Arn")
if __name__ == "__main__":
print(template().to_json())
| 5c05c65ce0a891625a994ed4fff83c010c0d48b6 | [
"Markdown",
"JavaScript",
"Python",
"Text",
"Shell"
] | 26 | Python | powellquiring/bigimage | 5a5367177789e910e862de4baecb12c7cf0d8afc | f4ec2937c19f442963cf3c5eaf6a7e09670ad7a4 |
refs/heads/master | <file_sep>package com.salemkb.sampleapp;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Salem on 9/16/2017.
*/
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.ViewHolder> {
private Context context;
private List<PostModel> items;
public PostsAdapter(Context context, List<PostModel> items) {
this.context = context;
this.items = items;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_post, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.userId.setText(String.valueOf(items.get(position).getUserId()));
holder.title.setText(items.get(position).getTitle());
holder.body.setText(items.get(position).getBody());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "id = " + String.valueOf(items.get(position).getId()), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return items.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.userId)
TextView userId;
@BindView(R.id.title)
TextView title;
@BindView(R.id.body)
TextView body;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
<file_sep>package com.salemkb.paginator;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.paginate.Paginate;
import com.paginate.recycler.RecyclerPaginate;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.List;
import java.util.Map;
/**
* Created by Salem on 8/14/2017.
*/
public abstract class Paginator {
private Context context;
private RecyclerView recyclerView;
private List items;
private String paramsString;
private String baseUrl;
private Class modelType;
private RecyclerPaginate.Builder builder;
private Paginate paginate;
private boolean noMore = false;
private boolean isLoading = false;
private boolean hasParams = false;
public Paginator(Context context,
RecyclerView recyclerView,
List items, String baseUrl,
@Nullable Map<String, Object> params,
Class modelType) {
this.context = context;
this.recyclerView = recyclerView;
this.items = items;
this.baseUrl = baseUrl;
this.modelType = modelType;
this.paramsString = initParams(params);
initPagenator();
}
protected abstract String getUrl(String baseUrl, List data);
protected abstract JSONArray getArray(String response) throws JSONException;
protected View getRefreshView() {
return null;
}
private void enableRefreshView(boolean enable) {
if(getRefreshView() != null)
getRefreshView().setEnabled(enable);
}
private String initParams(@Nullable Map<String, ?> params) {
if (params == null)
return "";
String url = "";
for (String key : params.keySet())
url += "&" + key + "=" + params.get(key).toString();
hasParams = (params.size() > 0);
return url;
}
private void initPagenator() {
paginate = null;
builder = Paginate.with(recyclerView, callbacks)
.addLoadingListItem(true)
.setLoadingTriggerThreshold(2);
}
public void enablePagenate() {
if (paginate != null)
paginate.unbind();
noMore = false;
isLoading = false;
paginate = builder.build();
}
public void disablePagenate() {
if (paginate != null)
paginate.unbind();
}
public boolean isLoading() {
return isLoading;
}
private Paginate.Callbacks callbacks = new Paginate.Callbacks() {
@Override
public void onLoadMore() {
isLoading = true;
Volley.newRequestQueue(recyclerView.getContext())
.add(new StringRequest(
getUrl(baseUrl, items) + paramsString,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONArray array = new JSONArray();
try {
array = getArray(response);
Gson gson = new Gson();
for (int i = 0; i < array.length(); i++)
items.add(gson.fromJson(array.getJSONObject(i).toString(), modelType));
} catch (Exception e) {
e.printStackTrace();
}
isLoading = false;
if (array.length() == 0) {
paginate.setHasMoreDataToLoad(false);
noMore = true;
}
recyclerView.getAdapter().notifyDataSetChanged();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
isLoading = false;
recyclerView.getAdapter().notifyDataSetChanged();
}
}
)
);
}
@Override
public boolean isLoading() {
return isLoading;
}
@Override
public boolean hasLoadedAllItems() {
return noMore;
}
};
}
| e5ba8b4f4f68035486df9a00513f088100544154 | [
"Java"
] | 2 | Java | Salem-Kabbani/Paginator | 78d6250ed96bf1d697b7aaf8161fdff1817bbf26 | 8f3f0c6b2b94e37b89960b6f3a980e2a970fde27 |
refs/heads/master | <repo_name>yuhsuanhuang-tw/JavaTutorial<file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/files/FileWriterWithBomUtf8Example.java
/**
* @author <NAME>
*
* Create the File with BOM UTF-8 Header
*
*/
package pers.sample.tutorial.files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
public class FileWriterWithBomUtf8Example {
public static void main(String[] args) {
String array[] = {"1", "2"};
System.out.println(array.length);
byte[] BOM_UTF8 = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };
String filePath = "/Users/hsuanhuang/Documents/GitHub/JavaTutorial/JavaBasicTutorial/src/pers/sample/tutorial/files/Test-Log.csv";
String context = "id,user_id,source_id,destination_id,procedure_name,schema_name,table_name,action_type,sql_script,sql_status,sql_rows,sql_result,ss_seq,created_at\n"+
"6738,999999,10.112.215.118,10.1.9.49,null,BOTIMA_DEV,null,L,null,101,null,IMALOAD - Login successful : 測試員,0,2017/11/02 10:51:27\n"+
"6739,999999,10.112.215.118,10.1.9.49,null,BOTIMA_DEV,null,L,null,101,null,IMALOAD - Login successful : 測試員,0,2017/11/02 10:53:34\n"+
"7716,admin,10.112.215.234,10.1.9.49,null,BOTIMA,null,L,null,101,null,Login successful:admin,0,2017/11/02 10:05:29\n"+
"7723,116717,10.112.215.118,10.1.9.49,null,BOTIMA,null,L,null,101,null,Login successful:116717,0,2017/11/02 10:44:50\n";
try {
File file = new File(filePath);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
bw.write(BOM_UTF8.toString());
bw.write(context);
bw.flush();
bw.close();
FileOutputStream wrFile = new FileOutputStream(filePath,false);
wrFile.write(BOM_UTF8);
wrFile.write(context.getBytes("utf8"));
wrFile.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
//TODO close
}
System.out.println(context.replaceAll(",|\n", " "));
}
}
<file_sep>/JavaJdbcTutorial2/src/main/java/pers/sample/jdbc/tutorial/JDBCExecutor.java
/**
* Author: <NAME>
* Date 2021-07-08
*/
package pers.sample.jdbc.tutorial;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import pers.sample.jdbc.tutorial.dao.UserDAO;
import pers.sample.jdbc.tutorial.model.User;
public class JDBCExecutor {
public static void main(String[] args) {
//Sample 1 - Test Connection
// testConnection();
//Sample 2 - Test Creating a new Data using DAO
// createData();
//Sample 3 - Test Getting data by ID
// readData(1);
//Sample 4 - Test Updating data
// updateData();
//Sample 5 - Test Deleting data
// testConnection(); //count total
// deleteData(10);
// testConnection(); //count total
//Sample 6 - Limit results
// limitData(3);
//Sample 7 - Page results
pageData(3, 1);
pageData(3, 2);
pageData(6, 1);
}
/**
* Sample 1 - Test Connection
*/
public static void testConnection() {
//instantiate database connection manager object
DatabaseConnctionManager dcm = new DatabaseConnctionManager("localhost", "jdbc_tutorial", "root", "1qaz!QAZ");
//test connect
try {
Connection connection = dcm.getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) FROM USER");
while(resultSet.next()) {
System.out.println(resultSet.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Sample 2 - create util (1. DataTransferObject, 2. DataAccessObject), model (User) and DAO (UserDAO), then useing the DAO to create a new data
*/
public static void createData() {
//instantiate database connection manager object
DatabaseConnctionManager dcm = new DatabaseConnctionManager("localhost", "jdbc_tutorial", "root", "1qaz!QAZ");
try {
Connection connection = dcm.getConnection();
UserDAO userDAO = new UserDAO(connection);
User user = new User();
user.setName("Bob");
userDAO.create(user);
System.out.println("Finished adding...");
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Sample 3 - get data by id
*/
public static void readData(int id) {
//instantiate database connection manager object
DatabaseConnctionManager dcm = new DatabaseConnctionManager("localhost", "jdbc_tutorial", "root", "1qaz!QAZ");
try {
Connection connection = dcm.getConnection();
UserDAO userDAO = new UserDAO(connection);
User user = userDAO.findById(id);
System.out.println(user.toString());
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Sample 4 - update data
*/
public static void updateData() {
//instantiate database connection manager object
DatabaseConnctionManager dcm = new DatabaseConnctionManager("localhost", "jdbc_tutorial", "root", "1qaz!QAZ");
try {
Connection connection = dcm.getConnection();
UserDAO userDAO = new UserDAO(connection);
User user = userDAO.findById(10);
System.out.println("Before:\t" + user.toString());
user.setName("Emily");;
user = userDAO.update(user);
System.out.println("After:\t" + user.toString());
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Sample 5 - deleting data
*/
public static void deleteData(int id) {
//instantiate database connection manager object
DatabaseConnctionManager dcm = new DatabaseConnctionManager("localhost", "jdbc_tutorial", "root", "1qaz!QAZ");
try {
Connection connection = dcm.getConnection();
UserDAO userDAO = new UserDAO(connection);
userDAO.delete(id);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Sample 6 - Limiting results
*/
public static void limitData(int limit) {
//instantiate database connection manager object
DatabaseConnctionManager dcm = new DatabaseConnctionManager("localhost", "jdbc_tutorial", "root", "<PASSWORD>");
try {
Connection connection = dcm.getConnection();
UserDAO userDAO = new UserDAO(connection);
List<User> users = userDAO.findAllSorted(limit);
for(User user: users) {
System.out.println(user.toString());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Sample 7 - Paging results
*/
public static void pageData(int limit, int pageNumber) {
//instantiate database connection manager object
DatabaseConnctionManager dcm = new DatabaseConnctionManager("localhost", "jdbc_tutorial", "root", "<PASSWORD>");
try {
Connection connection = dcm.getConnection();
UserDAO userDAO = new UserDAO(connection);
List<User> users = userDAO.findPagedSorted(limit, pageNumber);
for(User user: users) {
System.out.println(user.toString());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
<file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/permission/PermissionExample.java
package pers.sample.tutorial.permission;
public class PermissionExample {
/**
* Access Control
* Now class, Now packages, Child class, Other packages
* public y,y,y,y
* protected y,y,y,n
* default y,y,n,n
* private y,n,n,n
*/
public String param1 = "public";
protected String param2 = "protected";
String param3 = "default";
private String param4 = "private";
/**
* Static Variable
* No matter how many object you instantiate from class, there is only one static variable. like, a global variable.
*
* Static Method
* Static method cannot use the variable which is not static variable in the class.
*/
public static String staticParam = "STATIC";
public static String staticMethod() {
//Error: not static variable
//return param3;
return staticParam;
}
/**
* final variable
* final variable only can be initial once and cannot be modify
*
* final method
* final method can be extend but cannot modify the content
*
* final class
* final class cannot be extend
*/
public final int int1 = 1;
final public int int2 = 2;
/**
* synchronized method only can be access by one thread on same time.
*/
public synchronized void getDepositeMoney(int getMoney) {
//deposite-getMoney
}
/**
* transient keyword
* 序列化的class包含 transient變數時,JVM會跳過該特定的變數
*/
//不會持久化
//public transient int sortNumber = 7;
//會持久化
//public transient int number;
/**
* A value of volatile variable will force reload this value from share memories when each thread access.
*/
public volatile int deposite = 1000000;
}
<file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/polymorphism/Cat.java
/**
* @author <NAME>
*
*/
package pers.sample.tutorial.polymorphism;
//Subtype
public class Cat extends Animal {
//Override
void sound() {
System.out.println("mew mew mew ~~~");
}
}
<file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/polymorphism/Dog.java
/**
* @author <NAME>
*
*/
package pers.sample.tutorial.polymorphism;
//Subtype
public class Dog extends Animal {
//Override
void sound() {
System.out.println("woof woof woof ~~~");
}
}
<file_sep>/JavaJdbcTutorial2/src/main/java/pers/sample/jdbc/tutorial/DatabaseConnctionManager.java
/**
* Auther: <NAME>
* Date: 2021-07-08
*
* Step 1: Create a 'DatabaseConnectionManager' class
* Step 2: Init connection information for database
* Step 3: Use DriverManager to get the database connection
*
*/
package pers.sample.jdbc.tutorial;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DatabaseConnctionManager {
private final String url;
private final Properties properties;
public DatabaseConnctionManager(String host, String databaseName, String username, String password) {
//The connection statement depend on which database you are use
//Ex. postgreSQL -> "jdbc:postgresql://... ..."
this.url = "jdbc:mysql://" + host + "/" + databaseName + "?autoReconnect=true&useSSL=false";// + "?serverTimezone=UTC";
//set user and password to properties
this.properties = new Properties();
this.properties.setProperty("user", username);
this.properties.setProperty("password", <PASSWORD>);
}
// connection
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, this.properties);
}
}
<file_sep>/JavaJdbcTutorial2/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>pers.sample.jdbc.tutorial</groupId>
<artifactId>JavaJdbcTutorial2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>JavaJdbcTutorial2</name>
<properties>
<java.version>1.7</java.version>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.compiler.source>${java.version}</maven.compiler.source>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
</dependencies>
</project><file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/files/FileSparatorExample.java
/**
* @author <NAME>
*
* Understand use the file separator, because it may have different separator in different OS.
*
*/
package pers.sample.tutorial.files;
import java.io.File;
public class FileSparatorExample {
public static void main(String[] args) {
System.out.println("File.separator = "+File.separator);
System.out.println("File.separatorChar = "+File.separatorChar);
System.out.println("File.pathSeparator = "+File.pathSeparator);
System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
}
}
<file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/abstracts/AbstractClass.java
/**
* @author <NAME>
*
* Abstract class must be inherited to use
*
* 2. This class extends ParentsAbstractClass
*
*/
package pers.sample.tutorial.abstracts;
public abstract class AbstractClass extends ParentsAbstractClass {
public int age = 18;
public String addr;
public abstract void printHello();
public void printName(String name) {
System.out.println("Hello " + name);
}
public void printAge() {
System.out.println("Age : " + age);
}
public void printAddr() {
System.out.println("Address : " + addr);
}
}
<file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/abstracts/ExtendsClass.java
/**
* @author <NAME>
*
* Abstract class must be inherited to use
*
* 3. This class extends AbstractClass.
* 4. Must write content to abstract method.
*
*/
package pers.sample.tutorial.abstracts;
public class ExtendsClass extends AbstractClass {
//Must write content to abstract method. (This method is from AbstractClass)
@Override
public void printHello() {
System.out.println("Hello");
}
//Must write content to abstract method. (This method is from ParentsAbstractClass)
@Override
public void setRole(String role) {
super.role = role;
}
public void updateAge(int age) {
super.age = age;
}
public void updateAddr(String addr) {
super.addr = addr;
}
}
<file_sep>/JavaDataStructureTutorial/src/pers/sample/tutorial/stack/StackExample.java
/**
*
* @author <NAME>
*
* You should understand linked list first.
*
* Stack A stack is a linear data structure in which
* elements can be inserted and deleted only from one side of the list, called the top.
*
* A stack follows the LIFO (Last In First Out) principle
*
* The insertion of an element into stack is called "push" operation, and deletion of an element from the stack is called "pop" operation
*
* Applications:
* 1. Converting a decimal number into a binary number
* 2. Parsing
* 3. Expression Conversion(Infix to Postfix, Postfix to Prefix etc)
* 4. Towers of Hanoi
* 5. Rat in a Maze solving
*
*/
package pers.sample.tutorial.stack;
import java.util.LinkedList;
public class StackExample {
public static void main(String[] args) {
LinkedList<String> stack = new LinkedList<String>();
//push
//add() - Appends the specified element to the end of this list.
stack.add("Winnie");
stack.add("Lai");
stack.add("<NAME>");
//pop
//removeLast() - Removes and returns the last element from this list.
System.out.println(stack.removeLast());
System.out.println(stack.removeLast());
System.out.println(stack.removeLast());
//another way to achieve stack
//use Stack class
}
}
<file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/interfaces/HumanInterface.java
/**
* @author <NAME>
*
* This interface extends AnimalInterface
*
*/
package pers.sample.tutorial.interfaces;
public interface HumanInterface extends AnimalInterface {
public String tool1 = "weapon";
public abstract void makeTool();
// public void makeTool();
}
<file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/override/Person.java
/**
* @author <NAME>
*
* Please check toString() Method
* Override: Supertype 's method has been override, so we can re-defined the method content in subtype.
*
*/
package pers.sample.tutorial.override;
public class Person {
private String name;
public Person() {
name = "unknow";
}
//This Method exist in the supertype
//We try to override the content in this method.
@Override
public String toString() {
//The existing code: call the super toString() Method
//return super.toString();
return "My name is " + name + "!!!";
}
}
<file_sep>/JavaJdbcTutorial2/src/main/java/pers/sample/jdbc/tutorial/util/DataTransferObject.java
package pers.sample.jdbc.tutorial.util;
public interface DataTransferObject {
long getId();
}
<file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/exception/ExceptionExample.java
/**
* @author <NAME>
*
* How to use Exception structure
*
* try ... catch ... finally
* throws exception
*
*/
package pers.sample.tutorial.exception;
public class ExceptionExample {
public static void main(String[] args) {
// String str = "123"; //Correct Test
String str = "123a"; //Incorrect Test
processExceptionInTryCatch(str);
//If method may throw exception, you should process in where you invoke the method.
//Otherwise, this exception (error) will cause that shut down your application.
dontProcessException(str);
}
//It will process exception in try-catch and print error/warning in Log file
public static void processExceptionInTryCatch(String str) {
try {
Long tmp = Long.valueOf(str);
System.out.println(tmp);
} catch(NumberFormatException e) { // NumberFormatException
System.out.println(e);
System.out.println(e.getMessage());
e.printStackTrace();
} catch(Exception e) { // The parent class of all the exception class
System.out.println(e);
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
// finally will always be executed before finish
System.out.println("end");
}
}
//It will not process exception. If exception occurs, it will throws the exception to the caller.
public static void dontProcessException(String str) throws NumberFormatException {
Long tmp = Long.valueOf(str);
System.out.println(tmp);
}
}
<file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/interfaces/ImplementsClass.java
/**
* @author <NAME>
*
* This class implements HumanInterface and SKillInterface.
* This class which implements interface must write content to abstract method.
*
*/
package pers.sample.tutorial.interfaces;
public class ImplementsClass implements HumanInterface, SkillInterface {
@Override
public void eat() {
System.out.println("Eat: " + food1);
}
@Override
public void draw() {
System.out.println("Make Tool: " + tool1);
}
@Override
public void coding() {
System.out.println("I can draw");
}
@Override
public void makeTool() {
System.out.println("I can coding");
}
}
<file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/token/TokenizerExample.java
/**
* @author <NAME>
*
* How to use different way to separate the string
* 1. split
* 2. StringTokenizer
*/
package pers.sample.tutorial.token;
import java.util.StringTokenizer;
public class TokenizerExample {
public static void main(String[] args) {
final String str = ",5,6,7,,1,2,3";
TokenizerExample.useSplit(str);
TokenizerExample.useStringTokenizer(str);
}
/**
* Using split
* @param str
*/
public static void useSplit(String str) {
System.out.println("Split");
String[] strArr = str.split(",");
System.out.println("strArr Length : " + strArr.length);
for(String s:strArr) {
System.out.println(s);
}
}
/**
* Using StringTokenizer
* @param str
*/
public static void useStringTokenizer(String str) {
System.out.println("StringTokenizer");
StringTokenizer st = new StringTokenizer(str, ",");
System.out.println("StringTokenizer Count : " + st.countTokens());
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
<file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/interfaces/AnimalInterface.java
/**
* @author <NAME>
*
* Interface:
* 1. Interface only has "public" level.
* 2. All of variables will be transform into "public static final" variables by implicit function in interface.
* 3. All of methods will be transform into "public abstract" methods by implicit function in interface.
*
*/
package pers.sample.tutorial.interfaces;
public interface AnimalInterface {
public String food1 = "meat";
public static final String food2 = "fish";
//Error
// public String food3;
// private String food4 = "fruit";
public void eat();
// public abstract void eat();
}
<file_sep>/JavaDataStructureTutorial/src/pers/sample/tutorial/set/SetExample.java
/**
* @author <NAME>
*
* A collection that contains no duplicate elements and at most one null element.
*
*/
package pers.sample.tutorial.set;
import java.util.HashSet;
import java.util.Set;
public class SetExample {
public static void main(String[] args) {
Set<Integer> integerSet = new HashSet<Integer>();
//new LinkedHashSet<>()
//new TreeSet<>()
//Add elements
integerSet.add(new Integer(111));
integerSet.add(new Integer(111)); //only be added once
integerSet.add(new Integer(112));
integerSet.add(new Integer(520));
integerSet.add(new Integer(530));
integerSet.add(new Integer(540));
System.out.println(integerSet.size() + "\n"); //5
//Set class don't have get method.
//Check the element in the set
System.out.println(integerSet.contains(new Integer(520)));
System.out.println(integerSet.contains(new Integer(522)));
//Iterator set
//Method - 1
System.out.println("\nMethod 1:");
for(Integer integer: integerSet) {
System.out.println(integer);
}
//Method - 2
System.out.println("\nMethod 2:");
integerSet.forEach((value) -> {
System.out.println(value);
});
}
}
<file_sep>/JavaDataStructureTutorial/src/pers/sample/tutorial/tree/TreeExample.java
/**
* @author <NAME>
*
* Tree types:
* General tree
* Binary tree
* Binary search tree
* AVL tree (a self-balancing binary search tree)
*
*
*/
package pers.sample.tutorial.tree;
public class TreeExample {
}
<file_sep>/JavaDataStructureTutorial/src/pers/sample/tutorial/array/ArrayExample.java
/**
*
* @author <NAME>
*
* Java data structure - Array
*
* how to declare an array and initialize
* how to change element
* how to iterate the all elements
*
*/
package pers.sample.tutorial.array;
public class ArrayExample {
public static void main(String[] args) {
//Declare an array
String[] array1;
//Declare an array with content
String[] array2 = {"Yu", "Hsuan", "Huang"};
//Access the Elements of an Array
System.out.println(array2[0]);
//Change an Array Element
array2[0] = "Sean";
System.out.println(array2[0]);
//Array Length
System.out.println(array2.length);
//Loop Through an Array
//for
for(int i=0; i<array2.length; i++) {
System.out.println(array2[i]);
}
//for-each
for(String str : array2) {
System.out.println(str);
}
//Multidimensional Arrays
int[][] array3;
int[][] array4 = { {1, 2, 3}, {4, 5, 6} };
}
}
<file_sep>/JavaBasicTutorial/src/pers/sample/tutorial/string/StringTypeExample.java
/**
* @author <NAME>
*
* Compare String, StringBuffer and StringBuilder.
*
* Best to use StringBuilder: Check below to know why
*
*/
package pers.sample.tutorial.string;
public class StringTypeExample {
public static void main(String[] args) {
/**
* operating speed:
* StringBuilder > StringBuffer > String
*
* String is most slow because String is immutable.
* It means String class will created new string even you use concatenation.
*/
//String is immutable.
String str1 = "string value";
String str2 = "string value"; //It will point memory address same as str1
String str3 = new String("string value"); //It will instantiate new object.
System.out.println("Memory Address:");
System.out.println("@" + Integer.toHexString(System.identityHashCode(str1)));
System.out.println("@" + Integer.toHexString(System.identityHashCode(str2)));
System.out.println("@" + Integer.toHexString(System.identityHashCode(str3)));
//String equal example
System.out.println("\nString Equal Example:");
if(str1 == str2)
System.out.println("str1 and str2 point out same memory address, so using (==) they are equal.");
if(str1 != str3)
System.out.println("str1 and str3 point out different memory address, so using (!=) they are not equal.");
if(str1.equals(str2))
System.out.println("str1 and str2 have same content, so using (equals mehtod) they are equal.");
if(str1.equals(str3))
System.out.println("str1 and str3 have same content, so using (equals mehtod) they are equal.");
//Both StringBuffer and StringBuilder are mutable objects.
/**
* Different between StringBuffer and StringBuilder.
*
* StringBuffer is synchronized, StringBuilder is not.
* So, StringBuilder is faster than StringBuffer because it's not synchronized.
*
* Simply use StringBuilder unless you really are trying to share a buffer between threads.
*/
//Test change StringBuilder and check memory address
System.out.println("\nStringBuilder modify example:");
StringBuilder strBud = new StringBuilder("string value");
System.out.println(strBud + ":" + "@" + Integer.toHexString(System.identityHashCode(strBud)));
strBud.append(" by StringBuilder");
System.out.println(strBud + ":" + "@" + Integer.toHexString(System.identityHashCode(strBud)));
//Test change StringBuffer and check memory address
System.out.println("\nStringBuffer modify example:");
StringBuffer strBuf = new StringBuffer("string value");
System.out.println(strBuf + ":" + "@" + Integer.toHexString(System.identityHashCode(strBuf)));
strBud.append(" by StringBuilder");
System.out.println(strBuf + ":" + "@" + Integer.toHexString(System.identityHashCode(strBuf)));
}
}
| d2059a9a5297173d1d8b50d6610b74d50d814a31 | [
"Java",
"Maven POM"
] | 22 | Java | yuhsuanhuang-tw/JavaTutorial | 53405879b0031d763806ca2ede0202b9c45c5958 | df25c0b72ce3552eaff997b4d443ede81a531b8a |
refs/heads/master | <file_sep>#REQUIRE:download_cells.py
#Script is used to output where the logs are located for each server
resource = '/home/rameshgummada/PYTHON_SCRIPTS'
import sys
import re
sys.path.insert(0, resource)
from select_cells import SelectCells
from log_report import LogReport
from html_render import RenderHTML
#Grab the list of servers to run
app = sys.argv[1] #PROJECT/B2B
env_type = sys.argv[2] #NONPROD/PROD
env = sys.argv[3] #DEV/FT
version = sys.argv[4] #U8/U7
html_loc = sys.argv[5] #html file path
log_loc = sys.argv[6] #log file path
servers = SelectCells.getServers(SelectCells(),app, env_type, env, version)
log = LogReport(log_loc)
html = RenderHTML(html_loc)
html.head("Log Locationss", servers[0]["V"], html_loc)
html.tableStart("Log Locations")
html.tableHeaders(["ENV","CELL","SERVER","V","SystemOut Location", "SystemError Location", "STDOut Location", "STDErr Location"])
if env_type == "NONPROD":
root_loc = "/home/rameshgummada/PYTHON_SCRIPTS"
else:
root_loc = "/home/rameshgummada/PYTHON_SCRIPTS"
for server in servers:
if not server["SERVER"] == "dmgr":
try:
vars = ''
var_file = open(root_loc + server["V"] + "/" + server["HOST"] + "/" + server["CELL"] + "/" + server["SERVER"] + "/SERVER/variables.xml")
for line in var_file:
vars += line
var_file.close()
server_loc = re.findall('SERVER_LOG_ROOT"\s+value="(.+)" description',vars)
if len(server_loc) == 0:
server_loc = ["N\A"]
serv = ''
server_file = open(root_loc + server["V"] + "/" + server["HOST"] + "/" + server["CELL"] + "/" + server["SERVER"] + "/SERVER/server.xml")
for line in server_file:
serv += line
server_file.close()
system_out = re.findall('fileName="(.+SystemOut.log)',serv)
system_err = re.findall('fileName="(.+SystemErr.log)',serv)
stdPath = re.findall('stdoutFilename="(.+)"\sstderrFilename="(.+)"/>',serv)
if len(system_out) == 0:
system_out = ["N\A"]
if len(system_err) == 0:
system_err = ["N\A"]
if len(stdPath) == 0:
stdPath = [["N\A","N\A"]]
stdout = str(stdPath[0][0]).replace("${PROJECT_SERVER_LOG_ROOT}", server_loc[0]).replace("${SERVER_LOG_ROOT}", server_loc[0]).replace("${WAS_SERVER_NAME}", "").replace("${LOG_ROOT}", "")
stderr = stdPath[0][1].replace("${PROJECT_SERVER_LOG_ROOT}", server_loc[0]).replace("${SERVER_LOG_ROOT}", server_loc[0]).replace("${WAS_SERVER_NAME}", "").replace("${LOG_ROOT}", "")
system_out = system_out[0].replace("${PROJECT_SERVER_LOG_ROOT}", server_loc[0]).replace("${SERVER_LOG_ROOT}", server_loc[0]).replace("${WAS_SERVER_NAME}", "").replace("${LOG_ROOT}", "")
system_err = system_err[0].replace("${PROJECT_SERVER_LOG_ROOT}", server_loc[0]).replace("${SERVER_LOG_ROOT}", server_loc[0]).replace("${WAS_SERVER_NAME}", "").replace("${LOG_ROOT}", "")
html_info = [server["ENV"], server["CELL"], server["SERVER"], server["V"], system_out, system_err, stdout, stderr]
html.tableBody(html_info)
except IOError as e:
log.writeLog(str(e))
html.tableEnd()
html.foot()
log.endLog()
log.endLog()
<file_sep># Delete the logs older than 45 days (List and Remove)
# Declare variables
CONFIGFILE="/opt/support/scripts/configFile"
HOURDATE=`date '+%Y%m%d%H%M'`
CLEANDIR="/opt/netprobe/log"
DELETELOG="/var/tmp/cleanup_$HOURDATE.log"
if [ ! -f $CONFIGFILE ]; then
echo "Configuration File not found under $CONFIGFILE" 2>&1
exit 1
fi
for read_line in `cat $CONFIGFILE`
do
log_name=`echo $read_line`
delete_logs $log_name
done
# | Sub Procedure to list the files & deletes them
delete_logs()
{
log_name=$1
echo "Listing files to remove..." >> $DELETELOG 2>&1
/usr/bin/find $CLEANDIR type -f -name "$log_name*.*" -mtime +45 -exec ls -ltr {} \; >> $DELETELOG 2>&1
echo "Removing files --> $HOURDATE" >> $DELETELOG 2>&1
/usr/bin/find $CLEANDIR type -f -name "$log_name*.*" -mtime +45 -exec rm {} \; >> $DELETELOG 2>&1
}
Get Outlook for iOS
<file_sep>#!/bin/ksh
# Author: <NAME>
myLoop()
{
vRDEXT=$1
vRDFIL=$2
case $vRDEXT in
jpg|png)
if [[ ! -d $vHDIR/$vRDEXT ]]; then
mkdir -vp $vHDIR/images
fi
mv -v $vHDIR/$vRDFIL $vHDIR/images/$vRDFIL
;;
mov|mp3)
if [[ ! -d $vHDIR/$vRDEXT ]]; then
mkdir -vp $vHDIR/movies
fi
mv -v $vHDR/$vRDFIL $vHDIR/movies/$vRDFIL
;;
log)
rm -vf $vHDIR/$vRDFIL
;;
*);;
esac
}
# Declare Variables
vHDIR=/var/tmp/ram123
vEXT=={ .jpg, .png, .mp3, .log} 2>/dev/null
#echo $vEXT
for vPARAM in `ls *$vEXT`
do
# echo $vPARAM
vFEXT="${PvPARAM##*.}"
myLoop $vFEXT $vPARAM
done
| 5a4f2f437e0837c34808267e7048413963e344ec | [
"Python",
"Shell"
] | 3 | Python | rameshgummada/Unix_ex | c842531f2dd2a3578588fe8323cf5ff35a3f12ca | 16893a12c3adbe5d424927f980066a25f9b6f83e |
refs/heads/master | <repo_name>dairafelix/idcard<file_sep>/app.js
function idCard() {
//First Name
let firstName =
document.getElementById("firstName").value;
console.log(firstName);
document.getElementById("cardName").innerHTML = firstName;
//Last Name
let lastName =
document.getElementById("lastName").value;
console.log(lastName);
document.getElementById("cardLastName").innerHTML = lastName;
//Address
let userAddress =
document.getElementById("userAddress").value;
console.log(userAddress);
document.getElementById("cardAddress").innerHTML = userAddress;
//Phone Number
let phoneNumber =
document.getElementById("phoneNumber").value;
console.log(phoneNumber);
document.getElementById("cardNumber").innerHTML = phoneNumber;
//Age
let userAge =
document.getElementById("userAge").value;
console.log(userAge);
document.getElementById("cardAge").innerHTML = userAge;
}
| 7061c4b50c5708ed76a65230ed5261f1b0b73a4a | [
"JavaScript"
] | 1 | JavaScript | dairafelix/idcard | af84f75f67fb4b019c4df1957077689bfe2b811f | 963eb291b3a07ac226bcdbafc7e803ba1e17c30f |
refs/heads/master | <repo_name>AnosAhmad/Array-Peak-value<file_sep>/README.md
# Array-Peak-value
<file_sep>/peak.cpp
#include<fstream>
#include<iostream>
#include <string>
#include <vector>
#include<math.h>
using namespace std;
//Name: <NAME>.
//FindPeak Algorithm in 1D.
std::pair<int, int> findpeak(vector<int> arrayofint, int start, int end)
{
//if the array contains only one integer
if (end == start)
{
return std::make_pair(arrayofint[start], start);
}
//if the array contains at least 2 integers
else{
//Divide by finding the mid point constant time Theta(1)
int mid = (end - start) / 2 + start;
/* Conqure phase by check if the mid value is peak (it is greater than both of its neighbours) then
return it, else If the left neighbour is greater, then find the peak recursively in the left side of the array.
else If the right neighbour is greater, then find the peak recursively in the right side of the array*/
if ((mid == 0 || arrayofint[mid - 1] <= arrayofint[mid]) && (mid == end || arrayofint[mid + 1] <= arrayofint[mid]))
{
return std::make_pair(arrayofint[mid], mid);
}
else {
if (mid > 0 && arrayofint[mid - 1] > arrayofint[mid])
{
return findpeak(arrayofint, start, mid - 1);
}
else {
if (arrayofint[mid + 1] > arrayofint[mid])
{
return findpeak(arrayofint, mid + 1, end);
}
}
}
}
}
//Read the series of integers from the Text file
vector<int> read(){
//Local variables
ifstream openfile;
string filename, linee;
vector<int> arrayofint;
int num;
//Name of text file
filename = "peak.txt";
//Open the file and Check if it exists
openfile.open(filename);
if (openfile.fail()) {
std::cout << "No data file"<< endl;
exit(1);
}
//If file exist in the Dir start reading
else{
while (!openfile.eof()) {
getline(openfile, linee);
num = atoi(linee.c_str());
arrayofint.push_back(num);
}
openfile.close();
//print out the Integer values
std::cout << "\nA = [";
for (int i = 0; i < arrayofint.size(); i++){
std::cout << " " << arrayofint.at(i);
}
std::cout << " ]\n" << endl;
}
return arrayofint;
}
//Main function
int main()
{
//Local variables
vector<int> arrayofint;
std::pair< int, int> peakinfo;
//Read the series of integers from the Text file
arrayofint = read();
//Find Peak Value and Index
peakinfo = findpeak(arrayofint, 0, arrayofint.size() - 1);
//print out the peak information
std::cout << "The Peak Value: " + to_string(peakinfo.first) + "\nThe Peak Index: " + to_string(peakinfo.second) << endl;
return 0;
}
| 042474177b963621433683c0a27abdbc5ab38d89 | [
"Markdown",
"C++"
] | 2 | Markdown | AnosAhmad/Array-Peak-value | 908ef129a17f22d8e694e9efbd290a393949e66c | d12727747448fc17908ee4205a9ca5fdb4a7f02c |
refs/heads/master | <file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { NavLink } from 'react-router-dom';
import { themeSettings, text } from '../lib/settings';
class FooterMenu extends React.Component {
constructor(props) {
super(props);
this.state = {
isActive: false
};
}
isActiveToggle = () => {
this.setState({
isActive: !this.state.isActive
});
};
render() {
const { title, items } = this.props;
let ulItems = null;
if (items && items.length > 0) {
ulItems = items.map((item, index) => (
<li key={index}>
<NavLink to={item.url || ''}>{item.text}</NavLink>
</li>
));
}
return (
<div className="column is-3">
<div
className={
'footer-title mobile-padding' +
(this.state.isActive ? ' footer-menu-open' : '')
}
onClick={this.isActiveToggle}
>
{title}
<span />
</div>
<ul className="footer-menu">{ulItems}</ul>
</div>
);
}
}
const SocialIcons = ({ icons }) => {
if (icons && icons.length > 0) {
const items = icons.map((icon, index) => (
<a
key={index}
href={icon.url || ''}
target="_blank"
rel="noopener"
title={icon.type}
className={icon.type}
/>
));
return <p className="social-icons">{items}</p>;
} else {
return null;
}
};
const Contacts = ({ contacts }) => {
if (contacts && contacts.length > 0) {
const items = contacts.map((item, index) => {
const contact = item ? item.text : null;
if (contact && contact.indexOf('@') > 0) {
return (
<li key={index}>
<a href={'mailto:' + contact}>{contact}</a>
</li>
);
} else {
return <li key={index}>{contact}</li>;
}
});
return <ul className="footer-contacts">{items}</ul>;
} else {
return null;
}
};
export default class Footer extends React.PureComponent {
render() {
return (
<section class="section has-text-centered" id='furfooter'>
<div class="container">
<div class="columns">
<div class="column">
<ul class='right-list'>
<li><a>Home</a></li>
<li><a>Chair</a></li>
<li><a>Table</a></li>
<li><a>Futon</a></li>
</ul>
</div>
<div class="column">
<figure class="image is-96x96" style={{ margin: 'auto' }}>
<img src="https://condehouse.com.au/wp-content/uploads/2018/12/50-th.png" />
</figure>
</div>
<div class="column right-copy">
<h3>Copyright <NAME> 2019</h3>
</div>
</div>
<div className='gap'></div>
</div>
</section>
);
}
}
<file_sep>import React, { Component } from 'react';
import { Fragment } from 'react';
import { NavLink } from 'react-router-dom';
const Furniture = () => (
<Fragment>
<section className="section">
<div className="container has-text-centered">
<h1
className="title has-text-weight-light"
style={{ color: '#726658', marginTop: '30px', marginBottom: '40px' }}
>
Welcome to Haiku Wares
</h1>
<h2 className="subtitle subhide">
Haiku wares provides handcrafted, custom wood furniture that is made
sustainably. We recognise and cherish Japan’s strong values of
craftsmanship and sustainability, and we're doing our part to help
spread those values across the country and the world.
</h2>
</div>
<div className="container" style={{ marginTop: '60px' }}>
<figure className="image">
<img src="https://res.cloudinary.com/dmjvm8vzc/image/upload/v1557660752/furnituretxet.jpg" />
</figure>
</div>
<div className="container" style={{ marginTop: '60px' }}>
<h1
className="title has-text-weight-light has-text-centered"
style={{ color: '#726658' }}
>
Product categories
</h1>
<div class="columns zoomimage">
<NavLink to="chair">
<div class="column">
<h2 class="subtitle has-text-centered category-text">CHAIR</h2>
<figure class="image">
<img src="https://cdn.condehouse.co.jp/upload/save_image/product/01100639_5a55b52d68733.jpg" />
</figure>
</div>
</NavLink>
<NavLink to="table">
<div class="column">
<h2 class="subtitle has-text-centered category-text">TABLE</h2>
<figure class="image">
<img src="https://cdn.condehouse.co.jp/upload/save_image/product/06150434_5b2341db73958.jpg" />
</figure>
</div>
</NavLink>
<NavLink to="sofa">
<div class="column">
<h2 class="subtitle has-text-centered category-text">SOFA</h2>
<figure class="image">
<img src="https://cdn.condehouse.co.jp/upload/save_image/product/07071123_53ba8328c37ea.jpg" />
</figure>
</div>
</NavLink>
<NavLink to="cabinets">
<div class="column">
<h2 class="subtitle has-text-centered category-text">CABINETS</h2>
<figure class="image">
<img src="https://cdn.condehouse.co.jp/upload/save_image/product/03250449_53310aeb80b4a.jpg" />
</figure>
</div>
</NavLink>
</div>
</div>
</section>
</Fragment>
);
export default Furniture;
| ac39ebea53d9f81e0c9413e10b2735fa25479b5f | [
"JavaScript"
] | 2 | JavaScript | cloudstrife9971/Haikyustore | 3d0dbbd5024f8c0d219e0edc20fc8f777fcf4b02 | aae1588a751020386e79e86f19d2b544f615d3c4 |
refs/heads/master | <repo_name>leungjch/procgen-sprite-cellular<file_sep>/js/sketch.js
var WORLDWIDTH = 4; // number of tiles (cells)
var WORLDHEIGHT = 8;
var SPRITEWIDTH = WORLDWIDTH*2+2; // include two border outlines
var SPRITEHEIGHT = WORLDHEIGHT+2;
var SHOW_GRID = true;
var framerate = 0.5;
var WIDTH, HEIGHT, GRIDSIZE;
if (SHOW_GRID)
{
WIDTH = 1920;
HEIGHT = 1080;
GRIDSIZE = WIDTH/SPRITEWIDTH/4;
}
else
{
WIDTH = SPRITEWIDTH*1;
HEIGHT = SPRITEHEIGHT*1;
GRIDSIZE = 1;
}
var sprite = [] // a 2D array containing the complete sprite (including )
var max_iteration = 2; // stop after 3 iterations
var finished = false;
var time = 0;
var config = {
'Name':"<NAME>",
'Type':moore_simple_neighborhood,
'Birth_Rule':[0,1],
'Alive_Rule':[2,3],
'Max_State':1,
'Width':WORLDWIDTH,
'Height':WORLDHEIGHT,
'Wrap_Edges':false
};
// 3x3 moore
var moore_simple_neighborhood = [
[1,1,1],
[1,0,1],
[1,1,1]
];
var von_neumann_simple_neighborhood = [
[0,1,0],
[1,0,1],
[0,1,0]
];
var alt_neighborhood = [
[1,0,1],
[0,0,0],
[1,0,1]
];
var neighborhood = von_neumann_simple_neighborhood;
var alive_color_code = "#2E8B9F"
// Implements a cellular automata system
class Cellular_Automata
{
// specify x,y position, initial state
constructor(config, neighborhood)
{
this.config = config;
this.neighborhood = neighborhood;
// a 2D array that cells that can be dead or alive
this.cells = [];
// an array of cells that are only alive. We render this this so that we don't waste time looping through empty array elements during render.
this.cells_alive = [];
// records cells over time: dimension. i-th element contains the i-th frame of cells
this.system = [];
this.system_alive = [];
}
// count a single cell's neighbours
count_neighbours(xPos, yPos, cell_snapshot)
{
var n_neighbours = 0;
for (let a = 0; a < this.neighborhood.length; a++)
{
for (let b = 0; b < this.neighborhood[0].length; b++)
{
// check if neighborhood item is true, else skip
if (this.neighborhood[a][b] === 1)
{
// get distance from center of neighborhood to current cell to check in neighborhood
var xDist = b - Math.floor(this.neighborhood.length/2);
var yDist = a - Math.floor(this.neighborhood[0].length/2);
// access cell xDist,yDist away from the center of the cell with global coordinates xPos, yPos
// check if within bounds
if (!this.config['Wrap_Edges'])
{
if (xPos+xDist >= 0 && xPos+xDist < this.config['Width'] && yPos+yDist >= 0 && yPos+yDist < this.config['Height'])
{
// if this cell is alive, update neighbour count
if (cell_snapshot[xPos+xDist][yPos+yDist].state === config['Max_State'])
{
n_neighbours = n_neighbours + 1
}
}
}
else
{
var wrap_x = xPos+xDist;
var wrap_y = yPos+yDist;
if (wrap_x === -1)
{
wrap_x = this.config['Width']-1
}
else if (wrap_x > this.config['Width']-1)
{
wrap_x = 0
}
if (wrap_y === -1)
{
wrap_y = this.config['Height'] - 1
}
else if (wrap_y > this.config['Height']-1)
{
wrap_y = 0
}
// console.log(wrap_y, wrap_x)
if (cell_snapshot[wrap_x][wrap_y].state === this.config['Max_State'])
{
n_neighbours = n_neighbours + 1
}
}
}
}
}
return n_neighbours;
}
init(use_random_probability = null)
{
// array data
this.cells = []
this.cells_alive = []
this.system_alive = []
this.system = []
for (let x = 0; x < this.config['Width']; ++x)
{
this.cells[x] = [];
for (let y = 0; y < this.config['Height']; ++y)
{
// create cell object at (x,y)
this.cells[x][y] = [];
// cells[x][y] = new Cell(xPos = x, yPos = y, state = config['Max_State'], rect = );
if (use_random_probability === null)
{
this.cells[x][y] = new Cell(x, y, 0);
}
else
{
this.cells[x][y] = new Cell(x, y, Math.random() > use_random_probability ? 0 : this.config["Max_State"]);
if (this.cells[x][y].state > 0)
{
this.cells_alive.push(this.cells[x][y])
}
}
}
}
}
// Update system n times (default 1)
iterate(n=1)
{
for (var z = 0; z < n; z++)
{
var myCells = this.cells
// create a copy of the system
// this is necessary because looping through and updating the system will cause
// later cells to be updated based on the *new* cells, which is not what we want
const cells_read_only = JSON.parse(JSON.stringify(myCells))
// const cells_read_only = Object.assign({}, myCells)
var cells_updated = myCells;
this.cells_alive = [];
for (let x = 0; x < WORLDWIDTH; ++x)
{
for (let y = 0; y < WORLDHEIGHT; ++y)
{
// Count neighbours
// pass in a snapshot of the cell system
var n_neighbours = this.count_neighbours(x,y, cells_read_only);
// For dead (empty) cells
// Create a new cell at this location if it is dead and contains n_neighbours in rule
if (this.config['Birth_Rule'].includes(n_neighbours) && cells_read_only[x][y].state === 0)
{
cells_updated[x][y].state = this.config['Max_State'];
this.cells_alive.push(cells_updated[x][y])
}
// Else check alive cells
// Keep cell alive if cell contains this many neighbours
else if (this.config['Alive_Rule'].includes(n_neighbours) && cells_read_only[x][y].state === this.config['Max_State'])
{
cells_updated[x][y].state = this.config[ 'Max_State'];
this.cells_alive.push(cells_updated[x][y])
}
// Else, cell loses 1 state (state--) or is dead (state=0)
else
{
cells_updated[x][y].state = Math.max(0, cells_read_only[x][y].state-1)
if (cells_updated[x][y].state > 0)
{
this.cells_alive.push(cells_updated[x][y])
}
}
}
}
// update cells
this.cells = cells_updated;
this.system.push(cells_updated);
this.system_alive.push(this.cells_alive);
}
}
}
// A cell object is simply a square on a grid with a state
class Cell
{
// specify x,y position, initial state
constructor(xPos, yPos, state)
{
this.x = xPos;
this.y = yPos;
this.state = state;
// this.rect = rect;
}
setState(number)
{
this.state = number;
}
}
class Square
{
// square contains color values and its type - "body" or "outline"
// color is a hex string
constructor(color, type)
{
this.color = color;
this.type = type;
}
}
class Sprite
{
// pass in a Cellular_Automata object to the sprite which we use to generate the full sprite
// symmetry refers to the axis of symmetry requested when we flip. Valid values: "none", "vertical", "horizontal", "left diagonal", "right diagonal"
constructor(cellular_automata, symmetry)
{
this.cellular_automata = cellular_automata;
this.symmetry = symmetry;
// set body color
this.color_body = "#" + Math.floor(Math.random()*16777215).toString(16);
this.color_edge = "#000000";
if (symmetry === "vertical")
{
this.SpriteWidth = this.cellular_automata.config['Width'] * 2 + 2 ;
this.SpriteHeight = this.cellular_automata.config['Height'] + 2;
}
else if (symmetry === "horizontal")
{
this.SpriteWidth = this.cellular_automata.config['Width'] + 2;
this.SpriteHeight = this.cellular_automata.config['Height'] * 2 + 2;
}
else if (symmetry === "center")
{
this.SpriteWidth = this.cellular_automata.config['Width'] * 2 + 2;
this.SpriteHeight = this.cellular_automata.config['Height'] * 2 + 2;
}
else
{
this.SpriteWidth = this.cellular_automata.config['Width'] + 2;
this.SpriteHeight = this.cellular_automata.config['Height'] + 2;
}
this.graphics = Array(this.SpriteWidth).fill( new Square("ffffff", "empty") )
.map(x => Array(this.SpriteHeight).fill( new Square("ffffff", "empty") )); // create an empty graphics array to fill with Square objects
}
// count surroundings at x,y (left,right,bottom,top,topright,topleft,bottomleft,bottomright)
// needed to fill outline
count_neighbours(xPos,yPos)
{
var n_neighbours = 0;
var moore_simple_neighborhood = [
[1,1,1],
[1,0,1],
[1,1,1]
];
for (let a = 0; a < moore_simple_neighborhood.length; a++)
{
for (let b = 0; b < moore_simple_neighborhood[0].length; b++)
{
// check if neighborhood item is true, else skip
if (moore_simple_neighborhood[a][b] === 1)
{
// get distance from center of neighborhood to current cell to check in neighborhood
var xDist = b - Math.floor(moore_simple_neighborhood.length/2);
var yDist = a - Math.floor(moore_simple_neighborhood.length/2);
// access cell xDist,yDist away from the center of the cell with global coordinates xPos, yPos
// check if within bounds
// console.log(xPos+xDist, yPos+yDist, this.graphics)
if (xPos+xDist >= 0 && xPos+xDist < this.SpriteWidth && yPos+yDist >= 0 && yPos+yDist < this.SpriteHeight)
{
// if this cell is alive, update neighbour count
if (this.graphics[xPos+xDist][yPos+yDist].type === "body")
{
n_neighbours = n_neighbours + 1
}
}
}
}
}
return n_neighbours;
}
// complete the sprite
generate_sprite()
{
if (this.symmetry == "vertical")
{
var limX = this.cellular_automata.config['Width']*2;
var limY = this.cellular_automata.config['Height'];
}
else if (this.symmetry == "horizontal")
{
var limX = this.cellular_automata.config['Width'];
var limY = this.cellular_automata.config['Height']*2;
}
else if (this.symmetry == "center")
{
var limX = this.cellular_automata.config['Width']*2;
var limY = this.cellular_automata.config['Height']*2;
}
// initialize big array
this.graphics = [];
for (var a = 0; a < limX; a++)
{
this.graphics[a] = []
for (var b = 0; b < limY; b++)
{
this.graphics[a][b] = new Square("#ffffff", "empty")
}
}
// copy the object
for (var x = 0; x < this.cellular_automata.config['Width']; x++)
{
for (var y = 0; y < this.cellular_automata.config['Height']; y++)
{
if (this.cellular_automata.cells[x][y].state > 0)
{
// fill square at location
this.graphics[x][y] = new Square(this.color_body, "body")
// apply symmetry
if (this.symmetry === "vertical")
{
this.graphics[limX-1-x][y] = new Square(this.color_body, "body")
}
else if (this.symmetry === "horizontal")
{
this.graphics[x][limY-1-y] = new Square(this.color_body, "body")
}
else if (this.symmetry === "center")
{
this.graphics[limX-1-x][y] = new Square(this.color_body, "body")
this.graphics[limX-1-x][limY-1-y] = new Square(this.color_body, "body")
this.graphics[x][limY-1-y] = new Square(this.color_body, "body")
}
}
}
// top and bottom
this.graphics[x].unshift(new Square("#ffffff", "empty"))
this.graphics[x].push(new Square("#ffffff", "empty"))
if (this.symmetry === "vertical")
{
this.graphics[limX-1-x].unshift(new Square("#ffffff", "empty"))
this.graphics[limX-1-x].push(new Square("#ffffff", "empty"))
}
// add padding
}
// add side padding
this.graphics.unshift( new Array(limY+2).fill( new Square("ffffff", "empty") ))
this.graphics.push( new Array(limY+2).fill( new Square("ffffff", "empty") ))
// fill edges
for (var x = 0; x < this.SpriteWidth; x++)
{
for (var y = 0; y < this.SpriteHeight; y++)
{
// console.log("width = ", this.SpriteWidth, this.SpriteHeight, limX, limY)
if (this.count_neighbours(x,y) > 0 && this.graphics[x][y].type === "empty")
{
this.graphics[x][y] = new Square("#4f3911", "edge")
}
}
}
}
generate_sprite_old()
{
// sprite has width+2 and height+2 to account for borders
// [\ \ \ \]
// [\ _ _ \]
// [\ _ _ \]
// [\ \ \ \]
// loop through cells
if (this.symmetry == "vertical")
{
var limX = Math.ceil(this.SpriteWidth/2);
var limY = this.SpriteHeight;
}
else if (this.symmetry == "horizontal")
{
var limX = this.SpriteWidth;
var limY = Math.ceil(this.SpriteHeight/2);
}
else if (this.symmetry == "center")
{
var limX = Math.ceil(this.SpriteWidth/2);
var limY = Math.ceil(this.SpriteHeight/2);
}
for (var x = 0; x < limX; x++)
{
this.graphics[x] = [];
for (var y = 0; y < limY; y++)
{
this.graphics[x][y] = new Square("#ffffff", "empty")
var isSquare = false;
var isEdge = false;
// console.log(this.cellular_automata.cells)
// console.log(x,y, this.SpriteWidth, this.SpriteHeight, this.cellular_automata.config['Width'], this.cellular_automata.config['Height'])
if (this.count_neighbours(x,y) > 0)
{
this.graphics[x][y] = new Square("#4f3911", "edge")
isEdge = true;
}
// check if we are inside the border
if ((x >= 1 && y >= 1)
&& (x < this.cellular_automata.config['Width'] && y < this.cellular_automata.config['Height'])
&& this.cellular_automata.cells[x][y].state > 0)
{
// console.log(x,y, this.SpriteWidth, this.SpriteHeight, this.cellular_automata.config['Width'], this.cellular_automata.config['Height'])
// fill in square at that location
this.graphics[x][y] = new Square(this.color_body, "body")
isSquare = true;
}
// check if we can fill edge if cell is empty
// check surroundings
// apply symmetry if requested
// flip on vertical axis of symmetry
if (this.symmetry == "vertical")
{
if (isSquare)
{
this.graphics[this.SpriteWidth-x-1][y] = new Square(this.color_body, "body")
}
else if (isEdge)
{
this.graphics[this.SpriteWidth-x-1][y] = new Square("#4f3911", "edge")
}
}
else if (this.symmetry == "horizontal")
{
if (isSquare)
{
this.graphics[x-1][y-1] = new Square(this.color_body, "body")
}
else if (isEdge)
{
this.graphics[x-1][y-1] = new Square("#4f3911", "edge")
}
}
else if (this.symmetry == "center")
{
if (isSquare)
{
this.graphics[x-1][y-1] = new Square(this.color_body, "body")
}
else if (isEdge)
{
this.graphics[x-1][y-1] = new Square("#4f3911", "edge")
}
}
}
}
}
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var System = new Cellular_Automata(config, neighborhood);
var Sprites = [];
var Systems = [];
function setup() {
createCanvas(WIDTH, HEIGHT);
frameRate(framerate);
}
function draw() {
Sprites = [];
Systems = [];
//https://gist.github.com/peterhellberg/3c5b30465a258f6b688a8f11955b12ba
for (var i = 0; i < 100; i++)
{
var random_neighborhood = Math.random()
if (random_neighborhood<0.3)
{
neighborhood = von_neumann_simple_neighborhood;
}
else if (random_neighborhood < 0.6)
{
neighborhood = moore_simple_neighborhood;
}
else
{
neighborhood = alt_neighborhood;
}
var System = new Cellular_Automata(config, neighborhood);
// System.init(0.05);
System.init(Math.random());
// System.iterate(Math.ceil(Math.random()*3));
// System.iterate(getRandomInt(2,5));
System.iterate(getRandomInt(0,4));
mySprite = new Sprite(System, "vertical")
mySprite.generate_sprite();
Systems.push(System);
Sprites.push(mySprite);
}
background(220);
noStroke()
var c = 0;
var z = 0;
if (SHOW_GRID)
{
// loop through only alive cells to speedup rendering
for (let mySprite of Sprites)
{
for (var x = 0; x < mySprite.graphics.length; x++)
{
for (var y = 0; y < mySprite.graphics[0].length; y++)
{
// console.log(x,y)
var squareColor = mySprite.graphics[x][y].color;
fill(squareColor);
stroke(squareColor)
rect(c*mySprite.SpriteWidth*GRIDSIZE/3 + x*GRIDSIZE/4+20,z*mySprite.SpriteHeight*GRIDSIZE/3 + y*GRIDSIZE/4+20,GRIDSIZE/4,GRIDSIZE/4)
}
}
if (c*mySprite.SpriteWidth*GRIDSIZE/3 + x*GRIDSIZE/4+20 > WIDTH-250)
{
c = 0;
z += 1;
}
else
{
c+=1;
}
}
}
else
{
for (var x = 0; x < Sprites[0].graphics.length; x++)
{
for (var y = 0; y < Sprites[0].graphics[0].length; y++)
{
var squareColor = mySprite.graphics[x][y].color;
// use transparency
if (mySprite.graphics[x][y].type !== "empty")
{
fill(squareColor);
}
else
{
noFill()
}
// nostroke(squareColor)
rect(x*GRIDSIZE,y*GRIDSIZE,GRIDSIZE,GRIDSIZE)
}
}
if (key === 's') {
saveCanvas('myCanvas', 'png');
}
console.log('done')
}
}<file_sep>/README.md
# procgen-sprite-prototype
Generating pixel sprites using cellular automata. An extension of <a href="https://github.com/yurkth/sprator">Sprator</a>'s method as it allows for variable rulesets, neighborhoods, symmetries.
# Usage
Go to the <a href="https://leungjch.github.io/procgen-sprite-cellular/">demo page</a> to see the generator in action.
<img src="screenshot_generator.png"> </img>
| de717b3a8a97c346e6acfeb03088bda2ff3e6fe2 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | leungjch/procgen-sprite-cellular | 743c0bb722acae90b1de4014a052d0f31479464b | ba72334b5b6a6428c615e49a00d45d00c08f3554 |
refs/heads/master | <repo_name>Cabe/Christmas-Lights<file_sep>/XmasLights/lights/lights.ino
#include <Adafruit_NeoPixel.h>
#define Count 150
#define Pin 6
Adafruit_NeoPixel strip = Adafruit_NeoPixel(Count,Pin,NEO_GRB + NEO_KHZ800);
const int buttonPin = 5; // the number of the pushbutton pin
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50; // the debounce time; increase if the output flickers
#define Brightness 10 //Set brightness to 1/10th
#define Full (255/Brightness)
void CandyCane (int sets,int width,int wait) { //Create scrolling red and white candy cane stripes.
//Try adjusting the width in pixels for various results.
//Value "sets" should evenly divide into strand length
int L;
for(int j=0;j<(sets*width);j++) {
for(int i=0;i< strip.numPixels();i++) {
L=strip.numPixels()-i-1;
if ( ((i+j) % (width*2) )<width)
strip.setPixelColor(L,0, 128,0);
else
strip.setPixelColor(L, 128, 128, 128);
};
strip.show();
delay(wait);
};
};
void Wreath (int sets,int width,int wait) { //Create scrolling red and green candy cane stripes.
//Try adjusting the width in pixels for various results.
//Value "sets" should evenly divide into strand length
int L;
for(int j=0;j<(sets*width);j++) {
for(int i=0;i< strip.numPixels();i++) {
L=strip.numPixels()-i-1;
if ( ((i+j) % (width*2) )<width)
strip.setPixelColor(L, 128, 0, 0);
else
strip.setPixelColor(L, 0, 128, 0);
};
strip.show();
delay(wait);
};
};
void ShootingStar (int sets,int width,int wait) {
int L;
for(int j=0;j<(sets*width);j++) {
for(int i=0;i< strip.numPixels();i++) {
L=strip.numPixels()-i-1;
if ( ((i+j) % (width*2) )<width)
strip.setPixelColor(L, 128, 128, 128);
else
strip.setPixelColor(L, 0, 0, 0);
};
strip.show();
delay(wait);
};
};
void RandomWhite (int sets, int wait) { //Create sets of random white or gray pixels
int V,i,j;
for (i=0;i<sets;i++) {
for(j=0;j<strip.numPixels();j++) {
V=random(Full);
strip.setPixelColor(j,V,V,V);
}
strip.show();
delay(wait);
}
};
void RandomColor (int sets, int wait) { //Create sets of random colors
int i,j;
for (i=0;i<sets;i++) {
for(j=0;j<strip.numPixels();j++) {
strip.setPixelColor(j,random(255)/Brightness,random(255)/Brightness,random(255)/Brightness);
}
strip.show();
delay(wait);
}
};
void RainbowStripe (int sets,int width,int wait) {
int L;
for(int j=0;j<(sets*width*6);j++) {
for(int i=0;i< strip.numPixels();i++) {
L=strip.numPixels()-i-1;
switch ( ( (i+j)/width) % 6 ) {
case 0: strip.setPixelColor(L,Full,0,0);break;//Red
case 1: strip.setPixelColor(L,Full,Full,0);break;//Yellow
case 2: strip.setPixelColor(L,0,Full,0);break;//Green
case 3: strip.setPixelColor(L,0,Full,Full);break;//Cyan
case 4: strip.setPixelColor(L,0,0,Full);break;//Blue
case 5: strip.setPixelColor(L,Full,0,Full);break;//Magenta
// default: strip.setPixelColor(L,0,0,0);//Use for debugging only
}
};
strip.show();
delay(wait);
};
};
void colorWipe(uint32_t c, uint8_t wait) { // Fill the dots one after the other with a color
for(uint16_t i=0; i<strip.numPixels(); i++) {
strip.setPixelColor(i, c);
strip.show();
delay(wait);
}
Serial.print("Blue");
Serial.print("\n");
}
void RainbowCycle(uint8_t sets, uint8_t wait) {
uint16_t i, j;
for(j=0; j<256*sets; j++) { //cycles of all colors on wheel
for(i=0; i< strip.numPixels(); i++) {
strip.setPixelColor(strip.numPixels()-i-1, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
}
strip.show();
delay(wait);
}
}
uint32_t Wheel(byte WheelPos) { // The colours are a transition r - g - b - back to r.
if(WheelPos < 85) {
return strip.Color((WheelPos * 3)/Brightness, (255 - WheelPos * 3)/Brightness, 0);
} else if(WheelPos < 170) {
WheelPos -= 85;
return strip.Color((255 - WheelPos * 3)/Brightness, 0, (WheelPos * 3)/Brightness);
} else {
WheelPos -= 170;
return strip.Color(0,(WheelPos * 3)/Brightness, (255 - WheelPos * 3)/Brightness);
}
}
void chase(uint32_t c) {
for(uint16_t i=0; i<strip.numPixels()+4; i++) {
strip.setPixelColor(i , c); // Draw new pixel
strip.setPixelColor(i-4, 0); // Erase pixel a few steps back
strip.show();
delay(25);
}
}
int animRedChaseWipe(){
colorWipe(strip.Color(0, 255, 0), 50); // Red
chase(0x00FF00); // Red
chase(0x00FF00); // Red
chase(0x00FF00); // Red
}
int animGreenChaseWipe(){
colorWipe(strip.Color(255, 0, 0), 50); // Green
chase(0xFF0000); // Green
chase(0xFF0000); // Green
chase(0xFF0000); // Green
}
int animBlueChaseWipe(){
colorWipe(strip.Color(0, 0, 255), 50); // Blue
chase(0x0000FF); // Blue
chase(0x0000FF); // Blue
chase(0x0000FF); // Blue
}
int pushbutton(){
int reading = digitalRead(buttonPin);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited
// long enough since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only animate the LEDS if the new button state is HIGH
if (buttonState == HIGH) {
//animation();
}
}
}
// save the reading. Next time through the loop,
// it'll be the lastButtonState:
lastButtonState = reading;
}
void setup() {
strip.begin();
strip.show(); // Initialize all pixels to 'off'
randomSeed(1234);//Set up random number generator
pinMode(buttonPin, INPUT);
//Serial.begin(9600);
}
void loop() {
chase(0xFFFFFF); // White
chase(0xFFFFFF); // White
chase(0xFFFFFF); // White
chase(0xFFFFFF); // White
chase(0xFFFFFF); // White
Wreath(30,5,500);
Wreath(30,5,500);
RainbowCycle(10,2);//10 rainbow cycles
RandomWhite(150,200);//50 sets of random grayscale
animRedChaseWipe();
animGreenChaseWipe();
animBlueChaseWipe();
RandomWhite(150,200);//50 sets of random grayscale
RainbowCycle(10,2);//10 rainbow cycles
CandyCane(30,5,250);//30 sets, 8 pixels wide, 50us delay
CandyCane(30,5,250);//30 sets, 8 pixels wide, 50us delay
animBlueChaseWipe();
animGreenChaseWipe();
animRedChaseWipe();
RainbowCycle(10,2);//10 rainbow cycles
}
| 4c956c97eaed47b9ace5294a970250ca03314595 | [
"C++"
] | 1 | C++ | Cabe/Christmas-Lights | c1efd5dc5903f07664870a3c0cde438961130469 | 47fc60ca96ddad9015684e3789cd3ded6f238361 |
refs/heads/master | <file_sep>package controller;
public class CeshiController {
}
<file_sep>package service;
public class ceshiService {
}
| 1002021ae3e1a840096fa47b6f4904f485e5707b | [
"Java"
] | 2 | Java | zhiguangsong5175/hanjialin | 686a083fcfafde53eb87ff5845b4e278e2be29ed | 9c6d36e0018074b489493673a3549c6b15433f64 |
refs/heads/master | <repo_name>liorbentov/nissix-plugins<file_sep>/plugins/prettier/src/index.ts
import { addDependecies, getPackages, run } from '@nissix/plugins'
export async function execute() {
// get all packages in repo
const packages = await getPackages()
// check if prettier is already installed
await Promise.all(
packages.map(async (pkg) => {
// if not
if (!pkg.content?.devDependencies?.hasOwnProperty('prettier')) {
// install prettier as dev dep
await addDependecies(['prettier'], 'development')
}
await run('npx prettier --write .', { cwd: pkg.path })
return pkg.path
}),
)
}
// TODO: this will export a manifest for options that will show to the user and be consumed in execute
// export async function getOptions() {
//
// }
| 57d07d17168387dfc05f3b1e7b6ab62cec1b146b | [
"TypeScript"
] | 1 | TypeScript | liorbentov/nissix-plugins | abd30e5ef0d9fe337473766f9ef9256484a0f9d6 | dabecd83f328fd176192c6e65592bf7a3dda271b |
refs/heads/master | <file_sep>library(sqldf)
# Set the appropriate locale, so the x-axis of this plot will be in English (not in my personal locale, which is Russian)
Sys.setlocale("LC_TIME", "en_US.UTF-8")
# Read required data
data <- read.csv2.sql(
'./household_power_consumption.txt',
sql="select * from file where Date = '1/2/2007' or Date = '2/2/2007'",
colClasses=c('character', 'character', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric')
)
# Convert it
data$Date <- strptime(paste(data$Date, data$Time), '%d/%m/%Y %H:%M:%S')
# Reserve space for 2*2 plots
par(mfrow=c(2, 2))
with(data, {
plot(Date, Global_active_power, type='l', xlab='', ylab='Global Active Power')
plot(Date, Voltage, type = 'l')
plot(Date, Sub_metering_1, type='l', xlab='', ylab='Energy sub metering')
lines(Date, Sub_metering_2, col='red')
lines(Date, Sub_metering_3, col='blue')
legend('topright', bty='n', lwd=1, col=c('black', 'red', 'blue'), legend=c('Sub_metering_1', 'Sub_metering_2', 'Sub_metering_3'))
plot(Date, Global_reactive_power, type='l')
})
# Output it. The resolution is 480*480 by default, so we won't change it here.
dev.copy(png, file='plot4.png')
dev.off()<file_sep>library(sqldf)
# Set the appropriate locale, so the x-axis of this plot will be in English (not in my personal locale, which is Russian)
Sys.setlocale("LC_TIME", "en_US.UTF-8")
# Read required data
data <- read.csv2.sql(
'./household_power_consumption.txt',
sql="select * from file where Date = '1/2/2007' or Date = '2/2/2007'",
colClasses=c('character', 'character', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric')
)
# Convert it
time <- strptime(paste(data$Date, data$Time), format="%d/%m/%Y %H:%M:%S")
# Build the plot
plot(time, data$Global_active_power, type="l", ylab="Global Active Power (kilowats)", xlab="")
# Output it. The resolution is 480*480 by default, so we won't change it here.
dev.copy(png, file='plot2.png')
dev.off()<file_sep>library(sqldf)
# Read required data
data <- read.csv2.sql(
'./household_power_consumption.txt',
sql="select * from file where Date = '1/2/2007' or Date = '2/2/2007'",
colClasses=c('character', 'character', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric', 'numeric')
)
# Build the histogram
hist(data$Global_active_power, xlab = "Global Active Power (kilowatts)", main = "Global Active Power", col='RED')
# Output it. The resolution is 480*480 by default, so we won't change it here.
dev.copy(png, file='plot1.png')
dev.off() | 59c4fade79f21b34bead3518160fe514aed0c4aa | [
"R"
] | 3 | R | agap/ExData_Plotting1 | e0c78c0554df6f8a6378511d2f285e451bef0bba | e34c070ed2829d860726d5f720795ba4263e8dba |
refs/heads/master | <repo_name>woowonjin/Computer-Architecture_ITE2031<file_sep>/Project1/Assembler/assemble.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINELENGTH 1000
int getAddress(char*);
int readAndParse(FILE*, char*, char*, char*, char*, char*);
int isNumber(char*);
static char* inFile;
int main(int argc, char* argv[]){
char* inFileString;
char* outFileString;
FILE* inFilePtr;
FILE* outFilePtr;
char label[MAXLINELENGTH], opcode[MAXLINELENGTH], arg0[MAXLINELENGTH],
arg1[MAXLINELENGTH], arg2[MAXLINELENGTH];
if(argc != 3){
printf("error: usage: %s <assembly-code-file> <machine-code-file>\n",argv[0]);
exit(1);
}
inFileString = argv[1];
inFile = inFileString;
outFileString = argv[2];
inFilePtr = fopen(inFileString, "r");
if(inFilePtr == NULL){
printf("error in opening %s\n", inFileString);
exit(1);
}
outFilePtr = fopen(outFileString, "w");
if(outFilePtr == NULL){
printf("error in opening %s\n", outFileString);
exit(1);
}
FILE* tempInFilePtr = fopen(inFileString, "r");
while(readAndParse(inFilePtr, label, opcode, arg0, arg1, arg2)){
if(strcmp(label, "") != 0){
int count = 0;
char tempLabel[MAXLINELENGTH];
while(readAndParse(tempInFilePtr, tempLabel, opcode, arg0, arg1, arg2)){
if(strcmp(tempLabel, label) == 0){
count++;
}
}
if(count > 1){
printf("Error : Duplicate label\n");
exit(1);
}
rewind(tempInFilePtr);
}
}
fclose(tempInFilePtr);
rewind(inFilePtr);
int PC = 0;
while(readAndParse(inFilePtr, label, opcode, arg0, arg1, arg2)){
int arg0Num, arg1Num, arg2Num, op, off, machineCode;
if(strcmp(opcode, "add") == 0){
op = 0;
arg0Num = atoi(arg0);
arg1Num = atoi(arg1);
arg2Num = atoi(arg2);
off = arg2Num;
}
else if(strcmp(opcode, "nor") == 0){
op = 1;
arg0Num = atoi(arg0);
arg1Num = atoi(arg1);
arg2Num = atoi(arg2);
off = arg2Num;
}
else if(strcmp(opcode, "lw") == 0){
op = 2;
arg0Num = atoi(arg0);
arg1Num = atoi(arg1);
if(isNumber(arg2)){
off = atoi(arg2);
}
else{
off = getAddress(arg2);
}
}
else if(strcmp(opcode, "sw") == 0){
op = 3;
arg0Num = atoi(arg0);
arg1Num = atoi(arg1);
if(isNumber(arg2)){
off = arg0Num + atoi(arg2);
}
else{
off = arg0Num + getAddress(arg2);
}
}
else if(strcmp(opcode, "beq") == 0){
op = 4;
arg0Num = atoi(arg0);
arg1Num = atoi(arg1);
if(isNumber(arg2)){
off = arg0Num + atoi(arg2);
}
else{
off = getAddress(arg2) - PC - 1;
}
}
else if(strcmp(opcode, "jalr") == 0){
op = 5;
arg0Num = atoi(arg0);
arg1Num = atoi(arg1);
off = 0;
}
else if(strcmp(opcode, "halt") == 0){
op = 6;
arg0Num = 0;
arg1Num = 0;
off = 0;
}
else if(strcmp(opcode, "noop") == 0){
op = 7;
arg0Num = 0;
arg1Num = 0;
off = 0;
}
else if(strcmp(opcode, ".fill") == 0){
if(isNumber(arg0)){
machineCode = atoi(arg0);
fprintf(outFilePtr, "%d\n", machineCode);
PC++;
continue;
}
else{
machineCode = getAddress(arg0);
fprintf(outFilePtr, "%d\n", machineCode);
PC++;
continue;
}
}
else{
printf("Error : this opcode does not exists!\n");
exit(1);
}
PC++;
if(off < -32768 || off > 32767){
printf("Error : Offset is overflowed\n");
exit(1);
}
if(off < 0){
off += 65536;
}
machineCode = (op<<22) + (arg0Num<<19) + (arg1Num << 16) + off;
fprintf(outFilePtr, "%d\n", machineCode);
}
fclose(inFilePtr);
fclose(outFilePtr);
exit(0);
}
int readAndParse(FILE* inFilePtr, char* label, char* opcode, char* arg0, char* arg1, char* arg2){
char line[MAXLINELENGTH];
char* ptr = line;
label[0] = opcode[0] = arg0[0] = arg1[0] = arg2[0] = '\0';
if(fgets(line, MAXLINELENGTH, inFilePtr) == NULL){
return 0;
}
if(strchr(line, '\n') == NULL){
printf("error: line too ling\n");
exit(1);
}
ptr = line;
if(sscanf(ptr, "%[^\t\n\r ]", label)){
ptr += strlen(label);
}
sscanf(ptr, "%*[\t\n\r ]%[^\t\n\r ]%*[\t\n\r ]%[^\t\n\r ]%*[\t\n\r ]%[^\t\n\r ]%*[\t\n\r ]%[^\t\n\r ]", opcode, arg0, arg1, arg2);
return(1);
}
int getAddress(char* targetLabel){
char label[MAXLINELENGTH], opcode[MAXLINELENGTH], arg0[MAXLINELENGTH],
arg1[MAXLINELENGTH], arg2[MAXLINELENGTH];
FILE* tempInFilePtr = fopen(inFile, "r");
int address = 0;
while(readAndParse(tempInFilePtr, label, opcode, arg0, arg1, arg2)){
if(strcmp(targetLabel, label) == 0){
fclose(tempInFilePtr);
return address;
}
address++;
}
fclose(tempInFilePtr);
printf("Error : Can't find label\n");
exit(1);
}
int isNumber(char* string){
int i;
return((sscanf(string, "%d", &i)) == 1);
}
<file_sep>/Project1/Simulator/simulate.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define NUMMEMORY 65536
#define NUMREGS 8
#define MAXLINELENGTH 1000
typedef struct stateStruct{
int pc;
int mem[NUMMEMORY];
int reg[NUMREGS];
int numMemory;
} stateType;
int convertNum(int);
void machineToAssembler(int, int*, int*, int*, int*);
void printState(stateType*);
int main(int argc, char* argv[]){
char line[MAXLINELENGTH];
stateType state;
FILE* filePtr;
if(argc != 2){
printf("error: usage: %s <machine-code file>\n", argv[0]);
exit(1);
}
filePtr = fopen(argv[1], "r");
if(filePtr == NULL){
printf("error: can't open file %s", argv[1]);
perror("fopen");
exit(1);
}
for(state.numMemory=0; fgets(line, MAXLINELENGTH, filePtr) != NULL; state.numMemory++){
if(sscanf(line, "%d", state.mem+state.numMemory) != 1){
printf("error in reading address %d\n", state.numMemory);
exit(1);
}
printf("memory[%d]=%d\n", state.numMemory, state.mem[state.numMemory]);
}
state.pc = 0;
for(int i = 0; i < NUMREGS; i++){
state.reg[i] = 0;
}
int op, reg0, reg1, off;
int count = 0;
while(1){
printState(&state);
machineToAssembler(state.mem[state.pc], &op, ®0, ®1, &off);
if(op == 0){ //add op
state.reg[off] = state.reg[reg0] + state.reg[reg1];
}
else if(op == 1){ // nor op
state.reg[off] = ~(state.reg[reg0] | state.reg[reg1]);
}
else if(op == 2){ // lw op
// printf("off :%d\n", off);
// printf("contents of reg0 : %d\n", state.reg[reg0]);
//printf("address of reg1 : %d\n", reg1);
state.reg[reg1] = state.mem[state.reg[reg0] + off];
}
else if(op == 3){ // sw op
state.mem[state.reg[reg0] + off] = state.reg[reg1];
}
else if(op == 4){ // beq op
if(state.reg[reg0] == state.reg[reg1]){
state.pc += off;
}
}
else if(op == 5){ // jalr op
state.reg[reg1] = state.pc + 1;
state.pc = state.reg[reg0] - 1;
}
else if(op == 6){ // halt op
printf("\nmachine halted\n");
printf("total of %d instructions executed\n", ++count);
printf("final state of machine:");
state.pc++;
printState(&state);
break;
}
else if(op == 7){ // noop op
}
else{
printf("Error : opcode does not exists!!\n");
exit(1);
}
state.pc++;
count++;
}
return 0;
}
void printState(stateType* statePtr){
int i;
printf("\n@@@\nstate:\n");
printf("\tpc %d\n", statePtr->pc);
printf("\tmemory:\n");
for(i = 0; i < statePtr->numMemory; i++){
printf("\t\tmem[ %d ] %d\n", i, statePtr->mem[i]);
}
printf("\tregisters:\n");
for(i = 0; i < NUMREGS; i++){
printf("\t\treg[ %d ] %d\n", i, statePtr->reg[i]);
}
printf("end state");
}
void machineToAssembler(int target, int* op, int* reg0, int* reg1, int* off){
*op = (target >> 22) & 7;
*reg0 = (target >> 19) & 7;
*reg1 = (target >> 16) & 7;
*off = convertNum(target & 65535);
}
int convertNum(int num){
if(num & (1<<15)){
num -= (1<<16);
}
return num;
}
| 8f1eff3ef6bcd53512ec035aca54986df4103685 | [
"C"
] | 2 | C | woowonjin/Computer-Architecture_ITE2031 | 5812d8ba73ce6e8c8c069f3fc572ccf29af5f0ca | d08bca07438654e48ef8921a7729bcab963b9acd |
refs/heads/master | <repo_name>nardy70/ivascor<file_sep>/ivascor.js
function Ivascor(tot, iva) {
value = (tot*100)/(100+iva);
return 'La cifra di ' + tot + ' scorporata del '
+ iva + '% ' + 'è di: ' + value.toFixed(2)
};
exports.ivascor = Ivascor;
<file_sep>/README.md
Function for VAT Spin-off.<br>
Use:<br>
var ivascor = require("ivascore");<br>
ivascor.ivascor(tot, iva);
| 9e648b9b07b072b23c5fa9e9d813a3fcc67fec00 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | nardy70/ivascor | 74929212412db1e48a56b29291021b293f6f9473 | 47f1b3e5f7da984a16fca24b9354edf19c60f4e0 |
refs/heads/master | <file_sep>package com.lzb.service.mapper;
import com.lzb.admin.bean.Role;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
@org.apache.ibatis.annotations.Mapper
public interface RoleMapper extends Mapper<Role> {
Role selectByIdRole(Long id);
List<Role> selectAll();
@Update("UPDATE t_admin_role ta SET ta.roleid=#{rid} WHERE ta.adminid=#{aid}")
int editRoles(Long aid,Long rid);
@Insert("INSERT INTO t_admin_role (roleid,adminid)values(#{rid},#{aid})")
int addRoles(Long aid,Long rid);
}
<file_sep>package com.lzb.service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("com.lzb.service.mapper")
@EnableDiscoveryClient
public class AdminServiceSpringBoot {
public static void main(String[] args) {
SpringApplication.run(AdminServiceSpringBoot.class);
}
}
<file_sep>package com.lzb.admin.vo;
import lombok.Data;
@Data
public class AdminVo {
private String loginacct;
private String password;
}
<file_sep>package com.lzb.service.service;
import com.lzb.admin.bean.Role;
import java.util.List;
public interface RoleService {
List<Role> selectRole();
Role selectByIdRole(Long id);
int editRoles(Long aid,Long rid);
}
<file_sep>package com.lzb.common.response;
import lombok.Data;
@Data
public class RestResponse<T> {
private int state;
private String message;
private T data;
private String token;
public RestResponse(int state,String message, T data,String token) {
this.state=state;
this.message=message;
this.data=data;
this.token=token;
}
}
<file_sep>package com.lzb.service.controller;
import com.github.pagehelper.PageInfo;
import com.lzb.admin.bean.Admin;
import com.lzb.admin.bean.Role;
import com.lzb.admin.vo.AdminVo;
import com.lzb.common.date.AppDateUtils;
import com.lzb.common.response.RestResponse;
import com.lzb.common.token.JwtToken;
import com.lzb.service.service.AdminService;
import com.lzb.service.service.RoleService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("admin")
public class AdminController {
@Resource
private AdminService adminService;
@Resource
private RoleService roleService;
@RequestMapping(value = "login")
public RestResponse<Admin> adminLogin(@RequestBody AdminVo adminVo){
Admin admin = adminService.adminLogin(adminVo);
if (admin==null){
return new RestResponse<>(500,"账号或密码错误", null,null);
}else {
String jwtToken = JwtToken.createJwtToken(admin.getId(), admin.getLoginacct(), 10);
return new RestResponse<>(200,"登录成功",admin,jwtToken);
}
}
@RequestMapping(value = "findAdmin")
public RestResponse<PageInfo<Admin>> findAdmin(@RequestParam(value = "page",defaultValue = "1") Integer page,@RequestParam(value = "rows",defaultValue = "5")Integer rows,@RequestParam(value = "key",required = false)String key){
PageInfo<Admin> adminPageInfo = adminService.findAdmin(page, rows, key);
return new RestResponse<>(200,null,adminPageInfo,null);
}
@RequestMapping(value = "findByAdmin")
public RestResponse<Admin> findByAdmin(Long id){
Admin admin = adminService.findByAdmin(id);
return new RestResponse<>(200,null,admin,null);
}
@RequestMapping(value = "editAdmin")
public RestResponse<Admin> editAdmin(@RequestBody Admin admin){
if (admin.getId()==0||admin.getUsername().trim().equals("")||admin.getPassword().trim().equals("")||admin.getUsername().trim().equals("")||admin.getEmail().trim().equals("")){
return new RestResponse<>(500,"不能为空",null,null);
}else {
int i = adminService.editAdmin(admin);
if (i==1){
return new RestResponse<>(200,"修改成功",null,null);
}else {
return new RestResponse<>(500,"修改失败",null,null);
}
}
}
@RequestMapping(value = "deleteAdmin")
public RestResponse<Admin> deleteAdmin(Long id){
if (id==1){
return new RestResponse<>(500,"无权删除",null,null);
}else {
int i = adminService.deleteAdmin(id);
if (i==1){
return new RestResponse<>(200,"删除成功",null,null);
}else {
return new RestResponse<>(500,"删除失败",null,null);
}
}
}
@RequestMapping(value = "addAdmin")
public RestResponse<Admin> addAdmin(@RequestBody Admin admin){
admin.setCreatetime(AppDateUtils.getFormatTime());
int i = adminService.addAdmin(admin);
if (i==1){
return new RestResponse<>(200,"添加成功",null,null);
}else {
return new RestResponse<>(500,"添加失败",null,null);
}
}
@RequestMapping(value = "deleteIdsAdmin")
public RestResponse<Admin> deleteIdsAdmin(String ids){
if (ids.trim().equals("")){
return new RestResponse<>(500,"未选中数据",null,null);
}else {
String[] split = ids.split(",");
boolean delete=false;
for (int i = 0; i <split.length; i++) {
if (split[i].trim().equals("1")){
break;
}else {
delete=true;
}
}
if (delete){
int i = adminService.deleteAdminIds(ids);
if (i>0){
return new RestResponse<>(200,"批量删除成功",null,null);
}else {
return new RestResponse<>(500,"批量删除失败",null,null);
}
}else {
return new RestResponse<>(500,"无权删除",null,null);
}
}
}
@RequestMapping(value = "selectRole")
public RestResponse<List<Role>> selectRole(){
List<Role> roles = roleService.selectRole();
return new RestResponse<>(200,null,roles,null);
}
@RequestMapping(value = "selectByIdRole")
public RestResponse<Role> selectByIdRole(Long id){
Role role = roleService.selectByIdRole(id);
return new RestResponse<>(200,null,role,null);
}
@RequestMapping(value = "editRoles")
public RestResponse<List<Role>> editRoles(Long aid,Long rid){
int i = roleService.editRoles(aid, rid);
if (i==1){
return new RestResponse<>(200,"分配成功",null,null);
}else {
return new RestResponse<>(500,"分配失败",null,null);
}
}
}
<file_sep>package com.lzb.common.token;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtToken {
public static String TOKEN="abc";
//生产token
public static String createJwtToken(Long id,String loginacct,int time) {
//签发时间
Date date = new Date();
//过期时间,1分钟过期
Calendar instance = Calendar.getInstance();
instance.add(Calendar.MINUTE,time);
Date times = instance.getTime();
//heander
HashMap<String, Object> map = new HashMap<>();
map.put("alg","HS256");
map.put("typ","JWT");
String token= null;//加密
try {
token = JWT.create()
.withHeader(map)//heander
.withClaim(id.toString(),loginacct)
.withExpiresAt(times)//过期时间
.withIssuedAt(date)//签名时间
.sign(Algorithm.HMAC256(TOKEN));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return token;
}
//解密token
public static Map<String, Claim> verifyToken(String token) throws Exception {
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN)).build();
DecodedJWT jwt=null;
try {
jwt = jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
e.printStackTrace();
throw new RuntimeException("令牌过期");
}
return jwt.getClaims();
}
}
<file_sep>import com.auth0.jwt.interfaces.Claim;
import com.lzb.common.token.JwtToken;
import java.util.Map;
public class JwtTokenDome {
public static void main(String[] args) throws Exception {
// String jwtToken = JwtToken.createJwtToken();
// System.out.println(jwtToken);
//
// Map<String, Claim> claimMap = JwtToken.verifyToken(jwtToken);
// System.out.println(claimMap.get("age").asString());
// Map<String, Claim> claimxMap = JwtToken.verifyToken("<KEY>");
// System.out.println(claimxMap.get("age").asString());
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.lzb</groupId>
<artifactId>crowd-financing-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<modules>
<module>crowd-financing-common</module>
<module>crowd-financing-registry</module>
<module>crowd-financing-api-gateway</module>
<module>crowd-financing-admin</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!-- junit -->
<junit.version>4.12</junit.version>
<!-- 时间日期操作 -->
<joda-time.version>2.9.9</joda-time.version>
<!-- 功能组件 -->
<jedis.version>2.9.0</jedis.version>
<mybatis.version>1.3.2</mybatis.version>
<tk.mybatis.version>2.0.2</tk.mybatis.version>
<spring-cloud.version>Finchley.RC1</spring-cloud.version>
<!-- 数据库 -->
<druid.version>1.1.0</druid.version>
<mysql.connector>5.1.42</mysql.connector>
<!-- 分页 -->
<pagehelper.version>5.0.3</pagehelper.version>
</properties>
<!-- 依赖管理 -->
<dependencyManagement>
<dependencies>
<!-- springCloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- 时间日期 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector}</version>
</dependency>
<!--druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- mybatis启动器 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- 通用Mapper启动器 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${tk.mybatis.version}</version>
</dependency>
<!-- 分页 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${pagehelper.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.0.1.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project><file_sep>package com.lzb.admin.bean;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class Menu {
private int menuid;
private int pid;
private String menuname;
private String icon;
private String url;
private List<Menu> children =new ArrayList<>();
}
<file_sep>package com.lzb.admin.bean;
import lombok.Data;
import javax.persistence.Id;
@Data
public class Admin {
@Id
private Long id;
private String loginacct;
private String username;
private String password;
private String email;
private String createtime;
private Role role;
}
| b5b5114d02205a0a97bb325c4a9673ab7dacfec2 | [
"Java",
"Maven POM"
] | 11 | Java | 2195319856/crowd-financing-parent | 7fafc6da67d9d33f94cf3ab15d1a1d6821f8adab | d8b21805dc71475397b7fa4acf0484c216478a56 |
refs/heads/master | <file_sep>library(yhatr);
model.require <- function() {
library(topicmodels);
library(tm);
}
model.transform <- function(df) {
df
}
model.predict <- function(df) {
corpus <- Corpus(VectorSource(df['text'], encoding='UTF-8'));
dtm <- DocumentTermMatrix(corpus, control = list(removePunctuation = TRUE,
removeNumbers = TRUE,
stopwords = TRUE,
stemming = TRUE));
topics <- posterior(model, dtm)$topics;
data.frame("topic" = 1:length(topics), "probability" = t(topics));
}<file_sep>library(topicmodels);
library(tm);
library(multicore);
data(AssociatedPress);
BURN <- 1000;
# Might have used 2000...
ITER <- 1000;
THIN <- 100;
# Sample and retain every 10th model for posterior assessment of convergence
control.gibbs <- list(verbose = 0, iter = ITER, burnin = BURN, thin = THIN, best = TRUE);
# Define the iteration sequence
iterSeq <- function() {
seq(2, 50, by = 1);
}
# Determine the optimal number of topics using
models <- mclapply(iterSeq(), function(x)
LDA(AssociatedPress[1:500,], k = x, method = "gibbs", control = control.gibbs),
mc.preschedule = FALSE, mc.cores = 8, mc.silent = FALSE);
# Assess the model based on the log liklihood
loglik <- mclapply(seq(1, length(models)), function(x) logLik(models[[x]]), mc.cores = 8);
# Assess the model on some extra data
perp <- mclapply(seq(1, length(models)), function(x) perplexity(models[[x]], AssociatedPress[550:600,]), mc.cores = 8);
# Select the model with the best loglik score
optimalTopics <- which(max(unlist(loglik)) == unlist(loglik)) + 1;
# Select the model with the optimal perplexity score based on hold out data
optimalPerp <- which(min(unlist(perp)) == unlist(perp)) + 1;
# Visualize
plot(iterSeq(), loglik, xlab="Number of Topics", ylab="Log lik", type="l", col="red",
main = paste("Optimal Topics:", optimalTopics));
plot(iterSeq(), perp, xlab="Number of Topics", ylab="Perplexity", type="l", col="green",
main = paste("Optimal Topics:", optimalPerp));
# Build a general model.
topicNumber = ceiling((optimalTopics + optimalPerp) / 2);
# Create a model with the optimal numebr of topics given the data set.
# In production we need to use the full data set to build the model and perform 10 fold
# cross validation on 20% hold out data to select the optimal topic number (on a 24 core EC2 instance ;p).
# Topic number selection may also depend on specific use case...
model <- LDA(AssociatedPress[1:500,], method="Gibbs", control = control.gibbs, k = topicNumber);
# Posterior
model.post <- posterior(model);<file_sep># AP Article Topics
The purpose of this project is to play with the LDA (Latent Dirichlet Allocation) algorithm and discover topics in the Associated Press data set (from CRAN package 'tm'). A side goal is to test out the yhat (yhathq.com) API.
We take a subset of the AP data set (for speed reasons) and build an LDA model for each of n topics to assess performance on both log likelihood and perlexity of hold out data to get a sense of the optimal topic number. More rigorous performance measures and full use of the data set should be employed in a production environment.
The model is deployed to the yhat API for hosting and RESTful access.
| 333ad31ece93de0a1d06bbc75f73d4ed3c553472 | [
"Markdown",
"R"
] | 3 | R | cfusting/aparticletopics | 65dc6236b82f3cee590ceec4e63e1d5d3a2a4305 | a6c10f96f8bc2b754192e13634e954717360e5f8 |
refs/heads/master | <repo_name>OlexandraSydorova/Lab1<file_sep>/src/lab1.java
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
public class lab1 {
public static void main(String[] args) {
Scanner sym = new Scanner(System.in);
System.out.println("Для вводу символа роздільника введіть 1, за замовчуванням введіть 0");
String choice = sym.nextLine();
while (!choice.equals("1") && !choice.equals("0"))
{
System.out.println("Введення є некоректним, введіть ще раз");
choice = sym.nextLine();
}
String del = ",";
if (choice.equals("1")) {
System.out.println("Введіть символ роздільник");
del = sym.nextLine();
}
System.out.println("Введіть символ об'єднувач");
String diz = sym.nextLine();
while (del.length()>1)
{
System.out.println("Введіть один символ");
del = sym.nextLine();
}
char[] delim = del.toCharArray();
System.out.println("Введіть шлях до вхідного файлу");
String filename = sym.nextLine();
File file = new File(filename);
while (!file.isFile())
{
System.out.println("Такий файл не існує, або його неможливо відкрити, введіть шлях ще раз");
filename = sym.nextLine();
file = new File(filename);
}
System.out.println("Введіть шлях до результативного файлу");
String filename_res = sym.nextLine();
File file_res = new File(filename_res);
while (!file_res.isFile())
{
System.out.println("Такий файл не існує, або його неможливо відкрити, введіть шлях ще раз");
filename_res = sym.nextLine();
file_res = new File(filename_res);
}
try {
Scanner sc = new Scanner(file);
Scanner sc1 = new Scanner(file);
PrintWriter res = new PrintWriter(file_res);
boolean ch = false;
while(sc.hasNext()){
String data = sc.nextLine();
char[] line = data.toCharArray();
int count = 0;
int k = 0;
for (int i = 0; i < line.length; i++)
{
k = 0;
if (i <= line.length-3&&((line[i] == '/' && line[i+1] == '*')||ch))
{
k = i + 2;
ch = true;
while (k <= line.length-3 && line[k] != '*' && line[k+1]!='/') {
k++;
}
res.write("\r\n");
if(line[k] == '*' && line[k+1]=='/') {
ch = false;
break;
}
i = k;
}
if (i == 0 && line[i] == '\"' && !ch)
{
k = i+1;
while (k!=line.length)
{
if(k!=line.length-1)
{
if (line[k] == '\"' && line[k + 1] == delim[0]) {
count = k - i - 2;
i = k;
break;
}
}
if (line[k] == '\"' && k==line.length-1)
{
count = k-i-2;
i = k;
break;
}
k++;
}
}
if (i!=0 && !ch)
if (line[i-1] == delim[0] && line[i] == '\"')
{
k = i+1;
while (k!=line.length)
{
if(k!=line.length-1)
{
if (line[k] == '\"' && line[k + 1] == delim[0]) {
count = k - i - 2;
i = k;
break;
}
}
if (line[k] == '\"' && k==line.length-1)
{
count = k-i-2;
i = k;
break;
}
k++;
}
}
if (line[i] != delim[0] && i<line.length-1 && !ch)
{
count++;
}
else
{
if (!ch) {
if (i != line.length - 1)
res.write(count + diz);
else {
if (line[i] != delim[0])
count++;
res.write(count + "\r\n");
}
count = 0;
}
}
}
}
sc.close();
res.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
} | c48f1f5dc892b8d8e4f3a19dc97d551c4b39ad94 | [
"Java"
] | 1 | Java | OlexandraSydorova/Lab1 | 6760943e0e7761c8c7cbacbad747105e14322fbe | b76be6f5a6d49bbccec646618e8976fb237554ea |
refs/heads/master | <file_sep>package Func;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Canvas extends JPanel implements Runnable, KeyListener {
private GameMediator aGameMediator;
private GameWindow aGameWindow;
private boolean acceptKeyPressed = true;
private BufferedImage img;
private boolean running;
private Graphics2D g2d;
private Thread thread;
public Canvas() {
ConfigSingleton singleton = ConfigSingleton.getInstance();
int width = singleton.getCanvasWidth() * singleton.getScale();
int height = singleton.getCanvasHeight() * singleton.getScale();
setPreferredSize(new Dimension(width, height));
setFocusable(true);
requestFocus();
}
public Canvas(GameWindow aGameWindow) {
this();
this.aGameWindow = aGameWindow;
}
public void addNotify() {
super.addNotify();
if (thread == null) {
addKeyListener(this);
thread = new Thread(this);
thread.start();
}
}
public void run() {
init();
while (running) {
long start = System.nanoTime();
aGameMediator.update();
aGameMediator.draw(g2d);
Keys.update();
drawToScreen();
long elapsed = System.nanoTime() - start;
int targetTime = ConfigSingleton.getInstance().getTargetTime();
long wait = targetTime - elapsed / 1000000;
if (wait < 0)
wait = targetTime;
try {
Thread.sleep(wait);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void init() {
running = true;
aGameMediator = GameMediator.getInstance();
aGameMediator.setCanvas(this);
img = new BufferedImage(ConfigSingleton.getInstance().getCanvasWidth(),
ConfigSingleton.getInstance().getCanvasHeight(), 1);
g2d = (Graphics2D) img.getGraphics();
}
private void drawToScreen() {
ConfigSingleton singleton = ConfigSingleton.getInstance();
int width = singleton.getCanvasWidth() * singleton.getScale();
int height = singleton.getCanvasHeight() * singleton.getScale();
Graphics g2 = getGraphics();
g2.drawImage(img, 0, 0, width, height, null);
g2.dispose();
}
public void noticeToGameOver(int score) {
aGameWindow.setGameOverComponents(score);
running = false;
}
@Override
public void keyPressed(KeyEvent e) {
if(acceptKeyPressed){
Keys.keySet(e.getKeyCode(), true);
Keys.setKeyStateNew(e.getKeyCode(), true);
}
acceptKeyPressed = false;
}
@Override
public void keyReleased(KeyEvent e) {
Keys.keySet(e.getKeyCode(), false);
acceptKeyPressed = true;
}
@Override
public void keyTyped(KeyEvent e) {
}
}<file_sep>package Func;
final public class ConfigSingleton {
private static ConfigSingleton instance = null;
private final int collisionDetectionDistance = -3;
private final int obstacleMinDistance = 32;
private final int obstacleTreeNumber = 5;
private final int initialJointNumber = 3;
private final int canvasHeight = 240; //15
private final int canvasWidth = 320; //20
private final int entityHeight = 16;
private final int entityWidth = 16;
private final int speedIncrement = 1;
private final int speedInitial = 2;
private final int speedMin = 1;
private final int scale = 2;
private final int fps = 30;
private ConfigSingleton(){}
public static synchronized ConfigSingleton getInstance(){
if(null == instance){
instance = new ConfigSingleton();
}
return instance;
}
public int getObstacleTreeNumber(){
return obstacleTreeNumber;
}
public int getObstacleMinDistance(){
return obstacleMinDistance;
}
public int getEntityWidth() {
return entityWidth;
}
public int getEntityHeight() {
return entityHeight;
}
public int getCanvasWidth(){
return canvasWidth;
}
public int getCanvasHeight(){
return canvasHeight;
}
public int getCanvasHeightWithMenu(){
return canvasHeight + 16;
}
public int getScale(){
return scale;
}
public int getTargetTime(){
return 1000 / fps;
}
public int getSpeedInitial(){
return speedInitial;
}
public int getSpeedIncrement(){
return speedIncrement;
}
public int getSpeedMin(){
return speedMin;
}
public int getInitialJointNumber(){
return initialJointNumber;
}
public int getCollisionDetectionDistance(){
return collisionDetectionDistance;
}
}
<file_sep>package Item;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import Func.ActiveObject;
import Func.ConfigSingleton;
import Func.GameMediator;
import Func.PassiveObject;
public class Tree extends Entity implements PassiveObject {
private static BufferedImage treeImage = null;
public Tree(){
super();
loadImage();
}
public Tree(int posx, int posy){
super(posx, posy);
loadImage();
}
private void loadImage(){
try {
if(null == treeImage){
treeImage = ImageIO.read(getClass().getResourceAsStream("tree.gif"));
}
setImage(treeImage);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean collisionCheck(ActiveObject anActiveObject) {
Entity anEntity = (Entity)anActiveObject;
if(this.calDistanceWithEntity(anEntity) < ConfigSingleton.getInstance().getCollisionDetectionDistance()){
anActiveObject.hitTree();
GameMediator.getInstance().randomPlace(this);
return true;
}
return false;
}
}
<file_sep>package Item;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import Func.ActiveObject;
import Func.PassiveObject;
public class Joint extends Entity implements PassiveObject {
private static BufferedImage jointImage = null;
public Joint(){
super();
loadImage();
}
private void loadImage(){
try {
if(null == jointImage){
jointImage = ImageIO.read(getClass().getResourceAsStream("joint.gif"));
}
setImage(jointImage);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean collisionCheck(ActiveObject anActiveObject) {
Entity anEntity = (Entity)anActiveObject;
int aoX = anEntity.getCenterX();
int aoY = anEntity.getCenterY();
int aoWidth = anEntity.getWidth();
int aoHeight = anEntity.getHeight();
if((Math.abs(getCenterX()-aoX)<this.getWidth()/8+aoWidth/8)
&& (Math.abs(getCenterY()-aoY)<this.getHeight()/8+aoHeight/8)){
anActiveObject.hitJoint();
return true;
}
return false;
}
}<file_sep>package Item;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class Entity {
protected int x;
protected int y;
protected int nextX;
protected int nextY;
protected int width;
protected int height;
protected int speed;
protected boolean up;
protected boolean right;
protected boolean down;
protected boolean left;
protected BufferedImage image;
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getCenterX(){
return x + width / 2;
}
public int getCenterY(){
return y + height / 2;
}
public void setCenterX(int posX){
x = posX - width / 2;
}
public void setCenterY(int posY){
y = posY - height / 2;
}
public int getWidth(){
return width;
}
public int getHeight(){
return height;
}
public void setMoveUp() {
stop();
up = true;
}
public void setMoveRight() {
stop();
right = true;
}
public void setMoveDown() {
stop();
down = true;
}
public void setMoveLeft() {
stop();
left = true;
}
public void stop(){
up = false;
right = false;
down = false;
left = false;
}
public void turnRight(){
if(this.isMovingLeft()){
this.setMoveUp();
}
else if(this.isMovingUp()){
this.setMoveRight();
}
else if(this.isMovingRight()){
this.setMoveDown();
}
else{
this.setMoveLeft();
}
}
public boolean isMovingUp() {
return up;
}
public boolean isMovingRight() {
return right;
}
public boolean isMovingDown() {
return down;
}
public boolean isMovingLeft() {
return left;
}
public void setSpeed(int spd){
speed = spd;
}
public int getSpeed(){
return speed;
}
protected void setImage(BufferedImage img){
if(null != img){
image = img;
width = img.getWidth();
height = img.getHeight();
}
}
public void setPosition(int posx, int posy){
x = posx;
y = posy;
nextX = x;
nextY = y;
}
public Entity(){}
public Entity(int posx, int posy){
x = posx;
y = posy;
nextX = x;
nextY = y;
}
public void update(){
getNextPosition();
setPosition(nextX, nextY);
}
public void getNextPosition() {
if (up) {
nextX = x;
nextY = y - speed;
}
else if(right){
nextX = x + speed;
nextY = y;
}
else if(down){
nextX = x;
nextY = y + speed;
}
else if(left){
nextX = x - speed;
nextY = y;
}
}
public void draw(Graphics2D g2d){
g2d.drawImage(
image,
x,
y,
null
);
}
public int calDistanceWithEntity(Entity anEntity){
int retvalue = Integer.MAX_VALUE;
if(null != anEntity){
double dis = Math.sqrt((anEntity.getCenterX() - this.getCenterX())
* (anEntity.getCenterX() - this.getCenterX())
+ (anEntity.getCenterY() - this.getCenterY())
* (anEntity.getCenterY() - this.getCenterY()));
dis = dis - anEntity.getWidth()/2 - this.getWidth()/2;
retvalue = (int)dis;
}
return retvalue;
}
}
<file_sep>package Func;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
@SuppressWarnings("serial")
public class GameWindow extends JFrame implements ActionListener{
private Container contentPane = getContentPane();
private Canvas canvas;
public Canvas getCanvas(){
return this.canvas;
}
public GameWindow(){
super("Hungry Caterpillar");
setSize(300, 200);
setLocationRelativeTo(null);
setTitleComponents();
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setTitleComponents(){
contentPane.removeAll();
JLabel titleLabel = new JLabel("Caterpillar Game");
JButton startGameButton = new JButton("Start!");
JButton quitGameButton = new JButton("Quit");
JPanel titlePanel = new JPanel();
JPanel buttonPanel = new JPanel();
startGameButton.addActionListener(this);
quitGameButton.addActionListener(this);
titlePanel.setLayout(new BoxLayout(titlePanel, BoxLayout.Y_AXIS));
titlePanel.add(titleLabel, BorderLayout.NORTH);
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
buttonPanel.add(startGameButton);
buttonPanel.add(quitGameButton);
contentPane.add(titlePanel, BorderLayout.NORTH);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
this.setVisible(true);
repaint();
}
public void setGameComponents(){
this.canvas = new Canvas(this);
contentPane.removeAll();
contentPane.add(this.canvas);
this.setResizable(false);
this.pack();
this.setVisible(true);
repaint();
this.canvas.requestFocus();
}
public void setGameOverComponents(int score){
setSize(300, 200);
contentPane.removeAll();
JLabel titleLabel = new JLabel("Game Over");
JLabel scoreLabel = new JLabel("Score: " + Integer.toString(score));
JButton restartGameButton = new JButton("Restart");
JButton quitGameButton = new JButton("Quit");
JPanel titlePanel = new JPanel();
JPanel buttonPanel = new JPanel();
restartGameButton.addActionListener(this);
quitGameButton.addActionListener(this);
titlePanel.setLayout(new BoxLayout(titlePanel, BoxLayout.Y_AXIS));
titlePanel.add(titleLabel, BorderLayout.CENTER);
titlePanel.add(scoreLabel, BorderLayout.CENTER);
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
buttonPanel.add(restartGameButton);
buttonPanel.add(quitGameButton);
contentPane.add(titlePanel, BorderLayout.CENTER);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
repaint();
}
public void actionPerformed(ActionEvent e){
Object obj = e.getSource();
JButton btn = (JButton)obj;
String labelString = btn.getText();
if("Start!".equals(labelString) || "Restart".equals(labelString)){
setGameComponents();
}
else if("Quit".equals(labelString)){
System.exit(0);
}
}
}<file_sep>package Func;
public interface ActiveObject{
public void hitJoint();
public void hitTree();
public void hitApple();
public void hitBanana();
} | 3139625c3a3da701a20f29ac5c10d922c8f71d99 | [
"Java"
] | 7 | Java | your3i/MushiGame | a54cd80e4f4a6bf8fd7faf9d386eb827fc825ae5 | ec1215ced046caab4435368cbad6e682811ba394 |
refs/heads/master | <repo_name>Fukuda57/LifeColor<file_sep>/README.md
# アプリ概要
LifeColor
-> 日頃どのような行動をして1日を過ごしているかを習慣ごとに色付けして記録することで、直感的に自分の生活パターンを把握できる生活管理アプリです。
日頃の行動を 仕事(学校) / 自己研鑽 / 遊び&趣味 / 浪費 の4つに分け、時間を入力することで1日の中での行動の割合を色合いでグラフィカルに表示・管理します。
1週間や1ヶ月の記録を振り返った時に、日々の色合いの変化で自分の行動パターンの変化を瞬時に把握することができます。
# URL
<!-- これから -->
# GitHub
https://github.com/Fukuda57/LifeColor
# 制作背景
自分の生活を習慣ごとに管理している中で、長いスパンで考えた時に数値だけの記録では習慣の把握がし辛いと感じたため、それらを色合いでグラフィカルに表現してくれるアプリケーションがあれば直感で自分の生活を捉えやすいと考えて実装を決めました。
# 使用技術
- HTML(HAML) / SCSS
- Javascript
- jQuery
- Ruby 2.6.5
- Rails 6.0.3.4
# 要件定義
- 機能要件
- 習慣記録の作成・保存・表示・編集・削除 機能
- ユーザー登録・ログイン・ログアウト 機能
- フレンド登録・相互フォロー 機能
- お気に入り機能
- コメント機能
- 非機能要件
<!-- これから -->
# usersテーブル
|Column|Type|Options|
|------|----|-------|
|nickname|string|null: false|
|email|string|null: false|
|password|string|null: false|
Association
- has_many: relationships
- has_many: records
- has_many: comments
- has_many: favorite
# relationshipテーブル
|Column|Type|Options|
|------|---|--------|
|user|references|null: false, foreign_key: true|
|follow|references|null: false, foreign_key: {to_table: :users }|
Association
- belongs_to: user
# recordsテーブル
|Column|Type|Options|
|-----|----|--------|
|work_time|?|null: false|
|self_time|?|null: false|
|play_time|?|null: false|
|waste_time|?|null: false|
|date|?|null: false|
|user|references|null: false, foreign_key: true|
Association
- belongs_to: user
- has_many: comments
- has_many: favorite
# commentsテーブル
|Column|Type|Options|
|-----|----|--------|
|content|string|null: false|
|user|references|null: false, foreign_key: true|
|record|references|null: false, foreign_key: true|
Association
- belongs_to: user
- belongs_to: record
# favoriteテーブル
|Column|Type|Options|
|-----|----|--------|
|user|references|null: false, foreign_key: true|
|record|references|null: false, foreign_key: true|
Association
- belongs_to: user
- belongs_to: record<file_sep>/config/routes.rb
Rails.application.routes.draw do
root 'home#top'
end
| a87974699b51b349219f03d111fb394c79a990d3 | [
"Markdown",
"Ruby"
] | 2 | Markdown | Fukuda57/LifeColor | b5b478d580bcb6cc660ce483843d96d19df40c76 | 6979233e24583f994d07f6a58c580e302a2fdd30 |
refs/heads/master | <file_sep>"""Módulo de controladores de partida."""
from itertools import cycle
from computadora import Jugador, Computadora
from tablero import Tablero, Jugada
class Partida():
"""Controlador de partida para un jugador"""
fichas = ["X", "O"]
tipos_partida = {"jugador_vs_computadora" : 0,
"jugador_vs_jugador": 1}
def __init__(self, interfaz, jugadores):
"""Inicializa una partida para un jugador"""
self.interfaz = interfaz
nombre_jugador = self.interfaz.registrar_jugador()
ficha_jugador = self.interfaz.seleccionar_ficha(self.fichas)
jugador = Jugador(nombre_jugador, ficha_jugador)
if self.fichas.index(jugador.ficha) == 0:
ficha_oponente = self.fichas[1]
else:
ficha_oponente = self.fichas[0]
if jugadores < 2:
jugador2 = Computadora(ficha_oponente)
else:
nombre_jugador = self.interfaz.registrar_jugador()
jugador2 = Jugador(nombre_jugador, ficha_oponente)
self.tablero = Tablero()
#inicializa un ciclo entre computadora y jugador.
self.jugadores = (jugador, jugador2)
self.turnos = cycle(self.jugadores)
def iniciar_partida(self):
"""inicializa la partida"""
partida_terminada = False
jugador = self.alternar_turno()
while not partida_terminada:
if isinstance(jugador, Jugador):
casilla = self.interfaz.pedir_jugada()
jugada = Jugada(casilla, jugador.ficha)
self.tablero.marcar_casilla(jugada)
partida_terminada = self.tablero.buscar_ganador(jugada)
elif isinstance(jugador, Computadora):
casilla = jugador.jugar(self.tablero)
jugada = Jugada(casilla, jugador.ficha)
self.tablero.marcar_casilla(jugada)
partida_terminada = self.tablero.buscar_ganador(jugada)
self.interfaz.mostrar_tablero(self.tablero)
jugador = self.alternar_turno()
self.interfaz.mostrar_tablero(self.tablero)
print("partida terminada! ganador {0}".format(jugador.ficha))
def alternar_turno(self):
"""intercala los turnos entre los jugadores"""
return next(self.turnos)
<file_sep>"""Modulo de interfaz"""
from abc import ABC, abstractmethod
import os
class Interfaz(ABC):
"""Esquema para las intefaces de la aplicación"""
@abstractmethod
def menu_principal(self, opciones, callback):
"""Menú principal de la aplicación"""
pass
@abstractmethod
def registrar_jugador(self):
"""implementar para permitir ingresar un nombre para los registros."""
pass
@abstractmethod
def seleccionar_ficha(self, opciones_fichas):
"""implementar para permitir al usuario seleccionar la ficha"""
@abstractmethod
def mostrar_tablero(self, tablero):
"""Interfaz del juego"""
pass
@abstractmethod
def notificacion(self, mensaje, limpiar_pantalla=False):
"""implementar para notificar errores al usuario."""
class InterfazLineaComando(Interfaz):
"""Interfaz por línea de comandos"""
saludo_inicial = ("TATETI Python \n")
fila = lambda fila, columna: '\033[' + str(fila) + str(columna) + 'H'
def __init__(self):
print("Interfaz inicializada")
def menu_principal(self, opciones, callback):
"""imprime el menú principal y recibe la opción seleccionada"""
print(self.saludo_inicial)
opciones_menu = InterfazLineaComando.generar_opciones(opciones)
for opcion in opciones_menu:
print(str(opcion) + "\n") #imprime la opción más un saldo de línea.
while True:
try:
opcion_index = int(input("Seleccioná una opción: "))
try:
opcion_seleccionada = opciones[opcion_index]
callback(opcion_seleccionada)
break
except IndexError:
print("el valor ingresado no corresponde a ninguna opción")
opcion_index = int(input("seleccioná una opción: "))
continue
except ValueError:
print("ingresá un valor numérico!")
continue
def registrar_jugador(self):
"""Solicita al usuario un nobre para registrar en el historial."""
nombre = input("Ingresá tu nombre: ")
return nombre
def seleccionar_ficha(self, opciones_fichas):
"""presenta las fichas para que el usuario elija"""
print("Seleccioná tu ficha: ")
opciones = InterfazLineaComando.generar_opciones(opciones_fichas)
self.print_opciones(opciones)
ficha_seleccionada = self.solicitar_opcion(opciones_fichas)
return ficha_seleccionada
def mostrar_tablero(self, tablero):
"""muestra el estado del tablero"""
filas_pantalla = [InterfazLineaComando.fila(x, 5) for x in range(3, 12)]
print('\n')
print('\033[2;4H TEST')
print(filas_pantalla[0] + " | | ")
print(filas_pantalla[1] + " {0} | {1} | {2} ".format(
tablero.tabla(1),
tablero.tabla(2),
tablero.tabla(3)))
print(filas_pantalla[2] + "________|_______|________")
print(filas_pantalla[3] + " | | ")
print(filas_pantalla[4] + " {3} | {4} | {5} ".format(
tablero.tabla(4),
tablero.tabla(5),
tablero.tabla(6)))
print(filas_pantalla[5] + "________|_______|_______")
print(filas_pantalla[6] + " | | ")
print(filas_pantalla[7] + " {6} | {7} | {8} ".format(
tablero.tabla(7),
tablero.tabla(8),
tablero.tabla(9)))
print(filas_pantalla[8] + " | | ")
def notificacion(self, mensaje, limpiar_pantalla=False):
"""imprime el mensaje"""
if limpiar_pantalla:
self.limpiar_pantalla()
print(mensaje)
def limpiar_pantalla(self):
"""limpia la pantalla"""
os.system('cls' if os.name == 'nt' else 'clear')
def solicitar_opcion(self, opciones):
"""método genérico que solicita al usuario que seleccione una opción"""
while True:
try:
opcion_index = int(input("\033[12;5HSeleccioná una opción: "))
try:
opcion_seleccionada = opciones[opcion_index]
return opcion_seleccionada
except IndexError:
print("el valor ingresado no corresponde a ninguna opción")
opcion_index = int(input("seleccioná una opción: "))
continue
except ValueError:
print("ingresá un valor numérico!")
continue
@staticmethod
def generar_opciones(opciones):
"""genera una lista tipo menú de opciones"""
opciones_interfaz = []
for i, opcion in enumerate(opciones):
opcion_interfaz = OpcionInterfaz(i, str(opcion), opcion)
opciones_interfaz.append(opcion_interfaz)
return opciones_interfaz
@staticmethod
def print_opciones(opciones):
"""método genérico para imprimir opciones en pantalla"""
for opcion in opciones:
print(str(opcion) + "\n") #imprime la opción más un salto de línea
def pedir_jugada(self):
"""recibe la jugada del usuario"""
while True:
try:
casilla = int(input("\n Seleccioná la casilla a marcar: "))
if casilla in range(1, 10):
return casilla
else:
print("seleccioná una casilla entre 1 y 9")
continue
except ValueError:
print("ingresá un valor numérico")
continue
class OpcionInterfaz:
"""estructura genérica para representar una opción en la interfaz"""
def __init__(self, indice, descripcion, valor):
"""
genera una opcion para la interfaz
indice : numero que corresponde a la opcion
descripcion : descripcion del valor que representa
valor : valor que representa.
"""
self.indice = indice
self.descripcion = descripcion
self.valor = valor
def __str__(self):
return "{0} - {1}".format(self.indice, self.descripcion)
<file_sep># -*- coding: utf-8 -*-
"""Inicia la aplicación"""
from interfaz import InterfazLineaComando
from partida import Partida
class Application:
"""Maneja los controladores de partida, BD, etc."""
opciones_menu_principal = ("partida de un jugador",
"partida de dos jugadores",
"historial")
def __init__(self):
"""crea el tablero, y los jugadores, y el controlador de partida"""
self.interfaz = InterfazLineaComando()
def manejar_opcion_menu_princial(opcion):
"""Maneja la opción seleccionada por el usuario en el menú
principal"""
if self.opciones_menu_principal.index(opcion) == 0:
self.partida_un_jugador()
elif self.opciones_menu_principal.index(opcion) == 1:
self.partida_dos_jugadores()
self.interfaz.menu_principal(self.opciones_menu_principal,
manejar_opcion_menu_princial)
def partida_un_jugador(self):
"""Inicializa una partida para un jugador"""
self.partida = Partida(self.interfaz, 1)
self.partida.iniciar_partida()
def partida_dos_jugadores(self):
"""inicializa una partida para dos jugadores"""
self.partida = Partida(self.interfaz, 2)
self.partida.iniciar_partida()
def historial(self):
"""obtiene el historial de partidas recientes"""
print("opción historial")
def salir(self):
"""
Cierra la aplicación.
"""
quit()
if __name__ == "__main__":
Application()
<file_sep># -*- coding: utf-8 -*-
"""Éste es el módulo que contiene los algoritmos de análisis de jugada"""
class Computadora:
"""Genera jugadas en base al análisis del tablero."""
def __init__(self, ficha):
"""inicializa el jugador de la CPU"""
self.ficha = ficha
def jugar(self, tablero):
"""analiza el tablero y retorna una jugada"""
disponibles = tablero.casillas_disponibles()
casilla_seleccionada = disponibles[0]
return casilla_seleccionada.indice
def buscar_victoria(self, tablero):
"""test"""
class Jugador:
"""Jugador fisico, tiene datos del jugador para el registro"""
def __init__(self, nombre, ficha):
"""asigna el símbolo (X ó O) y un nombre para el."""
self.nombre = nombre
self.ficha = ficha
def jugar(self):
"""jugar"""
pass
<file_sep>"""Módulo que contiene las definiciones de los controladores."""
class ControladorMenuPrincipal:
"""Controla la interacción en el menú principal"""
def __init__(self, interfaz):
"""Inicializacón del controlador"""
self.interfaz = interfaz
def menu_principal(self):
"""Muestra el menú principal y maneja la opción seleccionada"""
opcion_seleccionada = self.interfaz.menu_principal()
print("El usuario eligió... {0}", opcion_seleccionada)
<file_sep>#combinaciones ganadoras
class Tablero:
"""gestiona las casillas del juego"""
_tabla = []
# combinaciones_ganadoras = (
# [[(x, y) for y in range(3)] for x in range(3)] + # combinaciones horizontales
# [[(x, y) for x in range(3)] for y in range(3)] + # combinaciones verticales
# [[(d, d) for d in range(3)]] + # diagonal principal
# [[(2-d, d) for d in range(3)]] # diagonal secundaria.
# )
combinaciones_ganadoras = (
[(0, 1, 2), (3, 4, 5), (6, 7, 8)] + # combinaciones horizontales
[(0, 3, 6), (1, 4, 7), (2, 5, 8)] + # combinaciones verticales
[(0, 4, 8)] + # diagonal principal
[(2, 4, 6)] # diagonal secundaria.
)
def __init__(self):
"""carga el tablero"""
self.generar_tablero()
def generar_tablero(self):
"""genera un nuevo tablero"""
for codigo_casilla in range(1, 10):
self._tabla.append(Casilla(codigo_casilla))
def buscar_ganador(self, jugada):
"""busca un ganador según su ficha"""
combinaciones_posibles = self.combinaciones_para_jugada(jugada.casilla)
print("\n " + str(combinaciones_posibles))
for combinacion_ganadora in combinaciones_posibles:
#obtiene las combinaciones ganadores para la casilla seleccionada.
valores = [str(self._tabla[x]) for x in combinacion_ganadora]
if len(set(valores)) == 1:
return True
return False
def combinaciones_para_jugada(self, jugada):
"""obtiene las combinaciones ganadoras para una determinada jugada"""
combinaciones = []
for item in self.combinaciones_ganadoras:
if jugada in item:
combinaciones.append(item)
return combinaciones
def marcar_casilla(self, jugada):
"""marca una ficha en la casilla indicada"""
casilla_a_marcar = self.tabla(jugada.casilla)
if not casilla_a_marcar.habilitada:
return False
else:
casilla_a_marcar.valor = jugada.ficha
casilla_a_marcar.habilitada = False
self.tabla(jugada.casilla, casilla_a_marcar)
return True
def casillas_disponibles(self):
"""obtiene las casillas disponibles"""
casillas_disponibles = []
for casilla in self._tabla:
if casilla.habilitada:
casillas_disponibles.append(casilla)
return casillas_disponibles
def tabla(self, indice, valor=None):
"""
como en la interfaz se manejan casillas del 1 al 9
y a nivel de estructura el tablero va de 0 a 8,
se ajusta la difrencia entre el tablero del juego
y su estructura.
indice : indice de la casilla
valor: (opcional) permite asignar un valor a la casilla
"""
if valor:
self._tabla[indice - 1] = valor
return self._tabla[indice - 1]
def __str__(self):
tablero_string = (" | | \n"
" {0} | {1} | {2} \n"
"________|_______|_______\n"
" | | \n"
" {3} | {4} | {5} \n"
"________|_______|_______\n"
" | | \n"
" {6} | {7} | {8} \n"
" | | ").format(str(self.tabla(1)),
str(self.tabla(2)),
str(self.tabla(3)),
str(self.tabla(4)),
str(self.tabla(5)),
str(self.tabla(6)),
str(self.tabla(7)),
str(self.tabla(8)),
str(self.tabla(9)))
return tablero_string
class Casilla:
"""Define la estructura de las casillas"""
def __init__(self, indice):
"""
Inicializa una casilla
la casilla ayuda a manejar el tablero de forma más
amigable
"""
self.indice = indice
self.habilitada = True
self.valor = ""
def __str__(self):
if not self.valor:
return str(self.indice)
return self.valor
class Jugada:
"""Para unificar la estructura de una jugada"""
def __init__(self, casilla, ficha):
self.casilla = casilla
self.ficha = ficha
<file_sep># tic-tac-toe
Proyecto Tic tac toe con Orientación a Objetos y Python
| f875b4a0cb7ae071a62020340cb843a84cd78b0d | [
"Markdown",
"Python"
] | 7 | Python | abalbuena/tic-tac-toe | bab1d535b1c929590d974baa9704c26cd306a00a | 0956caf79756fd457ca3e368020beb60aace71f4 |
refs/heads/master | <repo_name>Kshitij0212/MyPlate<file_sep>/MyPlate_app/admin.py
from django.contrib import admin
from .models import FoodItems, SetGoal, Previous_records
# Register your models here.
class PreRecAdmin(admin.ModelAdmin):
readonly_fields = ('date',)
admin.site.register(FoodItems)
admin.site.register(SetGoal)
admin.site.register(Previous_records, PreRecAdmin)<file_sep>/MyPlate/views.py
import requests
from bs4 import BeautifulSoup
from django.views.generic import TemplateView
class HomePage(TemplateView):
template_name = 'index.html'
class LoggedIn(TemplateView):
template_name = 'loggedIn.html'
<file_sep>/MyPlate_app/views.py
from django.shortcuts import render, redirect
from django.views.generic import ListView, CreateView, TemplateView
from .models import FoodItems, Previous_records, SetGoal
from django.urls import reverse_lazy, reverse
from .filters import FoodFilter
# Create your views here.
class FoodListView(ListView):
model = FoodItems
template_name = 'MyPlate_app/list.html'
def get_context_data(self, **kwargs) :
context = super().get_context_data(**kwargs)
context['filter'] = FoodFilter(self.request.GET, queryset = self.get_queryset())
return context
class GoalCreateView(CreateView):
model = SetGoal
fields = ['goal',]
success_url = reverse_lazy('myplate_app:list')
class CheckOutView(TemplateView):
template_name = 'MyPlate_app/checkout.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['goal'] = SetGoal.objects.values().last().get("goal") #creates a dict with key value pair, where id and goal are the keys. The last() method is used to retrieve the last value. get() method retrives the value of the key 'goal'
return context
def save_records(request):
if request.method=="POST":
user = request.POST.get('user', '')
totalCalories= request.POST.get('totalCalories', '')
goal=request.POST.get('goal_set', '')
pre_records = Previous_records(user= user, totalCalories=totalCalories, goal_set=goal,)
pre_records.save()
return redirect('../previous_records')
return render(request, 'MyPlate_app/save_rec.html')
class PreRecordsView(ListView):
model = Previous_records
template_name = 'MyPlate_app/previous_records.html'
context_object_name = 'records'
def get_queryset(self):
filtered_list = Previous_records.objects.filter(user = self.request.user.first_name + ' ' + self.request.user.last_name)
return filtered_list.order_by('-date')[:10]
<file_sep>/MyPlate_app/migrations/0007_alter_previous_records_user.py
# Generated by Django 3.2.4 on 2021-07-02 08:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('MyPlate_app', '0006_alter_previous_records_user'),
]
operations = [
migrations.AlterField(
model_name='previous_records',
name='user',
field=models.CharField(max_length=100),
),
]
<file_sep>/MyPlate_app/migrations/0003_alter_previous_records_user.py
# Generated by Django 3.2.4 on 2021-07-02 08:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('MyPlate_app', '0002_alter_previous_records_user'),
]
operations = [
migrations.AlterField(
model_name='previous_records',
name='user',
field=models.IntegerField(max_length=10, null=True),
),
]
<file_sep>/MyPlate_app/models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE
# Create your models here.
class FoodItems(models.Model):
name = models.CharField(max_length=100, unique=True)
calories = models.DecimalField(decimal_places=2, max_digits=10)
image = models.ImageField(upload_to='images', null=True)
def str(self):
return self.name
class Meta:
ordering = ('name',)
verbose_name_plural = 'FoodItems'
class SetGoal(models.Model):
goal = models.DecimalField(decimal_places=2, max_digits=10)
def str(self):
return self.goal
class Previous_records(models.Model):
user = models.CharField(max_length=100)
date = models.DateField(auto_now=True)
totalCalories = models.DecimalField(decimal_places=2, max_digits=10)
goal_set = models.DecimalField(decimal_places=2, max_digits=10)
def str(self):
return self.user<file_sep>/MyPlate_app/migrations/0001_initial.py
# Generated by Django 3.2.4 on 2021-06-28 07:51
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='FoodItems',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, unique=True)),
('calories', models.DecimalField(decimal_places=2, max_digits=10)),
('image', models.ImageField(null=True, upload_to='images')),
],
options={
'verbose_name_plural': 'FoodItems',
'ordering': ('name',),
},
),
migrations.CreateModel(
name='SetGoal',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('goal', models.DecimalField(decimal_places=2, max_digits=10)),
],
),
migrations.CreateModel(
name='Previous_records',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateField(auto_now=True)),
('totalCalories', models.DecimalField(decimal_places=2, max_digits=10)),
('goal_set', models.DecimalField(decimal_places=2, max_digits=10)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user', to=settings.AUTH_USER_MODEL)),
],
),
]
<file_sep>/MyPlate_app/forms.py
from django import forms
from django.forms.widgets import HiddenInput
class PreRecordForm(forms.Form):
totalCalories = forms.DecimalField(max_digits=10, decimal_places=2, widget=HiddenInput, initial={} )
cc_myself = forms.BooleanField(required=False)<file_sep>/MyPlate_app/filters.py
from django.contrib.auth.models import User
import django_filters
from django_filters import CharFilter
from .models import FoodItems, Previous_records
class FoodFilter(django_filters.FilterSet):
food_name = CharFilter(field_name = 'name',lookup_expr = 'icontains', label='Search food items')
class Meta :
model = FoodItems
fields = ('food_name',)
<file_sep>/MyPlate_app/urls.py
from django.urls import path, include
from django.urls.resolvers import URLPattern
from . import views
app_name = 'myplate_app'
urlpatterns = [
path('myplate_app_list/',views.FoodListView.as_view(), name='list'),
path('set_goal/', views.GoalCreateView.as_view(), name='set_goal'),
path('checkout/', views.CheckOutView.as_view(), name='checkout'),
path('previous_records/',views.PreRecordsView.as_view(), name='pre_records'),
path('save_rec/', views.save_records, name='save_rec'),
]<file_sep>/README.md
# <i>MyPlate</i>
A calorie counter web application that allows you to set a calorie goal and calculate your calorie consumption. It also keeps track of your progress.
# Technologies used:
Frontend: HTML, CSS, Bootstrap, JavaScript<br>
Backend: Django, SQLite
<file_sep>/templates/index.html
{% extends "base.html" %}
{% load static %}
{% block style %}
<style>
body{
background-image: linear-gradient(to right, aqua, rgb(150, 68, 226), rgb(205, 43, 226))
}
img{
margin-top: 10px;
height: 600px;
width: 600px;
float: right;
border-radius: 300px;
margin-bottom: 10px;
margin-right: 15px;
}
h1{
padding-top: 25px;
font-size: 80px;
margin-left: 45px;
font-family: 'STIX Two Math', serif;
}
p{
font-size: 23px;
margin-left: 45px;
padding-top: 15px;
}
.btn{
margin-left: 45px;
margin-top: 10px;
background-color: #191970;
color: beige;
font-size: 19px;
}
.btn:hover{
color: beige;
}
</style>
{% endblock %}
{% block content %}
<div>
<section>
<img src="{% static 'images/bg.jpg' %}" alt="">
</section>
<div class="container">
<h1>Fitness starts <br> with what you <br> eat.</h1>
<p>Take control of your goals. Track calories, and <br> log activities with <b><i>My Plate</i></b>.</p>
<a href="{% url 'account_login' %}" class="btn">Let's get started</a>
</div>
</div>
{% endblock %} | 1c9cd39dfe1c6f6a303090a136d4751125b1e97c | [
"Markdown",
"Python",
"HTML"
] | 12 | Python | Kshitij0212/MyPlate | 9ad7910c484ad4bcde4420424f4903fecda7a412 | caa7cdbfbf81f180bb412f2e09da7031bd3ddf67 |
refs/heads/master | <file_sep>//
// MenuTableTableViewController.swift
// SplitViewController_demo
//
// Created by Jess on 2015-11-05.
// Copyright © 2015 Jess. All rights reserved.
//
import UIKit
//the pages we will be using for the table of splitview
struct PageOption {
let displayName: String
let url: String
}
class MenuTableTableViewController: UITableViewController {
//collection of pages to display
let pages = [
PageOption(displayName: "Google", url: "https://google.com"),
PageOption(displayName: "Apple", url: "https://apple.com"),
PageOption(displayName: "iOS Developer Library", url: "https://developer.apple.com/library/ios/navigation/"),
PageOption(displayName: "Twitter", url: "https://twitter.com"),
PageOption(displayName: "BCIT", url: "https://learn.bcit.ca")
]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return the number of pages
return pages.count
}
//returns the cells that populate the table list with the display name of the PageOption
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("pageSelectCell", forIndexPath: indexPath)
//set the names of the rows in the left panel
let pageOption = pages[indexPath.row]
cell.textLabel!.text = pageOption.displayName
return cell
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "segueIdentifier" {
var menuDetailViewController: MenuDetailViewController!
if let menuTableViewController = segue.destinationViewController as? UINavigationController {
menuDetailViewController = menuTableViewController.topViewController as! MenuDetailViewController
} else {
menuDetailViewController = segue.destinationViewController as! MenuDetailViewController
}
if let selectedPageOption = tableView.indexPathForSelectedRow {
let pageOption = pages[selectedPageOption.row]
menuDetailViewController.pageOption = pageOption
}
}
}
}
<file_sep>////
//// Support.swift
//// SplitViewController_demo
////
//// Created by Jess on 2015-11-05.
//// Copyright © 2015 Jess. All rights reserved.
////
//
//import UIKit
//
//extension UISplitViewController: UISplitViewControllerDelegate {
// struct ios7Support {
// static var modeButtonItem: UIBarButtonItem?
// }
//
// var backBarButtonItem: UIBarButtonItem? {
// get {
// if respondsToSelector(Selector("displayModeButtonItem")) == true {
// let button: UIBarButtonItem = displayModeButtonItem()
// return button
// } else {
// return ios7Support.modeButtonItem
// }
// }
// set {
// ios7Support.modeButtonItem = newValue
// }
// }
// // simple trick, without swizzling :-)
//
// func displayModeButtonItem(_: Bool = true)->UIBarButtonItem? {
// return backBarButtonItem
// }
//
// public func splitViewController(svc: UISplitViewController, willHideViewController aViewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController pc: UIPopoverController) {
// if (!svc.respondsToSelector(Selector("displayModeButtonItem"))) {
// if let detailView = svc.viewControllers[svc.viewControllers.count-1] as? UINavigationController {
// svc.backBarButtonItem = barButtonItem
// detailView.topViewController!.navigationItem.leftBarButtonItem = barButtonItem
// }
// }
// }
//
//
// public func splitViewController(svc: UISplitViewController, willShowViewController aViewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) {
// if (!svc.respondsToSelector(Selector("displayModeButtonItem"))) {
// if let detailView = svc.viewControllers[svc.viewControllers.count-1] as? UINavigationController {
// svc.backBarButtonItem = nil
// detailView.topViewController!.navigationItem.leftBarButtonItem = nil
// }
// }
// }
//
// MARK: - user defined imlementation of UISplitViewControllerDelegate
//
// public func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
// if let navController = primaryViewController as? UINavigationController {
// if let controller = navController.topViewController as? MenuTableTableViewController {
// return controller.collapseDetailViewController
// }
// }
// return true
// }
//}
<file_sep>//
// MenuDetailViewController.swift
// SplitViewController_demo
//
// Created by Jess on 2015-11-05.
// Copyright © 2015 Jess. All rights reserved.
//
import UIKit
class MenuDetailViewController: UIViewController {
var pageOption = PageOption(displayName: "Home", url: "https://support.google.com")
@IBOutlet weak var lbl_title: UILabel!
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view
self.lbl_title.text = "You are now Browsing: \(pageOption.displayName)"
let requestUrl = pageOption.url
let requestNSURL = NSURL(string: requestUrl)
let request = NSURLRequest(URL: requestNSURL!)
webView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep># SplitViewController_demo
###### Basic Example of a SplitView Controller in Swift
For BCIT COMP4977 [wiki page](http://www.comp4977playground.krusnix.com)
*[ For education purposes only ]*
| 492938b43ebb061052fefa8ac8141cfc8de271ad | [
"Swift",
"Markdown"
] | 4 | Swift | jtekenos/SplitViewController_demo | 822e623dc526d810adb6ed640ce4e0f69bfcf418 | 4d5194b5c1dc5625f58f162662bc2278bbce0327 |
refs/heads/main | <file_sep>var app = PetiteVue.createApp({
resources: [],
created: function() {
var self = this;
var resourceRegex = /\[(.+?)\]\((.+?)\)\|(.+)/;
axios.get('README.md')
.then(function (res) {
var data = res.data;
// Split the document into categories
var categories = data.trim().split(/##\s+/).slice(1);
for (var i = 0; i < categories.length; i++) {
var category = categories[i];
var categoryData = category.trim().split("\n\n\n");
var name = categoryData[0];
if (categoryData.length === 3) {
var description = categoryData[1].replace(/\n/g, "<br>");
var resources = categoryData[2];
} else {
var description = "";
var resources = categoryData[1];
}
// Reshape each resource and push the resulting list back into our state
var resourceList = resources.split("\n").slice(2).map(function (resource) {
var matches = resourceRegex.exec(resource);
return { "name": matches[1], "url": matches[2], "description": matches[3] };
});
self.resources.push({ "name": name, "description": description, "resources": resourceList });
}
// For some reason, petite-vue reads the array in reverse - flip it
self.resources = self.resources.reverse();
});
},
formatDescription: function(description) {
// Replace URL markdown with proper anchor tags
return description.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2">$1</a> ');
},
nameToId: function(category) {
return category.name.toLowerCase().replace(/[^a-z0-9]+/ig, '-');
}
})
.mount('#app');
<file_sep># Contributing
Thank you for contributing! Here are a few guidelines to follow before you post:
Websites that fall under multiple categories may be added multiple times, such as [Universalis](https://universalis.app), which is both a website and a web API.
Websites that have multiple distinct entries under a single category may have each entry added separately, such as [exdreams](https://exdreams.net/), which has a variety of distinct web applications on it.
Just some quick NOs:
* No Discord (or other chat) servers - There are a million of them. Likewise for forums. Websites that *have* a forum or a server associated with them are perfectly fine, as long as the website is not only a means of having people join a forum/server.
* No chat bots - They're easy to make, and there are tons of them.
* No TexTools mods - See above. Exceptions might be made for UI mods.
* No Dalamud plugins that are in the main plugin repository already.
* No XIVAPI clients that are on the GitHub organization already.
The exception to all of this is that I *will* accept aggregators of the above. For example, [XIV Mod Archive](https://www.xivmodarchive.com/) is linked, but specific mods are not.
"Cheating" software will be added at my own discretion; what crosses that line will be decided very arbitrarily.
## Sorting
Entries within each table should be alphabetized.
## Formatting
When adding a new category, it should match the following format:
```md
## Category Name
This is the category description. It is optional, but must still leave two new blank lines between the name and the table data.
Name|Description
---|---
[My Resource](https://example.com)|This is a description of my resource
```
| 2e52e46e0a553cb68967e0fda08a29e269b07b4a | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Gizmog/xiv-resources | c7f590d07c07da6da22cf678c4f5ddd26b28cf3b | e215a1c5cadca53404bfd0481540bac06bfde22e |
refs/heads/master | <repo_name>Belobobr/store<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/messages/chat/ChatFragment.java
package com.mixailsednev.storeproject.view.messages.chat;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.mixailsednev.storeproject.Injection;
import com.mixailsednev.storeproject.R;
import com.mixailsednev.storeproject.model.messages.chat.Message;
import com.mixailsednev.storeproject.view.common.BaseFragment;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class ChatFragment extends BaseFragment<ChatPresenter> implements ChatContract.ChatView {
public static final String TAG = ChatFragment.class.getSimpleName();
public static final String ARG_CHAT_ID = "chat_id";
public static ChatFragment newInstance(@NonNull String chat_id) {
ChatFragment fragment = new ChatFragment();
Bundle arguments = new Bundle();
arguments.putString(ChatFragment.ARG_CHAT_ID, chat_id);
fragment.setArguments(arguments);
return fragment;
}
@NonNull
private String chatId;
@BindView(R.id.messages_list)
protected RecyclerView recyclerView;
@BindView(R.id.progress)
protected View progressLayout;
@BindView(R.id.comment_message)
protected EditText messageEditText;
private ChatRecyclerViewAdapter chatRecyclerViewAdapter;
private LinearLayoutManager linearLayoutManager;
@Override
public ChatPresenter createPresenter() {
return new ChatPresenter(this, Injection.provideChatRepository(chatId));
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_CHAT_ID)) {
String chatId = getArguments().getString(ARG_CHAT_ID);
if (chatId != null) {
this.chatId = chatId;
} else {
throw new IllegalArgumentException("Chat ID can't be null");
}
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_chat, container, false);
ButterKnife.bind(this, rootView);
chatRecyclerViewAdapter = new ChatRecyclerViewAdapter(new ArrayList<>());
linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(chatRecyclerViewAdapter);
return rootView;
}
@Override
public void onNewViewStateInstance() {
}
@Override
public void setMessages(@NonNull List<Message> messages) {
int messageCount = chatRecyclerViewAdapter.getItemCount();
int lastVisiblePosition =
linearLayoutManager.findLastCompletelyVisibleItemPosition();
boolean scrollToLastMessage = lastVisiblePosition == messageCount - 1;
chatRecyclerViewAdapter.setMessages(messages);
if (scrollToLastMessage) {
recyclerView.scrollToPosition(chatRecyclerViewAdapter.getItemCount() - 1);
}
}
@OnClick(R.id.send)
protected void onSendButtonClick() {
getPresenter().addMessage(messageEditText.getText().toString());
messageEditText.setText("");
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/model/company/services/Service.java
package com.mixailsednev.storeproject.model.company.services;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class Service {
@Nullable
String id;
@NonNull
String name;
public Service(@Nullable String id, @NonNull String name) {
this.name = name;
this.id = id;
}
@NonNull
public String getName() {
return name;
}
@NonNull
public void setName(String name) {
this.name = name;
}
@Nullable
public String getId() {
return id;
}
public void setId(@Nullable String id) {
this.id = id;
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/company/info/CompanyInfoContract.java
package com.mixailsednev.storeproject.view.company.info;
import android.support.annotation.NonNull;
import com.mixailsednev.storeproject.model.company.CompanyInfo;
public class CompanyInfoContract {
public interface CompanyView {
void setCompany(@NonNull CompanyInfo companyInfo);
}
public interface ActionsListener {
void addComment(@NonNull String commentContent);
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/model/common/CompositeDataChangeListener.java
package com.mixailsednev.storeproject.model.common;
import android.support.annotation.NonNull;
import com.mixailsednev.storeproject.model.common.BaseRepository.DataChangeListener;
import java.util.HashMap;
import java.util.Map;
public class CompositeDataChangeListener {
private Map<BaseRepository, DataChangeListener> dataChangeListeners;
public CompositeDataChangeListener() {
dataChangeListeners = new HashMap<>();
}
public void addListener(@NonNull BaseRepository store, @NonNull DataChangeListener dataChangeListener) {
dataChangeListeners.put(store, dataChangeListener);
}
public void subscribe() {
for (BaseRepository store : dataChangeListeners.keySet()) {
store.addListener(dataChangeListeners.get(store));
}
}
public void unSubscribe() {
for (BaseRepository store : dataChangeListeners.keySet()) {
store.removeListener(dataChangeListeners.get(store));
}
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/company/info/CompanyInfoPresenter.java
package com.mixailsednev.storeproject.view.company.info;
import android.support.annotation.NonNull;
import com.mixailsednev.storeproject.view.common.BasePresenter;
public class CompanyInfoPresenter extends BasePresenter<CompanyInfoContract.CompanyView> {
public CompanyInfoPresenter(@NonNull CompanyInfoContract.CompanyView companyView) {
super(companyView);
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/model/messages/userChat/FirebaseUserChatsRepository.java
package com.mixailsednev.storeproject.model.messages.userChat;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import com.mixailsednev.storeproject.model.firebase.FirebaseUtils;
import java.util.ArrayList;
import java.util.List;
public class FirebaseUserChatsRepository extends UserChatsRepository {
public static String TAG = FirebaseUserChatsRepository.class.getSimpleName();
private static FirebaseUserChatsRepository instance = new FirebaseUserChatsRepository();
public static FirebaseUserChatsRepository getInstance() {
return instance;
}
private ValueEventListener userChatsEventListener;
@NonNull
private List<UserChat> userChats;
public FirebaseUserChatsRepository() {
this.userChats = new ArrayList<>();
}
//TODO если кто то наблюдает за репозитроием, то ему необходимо наблюдать за состоянием сервера
@Override
public void addListener(DataChangeListener dataChangeListener) {
super.addListener(dataChangeListener);
if (getListenersCount() == 1) {
userChatsEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<UserChat> userChats = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
UserChat userChat = snapshot.getValue(UserChat.class);
userChat.setId(snapshot.getKey());
userChats.add(userChat);
}
FirebaseUserChatsRepository.this.userChats = userChats;
notifyDataChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, databaseError.getMessage());
}
};
DatabaseReference currentUserRef = FirebaseUtils.getCurrentUserRef();
if (currentUserRef != null) {
currentUserRef.child("chats").addValueEventListener(userChatsEventListener);
}
}
}
@Override
public void removeListener(DataChangeListener dataDataChangeListener) {
super.removeListener(dataDataChangeListener);
if (getListenersCount() <= 0) {
DatabaseReference currentUserRef = FirebaseUtils.getCurrentUserRef();
if (currentUserRef != null) {
currentUserRef.child("chats").removeEventListener(userChatsEventListener);
}
}
}
@Override
public void removeUserChat(@NonNull UserChat userChat) {
}
@Override
public void addUserChat(@NonNull UserChat userChat) {
}
@Override
public void updateUserChat(@NonNull UserChat userChat) {
}
@NonNull
@Override
public List<UserChat> getUserChats() {
return userChats;
}
@Nullable
@Override
public UserChat getUserChat(@NonNull String userChatId) {
return null;
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/company/CompanyFragment.java
package com.mixailsednev.storeproject.view.company;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mixailsednev.storeproject.R;
import com.mixailsednev.storeproject.view.company.info.CompanyInfoFragment;
import com.mixailsednev.storeproject.view.company.news.NewsFragment;
import com.mixailsednev.storeproject.view.company.services.ServicesFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
public class CompanyFragment extends Fragment {
public static final String TAG = CompanyFragment.class.getSimpleName();
public static final String ARG_COMPANY_ID = "company_id";
public static CompanyFragment newInstance(@NonNull String companyId) {
CompanyFragment fragment = new CompanyFragment();
Bundle arguments = new Bundle();
arguments.putString(CompanyFragment.ARG_COMPANY_ID, companyId);
fragment.setArguments(arguments);
return fragment;
}
@NonNull
private String companyId;
@NonNull
@BindView(R.id.pager)
protected ViewPager viewPager;
@NonNull
@BindView(R.id.tab_layout)
protected TabLayout tabLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_COMPANY_ID)) {
String companyId = getArguments().getString(ARG_COMPANY_ID);
if (companyId != null) {
this.companyId = companyId;
} else {
throw new IllegalArgumentException("Company id can't be null");
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_company, container, false);
ButterKnife.bind(this, rootView);
CompanyPagerAdapter companyPagerAdapter =
new CompanyPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(companyPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
public class CompanyPagerAdapter extends FragmentPagerAdapter {
public CompanyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return CompanyInfoFragment.newInstance(companyId);
case 1:
return ServicesFragment.newInstance(companyId);
case 2:
return NewsFragment.newInstance(companyId);
default:
return null;
}
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.info);
case 1:
return getString(R.string.services);
case 2:
return getString(R.string.news);
default:
return "";
}
}
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/messages/userChat/UserChatsFragment.java
package com.mixailsednev.storeproject.view.messages.userChat;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mixailsednev.storeproject.Injection;
import com.mixailsednev.storeproject.R;
import com.mixailsednev.storeproject.model.messages.userChat.UserChat;
import com.mixailsednev.storeproject.view.common.BaseFragment;
import com.mixailsednev.storeproject.view.messages.userChat.UserChatsContract.UserChatsView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class UserChatsFragment extends BaseFragment<UserChatsPresenter> implements UserChatsView,
UserChatsRecyclerViewAdapter.UserChatRemovedListener {
public interface UserChatSelectedListener {
void userChatSelected(@NonNull String userChatID);
}
public static UserChatsFragment newInstance() {
return new UserChatsFragment();
}
@BindView(R.id.user_chats_list)
protected RecyclerView recyclerView;
@BindView(R.id.progress)
protected View progressLayout;
private UserChatsRecyclerViewAdapter userChatsRecyclerViewAdapter;
private UserChatSelectedListener userChatSelectedListener;
@Override
public UserChatsPresenter createPresenter() {
return new UserChatsPresenter(this, Injection.provideUserChatsRepository());
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_user_chats, container, false);
ButterKnife.bind(this, rootView);
userChatsRecyclerViewAdapter = new UserChatsRecyclerViewAdapter(new ArrayList<>(), userChatSelectedListener, this);
recyclerView.setAdapter(userChatsRecyclerViewAdapter);
return rootView;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof UserChatSelectedListener) {
userChatSelectedListener = (UserChatSelectedListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement UserChatSelectedListener");
}
}
@Override
public void onDetach() {
super.onDetach();
userChatSelectedListener = null;
}
@Override
public void setUserChats(@NonNull List<UserChat> userChats) {
userChatsRecyclerViewAdapter.setUserChats(userChats);
}
@Override
public void onNewViewStateInstance() {
}
@Override
public void userChatRemoved(@NonNull UserChat userChat) {
getPresenter().removeUserChat(userChat);
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/common/BaseActivity.java
package com.mixailsednev.storeproject.view.common;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
public abstract class BaseActivity<Presenter extends BasePresenter> extends AppCompatActivity {
protected Presenter presenter;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
presenter = getPresenter();
}
public abstract Presenter getPresenter();
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState == null) {
onNewViewStateInstance();
}
}
@Override
protected void onStart() {
super.onStart();
getPresenter().subscribeToDataStore();
}
@Override
protected void onStop() {
super.onStop();
getPresenter().unSubscribeFromDataStore();
}
public void onNewViewStateInstance() {
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/messages/chat/ChatRecyclerViewAdapter.java
package com.mixailsednev.storeproject.view.messages.chat;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.mixailsednev.storeproject.R;
import com.mixailsednev.storeproject.model.firebase.FirebaseUtils;
import com.mixailsednev.storeproject.model.messages.chat.Message;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ChatRecyclerViewAdapter extends RecyclerView.Adapter<ChatRecyclerViewAdapter.ViewHolder> {
private List<Message> messages;
public ChatRecyclerViewAdapter(List<Message> messages) {
this.messages = messages;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_message, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Message message = messages.get(position);
holder.message = message;
holder.messageTextView.setText(message.getContent());
if (message.getOwner().equals(FirebaseUtils.getCurrentUserId())) {
holder.messageContainer.setGravity(Gravity.RIGHT);
} else {
holder.messageContainer.setGravity(Gravity.LEFT);
}
}
public void setMessages(@NonNull List<Message> messages) {
this.messages = messages;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
return messages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.comment_message)
public TextView messageTextView;
@BindView(R.id.message_container)
public RelativeLayout messageContainer;
public View view;
public Message message;
public ViewHolder(View view) {
super(view);
this.view = view;
ButterKnife.bind(this, view);
}
@Override
public String toString() {
return super.toString() + " '";
}
}
}<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/product/details/ProductDetailFragment.java
package com.mixailsednev.storeproject.view.product.details;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mixailsednev.storeproject.Injection;
import com.mixailsednev.storeproject.R;
import com.mixailsednev.storeproject.model.product.Product;
import com.mixailsednev.storeproject.view.common.BaseFragment;
import com.mixailsednev.storeproject.view.custom.ProductParamView;
import com.mixailsednev.storeproject.view.product.details.ProductDetailsContract.ProductDetailsView;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ProductDetailFragment extends BaseFragment<ProductDetailsPresenter> implements ProductDetailsView {
public static final String ARG_PRODUCT_ID = "product_id";
public static ProductDetailFragment newInstance(@NonNull String productId) {
ProductDetailFragment fragment = new ProductDetailFragment();
Bundle arguments = new Bundle();
arguments.putString(ProductDetailFragment.ARG_PRODUCT_ID, productId);
fragment.setArguments(arguments);
return fragment;
}
@NonNull
private String productId;
@BindView(R.id.product_name)
protected ProductParamView productNameView;
@BindView(R.id.product_cost)
protected ProductParamView productCostView;
@BindView(R.id.product_description)
protected ProductParamView productDescriptionView;
@Override
public ProductDetailsPresenter createPresenter() {
return new ProductDetailsPresenter(this, Injection.provideProductRepository(), productId);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_PRODUCT_ID)) {
String productId = getArguments().getString(ARG_PRODUCT_ID);
if (productId != null) {
this.productId = productId;
} else {
throw new IllegalArgumentException("ProductId can't be null");
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_product_detail, container, false);
ButterKnife.bind(this, rootView);
return rootView;
}
@Override
public void setProduct(@NonNull Product product) {
productNameView.setParamValue(product.getName());
productCostView.setParamValue(product.getCost());
productDescriptionView.setParamValue(product.getDescription());
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/custom/FixedAspectRatioFrameLayout.java
package com.mixailsednev.storeproject.view.custom;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import com.mixailsednev.storeproject.R;
public class FixedAspectRatioFrameLayout extends FrameLayout {
private int aspectRationWidth;
private int aspectRationHeight;
public FixedAspectRatioFrameLayout(Context context) {
super(context);
}
public FixedAspectRatioFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public FixedAspectRatioFrameLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FixedAspectRatioFrameLayout);
aspectRationWidth = a.getInt(R.styleable.FixedAspectRatioFrameLayout_aspectRatioWidth, 4);
aspectRationHeight = a.getInt(R.styleable.FixedAspectRatioFrameLayout_aspectRatioHeight, 3);
a.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int originalWidth = MeasureSpec.getSize(widthMeasureSpec);
int calculatedHeight = originalWidth * aspectRationHeight / aspectRationWidth;
int finalWidth, finalHeight;
finalWidth = originalWidth;
finalHeight = calculatedHeight;
super.onMeasure(
MeasureSpec.makeMeasureSpec(finalWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(finalHeight, MeasureSpec.EXACTLY));
}
}<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'com.neenbedankt.android-apt'
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
applicationId "com.mixailsednev.storeproject"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion"
compile "com.android.support:support-v4:$rootProject.supportLibraryVersion"
compile "com.android.support:recyclerview-v7:$rootProject.supportLibraryVersion"
compile "com.android.support:design:$rootProject.supportLibraryVersion"
compile "com.jakewharton:butterknife:$rootProject.butterKnifeVersion"
apt "com.jakewharton:butterknife-compiler:$rootProject.butterKnifeVersion"
compile "de.hdodenhof:circleimageview:$rootProject.circleImageViewVersion"
compile "com.github.bumptech.glide:glide:$rootProject.glide"
compile "io.reactivex:rxandroid:$rootProject.RxAndroidVersion"
compile "io.reactivex:rxjava:$rootProject.RxJavaVersion"
compile "com.google.android.gms:play-services-auth:$rootProject.firebase"
compile "com.google.firebase:firebase-auth:$rootProject.firebase"
compile "com.google.firebase:firebase-database:$rootProject.firebase"
compile "com.google.firebase:firebase-crash:$rootProject.firebase"
compile "com.fasterxml.jackson.core:jackson-databind:$rootProject.jackson"
}
apply plugin: 'com.google.gms.google-services'<file_sep>/app/src/main/java/com/mixailsednev/storeproject/model/messages/userChat/UserChatsRepository.java
package com.mixailsednev.storeproject.model.messages.userChat;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.mixailsednev.storeproject.model.common.BaseRepository;
import java.util.List;
public abstract class UserChatsRepository extends BaseRepository{
abstract public void removeUserChat(@NonNull UserChat userChat);
abstract public void addUserChat(@NonNull UserChat userChat);
abstract public void updateUserChat(@NonNull UserChat userChat);
@NonNull
abstract public List<UserChat> getUserChats();
@Nullable
abstract public UserChat getUserChat(@NonNull String userChatId);
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/MainActivity.java
package com.mixailsednev.storeproject.view;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.mixailsednev.storeproject.R;
import com.mixailsednev.storeproject.view.company.CompanyActivity;
import com.mixailsednev.storeproject.view.company.CompanyFragment;
import com.mixailsednev.storeproject.view.company.list.CompaniesFragment;
import com.mixailsednev.storeproject.view.company.list.CompaniesRecyclerViewAdapter;
import com.mixailsednev.storeproject.view.messages.chat.ChatActivity;
import com.mixailsednev.storeproject.view.messages.chat.ChatFragment;
import com.mixailsednev.storeproject.view.messages.userChat.UserChatsFragment;
import com.mixailsednev.storeproject.view.product.details.ProductDetailFragment;
import com.mixailsednev.storeproject.view.product.edit.ProductEditFragment;
import com.mixailsednev.storeproject.view.product.list.ProductListFragment;
import com.mixailsednev.storeproject.view.utils.GlideUtil;
import com.mixailsednev.storeproject.view.welcome.WelcomeActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity implements
ProductListFragment.ProductSelectedListener,
Toolbar.OnMenuItemClickListener,
UserChatsFragment.UserChatSelectedListener,
NavigationView.OnNavigationItemSelectedListener,
CompaniesRecyclerViewAdapter.CompanySelectedListener
{
private boolean twoPane;
//TODO move to model view? / presenter
@NonNull
private String selectedProductId;
private ActionBarDrawerToggle drawerToggle;
@BindView(R.id.drawer_layout)
protected DrawerLayout drawerlayout;
@BindView(R.id.navigation_view)
protected NavigationView navigationView;
@Nullable
@BindView(R.id.detail_toolbar)
protected Toolbar detailsToolbar;
@BindView(R.id.main_toolbar)
protected Toolbar mainToolbar;
@BindView(R.id.app_bar)
protected View appBar;
@BindView(R.id.fab)
protected FloatingActionButton floatingActionButton;
protected ImageView userPhotoImageView;
protected TextView userNameTextView;
protected TextView userEmailTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
userPhotoImageView = ButterKnife.findById(navigationView.getHeaderView(0), R.id.user_photo);
userNameTextView = ButterKnife.findById(navigationView.getHeaderView(0), R.id.user_name);
userEmailTextView = ButterKnife.findById(navigationView.getHeaderView(0), R.id.user_email);
if (findViewById(R.id.details_container) != null) {
twoPane = true;
}
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.main_container, CompaniesFragment.newInstance())
.commit();
}
drawerToggle = new ActionBarDrawerToggle(this, drawerlayout, mainToolbar,
R.string.open_navigation_drawer, R.string.close_navigation_drawer) {
};
drawerlayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
if (detailsToolbar != null) {
detailsToolbar.setOnMenuItemClickListener(this);
}
navigationView.setNavigationItemSelectedListener(this);
updateAppBar();
updateUserInfo();
}
@OnClick(R.id.fab)
public void onCreateProduct(View view) {
if (twoPane) {
newProduct();
} else {
Intent intent = new Intent(MainActivity.this, ProductDetailActivity.class);
MainActivity.this.startActivity(intent);
}
}
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.sign_out:
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(this, WelcomeActivity.class));
return true;
case R.id.messages:
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_container, UserChatsFragment.newInstance())
.commit();
drawerlayout.closeDrawers();
updateAppBar();
floatingActionButton.show();
return true;
case R.id.companies:
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_container, CompaniesFragment.newInstance())
.commit();
drawerlayout.closeDrawers();
updateAppBar();
floatingActionButton.hide();
return true;
case R.id.barbershop:
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_container, CompanyFragment.newInstance("FAHAH"), CompanyFragment.TAG)
.commit();
drawerlayout.closeDrawers();
updateAppBar();
floatingActionButton.hide();
default:
menuItem.setChecked(true);
drawerlayout.closeDrawers();
floatingActionButton.hide();
return true;
}
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.edit:
editProduct(selectedProductId);
return true;
case R.id.complete:
editProductComplete();
return true;
}
return false;
}
@Override
public void onConfigurationChanged(final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
public void productSelected(@NonNull String productId) {
this.selectedProductId = productId;
if (twoPane) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.details_container, ProductDetailFragment.newInstance(productId))
.commit();
} else {
Intent intent = new Intent(this, ProductDetailActivity.class);
intent.putExtra(ProductDetailFragment.ARG_PRODUCT_ID, productId);
this.startActivity(intent);
}
}
@Override
public void userChatSelected(@NonNull String userChatID) {
if (twoPane) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.details_container, ProductDetailFragment.newInstance(userChatID))
.commit();
} else {
Intent intent = new Intent(this, ChatActivity.class);
intent.putExtra(ChatFragment.ARG_CHAT_ID, userChatID);
this.startActivity(intent);
}
}
@Override
public void companySelected(@NonNull String companyId) {
if (twoPane) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.details_container, CompanyFragment.newInstance(companyId))
.commit();
} else {
Intent intent = new Intent(this, CompanyActivity.class);
intent.putExtra(CompanyFragment.ARG_COMPANY_ID, companyId);
this.startActivity(intent);
}
}
private void newProduct() {
editProduct(null);
}
private void editProduct(@Nullable String productId) {
ProductEditFragment fragment = ProductEditFragment.newInstance(productId);
getSupportFragmentManager().beginTransaction()
.replace(R.id.details_container, fragment, ProductEditFragment.TAG)
.addToBackStack(null)
.commit();
updateDetailsToolbar();
}
private void editProductComplete() {
if (getProductEditFragment() != null) {
getProductEditFragment().editProductComplete();
}
getSupportFragmentManager().popBackStack();
updateDetailsToolbar();
}
private void updateDetailsToolbar() {
getSupportFragmentManager().executePendingTransactions();
int menuRes = inEditMode() ? R.menu.edit_menu_menu : R.menu.details_menu;
if (detailsToolbar != null) {
detailsToolbar.getMenu().clear();
detailsToolbar.inflateMenu(menuRes);
}
}
private void updateAppBar() {
getSupportFragmentManager().executePendingTransactions();
mainToolbar.getMenu().clear();
mainToolbar.inflateMenu(R.menu.main_menu);
mainToolbar.setTitle(getString(R.string.products));
mainToolbar.setNavigationIcon(R.drawable.ic_menu);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
appBar.setElevation(hasTabs() ? 0 : 4);
}
updateDetailsToolbar();
}
private void updateUserInfo() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
userNameTextView.setText(name);
userEmailTextView.setText(email);
if (photoUrl != null) {
GlideUtil.loadProfileIcon(photoUrl.toString(), userPhotoImageView);
}
}
}
private boolean hasTabs() {
return getSupportFragmentManager().findFragmentByTag(CompanyFragment.TAG) != null;
}
private boolean inEditMode() {
return getSupportFragmentManager().findFragmentByTag(ProductEditFragment.TAG) != null;
}
@Nullable
private ProductEditFragment getProductEditFragment() {
return (ProductEditFragment) getSupportFragmentManager().findFragmentByTag(ProductEditFragment.TAG);
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/product/list/ProductListFragment.java
package com.mixailsednev.storeproject.view.product.list;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mixailsednev.storeproject.Injection;
import com.mixailsednev.storeproject.R;
import com.mixailsednev.storeproject.model.product.Product;
import com.mixailsednev.storeproject.view.common.BaseFragment;
import com.mixailsednev.storeproject.view.product.list.ProductListContract.ProductListView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ProductListFragment extends BaseFragment<ProductListPresenter> implements ProductListView,
ProductRecyclerViewAdapter.ProductRemovedListener {
public interface ProductSelectedListener {
void productSelected(@NonNull String productId);
}
public static ProductListFragment newInstance() {
return new ProductListFragment();
}
@BindView(R.id.product_list)
protected RecyclerView recyclerView;
@BindView(R.id.progress)
protected View progressLayout;
private ProductRecyclerViewAdapter productRecyclerViewAdapter;
private ProductSelectedListener productSelectedListener;
@Override
public ProductListPresenter createPresenter() {
return new ProductListPresenter(this, Injection.provideProductRepository());
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_product_list, container, false);
ButterKnife.bind(this, rootView);
productRecyclerViewAdapter = new ProductRecyclerViewAdapter(new ArrayList<>(), productSelectedListener, this);
recyclerView.setAdapter(productRecyclerViewAdapter);
return rootView;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof ProductSelectedListener) {
productSelectedListener = (ProductSelectedListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement UserChatSelectedListener");
}
}
@Override
public void onDetach() {
super.onDetach();
productSelectedListener = null;
}
@Override
public void setProducts(@NonNull List<Product> products) {
productRecyclerViewAdapter.setProducts(products);
}
@Override
public void onNewViewStateInstance() {
}
@Override
public void productRemoved(@NonNull Product product) {
getPresenter().removeProduct(product);
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/model/product/ProductBuilder.java
package com.mixailsednev.storeproject.model.product;
import android.support.annotation.Nullable;
public class ProductBuilder {
@Nullable
private String id;
private String name;
private String cost;
private String description;
public ProductBuilder setId(@Nullable String id) {
this.id = id;
return this;
}
public ProductBuilder setName(String name) {
this.name = name;
return this;
}
public ProductBuilder setCost(String cost) {
this.cost = cost;
return this;
}
public ProductBuilder setDescription(String description) {
this.description = description;
return this;
}
public Product createProduct() {
return new Product(id, name, cost, description);
}
}<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/common/CommentView.java
package com.mixailsednev.storeproject.view.common;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.mixailsednev.storeproject.R;
import butterknife.BindView;
import butterknife.ButterKnife;
public class CommentView extends FrameLayout {
@BindView(R.id.comment_author_image)
protected ImageView authorImage;
@BindView(R.id.comment_author_name)
protected TextView authorName;
@BindView(R.id.comment_date)
protected TextView date;
@BindView(R.id.comment_message)
protected TextView message;
@BindView(R.id.like_comment)
protected ImageButton like;
public CommentView(Context context) {
super(context);
init();
}
public CommentView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CommentView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
View view = LayoutInflater.from(getContext()).inflate(R.layout.view_comment, this, true);
ButterKnife.bind(this, view);
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/product/list/ProductRecyclerViewAdapter.java
package com.mixailsednev.storeproject.view.product.list;
import android.support.annotation.NonNull;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.mixailsednev.storeproject.R;
import com.mixailsednev.storeproject.model.product.Product;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ProductRecyclerViewAdapter extends RecyclerView.Adapter<ProductRecyclerViewAdapter.ViewHolder> {
public interface ProductRemovedListener {
void productRemoved(@NonNull Product product);
}
private List<Product> products;
private ProductListFragment.ProductSelectedListener productSelectedListener;
private ProductRemovedListener productRemovedListener;
public ProductRecyclerViewAdapter(List<Product> products,
ProductListFragment.ProductSelectedListener productSelectedListener,
ProductRemovedListener productRemovedListener) {
this.products = products;
this.productSelectedListener = productSelectedListener;
this.productRemovedListener = productRemovedListener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_product, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.product = products.get(position);
holder.nameTextView.setText(products.get(position).getName());
holder.view.setOnClickListener((view) -> {
productSelectedListener.productSelected(holder.product.getId());
});
holder.popupMenuImageView.setOnClickListener((v) -> {
final PopupMenu popupMenu = new PopupMenu(v.getContext(), v, Gravity.RIGHT);
final Menu menu = popupMenu.getMenu();
popupMenu.getMenuInflater().inflate(R.menu.menu_item_product, menu);
popupMenu.setOnMenuItemClickListener((item) -> {
productRemovedListener.productRemoved(holder.product);
return true;
});
popupMenu.show();
});
}
public void setProducts(@NonNull List<Product> products) {
this.products = products;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
return products.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.product_name)
public TextView nameTextView;
@BindView(R.id.product_popup_menu)
public ImageView popupMenuImageView;
public View view;
public Product product;
public ViewHolder(View view) {
super(view);
this.view = view;
ButterKnife.bind(this, view);
}
@Override
public String toString() {
return super.toString() + " '";
}
}
}<file_sep>/app/src/main/java/com/mixailsednev/storeproject/model/product/ProductsRepository.java
package com.mixailsednev.storeproject.model.product;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.mixailsednev.storeproject.model.common.BaseRepository;
import java.util.List;
public abstract class ProductsRepository extends BaseRepository {
abstract public void removeProduct(@NonNull Product product);
abstract public void addProduct(@NonNull Product product);
abstract public void updateProduct(@NonNull Product product);
@NonNull
abstract public List<Product> getProducts();
@Nullable
abstract public Product getProduct(@NonNull String productId);
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/company/info/CompanyInfoView.java
package com.mixailsednev.storeproject.view.company.info;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.mixailsednev.storeproject.R;
import butterknife.BindView;
import butterknife.ButterKnife;
public class CompanyInfoView extends FrameLayout {
@BindView(R.id.company_address)
TextView addressTextView;
@BindView(R.id.company_raiting)
TextView ratingTextView;
public CompanyInfoView(Context context) {
super(context);
init();
}
public CompanyInfoView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CompanyInfoView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
View view = LayoutInflater.from(getContext()).inflate(R.layout.view_company_info, this, true);
ButterKnife.bind(this, view);
}
public void setAddress(@NonNull String address) {
addressTextView.setText(address);
}
public void setRating(@NonNull String rating) {
ratingTextView.setText(rating);
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/model/product/FirebaseProductsRepository.java
package com.mixailsednev.storeproject.model.product;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import com.mixailsednev.storeproject.model.firebase.FirebaseUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FirebaseProductsRepository extends ProductsRepository {
public static String TAG = FirebaseProductsRepository.class.getSimpleName();
private static ProductsRepository instance = new FirebaseProductsRepository();
public static ProductsRepository getInstance() {
return instance;
}
private ValueEventListener productEventListener;
@NonNull
private List<Product> products;
public FirebaseProductsRepository() {
this.products = new ArrayList<>();
}
//TODO если кто то наблюдает за репозитроием, то ему необходимо наблюдать за состоянием сервера
@Override
public void addListener(DataChangeListener dataChangeListener) {
super.addListener(dataChangeListener);
if (getListenersCount() == 1) {
productEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<Product> products = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Product product = snapshot.getValue(Product.class);
product.setId(snapshot.getKey());
products.add(product);
}
FirebaseProductsRepository.this.products = products;
notifyDataChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, databaseError.getMessage());
}
};
FirebaseUtils.getProductsRef().addValueEventListener(productEventListener);
}
}
@Override
public void removeListener(DataChangeListener dataDataChangeListener) {
super.removeListener(dataDataChangeListener);
if (getListenersCount() <= 0) {
FirebaseUtils.getProductsRef().removeEventListener(productEventListener);
}
}
@Override
public void removeProduct(@NonNull Product product) {
if (product.getId() != null) {
FirebaseUtils.getProductsRef().child(product.getId()).removeValue((databaseError, databaseReference) -> {
if (databaseError != null) {
Log.e(TAG, "Error remove product: " + databaseError.getMessage());
}
});
}
}
@Override
public void addProduct(@NonNull Product product) {
FirebaseUtils.getProductsRef().push().setValue(product, (databaseError, databaseReference) -> {
if (databaseError != null) {
Log.e(TAG, "Error add product: " + databaseError.getMessage());
}
});
}
@Override
public void updateProduct(@NonNull Product product) {
Map<String, Object> updatedUserData = new HashMap<>();
updatedUserData.put(
FirebaseUtils.getProductsPath() + product.getId(),
new ObjectMapper().convertValue(product, Map.class)
);
FirebaseUtils.getBaseRef().updateChildren(updatedUserData, (databaseError, databaseReference) -> {
if (databaseError != null) {
Log.e(TAG, "Error add product: " + databaseError.getMessage());
}
});
}
@NonNull
@Override
public List<Product> getProducts() {
return products;
}
@Nullable
@Override
public Product getProduct(@NonNull String productId) {
for (Product product : products) {
if (productId.equals(product.getId())) {
return product;
}
}
return null;
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/custom/ProductParamView.java
package com.mixailsednev.storeproject.view.custom;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.mixailsednev.storeproject.R;
public class ProductParamView extends LinearLayout {
private TextView paramValueTextView;
public ProductParamView(Context context) {
super(context);
}
public ProductParamView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public ProductParamView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ProductParamView);
Drawable icon = a.getDrawable(R.styleable.ProductParamView_product_icon);
String param = a.getString(R.styleable.ProductParamView_product_param);
a.recycle();
View view = LayoutInflater.from(context).inflate(R.layout.item_product_details, this, true);
ImageView iconImageView = ((ImageView) view.findViewById(R.id.icon));
TextView paramTextView = ((TextView) view.findViewById(R.id.param));
paramValueTextView = ((TextView) view.findViewById(R.id.param_value));
iconImageView.setImageDrawable(icon);
paramTextView.setText(param);
}
public void setParamValue(@Nullable String paramValue) {
paramValueTextView.setText(paramValue);
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/company/news/NewsFragment.java
package com.mixailsednev.storeproject.view.company.news;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mixailsednev.storeproject.R;
import butterknife.ButterKnife;
public class NewsFragment extends Fragment {
public static final String ARG_COMPANY_ID = "company_id";
public static NewsFragment newInstance(@NonNull String companyId) {
NewsFragment fragment = new NewsFragment();
Bundle arguments = new Bundle();
arguments.putString(NewsFragment.ARG_COMPANY_ID, companyId);
fragment.setArguments(arguments);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_company_news, container, false);
ButterKnife.bind(this, rootView);
return rootView;
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/view/company/news/NewsView.java
package com.mixailsednev.storeproject.view.company.news;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.mixailsednev.storeproject.R;
import butterknife.BindView;
import butterknife.ButterKnife;
public class NewsView extends FrameLayout {
@BindView(R.id.news_author_image)
protected ImageView authorImage;
@BindView(R.id.news_author_name)
protected TextView authorName;
@BindView(R.id.news_date)
protected TextView date;
@BindView(R.id.news_message)
protected TextView message;
@BindView(R.id.like_news)
protected ImageButton like;
@BindView(R.id.view_news_comments)
protected ImageButton newsComments;
public NewsView(Context context) {
super(context);
init();
}
public NewsView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public NewsView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
View view = LayoutInflater.from(getContext()).inflate(R.layout.view_news, this, true);
ButterKnife.bind(this, view);
}
}
<file_sep>/app/src/main/java/com/mixailsednev/storeproject/model/firebase/FirebaseUtils.java
package com.mixailsednev.storeproject.model.firebase;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class FirebaseUtils {
public static DatabaseReference getBaseRef() {
return FirebaseDatabase.getInstance().getReference();
}
@Nullable
public static String getCurrentUserId() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
return user.getUid();
}
return null;
}
@Nullable
public static DatabaseReference getCurrentUserRef() {
String uid = getCurrentUserId();
if (uid != null) {
return getBaseRef().child("users").child(getCurrentUserId());
}
return null;
}
public static DatabaseReference getProductsRef() {
return getBaseRef().child("products");
}
public static String getProductsPath() {
return "products/";
}
public static DatabaseReference getChatsRef() {
return getBaseRef().child("chats");
}
public static DatabaseReference getChatRef(@NonNull String chatId) {
return getChatsRef().child(chatId);
}
}
| f9008394c31e4359aa296e249bb9170f50e565f8 | [
"Java",
"Gradle"
] | 26 | Java | Belobobr/store | 58957783f6979a28979cd771b31b3ec9dc40f0a5 | 8c4546d5b412114d139d24159db079f4b164630c |
refs/heads/master | <repo_name>muasdev/BelajarPost<file_sep>/app/src/main/java/com/example/windows/aplikasipengaduan/ui/activity/DetailActivity.java
package com.example.windows.aplikasipengaduan.ui.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.windows.aplikasipengaduan.R;
public class DetailActivity extends AppCompatActivity {
private ImageView iv_detail_gambar;
private TextView tv_detail_nama, tv_detail_pengaduan;
String gmb, nama, uraian_pengaduan;
String gmbPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
iv_detail_gambar = (ImageView) findViewById(R.id.iv_detail_gambar);
tv_detail_nama = (TextView) findViewById(R.id.tv_detail_nama);
tv_detail_pengaduan = (TextView) findViewById(R.id.tv_detail_pengaduan);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
/*memanggil metode getIntentData()*/
getIntentData();
}
private void getIntentData() {
gmb = getIntent().getStringExtra("gmb");
nama = getIntent().getStringExtra("nm_lengkap");
uraian_pengaduan = getIntent().getStringExtra("uraian_pengaduan");
gmbPath = "http://pengaduan.xakti.tech/images/pelapor/" + gmb;
Glide.with(this)
.load(gmbPath)
.into(iv_detail_gambar);
tv_detail_nama.setText(nama);
tv_detail_pengaduan.setText(uraian_pengaduan);
}
}
| e556b266f2459dca08ca07c22146d17f1a725984 | [
"Java"
] | 1 | Java | muasdev/BelajarPost | 0b4409a3adf1311887cbb2670d2f78114ccc004f | 9d641f2eac3c9684f794b08fb9a4ef024f06cdff |
refs/heads/master | <repo_name>Dhiraj404/C-Project<file_sep>/project.c
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
void primenumber(){
int i=1,j,s=0;
while(i<=1000){
for(j=2;j<=i/2;j++)
if(i%j==0)
break;
if(j>i/2){
printf("%d\n",i);
s++;}
i++;
}
printf("total=%d",s);
}
void array(){
int a;
int array [21] = {0};
array [0] = 0;
array [1] = 1;
array [2] = 1;
for (a=3;a<=20;a++)
array [a] = array [a-1] + array [a-2];
for (a= 1; a<= 20; a++)
printf("%d,",array[a]);
}
void PI(){
int f;
float pi=1,e=1;
f=1;
while(f<=50){
e=((2.0*f)/(2.0*f-1))*((2.0*f)/(2.0*f+1));
pi=pi*e;
f++;
}
pi=pi*2;
printf("%4.2f",pi);
}
void sum(){
int a,b,c,d,i;
printf("input the number do you want:");
scanf("%d",&a);
printf("input how many times will it repeated (the range is between 1 and 9):");
scanf("%d",&b);
if((b>=1)&&(b<=9)){
i=1;
c=0;
d=a;
while(i<b){
c=c+d;
d=d*10+a;
i++;}
d=d+c;
printf("sum= %d",d);
}
else
printf("the number is not between 1 and 9!");
}
int main(){
int n,r;
do{
printf("\n*********************************\n1.Prime number\n2.fibonacci array\n3.pi\n4.sum\n0.exit\n*********************************\nplease input the number here:");
scanf("%d",&n);
if(n==1){
primenumber();
}
if(n==2){
array();
}
if(n==3){
PI();
}
if(n==4){
sum();
}
if(n==0)
exit (0);
printf("\npress any number to continue or press 0 to exit ");
scanf("%d",&r);
}
while(r!=0);
return 0;}
| 4a9d229ac2fbbed67d764528b4df49433182660c | [
"C"
] | 1 | C | Dhiraj404/C-Project | ba53999235538c6ef2ada10b8f32a0c037b382df | 421419da6afcec533c8476def4b832e6631771bb |
refs/heads/master | <file_sep>package com.codepath.instagramclone;
import android.content.Intent;
//import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
public class SignupActivity extends AppCompatActivity {
public static final String TAG = "SingupActivity";
private EditText name;
private EditText SignOne;
private EditText SignTwo;
private Button btnSign;
ParseUser user = new ParseUser();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
name = findViewById(R.id.name);
SignOne = findViewById(R.id.SignOne);
SignTwo = findViewById(R.id.SignTwo);
btnSign = findViewById(R.id.btnSign);
btnSign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = name.getText().toString();
String sign1 = SignOne.getText().toString();
String sign2 = SignTwo.getText().toString();
if(sign1 == sign2){
Toast.makeText(SignupActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
submit(username,sign1);
}
});
}
private void submit(String username, String sign1) {
user.setUsername(username);
user.setPassword(<PASSWORD>);
user.signUpInBackground(new SignUpCallback() {
@Override
public void done(ParseException e) {
if (e == null){
goMainActivity();
}
else {
Log.e(TAG,"Singing up Issue", e);
return;
}
}
});
}
private void goMainActivity() {
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
} | 156fc7a023ec4b4782fd67d9196673176633fc54 | [
"Java"
] | 1 | Java | tanzil7/InstagramClone | a9314e582c6681d4d1a52a91c0fe381d77dcbafb | d16335ae461cd2b1ab024790d89209db31e958de |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication11.Models;
using System.Data;
using System.IO;
using OfficeOpenXml;
namespace WebApplication11.Controllers
{
public class HomeController : Controller
{
db dbop = new db();
public IActionResult Index()
{
DataSet ds = dbop.Getrecord();
ViewBag.details = ds.Tables[0];
return View();
}
public IActionResult ExporttoExcel()
{
DataSet ds = dbop.Getrecord();
var stream = new MemoryStream();
using (var package = new ExcelPackage(stream))
{
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells.LoadFromDataTable(ds.Tables[0], true);
package.Save();
}
stream.Position = 0;
string excelname = $"Department.xlsx";
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelname);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MVC.Models;
namespace MVC.Controllers
{
public class EmployeeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Getdetails()
{
Employee emp = new Employee();
emp.EmployeeId = 1;
emp.Name = "Ankit";
return View(emp);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication10.Models;
using System.IO;
using OfficeOpenXml;
namespace WebApplication10.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public async Task<List<Department>> Import(Microsoft.AspNetCore.Http.IFormFile file)
{
var list = new List<Department>();
using (var stream = new MemoryStream())
{
await file.CopyToAsync(stream);
using (var package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
var rowcount = worksheet.Dimension.Rows;
for (int row = 2; row <= rowcount; row++)
{
list.Add(new Department
{
DepartmentId = worksheet.Cells[row, 1].Value.ToString().Trim(),
DepartmentName = worksheet.Cells[row, 2].Value.ToString().Trim(),
});
}
}
return list;
}
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MVCCrud.Models
{
public class EmployeeContext:DbContext
{
public EmployeeContext(DbContextOptions<EmployeeContext> options):base (options)
{
}
public DbSet<Employee> Employees { get; set; }
}
}
// Tools ->NuGetPackageManager->PackageManagerConsole
//Add-Migration "InitialCreate"
//Update-Database<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace MVCCrud.Models
{
public class Employee
{
[Key]
public int Empid { get; set; }
[Column(TypeName ="nvarchar(250)")]
[Required]
public String FullName { get; set; }
}
}
<file_sep>using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication11.Models
{
public class db
{
SqlConnection con;
public db()
{
var config = GetConfig();
con = new SqlConnection(config.GetSection("Data").GetSection("ConnectionString").Value);
}
private IConfigurationRoot GetConfig()
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
return builder.Build();
}
public DataSet Getrecord()
{
SqlCommand com = new SqlCommand("Sp_Department", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication8
{
public partial class WebForm1 : System.Web.UI.Page
{
WebService1 obj = new WebService1();
int a, b, c;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
a = Convert.ToInt32(txtFno.Text);
b = Convert.ToInt32(txtSno.Text);
c = obj.Add(a, b);
lblResult.Text = c.ToString();
}
protected void btnSub_Click(object sender, EventArgs e)
{
a = Convert.ToInt32(txtFno.Text);
b = Convert.ToInt32(txtSno.Text);
c = obj.Sub(a, b);
lblResult.Text = c.ToString();
}
}
} | dd9a877531d9bfdaf8820588170e5f0c2d81c7bc | [
"C#"
] | 7 | C# | MariMGK/05-05-21 | 5fe0c3e9c7d7b260b2779b4fdd90ef1e780408dd | ec06313ab3ad22e5b592986f8929b6abe197e6d5 |
refs/heads/master | <file_sep>TARGET: slicz slijent
CC = cc
CFLAGS = -O2
LFLAGS =
slijent: slijent.o err.o
$(CC) $(LFLAGS) $^ -o $@
slicz: slicz.o err.o
$(CC) $(LFLAGS) $^ -o $@
.PHONY: clean TARGET
clean:
rm -f slicz slijent *.o *~ *.bak
<file_sep>/**
* <NAME>
* 321 150
* zadanie nr 3 z sieci komputerowych
* slijent.c
*/
#include <stdio.h>
#include <errno.h>
#include "err.h"
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/epoll.h>
#include <linux/if.h>
#include <linux/if_tun.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#define MTU 1522
#define LIMIT_ZDARZEN 136
//globals section
int file_descriptor, error_int, gniazdo, epoll_file_descriptor, epol_ctl_result,
command;
struct addrinfo addr_hints_addrinfo_structure;
struct addrinfo *addr_result_addrinfo_structure;
struct sockaddr_in switch_address_sockaddr_in_structure;
struct sockaddr_in from_address_sockaddr_in_structure;
struct ifreq ifreq_struct_instance;
struct epoll_event *zdarzenia;
struct epoll_event zdarzenie_switcha;
struct epoll_event zdarzenie_interfacu;
char *numer_portu;
char *adres_hosta;
const char *nazwa_interfacu = "siktap";
/**
* Petla switcha
*/
void never_ending_story();
/**
* Ustawianie wartosci
*/
void init_configuration();
/**
* Odczytywanie parametrow wywolania programu, zapewnienie odpowiedniej ilosci argumentow
*/
void parse_arguments(int argc, char* argv[]);
int main(int argc, char* argv[]) {
parse_arguments(argc, argv);
init_configuration();
never_ending_story();
//cleaning, closing
free(zdarzenia);
if (close(gniazdo) == -1) {
syserr("error while closing socket!");
}
return 0;
}
void never_ending_story() {
while (1) {
int n, i;
ssize_t write_bytes, read_bytes;
socklen_t length;
char buffor[MTU];
n = epoll_wait(epoll_file_descriptor, zdarzenia, LIMIT_ZDARZEN, -1);
for (i = 0; i < n; i++) {
if (file_descriptor == zdarzenia[i].data.fd) {
if ((read_bytes = read(zdarzenia[i].data.fd, buffor,
sizeof(buffor))) < 0) {
fprintf(stderr, "error in read() function call!\n");
exit(1);
}
buffor[read_bytes + 1] = '\0';
printf("Ramka z interfacu (%d bajtow): <%s>\n",
(int) read_bytes, buffor);
length =
(socklen_t) sizeof(switch_address_sockaddr_in_structure);
if ((write_bytes =
sendto(gniazdo, buffor, read_bytes, 0,
(struct sockaddr *) &switch_address_sockaddr_in_structure,
length)) != (ssize_t) read_bytes)
syserr("error while sending datagram to client");
} else if (gniazdo == zdarzenia[i].data.fd) {
length = (socklen_t) sizeof(from_address_sockaddr_in_structure);
read_bytes = recvfrom(gniazdo, buffor,
(size_t)(sizeof(buffor) - 1), 0,
(struct sockaddr *) &from_address_sockaddr_in_structure,
&length);
buffor[read_bytes + 1] = '\0';
printf("Ramka od switcha (%d bajtow): <%s>\n", (int) read_bytes,
buffor);
if (length < 0) {
fprintf(stderr, "error in recvfrom() function call!\n");
close(zdarzenia[i].data.fd);
exit(1);
}
if ((write_bytes = write(file_descriptor, buffor, read_bytes))
< 0) {
fprintf(stderr, "error in write() function call!\n");
exit(1);
}
} else if ((zdarzenia[i].events & EPOLLERR)
|| (!(zdarzenia[i].events & EPOLLIN))
|| (zdarzenia[i].events & EPOLLHUP)) {
fprintf(stderr, "error in epoll!\n");
close(zdarzenia[i].data.fd);
} else {
exit(1);
}
}
}
}
void parse_arguments(int argc, char* argv[]) {
while ((command = getopt(argc, argv, ":d:")) != -1) {
if (command == 'd') {
nazwa_interfacu = optarg;
} else if (command == '?') {
fprintf(stderr, "Nieznana komenda '-%c'.\n", optopt);
exit(1);
} else if (command == ':') {
fprintf(stderr, "Nastepujaca opcja: '-%c' wymaga argumentu.\n",
optopt);
exit(1);
}
}
if (optind != argc - 1) {
fprintf(stderr,
"Nieprawidlowa ilosc argumentow, podaj <host>:<port>, bo jest to wymagane\n");
fprintf(stderr, "opcjonalnie -d <nazwa interfacu>\n");
exit(1);
}
adres_hosta = strsep(&argv[optind], ":");
numer_portu = strsep(&argv[optind], ":");
if ((numer_portu == NULL ) || (adres_hosta == NULL )) {
fprintf(stderr,
"Nieprawidlowa ilosc argumentow, podaj <host>:<port>, bo jest to wymagane\n");
fprintf(stderr, "opcjonalnie -d <nazwa interfacu>\n");
exit(1);
}
printf("adres hosta: %s\n", adres_hosta);
printf("numer port: %s\n", numer_portu);
}
void init_configuration() {
if ((file_descriptor = open("/dev/net/tun", O_RDWR)) < 0) {
perror("error while opening(/dev/net/tun)");
exit(1);
}
memset(&ifreq_struct_instance, 0, sizeof(ifreq_struct_instance));
(void) memset(&addr_hints_addrinfo_structure, 0, sizeof(struct addrinfo));
addr_hints_addrinfo_structure.ai_socktype = SOCK_DGRAM;
addr_hints_addrinfo_structure.ai_protocol = IPPROTO_UDP;
addr_hints_addrinfo_structure.ai_family = AF_INET;
strncpy(ifreq_struct_instance.ifr_name, nazwa_interfacu, IFNAMSIZ);
ifreq_struct_instance.ifr_flags = IFF_TAP | IFF_NO_PI;
error_int = ioctl(file_descriptor, TUNSETIFF,
(void *) &ifreq_struct_instance);
if (error_int < 0) {
perror("error during call ioctl(TUNSETIFF)");
exit(1);
}
if (getaddrinfo(adres_hosta, NULL, &addr_hints_addrinfo_structure,
&addr_result_addrinfo_structure) != 0) {
syserr("error in getaddrinfo() method call!");
}
switch_address_sockaddr_in_structure.sin_port = htons(
(uint16_t) atoi(numer_portu));
switch_address_sockaddr_in_structure.sin_addr.s_addr =
((struct sockaddr_in*) (addr_result_addrinfo_structure->ai_addr))->sin_addr.s_addr;
switch_address_sockaddr_in_structure.sin_family = AF_INET;
if ((gniazdo = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
syserr("error in socket() function call!");
}
if ((epoll_file_descriptor = epoll_create1(0)) < 0) {
syserr("error in epoll_create() function call");
}
zdarzenie_switcha.events = EPOLLIN;
zdarzenie_interfacu.events = EPOLLIN;
zdarzenie_interfacu.data.fd = file_descriptor;
zdarzenie_switcha.data.fd = gniazdo;
if ((epol_ctl_result = epoll_ctl(epoll_file_descriptor, EPOLL_CTL_ADD,
gniazdo, &zdarzenie_switcha)) < 0) {
syserr("error in epoll_ctl() function call! - switch event");
}
if ((epol_ctl_result = epoll_ctl(epoll_file_descriptor, EPOLL_CTL_ADD,
file_descriptor, &zdarzenie_interfacu)) < 0) {
syserr("error in epoll_ctl() function call! - interface event");
}
zdarzenia = calloc(LIMIT_ZDARZEN, sizeof(zdarzenie_switcha));
}
<file_sep>/**
* <NAME>
* 321 150
* slicz
* Sieci komputerowe, zadanie 3
*/
#include <sys/epoll.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <fcntl.h>
#include <stdlib.h>
#include "err.h"
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
//define section
#define RECEIVED_COUNTER 0
#define LIMIT_ILOSCI_ZDARZEN 136
#define LIMIT_AKTYWNYCH_PORTOW 100
#define ROZMIAR_BUFFORA_TCP 1600
#define LIMIT_SIECI_VLAN 4095
#define LIMIT_ILOSCI_POLACZEN 20
#define ERROR_COUNTER 2
#define ROZMIAR_BUFFORA 64000
#define LIMIT_ADRESOW_MAC 4096
#define SENT_COUNTER 1
//globals
int ilosc_aktywnych_portow = 0;
char tcp_buffor_size_table[LIMIT_ILOSCI_POLACZEN + 1][ROZMIAR_BUFFORA_TCP];
int counters_table[LIMIT_AKTYWNYCH_PORTOW][3];
int length_of_sum_received[LIMIT_ILOSCI_POLACZEN + 1];
int tablica_gniazd_tcp[LIMIT_ILOSCI_POLACZEN + 1];
int tablica_gniazd_udp[LIMIT_AKTYWNYCH_PORTOW];
char *tablica_konfiguracji[LIMIT_AKTYWNYCH_PORTOW][LIMIT_SIECI_VLAN + 8];
int ilosc_polaczen_tcp = 0;
char tablica_mac[LIMIT_ADRESOW_MAC][3][20];
int ilosc_adreos_w_tablicy_mac = 0;
char temporary_vlan[11];
int priorytety[LIMIT_ILOSCI_ZDARZEN + 1];
unsigned long tablica_adresow_ip_udp[LIMIT_AKTYWNYCH_PORTOW];
short tablica_vlanow[LIMIT_AKTYWNYCH_PORTOW][LIMIT_SIECI_VLAN + 5];
unsigned short tablica_portow_udp[LIMIT_AKTYWNYCH_PORTOW];
const char *TCP_port = "42420";
int gniazdo_tcp, wynik_odblokowania;
int epoll_file_descriptor, nbuffor, nsock;
char buf[ROZMIAR_BUFFORA_TCP];
struct epoll_event event;
struct epoll_event *events;
//function declaration
int sprawdz_tagowanie_vlanow(int index);
int stworz_port_udp(int index, int e_file_descriptor, int nbuffer);
int otworz_gniazda(int epoll_file_descriptor);
int daj_minimalny_numer_portu(int index);
void inicjalizacja();
void wyslij_ramke(char *buf, int rb, int m_i, int nsock, int ind, int t);
int czytaj_z_gniazda_tcp(int numer_buffora);
int sprawdz_address_mac(char *src, char *tmpv);
int parsuj_ramke(char *buffor, int firstly_added, int index, int *tagged);
int odblokuj_socket(int s_file_descriptor);
int zdarzenie_na_tcp(int sfd);
void gra_wstepna();
int zdarzenie_na_udp(int sfd);
int ustaw_gniazdo_tcp(const char *port);
void delete_port_udp(int index);
int skoryguj_andress_port(struct sockaddr_in *from_addr, int index);
void wyslij_datagram(char *prievous_buffor, int read_bytes, int nvlan,
int nsock, int index, int tagowanie);
int parsuj_argumenty_programu(char *c);
int daj_numer_portu(char *port);
void never_ending_story();
void odczytaj_argumenty(int argc, char *argv[]);
//--------------
int main(int argc, char *argv[]) {
inicjalizacja();
odczytaj_argumenty(argc, argv);
gra_wstepna(); // ;)
never_ending_story();
free(events);
close(gniazdo_tcp);
return 0;
}
//---------------
void gra_wstepna() {
if ((gniazdo_tcp = ustaw_gniazdo_tcp(TCP_port)) == -1) {
syserr("error in setting up tcp socket! Please, don't panic!");
}
if ((wynik_odblokowania = odblokuj_socket(gniazdo_tcp)) == -1) {
syserr("error: odblokowanie socketu tcp");
}
if ((wynik_odblokowania = listen(gniazdo_tcp, SOMAXCONN)) == -1) {
syserr("error while listen() tcp call! Don't panic!");
}
epoll_file_descriptor = epoll_create1(0);
if (epoll_file_descriptor == -1) {
syserr("epoll_create1");
}
event.events = EPOLLIN;
event.data.fd = gniazdo_tcp;
if ((wynik_odblokowania = epoll_ctl(epoll_file_descriptor, EPOLL_CTL_ADD,
gniazdo_tcp, &event)) == -1) {
syserr("epoll_ctl");
}
events = calloc(LIMIT_ILOSCI_ZDARZEN, sizeof event);
if (otworz_gniazda(epoll_file_descriptor)) {
fprintf(stderr, "udp socket creating error\n");
exit(1);
}
}
void never_ending_story() {
while (1) {
int n, i;
n = epoll_wait(epoll_file_descriptor, events, LIMIT_ILOSCI_ZDARZEN, -1);
for (i = 0; i < n; i++) {
if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP)
|| (!(events[i].events & EPOLLIN))) {
fprintf(stderr, "epoll error\n");
close(events[i].data.fd);
continue;
} else if (gniazdo_tcp == events[i].data.fd) {
while (1) {
struct sockaddr in_address_scokaddr_instance;
socklen_t in_length_socklen_t_instance;
int in_file_descriptor;
char host_buffer[NI_MAXHOST], server_buffer[NI_MAXSERV];
in_length_socklen_t_instance =
sizeof in_address_scokaddr_instance;
if ((in_file_descriptor = accept(gniazdo_tcp,
&in_address_scokaddr_instance,
&in_length_socklen_t_instance)) == -1) {
if (!(errno == EAGAIN) && !(errno == EWOULDBLOCK)) {
perror("error in accept accept");
break;
} else {
break;
}
}
wynik_odblokowania = getnameinfo(
&in_address_scokaddr_instance,
in_length_socklen_t_instance, host_buffer,
sizeof host_buffer, server_buffer,
sizeof server_buffer,
NI_NUMERICHOST | NI_NUMERICSERV);
if ((wynik_odblokowania = odblokuj_socket(
in_file_descriptor)) == -1) {
perror(
"error in epoll_ctl during dobblokuj_socket() function call!");
abort();
}
event.events = EPOLLIN;
event.data.fd = in_file_descriptor;
if ((wynik_odblokowania = epoll_ctl(epoll_file_descriptor,
EPOLL_CTL_ADD, in_file_descriptor, &event)) == -1) {
perror("error in epoll_ctl() function call!");
abort();
}
int j = 1;
while (j <= LIMIT_ILOSCI_POLACZEN) {
if (tablica_gniazd_tcp[j] == 0) {
tablica_gniazd_tcp[j] = in_file_descriptor;
break;
}
j++;
}
if (write(in_file_descriptor, "SLICZ\n", 6) < 0) {
fprintf(stderr,
"Error in writing handshake to client tcp socket: SLICZ\n");
}
}
} else if ((nbuffor = zdarzenie_na_tcp(events[i].data.fd))) {
int done = 0;
int res = czytaj_z_gniazda_tcp(nbuffor);
if (res == -2 || res == -1) {
done = 1;
if (write(tablica_gniazd_tcp[nbuffor], "reading error\n", 9)
< 0 && res == -1) {
fprintf(stderr, "writing error\n");
}
} else if (res == 1) {
int minimalny_port = LIMIT_AKTYWNYCH_PORTOW + 1;
int length2;
char send[ROZMIAR_BUFFORA_TCP];
char *current_buffor_size = tcp_buffor_size_table[nbuffor];
if (strstr(current_buffor_size, "getconfig\n")
== current_buffor_size) {
if (write(tablica_gniazd_tcp[nbuffor], "OK\n", 3) < 0) {
fprintf(stderr,
"write to socket client error: OK\n");
}
while ((minimalny_port = daj_minimalny_numer_portu(
minimalny_port)) != -1) {
if (tablica_portow_udp[minimalny_port] != 0) {
struct sockaddr_in tp;
tp.sin_addr.s_addr =
tablica_adresow_ip_udp[minimalny_port];
length2 = sprintf(send, "%s/%s:%d/",
tablica_konfiguracji[minimalny_port][0],
inet_ntoa(tp.sin_addr),
tablica_portow_udp[minimalny_port]);
} else {
length2 =
sprintf(send, "%s//",
tablica_konfiguracji[minimalny_port][0]);
}
int ind = 3;
while (tablica_konfiguracji[minimalny_port][ind]
!= NULL ) {
if (ind != 3) {
length2 += sprintf(length2 + send, ",");
}
length2 +=
sprintf(send + length2, "%s",
tablica_konfiguracji[minimalny_port][ind]);
if (tablica_vlanow[minimalny_port][atoi(
tablica_konfiguracji[minimalny_port][ind])]
== 2) {
length2 += sprintf(send + length2, "t");
}
ind++;
}
length2 += sprintf(send + length2, "\n");
if (write(tablica_gniazd_tcp[nbuffor], send,
length2) < 0) {
fprintf(stderr,
"write to socket client error\n");
}
}
if (write(tablica_gniazd_tcp[nbuffor], "END\n", 4)
< 0) {
fprintf(stderr,
"write to socket client error: END\n");
}
} else if (strstr(current_buffor_size, "counters\n")
== current_buffor_size) {
if (write(tablica_gniazd_tcp[nbuffor], "OK\n", 3) < 0) {
fprintf(stderr,
"write to client socket error: OK\n");
}
while ((minimalny_port = daj_minimalny_numer_portu(
minimalny_port)) != -1) {
length2 = sprintf(send,
"%s recvd:%d sent:%d errs:%d\n",
tablica_konfiguracji[minimalny_port][0],
counters_table[minimalny_port][0],
counters_table[minimalny_port][1],
counters_table[minimalny_port][2]);
if (write(tablica_gniazd_tcp[nbuffor], send,
length2) < 0) {
fprintf(stderr,
"write to socket client error\n");
}
}
if (write(tablica_gniazd_tcp[nbuffor], "END\n", 4)
< 0) {
fprintf(stderr,
"write to socket client error: END\n");
}
} else if (strstr(current_buffor_size, "setconfig ")
== current_buffor_size) {
char *port_number, *vlan;
struct sockaddr_in temporary_sockaddr_in_instance;
char *ipc = "", *portc = "";
int error = 0, index = 0;
current_buffor_size[strlen(current_buffor_size) - 1] =
'\0';
strsep(¤t_buffor_size, " ");
char *a = malloc(
(strlen(current_buffor_size) + 1)
* sizeof(char));
char *tofree = a;
strcpy(a, current_buffor_size);
if ((port_number = strsep(&a, "/")) == NULL || (portc =
strsep(&a, "/")) == NULL
|| (ipc = strsep(&portc, ":")) == NULL
|| (portc == NULL && strlen(ipc) > 0)) {
error = -1;
}
if (error == -1) {
if (write(tablica_gniazd_tcp[nbuffor],
"ERR invalid command\n", 20) < 0) {
fprintf(stderr,
"write to client socket error\n");
}
free(tofree);
continue;
}
index = daj_numer_portu(port_number);
for (i = 3; (vlan = strsep(&a, ",")) != NULL ; i++) {
if (strcmp(vlan, "") == 0) {
i++;
break;
}
tablica_konfiguracji[(
(i == 3 && index == -1) ?
ilosc_aktywnych_portow : index)][i] =
vlan;
}
int check = 0;
if (i != 3) {
if (tablica_konfiguracji[index][0] != NULL) {
free(tablica_konfiguracji[index][0]);
}
tablica_konfiguracji[index][0] = port_number;
tablica_konfiguracji[index][1] = ipc;
tablica_konfiguracji[index][2] = portc;
tablica_konfiguracji[index][i] = NULL;
if (tablica_konfiguracji[index][2] == NULL) {
tablica_adresow_ip_udp[index] = 0;
tablica_portow_udp[index] = 0;
} else {
inet_aton(tablica_konfiguracji[index][1],
&temporary_sockaddr_in_instance.sin_addr);
tablica_adresow_ip_udp[index] =
temporary_sockaddr_in_instance.sin_addr.s_addr;
tablica_portow_udp[index] =
htons(
(unsigned short) atoi(
tablica_konfiguracji[index][2]));
}
if (index == ilosc_aktywnych_portow) {
ilosc_aktywnych_portow++;
if (stworz_port_udp(index,
epoll_file_descriptor, nbuffor)) {
check = 1;
}
} else if (sprawdz_tagowanie_vlanow(index) == -1) {
delete_port_udp(index);
if (write(tablica_gniazd_tcp[nbuffor],
"ERR error while opening udp port\n",
33) < 0 && nbuffor != -1) {
fprintf(stderr, "err udp port open\n");
}
check = 1;
}
}
if (check) {
length_of_sum_received[nbuffor] = 0;
continue;
}
if (i == 3) {
if (index == -1) {
if (write(tablica_gniazd_tcp[nbuffor],
"ERR invalid command\n", 20) < 0)
fprintf(stderr,
"write to client socket error\n");
free(tofree);
} else if (index != -1) {
free(tofree);
delete_port_udp(index);
}
}
if ((i != 3 || index != -1)) {
fprintf(stderr, "write to client socket error\n");
}
if (write(tablica_gniazd_tcp[nbuffor], "OK\n", 3) < 0) {
fprintf(stderr,
"write to client socket error: OK\n");
}
} else if (write(tablica_gniazd_tcp[nbuffor],
"ERR invalid command\n", 20) < 0)
fprintf(stderr, "writing to client socket error\n");
length_of_sum_received[nbuffor] = 0;
}
if (done) {
tablica_gniazd_tcp[nbuffor] = 0;
length_of_sum_received[nbuffor] = 0;
close(events[i].data.fd);
}
} else if ((nsock = zdarzenie_na_udp(events[i].data.fd)) != -1) {
socklen_t length_socklen_t_instance;
int fres, j, index = -1;
int mac_index;
int t = 0;
ssize_t read_bytes;
struct sockaddr_in from_address_sockaddr_in_instance;
length_socklen_t_instance =
(socklen_t) sizeof(from_address_sockaddr_in_instance);
if ((read_bytes = recvfrom(events[i].data.fd, buf,
(size_t)(sizeof(buf) - 1), 0,
(struct sockaddr *) &from_address_sockaddr_in_instance,
&length_socklen_t_instance)) < 0
|| length_socklen_t_instance < 0) {
delete_port_udp(nsock);
fprintf(stderr, "recvfrom() function call error\n");
continue;
}
if ((fres = skoryguj_andress_port(
&from_address_sockaddr_in_instance, nsock)) < 0) {
fprintf(stderr, "packet from wrong address\n");
continue;
}
if ((mac_index = parsuj_ramke(buf, fres, nsock, &t)) < 0) {
fprintf(stderr, "some error with packet parsing\n");
continue;
}
counters_table[nsock][RECEIVED_COUNTER]++;
for (j = 0; j < ilosc_aktywnych_portow; j++)
if (strcmp(tablica_mac[mac_index][2],
tablica_konfiguracji[j][0]) == 0) {
index = j;
break;
}
if (nsock != index) {
wyslij_ramke(buf, read_bytes, mac_index, nsock, index, t);
} else {
fprintf(stderr, "nsock == index\n");
}
} else {
exit(1);
}
}
}
}
int daj_numer_portu(char *port) {
int i;
for (i = 0; i < ilosc_aktywnych_portow; i++) {
if ((strcmp(port, tablica_konfiguracji[i][0]) == 0)
|| (port == NULL && tablica_konfiguracji[i][0] == NULL )) {
return i;
}
}
return -1;
}
void inicjalizacja() {
int i, j;
for (i = 0; i <= LIMIT_ILOSCI_POLACZEN; i++) {
for (j = 0; j < ROZMIAR_BUFFORA_TCP; j++) {
tcp_buffor_size_table[i][j] = '\0';
}
tablica_gniazd_tcp[i] = 0;
length_of_sum_received[i] = 0;
}
for (i = 0; i < LIMIT_ADRESOW_MAC; i++) {
tablica_mac[i][0][0] = '\0';
tablica_mac[i][1][0] = '\0';
tablica_mac[i][2][0] = '\0';
}
for (i = 0; i < LIMIT_AKTYWNYCH_PORTOW; i++) {
for (j = 0; j < 3; j++) {
counters_table[i][j] = 0;
}
tablica_gniazd_udp[i] = 0;
tablica_portow_udp[i] = 0;
tablica_adresow_ip_udp[i] = 0;
for (j = 0; j - 2 <= LIMIT_SIECI_VLAN; j++) {
tablica_vlanow[i][j] = 0;
tablica_konfiguracji[i][j] = NULL;
}
}
}
int czytaj_z_gniazda_tcp(int numer_buffora) {
ssize_t length_ssize_t_instance = 0;
while (1) {
length_ssize_t_instance = read(tablica_gniazd_tcp[numer_buffora],
(tcp_buffor_size_table[numer_buffora]
+ length_of_sum_received[numer_buffora]), 1);
length_of_sum_received[numer_buffora] += length_ssize_t_instance;
if (length_ssize_t_instance == 0) {
return -2;
}
if (length_ssize_t_instance == -1) {
if (errno != EAGAIN) {
fprintf(stderr, "error while reading from tcp socket\n");
return -1;
}
if (tcp_buffor_size_table[numer_buffora][length_of_sum_received[numer_buffora]
- 1] == '\n') {
tcp_buffor_size_table[numer_buffora][length_of_sum_received[numer_buffora]] =
'\0';
return 1;
}
return 0;
}
if (tcp_buffor_size_table[numer_buffora][length_of_sum_received[numer_buffora]
- 1] == '\n' && length_ssize_t_instance == 1) {
tcp_buffor_size_table[numer_buffora][length_of_sum_received[numer_buffora]] =
'\0';
return 1;
}
if (length_of_sum_received[numer_buffora] == ROZMIAR_BUFFORA_TCP) {
return -1;
}
}
}
int daj_minimalny_numer_portu(int index) {
int i, maksymalna_dlugosc, minimalna_dlugosc, dlugosc_konfiguracji, result =
-1;
const char* maksimum = "123456789";
const char* minimum = "0";
if (index != LIMIT_AKTYWNYCH_PORTOW + 1) {
minimum = tablica_konfiguracji[index][0];
}
for (i = 0; i < ilosc_aktywnych_portow; i++) {
maksymalna_dlugosc = strlen(maksimum);
minimalna_dlugosc = strlen(minimum);
dlugosc_konfiguracji = strlen(tablica_konfiguracji[i][0]);
if (((dlugosc_konfiguracji == maksymalna_dlugosc)
&& (strcmp(maksimum, tablica_konfiguracji[i][0]) > 0))
|| (dlugosc_konfiguracji < maksymalna_dlugosc)
&&
((dlugosc_konfiguracji > minimalna_dlugosc)
|| (dlugosc_konfiguracji == minimalna_dlugosc
&& strcmp(minimum,
tablica_konfiguracji[i][0]) < 0))
) {
result = i;
maksimum = tablica_konfiguracji[i][0];
}
}
return result;
}
void odczytaj_argumenty(int argc, char *argv[]) {
int command;
while ((command = getopt(argc, argv, ":c:p:")) != -1) {
if (command == 'c') {
TCP_port = optarg;
} else if (command == '?') {
fprintf(stderr, "Nieznana opcja '-%c'.\n", optopt);
exit(1);
} else if (command == 'p') {
if (parsuj_argumenty_programu(optarg) != 0) {
fprintf(stderr, "Nieznana konfiguracja\n");
exit(1);
}
} else if (command == ':') {
fprintf(stderr, "Ta opcja (-%c) wymaga argumentu.\n", optopt);
exit(1);
}
}
if (optind != argc) {
fprintf(stderr, "Uzycie: ./slicz -c <port_tcp> -p <konfiguracje>");
exit(1);
}
}
int parsuj_argumenty_programu(char *c) {
char *config = malloc(sizeof(char) * (strlen(c) + 1));
char *tofree = config;
int i;
struct sockaddr_in temporary_sockaddr_in_instance;
strcpy(config, c);
tablica_konfiguracji[ilosc_aktywnych_portow][0] = strsep(&config, "/");
tablica_konfiguracji[ilosc_aktywnych_portow][2] = strsep(&config, "/");
if (tablica_konfiguracji[ilosc_aktywnych_portow][0] == NULL
|| tablica_konfiguracji[ilosc_aktywnych_portow][2] == NULL) {
free(tofree);
return -1;
}
if ((tablica_konfiguracji[ilosc_aktywnych_portow][1] = strsep(
&tablica_konfiguracji[ilosc_aktywnych_portow][2], ":")) == NULL) {
free(tofree);
return -1;
}
if (tablica_konfiguracji[ilosc_aktywnych_portow][2] == NULL
&& strlen(tablica_konfiguracji[ilosc_aktywnych_portow][1]) > 0) {
free(tofree);
return -1;
}
if (tablica_konfiguracji[ilosc_aktywnych_portow][2] != NULL) {
inet_aton(tablica_konfiguracji[ilosc_aktywnych_portow][1],
&temporary_sockaddr_in_instance.sin_addr);
tablica_portow_udp[ilosc_aktywnych_portow] = htons(
(unsigned short) atoi(
tablica_konfiguracji[ilosc_aktywnych_portow][2]));
tablica_adresow_ip_udp[ilosc_aktywnych_portow] =
temporary_sockaddr_in_instance.sin_addr.s_addr;
}
for (i = 3;
(tablica_konfiguracji[ilosc_aktywnych_portow][i] = strsep(&config,
",")) != NULL ; i++) {
}
if (i == 3) {
free(tofree);
return -1;
}
ilosc_aktywnych_portow += 1;
return 0;
}
int odblokuj_socket(int s_file_descriptor) {
int flags, s;
flags = fcntl(s_file_descriptor, F_GETFL, 0);
if (flags == -1) {
return -1;
}
flags |= O_NONBLOCK;
s = fcntl(s_file_descriptor, F_SETFL, flags);
if (s == -1) {
return -1;
}
return 0;
}
int zdarzenie_na_tcp(int sfd) {
int i;
for (i = 1; i <= LIMIT_ILOSCI_POLACZEN; i++) {
if (tablica_gniazd_tcp[i] == sfd) {
return i;
}
}
return 0;
}
int zdarzenie_na_udp(int sfd) {
int i;
for (i = 0; i < LIMIT_AKTYWNYCH_PORTOW; i++) {
if (tablica_gniazd_udp[i] == sfd) {
return i;
}
}
return -1;
}
void delete_port_udp(int index) {
int i, j;
if (tablica_konfiguracji[index][0] != NULL) {
free(tablica_konfiguracji[index][0]);
}
tablica_konfiguracji[index][0] = NULL;
tablica_adresow_ip_udp[index] = 0;
tablica_portow_udp[index] = 0;
priorytety[index] = 0;
close(tablica_gniazd_udp[index]);
for (i = index; tablica_konfiguracji[i][0] != NULL ; i++) {
for (j = 0; tablica_konfiguracji[i + 1][j] != NULL ; j++) {
tablica_konfiguracji[i][j] = tablica_konfiguracji[i + 1][j];
tablica_gniazd_udp[i] = tablica_gniazd_udp[i + 1];
}
tablica_gniazd_udp[i] = 0;
tablica_konfiguracji[i][j] = NULL;
}
ilosc_aktywnych_portow -= 1;
}
int sprawdz_tagowanie_vlanow(int index) {
int i, nvlan, length, tag, count = 0;
for (i = 0; i - 1 <= LIMIT_SIECI_VLAN; i++) {
tablica_vlanow[index][i] = 0;
}
for (i = 3; tablica_konfiguracji[index][i] != NULL ; i++) {
length = strlen(tablica_konfiguracji[index][i]);
count++;
tag = 1;
if (tablica_konfiguracji[index][i][length - 1] == 't') {
tag = 2;
count--;
tablica_konfiguracji[index][i][length - 1] = '\0';
}
if (count > 1) {
return -1;
}
nvlan = atoi(tablica_konfiguracji[index][i]);
if (nvlan == 0) {
return -1;
}
if (tablica_vlanow[index][nvlan]
!= 0|| nvlan < 1 || nvlan > LIMIT_SIECI_VLAN) {return
- 1;
}
if ((tablica_vlanow[index][nvlan] = tag) == 1) {
tablica_vlanow[index][LIMIT_SIECI_VLAN + 1] = nvlan;
}
}
return 0;
}
int stworz_port_udp(int index, int e_file_descriptor, int nbuffer) {
int sendbuf = ROZMIAR_BUFFORA, sock, s;
struct sockaddr_in client_address_sockaddr_in_instance;
struct epoll_event slicz_event_epoll;
client_address_sockaddr_in_instance.sin_addr.s_addr = htonl(INADDR_ANY );
client_address_sockaddr_in_instance.sin_port = htons(
atoi(tablica_konfiguracji[index][0]));
client_address_sockaddr_in_instance.sin_family = AF_INET;
tablica_gniazd_udp[index] = (sock = socket(AF_INET, SOCK_DGRAM, 0));
priorytety[index] = 0;
setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sendbuf, sizeof(sendbuf));
if (sprawdz_tagowanie_vlanow(index) == -1 || sock < 0) {
delete_port_udp(index);
if (write(tablica_gniazd_tcp[nbuffer], "ERR while opening udp port\n",
27) < 0 && nbuffer != -1) {
fprintf(stderr, "error while opening udp port\n");
}
return 1;
}
if ((s = odblokuj_socket(sock)) < 0) {
delete_port_udp(index);
if (nbuffer != -1
&& write(tablica_gniazd_tcp[nbuffer],
"ERR while opening udp port\n", 27) < 0)
fprintf(stderr, "error while opening udp port\n");
return 1;
}
if (bind(sock, (struct sockaddr *) &client_address_sockaddr_in_instance,
(socklen_t) sizeof(client_address_sockaddr_in_instance)) < 0) {
delete_port_udp(index);
if (nbuffer != -1
&& write(tablica_gniazd_tcp[nbuffer],
"ERR while opening udp port\n", 27) < 0) {
fprintf(stderr, "error while opening udp port\n");
}
return 1;
}
slicz_event_epoll.data.fd = sock;
slicz_event_epoll.events = EPOLLIN;
if ((s = epoll_ctl(e_file_descriptor, EPOLL_CTL_ADD, sock,
&slicz_event_epoll)) < 0) {
delete_port_udp(index);
if (nbuffer != -1
&& write(tablica_gniazd_tcp[nbuffer],
"ERR while opening udp port\n", 27) < 0) {
fprintf(stderr, "error while opening udp port\n");
}
return 1;
}
return 0;
}
int ustaw_gniazdo_tcp(const char *port) {
struct addrinfo *result, *addrinfo_instance_tmp;
int s, integer_file_descriptor;
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_flags = 0;
hints.ai_socktype = SOCK_STREAM;
if ((s = getaddrinfo(NULL, port, &hints, &result)) != 0) {
return -1;
}
addrinfo_instance_tmp = result;
if ((integer_file_descriptor = socket(addrinfo_instance_tmp->ai_family,
addrinfo_instance_tmp->ai_socktype,
addrinfo_instance_tmp->ai_protocol)) == -1) {
return -1;
}
if ((s = bind(integer_file_descriptor, addrinfo_instance_tmp->ai_addr,
addrinfo_instance_tmp->ai_addrlen)) < 0) {
return -1;
}
freeaddrinfo(result);
return integer_file_descriptor;
}
int otworz_gniazda(int epoll_file_descriptor) {
int i;
for (i = 0; i < ilosc_aktywnych_portow; i++) {
if (stworz_port_udp(i, epoll_file_descriptor, -1)) {
return 1;
}
}
return 0;
}
int skoryguj_andress_port(struct sockaddr_in *from_addr, int index) {
if (tablica_portow_udp[index] != 0
&& tablica_portow_udp[index] == from_addr->sin_port
&& tablica_adresow_ip_udp[index] == from_addr->sin_addr.s_addr) {
return 0;
}
if (tablica_portow_udp[index] == 0) {
tablica_portow_udp[index] = from_addr->sin_port;
tablica_adresow_ip_udp[index] = from_addr->sin_addr.s_addr;
return 1;
}
return -1;
}
int sprawdz_mac(char *src, char *tmpv) {
int i;
for (i = 0; i < LIMIT_ADRESOW_MAC; i++) {
if (atoi(tablica_mac[i][1]) == atoi(tmpv)
&& strcmp(tablica_mac[i][0], src) == 0) {
return 0;
}
}
return -1;
}
int parsuj_ramke(char *buffor, int firstly_added, int index, int *tagged) {
char dst[7];
char src[7];
int i, counter = 0, nvlan = 0;
*tagged = 0;
strncpy(dst, buffor, 6);
strncpy(src, buffor + 6, 6);
dst[6] = src[6] = '\0';
if (buffor[12] == -127 && buffor[13] == 0) {
nvlan = (256 * (buffor[14] & 1)) + (512 * (buffor[14] & 2))
+ (1024 * (buffor[14] & 4)) + (2048 * (buffor[14] & 8))
+ (int) buffor[15];
buffor[14] = buffor[14] & 15;
*tagged = 1;
} else if (tablica_vlanow[index][LIMIT_SIECI_VLAN + 1] != 0) {
nvlan = tablica_vlanow[index][LIMIT_SIECI_VLAN + 1];
} else {
fprintf(stderr, "invalid tags\n");
return -1;
}
snprintf(temporary_vlan, 10, "%d", nvlan);
if (sprawdz_mac(src, temporary_vlan) < 0) {
strncpy(tablica_mac[ilosc_adreos_w_tablicy_mac][0], src, 6);
snprintf(tablica_mac[ilosc_adreos_w_tablicy_mac][1], 10, "%d", nvlan);
strcpy(tablica_mac[ilosc_adreos_w_tablicy_mac][2],
tablica_konfiguracji[index][0]);
tablica_mac[ilosc_adreos_w_tablicy_mac][0][6] = '\0';
ilosc_adreos_w_tablicy_mac = (ilosc_adreos_w_tablicy_mac + 1)
% LIMIT_ADRESOW_MAC;
}
for (i = 0; i < 6; i++) {
if (dst[i] == -1) {
counter++;
}
}
if (counter == 6) {
return LIMIT_ADRESOW_MAC + 1;
}
for (i = 0; i < LIMIT_ADRESOW_MAC; i++) {
if (strcmp(dst, tablica_mac[i][0]) == 0
&& nvlan == atoi(tablica_mac[i][1])) {
return i;
}
}
fprintf(stderr, "mac addres could not be found\n");
return -1;
}
void wyslij_datagram(char *prievous_buffor, int read_bytes, int nvlan,
int nsock, int index, int tagowanie) {
int write_bytes, length;
int i;
char buffor[ROZMIAR_BUFFORA_TCP];
struct sockaddr_in slicz_address;
for (i = 0; i < read_bytes; i++) {
buffor[i] = prievous_buffor[i];
}
if (tagowanie == 0) {
if (tablica_vlanow[index][nvlan] == 2) {
for (i = read_bytes; i >= 12; i--) {
buffor[i + 4] = buffor[i];
}
read_bytes += 4;
buffor[12] = (char) -127;
buffor[13] = (char) 0;
buffor[14] = buffor[15] = 0;
buffor[14] = ((((buffor[14] | (nvlan & 256)) | (nvlan & 512))
| (nvlan & 1024)) | (nvlan & 2048));
buffor[15] =
((((((((buffor[15] | (nvlan & 1)) | (nvlan & 2))
| (nvlan & 4)) | (nvlan & 8)) | (nvlan & 16))
| (nvlan & 32)) | (nvlan & 64)) | (nvlan & 128));
buffor[14] = buffor[14] & 15;
}
} else if (tablica_vlanow[index][nvlan] == 1) {
for (i = 12; i <= read_bytes; i++) {
buffor[i] = buffor[i + 4];
}
read_bytes -= 4;
}
if (tablica_vlanow[nsock][nvlan] == 0
|| tablica_vlanow[index][nvlan] == 0) {
fprintf(stderr,
"konfiguracja nie jest obslugiwana: tablica_vlanow - %d\n",
nvlan);
return;
}
slicz_address.sin_port = tablica_portow_udp[index];
slicz_address.sin_addr.s_addr = tablica_adresow_ip_udp[index];
slicz_address.sin_family = AF_INET;
length = (socklen_t) sizeof(slicz_address);
write_bytes = sendto(tablica_gniazd_udp[index], buffor, read_bytes, 0,
(struct sockaddr *) &slicz_address, length);
if (write_bytes < 0) {
counters_table[index][ERROR_COUNTER]++;
} else {
counters_table[index][SENT_COUNTER]++;
}
}
void wyslij_ramke(char *buf, int rb, int m_i, int nsock, int ind, int t) {
int i, j;
if (m_i == LIMIT_ADRESOW_MAC + 1) {
for (i = 0; i < LIMIT_ADRESOW_MAC; i++) {
if (atoi(temporary_vlan) == atoi(tablica_mac[i][1])
&& atoi(tablica_mac[i][2])
!= atoi(tablica_konfiguracji[nsock][0])) {
for (j = 0; j < ilosc_aktywnych_portow; j++) {
if (atoi(tablica_mac[i][2])
== atoi(tablica_konfiguracji[j][0])) {
ind = j;
break;
}
}
if (ind == -1) {
break;
}
wyslij_datagram(buf, rb, atoi(temporary_vlan), nsock, ind, t);
}
}
} else if (ind != -1) {
wyslij_datagram(buf, rb, atoi(temporary_vlan), nsock, ind, t);
} else {
fprintf(stderr, "mac unknown\n");
}
}
<file_sep>VirtualSwitch
=============
Academic project for subject: Computer Networks. Virtual switch that pretend to be a network switch, operate on VLans according to 802.1q. Program listens simultaneously on multiple UDP ports. Each received datagram is treated like an ethernet frame that should be passed to selected port.
| 978dc5f02a930ab6bd7f1ac16279406d20ec3149 | [
"Markdown",
"C",
"Makefile"
] | 4 | Makefile | Tom-Potanski/VirtualSwitch | 3c62caf41bb7c315be6bae787822a71d04746bed | e24bc5c8a9ac8d5a29aaf9fb16e00582b2ed75cb |
refs/heads/master | <file_sep>const express = require('express');
const mysql = require('mysql');
const app = express();
const PORT = process.env.PORT || 3000;
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: '<PASSWORD>',
database: 'wizard_schools_db',
});
connection.connect(err => {
if (err) {
console.error(`error connecting: ${err.stack}`);
return;
}
console.log(`connected as id ${connection.threadId}`);
});
// Routes
app.get('/', (req, res) => {
connection.query('SELECT * FROM schools', (err, result) => {
let html = '<h1>Magical Schools</h1>';
html += '<ul>';
result.forEach(item => {
html += `<li><p> ID: ${item.id}</p>`;
html += `<p>School: ${item.name} </p></li>`;
});
html += '</ul>';
res.send(html);
});
});
| 7702423f975142ad87397b41852e082fdedeba5d | [
"JavaScript"
] | 1 | JavaScript | Dujota/express-example | 759df695e66bf2d76ea24a3e32dfc08b8a479f0d | 335df5bc9ac4cc4b57c45d8b1c269d4ab4b64c84 |
refs/heads/master | <repo_name>DevKumRos/PdfWriter<file_sep>/src/main/java/com/kumar/PDFReader.java
package com.kumar;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
public class PDFReader {
private static final String FILE_NAME = "C:/Users/IBM_ADMIN/Desktop/Knowledge_Transfer/test/target/output.pdf";
public static void main(String[] args) throws DocumentException {
PdfReader reader;
Map<Integer, String> fieldTypes = createFeildType();
try {
reader = new PdfReader("C:/Users/IBM_ADMIN/Desktop/Knowledge_Transfer/test/form.pdf");
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_NAME));
// pageNumber = 1
AcroFields fields = stamp.getAcroFields();
Set<String> fieldNames = fields.getFields().keySet();
for (String fieldName : fieldNames) {
System.out.println( "Field Type :"+ fieldTypes.get(fields.getFieldType(fieldName)) +", Name :" +fieldName + ", Value :" + fields.getField( fieldName ) );
if(fields.getFieldType(fieldName) == 2) {
fields.setField(fieldName, "Yes");
}else if(fields.getFieldType(fieldName) == 4) {
fields.setField(fieldName, "Done");
}
}
stamp.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static Map<Integer, String> createFeildType() {
Map<Integer, String> fieldType = new HashMap<Integer, String>();
fieldType.put(0, "NONE");
fieldType.put(1, "PUSHBUTTON");
fieldType.put(2, "CHECKBOX");
fieldType.put(3, "RADIOBUTTON");
fieldType.put(4, "TEXT");
fieldType.put(5, "LIST");
fieldType.put(6, "COMBO");
fieldType.put(7, "SIGNATURE");
return fieldType;
}
}
| 24e31f9083e74165d9ac89b0b73f248774da9635 | [
"Java"
] | 1 | Java | DevKumRos/PdfWriter | cc1d5186e69265d1573771c9c613fb6e4ba6d7ff | 006393677243300505c480b540e480eb6342cf92 |
refs/heads/master | <repo_name>kpnetorians/junit-get-started<file_sep>/src/test/java/org/jbossoutreach/Alamo18Test.java
package org.jbossoutreach;
import org.junit.Assert;
import org.junit.Test;
public class Alamo18Test {
@Test
public void sampleTest() {
System.out.println("@Test - test_method_1");
}
@Test
public void fiveTimesTenEqualsFifty() {
// Expected method return 0, since 10*5 = 50
Assert.assertEquals(50, 10*5);
}
@Test
public void ceilTest(){
double random = 10.3;
Assert.assertFalse(Math.ceil(random) == 10);
}
@Test
public void uniaryOperatorTest(){
int number = 8;
int expected = 9;
boolean calculate = ++number == expected;
Assert.assertTrue(calculate);
}
@Test
public void ArrayCompare() {
int[] original = {1, 2, 6, 9};
int[] expected = {1, 2, 6, 9};
Assert.assertArrayEquals(original, expected);
}
}
<file_sep>/src/test/java/org/jbossoutreach/AnhaiWangApplicationTest.java
package org.jbossoutreach;
import org.junit.Assert;
import org.junit.Test;
public class AnhaiWangApplicationTest {
private int val1 = 567;
private int val2 = 233;
private String str1 = "APPLICATION";
private String str2 = "TEST";
private String imNull = null;
@Test
public void sampleTest() {
System.out.println("@Test - test_method_1");
}
@Test
public void testEquals() {
int sum = val1 + val2;
Assert.assertEquals(sum, 800);
Assert.assertEquals(val1 + sum, 1367);
Assert.assertEquals(val2 + sum, 1033);
}
@Test
public void testTrue() {
int difference = val1 - val2;
Assert.assertTrue(difference == 334);
Assert.assertTrue(val1 - difference == val2);
}
@Test
public void testFalse() {
int product = val1 * val2;
Assert.assertFalse(product == 0);
Assert.assertFalse(product == val1);
Assert.assertFalse(product == val2);
}
@Test
public void testNull() {
Assert.assertNull(imNull);
}
@Test
public void testArrayEquals() {
int[] arrayVals = {val1, val2};
int[] arrayValsExpected = {567, 233};
String[] arrayStrs = {str1, str2};
String[] arrayStrsExpected = {"APPLICATION", "TEST"};
Assert.assertArrayEquals(arrayVals, arrayValsExpected);
Assert.assertArrayEquals(arrayStrs, arrayStrsExpected);
}
}
<file_sep>/settings.gradle
rootProject.name = 'testing-get-started'
<file_sep>/src/test/java/org/jbossoutreach/DivyanshApplicationTest.java
package org.jbossoutreach;
import org.junit.Assert;
import org.junit.Test;
public class DivyanshApplicationTest {
int val1 = 20;
int val2 = 6;
String string1 = "Jboss";
String string2 = "Community";
@Test
public void sampleTest() {
System.out.println("@Test - test_method_1");
}
@Test
public void isTrue() {
Assert.assertTrue((val1*val2)==120); //returns the result(boolean) of the statement, true if statement is true
}
@Test
public void isFalse() {
Assert.assertFalse((val1-val2)==12); //returns the result(boolean) of the statement, true if statement is false
}
@Test
public void addsTwo(){ //checks if the calculated value is equal to the actual value
int total = val1+val2;
Assert.assertEquals(total,26);
}
@Test
public void sameOrNot(){
Assert.assertNotSame(string1,string2); //checks whether they are "not same"
}
@Test
public void areArraysEqual() {
int [] array1 = {2,4,6,8,10};
int [] array2 = {2,4,6,8,10};
Assert.assertArrayEquals(array1,array2); //checks whether the arrays are equal
}
}
<file_sep>/README.md
# Getting equipped with Unit Testing In Java
[](https://travis-ci.org/jboss-outreach/junit-get-started)
This repository is structured to help you getting started with unit testing and integration testing with `JUnit` , `Java` and `Gradle`.
## What is Unit Testing?
Unit testing is a testing technique used by developers or software testers using which individual modules of the program are tested to determine if there are any issues.
We are going to be using [JUnit](http://junit.org/junit5/), a unit testing framework for Java.
## Why JUnit?
We have preferred JUnit because:-
1. It provides better features and reliability like Lamda Support,Extensions ...
2. It is opensource thus provides developers to have precise control over APIs
3. The entire goal of the JUnit 5 revamp was to allow the success of JUnit to enable the use of other testing frameworks so you can combine it with other frameworks
## Contents
* [Setting up the project](#set)
* [Running the tests](#run)
* [Contribution Guidelines](#cont)
* [References](#ref)
## <a id="set"></a>Setting up the Project
* Download [Java 8 JDK](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html). Make sure that it is for your Operating System!
* Make sure you have declared the `JAVA_HOME` environment variable to the directory where JDK was installed.
* Fork the repository by clicking on the *Fork* icon at the top right corner of this page.
* Clone the repository to your local machine by running the following commands on git:
`git clone https://github.com/[YOUR-USERNAME]/junit-get-started.git`
* If you need help, refer [Forking and Cloning in git](https://help.github.com/articles/fork-a-repo/).
* Make the necessary changes to the cloned repository.
* Use `git push` to push the changes to your repository.
## <a id="run"></a>Running the tests
1. Set the present working directory in terminal (or cmd) to your project. (`cd \YOUR_PROJECT_DIRECTORY`).
2. Run `./gradlew test` on Linux/Unix or `gradlew test` on Windows.
* If the file is being denied to open, the use `chmod +x ./gradlew` (for Linux/Unix) or run `cmd as admin` (for Windows).
* If the file is being denied to open, the use `chmod +x ./gradlew` (for Linux/Unix) or run `cmd as admin` (for Windows).
###### Alternatively, if you are using an IDE like [Intellij IDEA](https://www.jetbrains.com/idea/)
1. Import the Git repository into the IDE and allow Gradle.
2. Right-click the src/test/ directory.
3. Click `Run 'All Tests'` or simply use the `Ctrl-Shift-F10` keyboard shortcut.
## <a id="cont"></a>Contribution Guidelines
1. Add a **new** test class under src/test/java for the suite of test cases to be added.
2. Add 5 JUnit test cases in that class, one for each:
-assertTrue
-assertFalse
-assertEquals
-and any other two variety.
3. Do verify that the tests successfully builds.
4. Create a [pull request](https://help.github.com/articles/about-pull-requests/) requesting to merge the commits on your fork to this repository.
5. Write a very conscise but informative pull request message,explaining the test cases in your pull request! Remember to use your words wisely.
## Points to keep in mind while contributing
* There is not much content in main code (src/main/). *Add your test code to (src/test/) only.*
* Do not edit ApplicationTest.java! Create a **new test class** instead to avoid merge conflicts.
* Remember to add comments in your code so that the other person can know what the test module does.
* Class names should always be in PascalCase.
* This repository has [Travis CI integration](https://travis-ci.org/), verify that it builds successfully before submitting the task.
# <a id="ref"></a>References
* [How to set JAVA_HOME](https://docs.oracle.com/cd/E19182-01/820-7851/inst_cli_jdk_javahome_t/)
* [Assert Documentation](http://junit.sourceforge.net/javadoc/org/junit/Assert.html)
* [Junit Test Framework](https://www.tutorialspoint.com/junit/junit_test_framework.htm)
* [Best Coding Practices](https://en.wikipedia.org/wiki/Best_coding_practices)
* [How to use GitHub](https://guides.github.com/activities/hello-world/)
* [Git basics](https://git-scm.com/book/en/v2/Getting-Started-Git-Basics)
* [Git commands handbook](https://git-scm.com/docs)
* [Command Prompt handbook](http://www.makeuseof.com/tag/a-beginners-guide-to-the-windows-command-line/)
* [Linux Terminal handbook](http://linuxcommand.org/)
* [MacOS Terminal handbook](https://developer.apple.com/library/content/documentation/OpenSource/Conceptual/ShellScripting/CommandLInePrimer/CommandLine.html)
* [Heroku Handbook](https://devcenter.heroku.com/)
* [Maven Handbook](http://www.jcabi.com/jcabi-heroku-maven-plugin/example-start.html)
* [Chat with us !](https://gitter.im/jboss-outreach)
<file_sep>/src/test/java/org/jbossoutreach/sidTest.java
package org.jbossoutreach;
import org.junit.Assert;
import org.junit.Test;
public class sidTest {
private int x = 666;
private int y = 242;
@Test
public void sampleTest() {
System.out.println("@Test_Test_Method_2");
}
@Test
public void testArrayEquals(){ // Checks if array turns out to be same
int[] array1={x,y};
int[] array2_Expected={666,242};
Assert.assertArrayEquals(array1, array2_Expected);
}
@Test
public void testFalse() { // Checks if Product is Fals
int pro = x * y;
Assert.assertFalse(pro == 300);
Assert.assertFalse(pro == 99);
Assert.assertFalse(pro == 10000000);
Assert.assertFalse(pro == -10000000);
Assert.assertFalse(pro == 0);
}
@Test
public void testEquals() { // Checks if Sum is equal
int sum = x + y;
Assert.assertEquals(sum, 908);
Assert.assertEquals(x + 30, 696);
Assert.assertEquals(y + 30, 272);
}
@Test
public void testTrue() { // Checks is difference is true
int diff = x - y;
Assert.assertTrue(diff == 424);
Assert.assertTrue(x - diff == y);
}
@Test
public void testDifferent() { // Checks if x & y are different
Assert.assertNotSame(x, y);
}
}
<file_sep>/src/test/java/org/jbossoutreach/JUnitExampleAniol.java
package org.jbossoutreach;
import org.junit.Assert;
import org.junit.Test;
import org.junit.After;
import org.junit.Before;
public class JUnitExampleAniol {
@Test
public void assert_True()
{
int s = 8 + 2;
Assert.assertTrue(s == 10);
}
@Test
public void assert_False()
{
int s = 6 - 4;
Assert.assertFalse(s == 0);
}
@Test
public void assert_Equals()
{
int e = 18 / 3;
Assert.assertEquals(e, 6);
}
@Test
public void assert_Array_Equals()
{
int a1[]={4,5,6};
int a2[]={4,5,6};
Assert.assertArrayEquals(a1 ,a2);
}
@Test
public void assert_notnull()
{
int i = 9;
Assert.assertNotNull(i);
}
}
| 21c26ea90e308f6491117bfa968b869ebe3e86a3 | [
"Markdown",
"Java",
"Gradle"
] | 7 | Java | kpnetorians/junit-get-started | cc5bfbc11bbbadf34c9c6c62796b52fedc5454c1 | 0637118f2fc2871fe73fa4cd4e828626ca424988 |
refs/heads/master | <repo_name>jeffAmerson/FirstSpringWeb<file_sep>/src/main/java/first/ali/repositories/StudentsRepositories.java
package first.ali.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import first.ali.model.Students;
@Repository
public interface StudentsRepositories extends JpaRepository<Students,Long> {
}
| 32d3aebe41323482b5c8f925e522ccf4d070e39a | [
"Java"
] | 1 | Java | jeffAmerson/FirstSpringWeb | eef07931ad834290ec146abed14aae4cd029e8ef | a39e74dfbc88a5bd50c83cf412583d5dfdc162d0 |
refs/heads/master | <repo_name>LuvMeReal/ComputerNetworkAssignment<file_sep>/Assignment 5/作业5.md
#### P5
用10101010100000除以10011,得到1011011100,余数得R=0100
#### P6
算法相同
a. 除法运算后得1000110000,余数得R=0000
b. 除法运算后得0101010101,余数得R=1111
a. 除法运算后得1011010111,余数得R=1001
#### P7
a. 如果0<=i<=d+r-1,第i位字节反转,单比特差错表明接收到的数据为K=D*2r XOR R+2i。所以我们用K除以G时余数一定不为0。如果G含至少两个1,那么单比特差错就总是可以被检测到。
b. 可以。G可以被11整除,但任何奇数比特差错都不能被11整除,所以也不能被G整除。
#### P8
a. 对Np(1-p)^(N-1),求导并令导数为0,求得此时p'=1/N
b. 带入p'=1/N,得效率为(1-1/N)^N-1,此时效率趋近于1/e
#### P9
此时效率为Np(1-p)^(2(N-1)),求导令导数为0,得p'=1/(2N-1),将其带入,令N->infinity,此时效率趋近于1/2e
<file_sep>/Assignment 3/2016302580192_蔡鸿阳 作业3.md
#### P1
假设A向S传送报文的端口为a,B向S传送报文的端口为b
a. A->S,源端口号为a,目的端口号为23
b. B->S,源端口号为b,目的端口号为23
c. S->A,源端口号为23,目的端口号为a
d. S->B,源端口号为23,目的端口号为b
e. 可能相同
f. 如果是同一台主机,则不可能相同
#### P3
先进行相加
01010011+01100110 = 10111001
10111001+01110100 = 100101101 溢出一位,所以向最低位进一位
00101101+1 = 00101110
所以其反码为 11010001
如何检验差错:将三个字节和检验和相加,如果有任何一位为0则一定有错。
1比特的差错一定会导致结果不相同。
2比特可能检测不出,比如最低位交换,相加结果不会变。
#### P4
a. 01011100+01100101 = 11000001 反码为00111110
b. 11011010+01100101 = 100111111 最高位进到最低位 00111111+1=01000000 反码为10111111
c. 两个字节变为01011101和01100100
#### P5
不能确保,比如2比特的最低位交换差错就无法被发现。
#### P40
a. 1-6、23-26
b. 6-16、17-22
c. 3个冗余ACK
d. 超时
e. ssthresh初始值为32
f. 42/2=21
g. 29/2=14
h. t1:p1
t2:p2-p3
t3:p4-p7
t4:p8-p15
t5:p16-p31
t6:p32-p63
t7:p64-p127
所以第七十个报文在第7个传输轮回发送
i. ssthresh=8/2=4,拥塞窗口长度为4+3=7
j. 19轮回时,ssthresh为21,拥塞窗口长度为4
k. t17:1
t18:2
t19:4
t20:8
t21:16
t22:21
1 + 2 + 4 + 8 + 16 + 21 = 52 个
<file_sep>/Assignment 6/作业6.md
### P10
a. 结点A的平均吞吐量公式为:pA*(1-pB)
具有这两个结点的协议的总体效率为两个结点平均吞吐量之和,即:pA\*(1-pB)+pB\*(1-pA)
b. A的平均吞吐量:2pB\*(1-pB)=2pB-2pB^2,B的平均吞吐量:pB\*(1-2pB)=pB-2pB^2,显然不是二倍的关系。如要为二倍关系,pA\*(1-pB)=2\*pB\*(1-pA) ,得出pA=2pB/(pB+1)
c. A的平均吞吐量:2p*(1-p)^(N-1);其它结点:p\*(1-2p)\*(1-p)^(N-2)
### P11
a. 即前四个时隙未成功,最后一个成功:p‘*(1-p’)^4
而p'表示B、C、D结点传输失败而A结点传输成功,则p'=p*(1-p)^3,代入即可
b. A成功:pA=p*(1-p)^3,B、C、D相同,所以总的概率为4pA
c. 某一结点成功概率为4\*p\*(1-p)^3,无结点成功为1-4\*p\*(1-p)^3
所以在时隙3出现第一个成功:(1-4\*p\*(1-p)^3)^2\*4\*p\*(1-p)^3
d. 四个结点的效率即某一时隙中某一结点成功的概率:4\*p*(1-p)^3
### P13
一个轮询周期T为:N(Q/R+dpoll);而一个周期所需要传输的总比特数为:NQ,则最大吞吐量为NQ/T=QR/(Q+dpoll*R)
### P17
对于10Mbps:100*512bit/10Mbps=5.12ms
对于100Mbps:100*512bit/100Mbps=0.512ms
### P18
t=0时刻,A开始传输,在t=325时,第一个bite到达B,而在最坏情况下,B在t=324时开始传送自己的帧,当t=324+325=649时,此帧到达A,但是649>512+64,所以在A检测到B完成传输之前A已经完成传输,因此A错误地认为自己已经完成传输。<file_sep>/Assignment 3/client.py
#client.py
from socket import *
sName = 'localhost'
sPort = 11000
cSocket = socket(AF_INET,SOCK_STREAM)
cSocket.connect((sName,sPort))
sentence = input("Input a number:")
cSocket.send(sentence.encode())
modifiedSentence = cSocket.recv(1024)
print("From Server:",modifiedSentence.decode())
cSocket.close()<file_sep>/Assignment 3/server.py
#server.py
from socket import *
sPort = 11000
sSocket = socket(AF_INET,SOCK_STREAM)
sSocket.bind(('localhost',sPort))
sSocket.listen(1)
print ("Ready to receive...")
while True:
connectionSocket, addr = sSocket.accept()
sentence = connectionSocket.recv(1024).decode()
mutipliedSentence = str(int(sentence,10)*10)
connectionSocket.send(multipliedSentence.encode())
connectionSocket.close()<file_sep>/Assignment 2/2016302580192_蔡鸿阳 作业2.md
##### P1
a. 错误
b. 正确
c. 错误 在非持续链接中 一个TCP报文段只能携带一个请求报文
d. 错误 指出的是做后一次更新的时间
e. 错误 存在空的报文体
##### P2
RETR 令服务端将路径制定文件传送到另一端
STOR 令服务端接收数据并存储到路径目录下
STOU 要求将文件保存在当前目录且文件名唯一
APPE 将接收到的数据追加到制定文件
ALLO 手动为新文件分配空间
REST 要求跳到文件指定的数据检查点
RNFR 制定一个需要被改名的文件
RNTO 命名一个文件
ABOR 放弃之前的FTP指令 关闭数据连接
DELE 删除文件
RMD 删除目录
MKD 创建目录
PWD 返回当前工作目录
LIST 返回路径目录下文件列表到被动DTP
NLIST 返回路径目录下文件列表到客户端
SYST 查找服务器操作系统类型
NOOP 要求服务器发回OK回应
##### P3
应用层需要DNS HTTP协议
运输层中DNS需要UDP协议 HTTP需要TCP协议
##### P4
a. gaia.cs.umass.edu
b. 1.1
c. 持续连接
d. 没有IP地址
e. 浏览器是Mozilla 5.0 因为可以针对不同浏览器发送不同版本的网页
##### P5
a. 能成功找到文档 时间是Tue, 07 Mar 2008 12:39:45GMT
b. Last-Modified: Sat, 10 Dec2005 18:27:46
c. Content-Length: 3874
d. 前五个字节是:"<!doc" 同意一条持续连接 | b88c1a9527cf6159aff671a79cf8648ef01da10e | [
"Markdown",
"Python"
] | 6 | Markdown | LuvMeReal/ComputerNetworkAssignment | 4cf3697aacdc0952adf3b7a28d2a586c88ebbb88 | 734432e84291ae0d0b4772a322637d099c5bec65 |
refs/heads/main | <file_sep>import { Component, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { AdminComponent } from './admin.component';
import { CategoriasComponent } from './categorias/categorias.component';
import { ClientesComponent } from './clientes/clientes.component';
import { UsuariosComponent } from './usuarios/usuarios.component';
import { ProductosComponent } from './productos/productos.component';
import { CatalogoComponent } from './productos/catalogo/catalogo.component';
import { VentasComponent } from './ventas/ventas.component';
const routes: Routes = [
{
path:'',
component: AdminComponent,
children:[
{
path:'categoria',
component: CategoriasComponent,
},
{
path:'clientes',
component: ClientesComponent,
},
{
path:'usuarios',
component: UsuariosComponent,
},
{
path:'productos',
component: ProductosComponent,
},
{
path:'catalogo',
component: CatalogoComponent,
},
{
path:'ventas',
component: VentasComponent,
}
]
}
];
@NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule.forChild(routes)
],
exports:[
RouterModule
],
})
export class AdminRoutingModule { }
<file_sep>export interface Usuario{
nombre: String;
apellidos: String;
correo: String;
password: String;
estado: Boolean;
rol: string;
}<file_sep>import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { CarritoComprasService } from './carrito-compras/carrito-compras.service';
import { DatosUsuarioComponent } from './usuarios/datos-usuario/datos-usuario.component';
import { UsuarioService } from './usuarios/usuario.service';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
toggledValue = true;
public id_usuario: any;
public carrito:any;
estado: boolean = false;
constructor(private carritoComprasService: CarritoComprasService,
private router: Router,
public dialog : MatDialog,)
{}
ngOnInit(): void {
const tok = localStorage.getItem("token");
if(tok)
{
if(this.id_usuario.rol === "Administrador")
{
this.estado = false;
}
else{
this.estado = true;
}
}
else
{
this.router.navigate([""]);
}
}
openNav(){
this.carritoComprasService.openNav();
}
toggled($event){
this.toggledValue = $event;
}
}
<file_sep>import { Component, OnInit,Output,EventEmitter } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { UsuarioService } from '../../usuarios/usuario.service';
import { DatosUsuarioComponent } from './../../usuarios/datos-usuario/datos-usuario.component';
@Component({
selector: 'app-admin-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
toggledValue = true;
@Output() toggleChange = new EventEmitter<boolean>();
public id_usuario: any;
constructor(private router: Router,
private usuarioService: UsuarioService,
public dialog : MatDialog) {
this.id_usuario = this.usuarioService.getIdentidad();
}
ngOnInit(): void {
}
toggled(){
if(this.toggledValue === undefined)
{
this.toggledValue = true;
}
this.toggledValue = !this.toggledValue;
this.toggleChange.emit(this.toggledValue);
}
logout(){
localStorage.removeItem('token');
localStorage.removeItem('usuario');
this.router.navigate([""]);
}
nuevo(){
this.dialog.open(DatosUsuarioComponent, {
width: '400px',});
}
}
<file_sep>export interface Productos{
_id: string;
nombre: String;
precio_venta : number;
precio_compra: Number;
stock: Number;
imagen: String;
descripcion: String;
idCategoria: String;
cantidad: number;
}
<file_sep>import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CatalogoService {
carrito = [];
constructor() { }
add_carrito(productos){
/* let id = productos._id;
let p = this.carrito.push(id);
console.log("carrito: ", p);*/
}
}
<file_sep>import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { MatDialog, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { Usuario } from 'src/app/login/usuario';
import Swal from 'sweetalert2';
import { UsuarioService } from '../usuario.service';
let user: Usuario[] = [];
@Component({
selector: 'app-cambiar-password',
templateUrl: './cambiar-password.component.html',
styleUrls: ['./cambiar-password.component.css']
})
export class CambiarPasswordComponent implements OnInit {
id: any;
hide = true;
id_usuario: any;
public user:any;
constructor(private usuarioService: UsuarioService,
private router:Router,
public dialog: MatDialog,
@Inject(MAT_DIALOG_DATA) public data:any)
{
this.id_usuario = this.usuarioService.getIdentidad();
}
userForm = new FormGroup({
nombreCompleto: new FormControl(''),
nombre: new FormControl(''),
apellidos: new FormControl(''),
correo: new FormControl(''),
password: new FormControl(''),
estado: new FormControl(''),
rol: new FormControl('')
});
ngOnInit(): void {
this.get_datos();
}
get_datos(){
let id = this.id_usuario._id;
this.usuarioService.mostrar_id(id).subscribe(
(res:any)=>{
user = res;
this.userForm = new FormGroup({
nombreCompleto: new FormControl(res.user.nombre + " " +res.user.apellidos),
nombre: new FormControl(res.user.nombre),
apellidos: new FormControl(res.user.apellidos),
correo: new FormControl(res.user.correo),
password: new FormControl(''),
estado: new FormControl(res.user.estado),
rol: new FormControl(res.user.rol)
});
this.id = this.id_usuario._id;
},
(error) => {
console.log(error);
});
}
modificar(){
this.usuarioService.cambiarContra(this.id , {
nombre : this.userForm.value.nombre,
apellidos: this.userForm.value.apellidos,
correo: this.userForm.value.correo,
password: this.userForm.value.password,
estado: this.userForm.value.estado,
rol: this.userForm.value.rol
}).subscribe(
res => {
Swal.fire({
position: 'center',
icon: 'success',
title: 'Datos modificados',
showConfirmButton: false,
timer: 900
})
this.dialog.closeAll();
},
error => {
console.log(error);
}
)
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AdminRoutingModule } from './admin-routing.module';
import { AdminComponent } from './admin.component';
import { CategoriasComponent } from './categorias/categorias.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatIconModule } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatCardModule } from '@angular/material/card';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSelectModule } from '@angular/material/select';
import {MatButtonModule} from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import {MatDialogModule} from '@angular/material/dialog';
import { ClientesComponent } from './clientes/clientes.component';
import { CrearModificarClienteComponent } from './clientes/crear-modificar-cliente/crear-modificar-cliente.component';
import { UsuariosComponent } from './usuarios/usuarios.component';
import { DatosUsuarioComponent } from './usuarios/datos-usuario/datos-usuario.component';
import { CambiarPasswordComponent } from './usuarios/cambiar-password/cambiar-password.component';
import { CreateUsuarioDialogComponent } from './usuarios/create-usuario-dialog/create-usuario-dialog.component';
import { ProductosComponent } from './productos/productos.component';
import { CreateProdutoDialogComponent } from './productos/create-produto-dialog/create-produto-dialog.component';
import { ModificarProductoDialogComponent } from './productos/modificar-producto-dialog/modificar-producto-dialog.component';
import { CatalogoComponent } from './productos/catalogo/catalogo.component';
import { CarritoComprasModule } from './carrito-compras/carrito-compras.module';
import { HeaderComponent } from './componentes/header/header.component';
import { NavComponent } from './componentes/nav/nav.component';
import { VentasComponent } from './ventas/ventas.component';
@NgModule({
declarations: [
AdminComponent,
CategoriasComponent,
ClientesComponent,
CrearModificarClienteComponent,
UsuariosComponent,
DatosUsuarioComponent,
CambiarPasswordComponent,
CreateUsuarioDialogComponent,
ProductosComponent,
CreateProdutoDialogComponent,
ModificarProductoDialogComponent,
CatalogoComponent,
HeaderComponent,
NavComponent,
VentasComponent,
],
imports: [
CommonModule,
HttpClientModule,
AdminRoutingModule,
ReactiveFormsModule,
CarritoComprasModule,
MatFormFieldModule,
FormsModule,
MatCardModule,
MatTableModule,
MatPaginatorModule,
MatSelectModule,
MatIconModule,
MatIconModule,
MatButtonModule,
MatInputModule,
MatDialogModule,
],
exports:[]
})
export class AdminModule { }
<file_sep>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Usuario } from './usuario';
import {environment} from '../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class LoginService {
urlBase = environment.servidor;
constructor(private http: HttpClient) { }
login(usuario: Usuario){
return this.http.post(`${this.urlBase}/login`, usuario);
}
}<file_sep>import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { Router } from '@angular/router';
import { environment } from 'src/environments/environment';
import Swal from 'sweetalert2';
import { CreateProdutoDialogComponent } from './create-produto-dialog/create-produto-dialog.component';
import { ModificarProductoDialogComponent } from './modificar-producto-dialog/modificar-producto-dialog.component';
import { ProductoService } from './producto.service';
import { Productos } from './productos';
let productos:Productos[] = [];
@Component({
selector: 'app-productos',
templateUrl: './productos.component.html',
styleUrls: ['./productos.component.css']
})
export class ProductosComponent implements OnInit {
displayedColumns: string[] = ['nombre','precio_compra','precio_venta','stock','imagen','descripcion','editar', 'eliminar'];
dataSource = new MatTableDataSource(productos);
@ViewChild(MatPaginator)
paginator!: MatPaginator;
urlBase: string;
constructor(
private productoService: ProductoService,
public dialog: MatDialog,
private router: Router
)
{ this.urlBase = environment.servidor; }
ngOnInit(): void {
this.mostrar();
}
mostrar(){
this.productoService.mostrar('').subscribe(
(datos:any) => {
productos = datos;
this.dataSource = new MatTableDataSource(productos);
this.dataSource.paginator = this.paginator;
console.log(datos);
},
(error)=>{
console.log(error);
localStorage.clear();
this.router.navigate(['']);
}
);
}
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
}
nuevo(datos = null){
if(datos == null)
{
this.dialog.open(CreateProdutoDialogComponent, {
width: '880px',
});
}else{
this.dialog.open(ModificarProductoDialogComponent,{
width: '880px',
data:datos,
});
}
this.dialog.afterAllClosed.subscribe((result:any) =>{
console.log('Resultado', result);
this.mostrar();
});
}
eliminar(id:any){
Swal.fire({
title: '¿Esta seguro?',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
cancelButtonText: 'Cancelar',
confirmButtonText: 'Confirmar'
}).then((result) => {
if (result.isConfirmed) {
this.productoService.eliminar(id).subscribe(res => {
console.log(res);
this.mostrar();
}, error => {
console.log(error);
});
Swal.fire(
'¡Eliminado!',
'Usuario eliminado exitosamente',
'success'
)
}
})
}
}
<file_sep>import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { environment } from 'src/environments/environment';
import { ProductoService } from '../producto.service';
interface HtmlInputEvent extends Event{
target: HTMLInputElement & EventTarget;
}
@Component({
selector: 'app-create-produto-dialog',
templateUrl: './create-produto-dialog.component.html',
styleUrls: ['./create-produto-dialog.component.css']
})
export class CreateProdutoDialogComponent implements OnInit {
public file :File;
public imgSelect : String | ArrayBuffer;
id: string | undefined;
estado: boolean = false;
public categorias;
public urlBase;
productForm = new FormGroup({
nombre: new FormControl('',[Validators.required]),
precio_compra: new FormControl('',[Validators.required]),
precio_venta: new FormControl('',[Validators.required]),
stock: new FormControl('' ),
descripcion: new FormControl(''),
imagen: new FormControl(''),
idCategoria : new FormControl(''),
});
constructor( private router: Router,
private productoService: ProductoService)
{
this.urlBase = environment.servidor;
}
ngOnInit(): void {
this.get_categoria();
}
get_categoria(){
this.productoService.mostrar_categoria().subscribe(
(res:any) =>{
this.categorias = res.Categoria;
}
)
}
imgSelected(event: HtmlInputEvent){
if(event.target.files && event.target.files[0]){
this.file = <File>event.target.files[0];
const reader = new FileReader();
reader.onload = e => this.imgSelect = reader.result;
reader.readAsDataURL(this.file);
}
}
guardarProducto(productForm) {
this.productoService.guardar({
nombre: this.productForm.value.nombre,
precio_compra: this.productForm.value.precio_compra,
precio_venta: this.productForm.value.precio_venta,
stock: this.productForm.value.stock,
descripcion: this.productForm.value.descripcion,
imagen: this.file,
idCategoria: this.productForm.value.idCategoria,
}).subscribe(
(res) => {
console.log("Se registro el producto",res);
this.imgSelect = '../../../assets/img/images.png';
},
(error) => {
console.log(JSON.stringify(error));
}
);
}
}
<file_sep>export interface Cliente{
nombre: String;
apellidos: String;
ci: String;
email: String;
telefono: String;
}<file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class ProductoService {
urlBase = environment.servidor;
headers: HttpHeaders | undefined;
constructor(private http: HttpClient) {
try{
let token = JSON.parse(atob(localStorage.getItem("token")||'{}'));
this.headers = new HttpHeaders({
'Content-Type': 'application/json; charset=utf-8',
'Authorization': 'Bearer '+ token.access_token,
});
}
catch(error){
console.log(error);
}
}
mostrar(filtro):Observable<any>{
return this.http.get(`${this.urlBase}/producto/${filtro}`, {headers: this.headers});
}
mostrar_categoria()
{
return this.http.get(`${this.urlBase}/categoria/`,{headers: this.headers});
}
eliminar(id:any){
return this.http.delete(`${this.urlBase}/producto/${id}`,{headers: this.headers});
}
guardar(data:any)
{
const fd = new FormData();
fd.append('nombre', data.nombre);
fd.append('precio_compra', data.precio_compra);
fd.append('precio_venta', data.precio_venta);
fd.append('stock', data.stock);
fd.append('descripcion', data.descripcion);
fd.append('imagen', data.imagen);
fd.append('idCategoria',data.idCategoria);
return this.http.post(`${this.urlBase}/producto`,fd);
}
modificar(data){
const fd = new FormData();
fd.append('nombre', data.nombre);
fd.append('precio_compra', data.precio_compra);
fd.append('precio_venta', data.precio_venta);
fd.append('stock', data.stock);
fd.append('descripcion', data.descripcion);
fd.append('imagen', data.imagen);
fd.append('idCategoria',data.idCategoria);
return this.http.put(`${this.urlBase}/producto/${data._id}/${data.img_name}`,fd);
}
}
<file_sep>import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Categoria } from './categoria';
import { CategoriaService } from './categoria.service';
import Swal from 'sweetalert2';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { ViewChild } from '@angular/core';
import { Router } from '@angular/router';
let categoria: Categoria[] = [];
@Component({
selector: 'app-categorias',
templateUrl: './categorias.component.html',
styleUrls: ['./categorias.component.css']
})
export class CategoriasComponent implements OnInit {
displayedColumns: string[] = ['Nombre', 'Descripcion', 'Editar', 'Eliminar'];
dataSource = new MatTableDataSource(categoria);
id: string | undefined;
estado: boolean = false;
@ViewChild(MatPaginator)
paginator!: MatPaginator;
constructor(private categoriatoService: CategoriaService,
private router: Router ){}
productForm = new FormGroup({
titulo: new FormControl('',[Validators.required]),
descripcion: new FormControl(''),
});
ngOnInit(): void {
const tok = localStorage.getItem("token");
if(tok)
{
this.mostrar();
}
else
{
this.router.navigate([""]);
}
}
mostrar(){
this.categoriatoService.mostrar_prod().subscribe(
(datos:any) => {
categoria = datos.Categoria;
this.dataSource = new MatTableDataSource(categoria);
this.dataSource.paginator = this.paginator;
console.log(categoria);
},
(error)=>{
console.log(error);
}
);
}
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
}
nuevo(){
this.estado = false;
this.productForm = new FormGroup({
titulo: new FormControl(''),
descripcion: new FormControl(''),
});
}
guardar(){
if(this.productForm.valid)
{
this.categoriatoService.guardar({
titulo: this.productForm.value.titulo,
descripcion: this.productForm.value.descripcion,
}).subscribe(
(datos:any) => {
this.mostrar();
},
(error)=>{
console.log(error);
}
);
}
else{
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Revise los datos!',
})
}
}
mod_datos(data:any){
if(data == null)
{
console.log("NADA");
}else{
console.log("Datos: "+ JSON.stringify(data));
this.productForm = new FormGroup({
titulo: new FormControl(data.titulo, [Validators.required]),
descripcion: new FormControl(data.descripcion),
});
this.id = data._id;
this.estado = true;
}
}
modificar(){
this.categoriatoService.modificar(this.id, this.productForm.value).subscribe(
res => {
console.log(res);
this.productForm = new FormGroup({
titulo: new FormControl(''),
descripcion: new FormControl(''),
});
Swal.fire({
position: 'center',
icon: 'success',
title: 'Datos modificados',
showConfirmButton: false,
timer: 500
})
this.mostrar();
},
error => {
console.log(error);
}
)
}
eliminar(id:any){
Swal.fire({
title: '¿Esta seguro?',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
cancelButtonText: 'Cancelar',
confirmButtonText: 'Confirmar'
}).then((result) => {
if (result.isConfirmed) {
this.categoriatoService.eliminar(id).subscribe(res => {
console.log(res);
this.mostrar();
}, error => {
console.log(error);
});
Swal.fire(
'¡Eliminado!',
'Categoria eliminada exitosamente',
'success'
)
}
})
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { LoginService } from './login.service';
import Swal from 'sweetalert2';
import { UsuarioService } from '../admin/usuarios/usuario.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
hide = true;
public id_usuario: any;
profileForm = new FormGroup({
correo : new FormControl('', [Validators.email, Validators.required] ),
password : new FormControl('', [Validators.required]),
});
constructor( private usuarioService: UsuarioService,
private loginService: LoginService,
private router: Router ) {
this.id_usuario = this.usuarioService.getIdentidad();
}
ngOnInit(): void {
}
ingresar(){
this.loginService.login(this.profileForm.value).subscribe(
(datos:any)=>{
if(!datos.access_token){
Swal.fire({
icon: 'error',
title: datos.mensaje,
})
}
else{
localStorage.setItem("token",btoa(JSON.stringify(datos)));
localStorage.setItem("usuario",JSON.stringify(datos.Usuario));
this.router.navigate(["admin"]);
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'Bienvenid@ '+ datos.Usuario.nombre,
showConfirmButton: false,
timer: 1000
})
console.log(datos);
localStorage.setItem("token",btoa(JSON.stringify(datos)));
this.router.navigate(["admin"]);
}
},
(error:any) =>{
Swal.fire({
icon: 'error',
title: error.mensaje,
})
}
)
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UsuarioService } from '../admin/usuarios/usuario.service';
@Component({
selector: 'app-inicio',
templateUrl: './inicio.component.html',
styleUrls: ['./inicio.component.css']
})
export class InicioComponent implements OnInit {
public id_usuario;
constructor(
private usuarioService: UsuarioService,
private router: Router) {
this.id_usuario = this.usuarioService.getIdentidad();
}
ngOnInit(): void {
const token = localStorage.getItem('token');
if(token)
{
this.router.navigate(["admin"]);
}/**/
}
}
<file_sep>import { TestBed } from '@angular/core/testing';
import { CarritoComprasService } from './../carrito-compras/carrito-compras.service';
describe('CarritoComprasService', () => {
let service: CarritoComprasService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(CarritoComprasService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
<file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class ClientesService {
urlBase = environment.servidor;
headers: HttpHeaders | undefined;
constructor(private http: HttpClient)
{
try{
let token = JSON.parse(atob(localStorage.getItem("token")||'{}'));
this.headers = new HttpHeaders({
'Content-Type': 'application/json; charset=utf-8',
'Authorization': 'Bearer '+ token.access_token,
});
}
catch(error){
console.log(error);
}
}
mostrar(){
return this.http.get(`${this.urlBase}/cliente/`, {headers: this.headers});
}
guardar(cliente:any){
return this.http.post(`${this.urlBase}/cliente`, cliente , {headers:this.headers});
}
modificar(id:any,cliente:any){
return this.http.put(`${this.urlBase}/cliente/${id}`,cliente,{headers: this.headers});
}
eliminar(id:any){
return this.http.delete(`${this.urlBase}/cliente/${id}`, {headers: this.headers});
}
}
<file_sep>import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import Swal from 'sweetalert2';
import { ClientesService } from '../clientes.service';
interface HtmlInputEvent extends Event{
target: HTMLInputElement & EventTarget;
}
@Component({
selector: 'app-crear-modificar-cliente',
templateUrl: './crear-modificar-cliente.component.html',
styleUrls: ['./crear-modificar-cliente.component.css']
})
export class CrearModificarClienteComponent implements OnInit {
clienteForm = new FormGroup({
nombre: new FormControl('',[Validators.required]),
apellidos: new FormControl('',[Validators.required]),
ci: new FormControl('' ,[Validators.required]),
email: new FormControl('',[Validators.required]),
telefono: new FormControl(''),
});
id: string | undefined;
estado: boolean = false;
constructor(private clienteService: ClientesService,
@Inject(MAT_DIALOG_DATA) public data:any){
if(data!=null)
{
this.clienteForm = new FormGroup({
nombre: new FormControl(data.nombre, [Validators.required]),
apellidos: new FormControl(data.apellidos, [Validators.required]),
ci: new FormControl(data.ci,[Validators.required]),
email: new FormControl(data.email,[Validators.required]),
telefono: new FormControl(data.telefono),
});
this.id = data._id;
this.estado = true;
console.log("ID: ", this.id);
}}
ngOnInit(): void {
}
guardar(){
if(this.clienteForm.valid)
{
this.clienteService.guardar({
nombre: this.clienteForm.value.nombre,
apellidos: this.clienteForm.value.apellidos,
ci: this.clienteForm.value.ci,
email: this.clienteForm.value.email,
telefono: this.clienteForm.value.telefono,
}).subscribe(
(res)=>{
console.log("Datos guardados");
},
(error)=>{
console.log("Error guardando al cliente",JSON.stringify(error));
}
)
}
else{
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Revise los datos!',
})
}
}
modificar(){
this.clienteService.modificar(this.id, this.clienteForm.value)
.subscribe(
(res) => {
console.log(res);
console.log("funciona");
},
(error)=>{
console.log(error);
}
)
}
}
<file_sep>import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { InicioComponent } from './inicio/inicio.component';
import { TodoComponent } from './inicio/todo/todo.component';
import { LoginComponent } from './login/login.component';
const routes: Routes = [
{
path: '',
component: InicioComponent,
children:[
{
path: 'login',
component: LoginComponent
},
{
path: 'todo',
component: TodoComponent
}
]
},
{
path:'admin',
loadChildren:() => import('./admin/admin.module')
.then((m) => m.AdminModule),
},
];
@NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { Router } from '@angular/router';
import { Usuario } from 'src/app/login/usuario';
import Swal from 'sweetalert2';
import { CreateUsuarioDialogComponent } from './create-usuario-dialog/create-usuario-dialog.component';
import { UsuarioService } from './usuario.service';
let usuario: Usuario[] = [];
@Component({
selector: 'app-usuarios',
templateUrl: './usuarios.component.html',
styleUrls: ['./usuarios.component.css']
})
export class UsuariosComponent implements OnInit {
public identidad;
constructor(private usuarioService: UsuarioService,
public dialog : MatDialog,
private router: Router)
{
this.identidad = usuarioService.getIdentidad();
}
displayedColumns: string[] = ['Nombre', 'Correo', 'Rol', 'Estado', 'Editar', 'Eliminar'];
dataSource = new MatTableDataSource(usuario);
@ViewChild(MatPaginator)
paginator!: MatPaginator;
ngOnInit(): void {
if(this.identidad.rol === 'Administrador')
{
this.mostrar();
}
if(this.identidad.rol === 'Empleado')
{
this.router.navigate(["admin"]);
}
}
mostrar(){
this.usuarioService.mostrar().subscribe(
(datos:any)=>{
usuario = datos;
console.log(usuario);
this.dataSource = new MatTableDataSource(usuario);
this.dataSource.paginator = this.paginator;
},
(error)=>{
console.log(error)
}
);
}
nuevo(datos = null){
if(datos == null)
{
this.dialog.open( CreateUsuarioDialogComponent, {
width: '380px',
});
}else{
this.dialog.open( CreateUsuarioDialogComponent,{
width: '380px',
data:datos,
});
}
this.dialog.afterAllClosed.subscribe((result:any) =>{
console.log('Resultado', result);
this.mostrar();
});
}
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
}
eliminar(id:any){
Swal.fire({
title: '¿Esta seguro?',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
cancelButtonText: 'Cancelar',
confirmButtonText: 'Confirmar'
}).then((result) => {
if (result.isConfirmed) {
this.usuarioService.eliminar(id).subscribe(res => {
this.mostrar();
}, error => {
console.log(error);
});
Swal.fire(
'¡Eliminado!',
'Usuario eliminado exitosamente',
'success'
)
}
})
}
}
<file_sep>import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { environment } from "src/environments/environment";
@Injectable({
providedIn: 'root'
})
export class UsuarioService{
public ide_usuario: any;
urlBase = environment.servidor;
headers: HttpHeaders | undefined;
constructor(private http: HttpClient){
try{
let token = JSON.parse(atob(localStorage.getItem("token")||'{}'));
this.headers = new HttpHeaders({
'Content-Type': 'application/json; charset=utf-8',
'Authorization': 'Bearer '+ token.access_token,
});
}
catch(error){
console.log(error);
}
}
getIdentidad(){
let identidad = JSON.parse(localStorage.getItem('usuario') ||"{}");
if(identidad)
{
this.ide_usuario = identidad;
}
else
{
this.ide_usuario= null;
}
return this.ide_usuario;
}
mostrar()
{
return this.http.get(`${this.urlBase}/usuario/`,{headers: this.headers});
}
mostrar_id(id:any){
return this.http.get(`${this.urlBase}/usuario/${id}`,{headers: this.headers});
}
guardar(usuario:any){
return this.http.post(`${this.urlBase}/usuario`,usuario, {headers: this.headers});
}
modificar(id:any,usuario:any){
return this.http.put(`${this.urlBase}/usuario/${id}`, usuario,{headers: this.headers});
}
cambiarContra(id:any,cuerpo:any)
{
return this.http.put(`${this.urlBase}/usuario/${id}`,cuerpo, {headers: this.headers});
}
eliminar(id:any){
return this.http.delete(`${this.urlBase}/usuario/${id}`, {headers: this.headers});
}
}<file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class CategoriaService {
urlBase = environment.servidor;
headers: HttpHeaders | undefined;
constructor(private http: HttpClient)
{
try{
let token = JSON.parse(atob(localStorage.getItem("token")||'{}'));
this.headers = new HttpHeaders({
'Content-Type': 'application/json; charset=utf-8',
'Authorization': 'Bearer '+ token.access_token,
});
}
catch(error){
console.log(error);
}
}
mostrar_prod()
{
return this.http.get(`${this.urlBase}/categoria/`,{headers: this.headers});
}
guardar(categoria:any){
return this.http.post(`${this.urlBase}/categoria`,categoria, {headers: this.headers});
}
modificar(id:any,categoria:any){
return this.http.put(`${this.urlBase}/categoria/${id}`,categoria,{headers: this.headers});
}
eliminar(id:any){
return this.http.delete(`${this.urlBase}/categoria/${id}`,{headers: this.headers});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { CambiarPasswordComponent } from '../cambiar-password/cambiar-password.component';
import { UsuarioService } from '../usuario.service';
@Component({
selector: 'app-datos-usuario',
templateUrl: './datos-usuario.component.html',
styleUrls: ['./datos-usuario.component.css']
})
export class DatosUsuarioComponent implements OnInit {
public id_usuario: any;
constructor(public dialog: MatDialog,
private usuarioService: UsuarioService)
{
this.id_usuario = this.usuarioService.getIdentidad();
}
ngOnInit(): void {
}
cambiar_contra(){
this.dialog.open(CambiarPasswordComponent, {
width: '380px',
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { environment } from 'src/environments/environment';
import { DetalleVenta } from '../productos/catalogo/detalleventa';
import { Productos } from '../productos/productos';
import { CarritoComprasService } from './carrito-compras.service';
@Component({
selector: 'app-carrito-compras',
templateUrl: './carrito-compras.component.html',
styleUrls: ['./carrito-compras.component.css']
})
export class CarritoComprasComponent implements OnInit {
urlBase: String;
cart : DetalleVenta;
constructor(
private carritoComprasService: CarritoComprasService)
{this.urlBase = environment.servidor;
this.carritoComprasService.itemsVar$.subscribe(
(data: DetalleVenta)=>{
if(data !== undefined && data !== null)
{
this.cart = data;
}
})}
ngOnInit(): void {
this.cart = this.carritoComprasService.initialize();
console.log("Info carrito",this.cart);
}
clear(){
this.carritoComprasService.clear();
}
clearItem(producto: Productos){
producto.cantidad = 0;
this.carritoComprasService.manageProduct(producto);
}
openNav(){
this.carritoComprasService.openNav();
}
closeNav(){
this.carritoComprasService.closeNav();
}
}
<file_sep>import { Productos } from "../productos";
export interface DetalleVenta{
productos: Array<Productos>;
total: number;
}<file_sep>import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';
import { ComponentFactoryResolver, Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { Productos } from '../productos/productos';
import { DetalleVenta } from '../productos/catalogo/detalleventa';
@Injectable({
providedIn: 'root'
})
export class CarritoComprasService {
productos:Productos[] = [];
carrito = [];
detalle_carrito = [];
detalle: DetalleVenta ={
productos : this.productos,
total: 0,
}
//Para gestionr los productos con las notificaciones cuando se realian acciones como borrar
public itemsVar = new Subject<DetalleVenta>();
public itemsVar$ = this.itemsVar.asObservable();
constructor() { }
initialize(){
/**
* Inicializar el carrito para tner la info almacenada
*/
const storeData = JSON.parse(localStorage.getItem('cart'));
if(storeData !== null)
{
this.detalle = storeData;
}
return this.detalle;
}
public updateItemsInCart(newValue: DetalleVenta){
this.itemsVar.next(newValue);
}
manageProduct(productos: Productos){
let actionUpdateOk = false;
const det_prod = this.detalle.productos.length;
if(det_prod === 0)
{
productos.cantidad = 1;
this.detalle.productos.push(productos);
}
else{
for(let i=0; i<det_prod ; i++)
{
if(productos._id === this.detalle.productos[i]._id)
{
if(productos.cantidad === 0)
{
console.log("Borrando elemento");
this.detalle.productos.splice(i,1);
}
else{
this.detalle.productos[i].cantidad +=1;
this.detalle.productos[i] = productos;
}
actionUpdateOk = true;
i = det_prod;
}
}
if(!actionUpdateOk)
{
productos.cantidad = 1;
this.detalle.productos.push(productos);
}
}
this.total();
}
total(){
let total = 0;
this.detalle.productos.map((productos: Productos)=>{
total += productos.precio_venta * productos.cantidad;
});
this.detalle.total = total;
this.setInfo();
console.log("Total: ", this.detalle);
}
clear(){
this.productos = [];
this.detalle = {
total: 0,
productos: this.productos,
};
this.setInfo();
console.log('Borrando informacion');
return this.detalle;
}
private setInfo(){
localStorage.setItem('cart',JSON.stringify(this.detalle));
this.updateItemsInCart(this.detalle);
}
openNav(){
document.getElementById("mySidenav").style.width = "450px";
document.getElementById('overlay').style.display = 'block';
document.getElementById('app').style.overflow = 'hidden';
}
closeNav(){
document.getElementById("mySidenav").style.width = "0";
document.getElementById('overlay').style.display = 'none';
document.getElementById('app').style.overflow = 'auto';
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { environment } from 'src/environments/environment';
import { CarritoComprasService } from '../../carrito-compras/carrito-compras.service';
import { ProductoService } from '../producto.service';
import { Productos } from '../productos';
import { CatalogoService } from './catalogo.service';
import {DetalleVenta} from './detalleventa';
let productos:Productos[] = [];
@Component({
selector: 'app-catalogo',
templateUrl: './catalogo.component.html',
styleUrls: ['./catalogo.component.css']
})
export class CatalogoComponent implements OnInit {
public productos;
urlBase: String;
cart: DetalleVenta;
signoMonetario = "Bs";
detalle: DetalleVenta ={
productos : productos,
total: 0,
}
constructor(private productoService: ProductoService,
private catalogoService: CatalogoService,
private carritoService: CarritoComprasService)
{ this.urlBase = environment.servidor; }
ngOnInit(): void {
this.mostrar();
}
mostrar(){
this.productoService.mostrar('').subscribe(
(datos:any) => {
this.productos = datos;
},
(error)=>{
console.log(error);
}
);
}
add_carrito(productos){
this.carritoService.manageProduct(productos);
}
}
<file_sep>import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { environment } from 'src/environments/environment';
import { ProductoService } from '../producto.service';
interface HtmlInputEvent extends Event{
target: HTMLInputElement & EventTarget;
}
@Component({
selector: 'app-modificar-producto-dialog',
templateUrl: './modificar-producto-dialog.component.html',
styleUrls: ['./modificar-producto-dialog.component.css']
})
export class ModificarProductoDialogComponent implements OnInit {
public urlBase;
public categorias;
public file :File;
public imgSelect : String | ArrayBuffer;
productForm: any;
id: string | undefined;
constructor( private router: Router,
private productoService: ProductoService,
@Inject(MAT_DIALOG_DATA) public data:any)
{
this.urlBase = environment.servidor;
if(data!=null)
{
this.productForm = new FormGroup({
nombre: new FormControl(data.nombre, [Validators.required]),
precio_compra: new FormControl(data.precio_compra, [Validators.required]),
precio_venta: new FormControl(data.precio_venta, [Validators.required]),
stock: new FormControl(data.stock),
descripcion: new FormControl(data.descripcion),
imagen: new FormControl(data.imagen),
idCategoria: new FormControl(data.idCategoria),
});
this.id = data._id;
}
}
ngOnInit(): void {
this.get_categoria();
}
get_categoria(){
this.productoService.mostrar_categoria().subscribe(
(res:any) =>{
this.categorias = res.Categoria;
}
)
}
imgSelected(event: HtmlInputEvent){
if(event.target.files && event.target.files[0]){
this.file = <File>event.target.files[0];
const reader = new FileReader();
reader.onload = e => this.imgSelect = reader.result;
reader.readAsDataURL(this.file);
}
}
modificar(productForm){
this.productoService.modificar({
_id: this.id,
nombre: productForm.value.nombre,
precio_compra: productForm.value.precio_compra,
precio_venta: productForm.value.precio_venta,
descripcion: productForm.value.descripcion,
stock: productForm.value.stock,
imagen: this.file,
idCategoria: productForm.value.idCategoria,
img_name : productForm.value.imagen,
}).subscribe(
response=>{
console.log(response);
},
error=>{
}
);
}
}
<file_sep>import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import Swal from 'sweetalert2';
import { UsuarioService } from '../usuario.service';
import { Rol } from './rol';
import { UsuarioEstado } from './usuarioEstado';
interface HtmlInputEvent extends Event{
target: HTMLInputElement & EventTarget;
}
@Component({
selector: 'app-create-usuario-dialog',
templateUrl: './create-usuario-dialog.component.html',
styleUrls: ['./create-usuario-dialog.component.css']
})
export class CreateUsuarioDialogComponent implements OnInit {
roles: Rol[] = [
{value: 'Empleado', viewValue: 'Empleado'},
{value: 'Administrador', viewValue: 'Administrador'}
];
estados: UsuarioEstado[] = [
{value: true, viewValue: 'Habilitado'},
{value: false, viewValue: 'Inhabilitado'}
];
usuarioForm = new FormGroup({
nombre: new FormControl('',[Validators.required]),
apellidos: new FormControl('',[Validators.required]),
correo: new FormControl('',[Validators.required]),
password: new FormControl('',[Validators.required]),
rol: new FormControl('',[Validators.required]),
estado: new FormControl('',[Validators.required]),
});
id: string | undefined;
estado: boolean = false;
constructor(private usuarioService : UsuarioService,
@Inject(MAT_DIALOG_DATA) public data:any){
if(data!=null)
{
this.usuarioForm = new FormGroup({
nombre: new FormControl(data.nombre,[Validators.required]),
apellidos: new FormControl(data.apellidos,[Validators.required]),
correo: new FormControl(data.correo,[Validators.required]),
password: new FormControl(data.password,[Validators.required]),
rol: new FormControl(data.rol,[Validators.required]),
estado: new FormControl(data.estado,[Validators.required]),
});
this.id = data._id;
this.estado = true;
}
}
ngOnInit(): void {
}
guardar(){
if(this.usuarioForm.valid)
{
this.usuarioService.guardar({
nombre: this.usuarioForm.value.nombre,
apellidos: this.usuarioForm.value.apellidos,
correo: this.usuarioForm.value.correo,
password: this.usuarioForm.value.password,
rol: this.usuarioForm.value.rol,
estado: this.usuarioForm.value.estado,
}).subscribe(
(res)=>{
console.log("Datos guardados");
},
(error)=>{
console.log("Error guardando al cliente",JSON.stringify(error));
}
)
}
else{
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Revise los datos!',
})
}
}
modificar(){
this.usuarioService.modificar(this.id, this.usuarioForm.value)
.subscribe(
(res) => {
console.log(res);
},
(error)=>{
console.log(error);
}
)
}
}
| 4d651aa5a489e728629d1324d444b310068825d6 | [
"TypeScript"
] | 30 | TypeScript | fla1004/front-pedidos | 516f92652735ef81ed6ba482865bb522beb88bbe | 976533a3e31a48f47f0dc82526a5b14330f8f8b0 |
refs/heads/master | <repo_name>afoals/HoffVsZombies<file_sep>/main.js
function BufferLoader(context, urlList, callback) {
this.context = context;
this.urlList = urlList;
this.onload = callback;
this.bufferList = new Array();
this.loadCount = 0;
}
BufferLoader.prototype.loadBuffer = function(url, index) {
// Load buffer asynchronously
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
var loader = this;
request.onload = function() {
// Asynchronously decode the audio file data in request.response
loader.context.decodeAudioData(
request.response,
function(buffer) {
if (!buffer) {
alert('error decoding file data: ' + url);
return;
}
loader.bufferList[index] = buffer;
if (++loader.loadCount == loader.urlList.length)
loader.onload(loader.bufferList);
},
function(error) {
console.error('decodeAudioData error', error);
}
);
}
request.onerror = function() {
alert('BufferLoader: XHR error');
}
request.send();
}
BufferLoader.prototype.load = function() {
for (var i = 0; i < this.urlList.length; ++i)
this.loadBuffer(this.urlList[i], i);
}
$(function() { //canvas variables
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// game variables
var startingScore = 0;
var continueAnimating = false;
var score;
// block variables
var blockWidth = 30;
var blockHeight = 15;
var blockSpeed = 10;
var block = {
x: 0,
y: canvas.height - blockHeight,
width: blockWidth,
height: blockHeight,
blockSpeed: blockSpeed
}
// rock variables
var rockWidth = 15;
var rockHeight = 15;
var totalRocks = 10;
var rocks = [];
for (var i = 0; i < totalRocks; i++) {
addRock();
}
var audioContext;
var audioBufferLoader;
var audioBufferList;
var ctls = [];
var currentSoundCtl = 0;
var hitCount = 0;
function startAudio(buffers) {
function createSource(buffer) {
var source = audioContext.createBufferSource();
var gainNode = audioContext.createGain ? audioContext.createGain() : audioContext.createGainNode();
source.buffer = buffer;
source.loop = true;
source.connect(gainNode);
gainNode.connect(audioContext.destination);
return {
source: source,
gainNode: gainNode
};
};
ctls.push(createSource(buffers[0]));
ctls.push(createSource(buffers[1]));
ctls.push(createSource(buffers[2]));
ctls.push(createSource(buffers[3]));
ctls[1].gainNode.gain.value = 0;
ctls[2].gainNode.gain.value = 0;
ctls[3].gainNode.gain.value = 0;
// Start playback in a loop
if (!ctls[0].source.start) {
ctls[0].source.noteOn(0);
ctls[1].source.noteOn(0);
ctls[2].source.noteOn(0);
ctls[3].source.noteOn(0);
} else {
ctls[0].source.start(0);
ctls[1].source.start(0);
ctls[2].source.start(0);
ctls[3].source.start(0);
}
}
function addRock() {
var rock = {
width: rockWidth,
height: rockHeight
}
resetRock(rock);
rocks.push(rock);
}
// move the rock to a random position near the top-of-canvas
// assign the rock a random speed
function resetRock(rock) {
rock.x = Math.random() * (canvas.width - rockWidth);
rock.y = 15 + Math.random() * 30;
rock.speed = 0.2 + Math.random() * 0.5;
}
//left and right keypush event handlers
document.onkeydown = function (event) {
if (event.keyCode == 39) {
block.x += block.blockSpeed;
if (block.x >= canvas.width - block.width) {
continueAnimating = false;
alert("Completed with a score of " + score);
}
} else if (event.keyCode == 37) {
block.x -= block.blockSpeed;
if (block.x <= 0) {
block.x = 0;
}
}
}
function animate() {
// request another animation frame
if (continueAnimating) {
requestAnimationFrame(animate);
}
// for each rock
// (1) check for collisions
// (2) advance the rock
// (3) if the rock falls below the canvas, reset that rock
for (var i = 0; i < rocks.length; i++) {
var rock = rocks[i];
// test for rock-block collision
if (isColliding(rock, block)) {
score += 10;
resetRock(rock);
hitCount++;
if (hitCount == 5) {
hitCount = 0;
if (currentSoundCtl < 3) {
currentSoundCtl++;
console.log('incrementing sound ctl', currentSoundCtl);
ctls[currentSoundCtl].gainNode.gain.value = 1;
} else {
console.log('max sound ctl');
}
}
}
// advance the rocks
rock.y += rock.speed;
// if the rock is below the canvas,
if (rock.y > canvas.height) {
resetRock(rock);
}
}
// redraw everything
drawAll();
}
function isColliding(a, b) {
return !(
b.x > a.x + a.width || b.x + b.width < a.x || b.y > a.y + a.height || b.y + b.height < a.y);
}
function drawAll() {
// clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw the background
// (optionally drawImage an image)
ctx.fillStyle = "rgba(0, 0, 200, 0)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// draw the block
ctx.fillStyle = "skyblue";
ctx.fillRect(block.x, block.y, block.width, block.height);
ctx.strokeStyle = "lightgray";
ctx.strokeRect(block.x, block.y, block.width, block.height);
// draw all rocks
for (var i = 0; i < rocks.length; i++) {
var rock = rocks[i];
// optionally, drawImage(rocksImg,rock.x,rock.y)
ctx.fillStyle = "gray";
ctx.fillRect(rock.x, rock.y, rock.width, rock.height);
}
// draw the score
ctx.font = "14px Times New Roman";
ctx.fillStyle = "black";
ctx.fillText("Score: " + score, 10, 15);
}
// button to start the game
$("#start").click(function () {
window.AudioContext = window.AudioContext||window.webkitAudioContext;
audioContext = new AudioContext();
audioBufferLoader = new BufferLoader(
audioContext,
['samples/axel-1-drum.mp3', 'samples/axel-2-bass.mp3', 'samples/axel-3-beat.mp3', 'samples/axel-4-tune.mp3'],
startAudio);
audioBufferLoader.load();
score = startingScore
block.x = 0;
for (var i = 0; i < rocks.length; i++) {
resetRock(rocks[i]);
}
if (!continueAnimating) {
continueAnimating = true;
animate();
};
});
$(".splash").click(function() {
$(this).hide();
});
});
| cecd1fb8328669e499605c0019c5871560a870c3 | [
"JavaScript"
] | 1 | JavaScript | afoals/HoffVsZombies | caa1795f765848f43073d4a3bf51a82bd3d72f2a | 62c2a3cefe989b52261ba2f8ff2eb231b80988ef |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.